blob: 8780d031c4e1918d165bb699f36a90b04fe54447 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it.
80 if (Inner != Temp)
81 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
George Burgess IVa51c4072015-10-16 01:49:01 +0000117 uint64_t &ArraySize, QualType &Type,
118 bool &IsArray) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000119 unsigned MostDerivedLength = 0;
120 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000121 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000122 if (Type->isArrayType()) {
123 const ConstantArrayType *CAT =
124 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
125 Type = CAT->getElementType();
126 ArraySize = CAT->getSize().getZExtValue();
127 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000128 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000129 } else if (Type->isAnyComplexType()) {
130 const ComplexType *CT = Type->castAs<ComplexType>();
131 Type = CT->getElementType();
132 ArraySize = 2;
133 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000134 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000135 } else if (const FieldDecl *FD = getAsField(Path[I])) {
136 Type = FD->getType();
137 ArraySize = 0;
138 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000139 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000140 } else {
Richard Smith80815602011-11-07 05:07:52 +0000141 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000143 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 }
Richard Smith80815602011-11-07 05:07:52 +0000145 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000146 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000147 }
148
Richard Smitha8105bc2012-01-06 16:39:00 +0000149 // The order of this enum is important for diagnostics.
150 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000151 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000152 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000153 };
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// A path from a glvalue to a subobject of that glvalue.
156 struct SubobjectDesignator {
157 /// True if the subobject was named in a manner not supported by C++11. Such
158 /// lvalues can still be folded, but they are not core constant expressions
159 /// and we cannot perform lvalue-to-rvalue conversions on them.
160 bool Invalid : 1;
161
Richard Smitha8105bc2012-01-06 16:39:00 +0000162 /// Is this a pointer one past the end of an object?
163 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000164
George Burgess IVa51c4072015-10-16 01:49:01 +0000165 /// Indicator of whether the most-derived object is an array element.
166 bool MostDerivedIsArrayElement : 1;
167
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 /// The length of the path to the most-derived object of which this is a
169 /// subobject.
George Burgess IVa51c4072015-10-16 01:49:01 +0000170 unsigned MostDerivedPathLength : 29;
Richard Smitha8105bc2012-01-06 16:39:00 +0000171
George Burgess IVa51c4072015-10-16 01:49:01 +0000172 /// The size of the array of which the most-derived object is an element.
173 /// This will always be 0 if the most-derived object is not an array
174 /// element. 0 is not an indicator of whether or not the most-derived object
175 /// is an array, however, because 0-length arrays are allowed.
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 uint64_t MostDerivedArraySize;
177
178 /// The type of the most derived object referred to by this address.
179 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000180
Richard Smith80815602011-11-07 05:07:52 +0000181 typedef APValue::LValuePathEntry PathEntry;
182
Richard Smith96e0c102011-11-04 02:25:55 +0000183 /// The entries on the path from the glvalue to the designated subobject.
184 SmallVector<PathEntry, 8> Entries;
185
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000187
Richard Smitha8105bc2012-01-06 16:39:00 +0000188 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000189 : Invalid(false), IsOnePastTheEnd(false),
190 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
191 MostDerivedArraySize(0), MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000192
193 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000194 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
195 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
196 MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000197 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000198 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000199 ArrayRef<PathEntry> VEntries = V.getLValuePath();
200 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000201 if (V.getLValueBase()) {
202 bool IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000203 MostDerivedPathLength =
204 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
205 V.getLValuePath(), MostDerivedArraySize,
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 MostDerivedType, IsArray);
207 MostDerivedIsArrayElement = IsArray;
208 }
Richard Smith80815602011-11-07 05:07:52 +0000209 }
210 }
211
Richard Smith96e0c102011-11-04 02:25:55 +0000212 void setInvalid() {
213 Invalid = true;
214 Entries.clear();
215 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000216
217 /// Determine whether this is a one-past-the-end pointer.
218 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000219 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 if (IsOnePastTheEnd)
221 return true;
George Burgess IVa51c4072015-10-16 01:49:01 +0000222 if (MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000223 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
224 return true;
225 return false;
226 }
227
228 /// Check that this refers to a valid subobject.
229 bool isValidSubobject() const {
230 if (Invalid)
231 return false;
232 return !isOnePastTheEnd();
233 }
234 /// Check that this refers to a valid subobject, and if not, produce a
235 /// relevant diagnostic and set the designator as invalid.
236 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
237
238 /// Update this designator to refer to the first element within this array.
239 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000240 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000241 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000242 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000243
244 // This is a most-derived object.
245 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247 MostDerivedArraySize = CAT->getSize().getZExtValue();
248 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000249 }
250 /// Update this designator to refer to the given base or member of this
251 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000252 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000253 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000254 APValue::BaseOrMemberType Value(D, Virtual);
255 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000256 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000257
258 // If this isn't a base class, it's a new most-derived object.
259 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
260 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000261 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 MostDerivedArraySize = 0;
263 MostDerivedPathLength = Entries.size();
264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
Richard Smith66c96992012-02-18 22:04:06 +0000266 /// Update this designator to refer to the given complex component.
267 void addComplexUnchecked(QualType EltTy, bool Imag) {
268 PathEntry Entry;
269 Entry.ArrayIndex = Imag;
270 Entries.push_back(Entry);
271
272 // This is technically a most-derived object, though in practice this
273 // is unlikely to matter.
274 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000275 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000276 MostDerivedArraySize = 2;
277 MostDerivedPathLength = Entries.size();
278 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000280 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000281 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000282 if (Invalid) return;
George Burgess IVa51c4072015-10-16 01:49:01 +0000283 if (MostDerivedPathLength == Entries.size() &&
284 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000285 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000286 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
287 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
288 setInvalid();
289 }
Richard Smith96e0c102011-11-04 02:25:55 +0000290 return;
291 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000292 // [expr.add]p4: For the purposes of these operators, a pointer to a
293 // nonarray object behaves the same as a pointer to the first element of
294 // an array of length one with the type of the object as its element type.
295 if (IsOnePastTheEnd && N == (uint64_t)-1)
296 IsOnePastTheEnd = false;
297 else if (!IsOnePastTheEnd && N == 1)
298 IsOnePastTheEnd = true;
299 else if (N != 0) {
300 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000301 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000302 }
Richard Smith96e0c102011-11-04 02:25:55 +0000303 }
304 };
305
Richard Smith254a73d2011-10-28 22:34:42 +0000306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
308 EvalInfo &Info;
309
310 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000311 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000312
Richard Smithf6f003a2011-12-16 19:06:07 +0000313 /// CallLoc - The location of the call expression for this call.
314 SourceLocation CallLoc;
315
316 /// Callee - The function which was called.
317 const FunctionDecl *Callee;
318
Richard Smithb228a862012-02-15 02:18:13 +0000319 /// Index - The call index of this call.
320 unsigned Index;
321
Richard Smithd62306a2011-11-10 06:34:14 +0000322 /// This - The binding for the this pointer in this call, if any.
323 const LValue *This;
324
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000325 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000326 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000327 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000328
Eli Friedman4830ec82012-06-25 21:21:08 +0000329 // Note that we intentionally use std::map here so that references to
330 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000331 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000332 typedef MapTy::const_iterator temp_iterator;
333 /// Temporaries - Temporary lvalues materialized within this stack frame.
334 MapTy Temporaries;
335
Richard Smithf6f003a2011-12-16 19:06:07 +0000336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000338 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000339 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000340
341 APValue *getTemporary(const void *Key) {
342 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000343 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000344 }
345 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000346 };
347
Richard Smith852c9db2013-04-20 22:23:05 +0000348 /// Temporarily override 'this'.
349 class ThisOverrideRAII {
350 public:
351 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
352 : Frame(Frame), OldThis(Frame.This) {
353 if (Enable)
354 Frame.This = NewThis;
355 }
356 ~ThisOverrideRAII() {
357 Frame.This = OldThis;
358 }
359 private:
360 CallStackFrame &Frame;
361 const LValue *OldThis;
362 };
363
Richard Smith92b1ce02011-12-12 09:28:41 +0000364 /// A partial diagnostic which we might know in advance that we are not going
365 /// to emit.
366 class OptionalDiagnostic {
367 PartialDiagnostic *Diag;
368
369 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000370 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
371 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000372
373 template<typename T>
374 OptionalDiagnostic &operator<<(const T &v) {
375 if (Diag)
376 *Diag << v;
377 return *this;
378 }
Richard Smithfe800032012-01-31 04:08:20 +0000379
380 OptionalDiagnostic &operator<<(const APSInt &I) {
381 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000382 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000383 I.toString(Buffer);
384 *Diag << StringRef(Buffer.data(), Buffer.size());
385 }
386 return *this;
387 }
388
389 OptionalDiagnostic &operator<<(const APFloat &F) {
390 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000391 // FIXME: Force the precision of the source value down so we don't
392 // print digits which are usually useless (we don't really care here if
393 // we truncate a digit by accident in edge cases). Ideally,
394 // APFloat::toString would automatically print the shortest
395 // representation which rounds to the correct value, but it's a bit
396 // tricky to implement.
397 unsigned precision =
398 llvm::APFloat::semanticsPrecision(F.getSemantics());
399 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000400 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000401 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000402 *Diag << StringRef(Buffer.data(), Buffer.size());
403 }
404 return *this;
405 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000406 };
407
Richard Smith08d6a2c2013-07-24 07:11:57 +0000408 /// A cleanup, and a flag indicating whether it is lifetime-extended.
409 class Cleanup {
410 llvm::PointerIntPair<APValue*, 1, bool> Value;
411
412 public:
413 Cleanup(APValue *Val, bool IsLifetimeExtended)
414 : Value(Val, IsLifetimeExtended) {}
415
416 bool isLifetimeExtended() const { return Value.getInt(); }
417 void endLifetime() {
418 *Value.getPointer() = APValue();
419 }
420 };
421
Richard Smithb228a862012-02-15 02:18:13 +0000422 /// EvalInfo - This is a private struct used by the evaluator to capture
423 /// information about a subexpression as it is folded. It retains information
424 /// about the AST context, but also maintains information about the folded
425 /// expression.
426 ///
427 /// If an expression could be evaluated, it is still possible it is not a C
428 /// "integer constant expression" or constant expression. If not, this struct
429 /// captures information about how and why not.
430 ///
431 /// One bit of information passed *into* the request for constant folding
432 /// indicates whether the subexpression is "evaluated" or not according to C
433 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
434 /// evaluate the expression regardless of what the RHS is, but C only allows
435 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000436 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000437 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000438
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 /// EvalStatus - Contains information about the evaluation.
440 Expr::EvalStatus &EvalStatus;
441
442 /// CurrentCall - The top of the constexpr call stack.
443 CallStackFrame *CurrentCall;
444
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000445 /// CallStackDepth - The number of calls in the call stack right now.
446 unsigned CallStackDepth;
447
Richard Smithb228a862012-02-15 02:18:13 +0000448 /// NextCallIndex - The next call index to assign.
449 unsigned NextCallIndex;
450
Richard Smitha3d3bd22013-05-08 02:12:03 +0000451 /// StepsLeft - The remaining number of evaluation steps we're permitted
452 /// to perform. This is essentially a limit for the number of statements
453 /// we will evaluate.
454 unsigned StepsLeft;
455
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000456 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000457 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000458 CallStackFrame BottomFrame;
459
Richard Smith08d6a2c2013-07-24 07:11:57 +0000460 /// A stack of values whose lifetimes end at the end of some surrounding
461 /// evaluation frame.
462 llvm::SmallVector<Cleanup, 16> CleanupStack;
463
Richard Smithd62306a2011-11-10 06:34:14 +0000464 /// EvaluatingDecl - This is the declaration whose initializer is being
465 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000466 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000467
468 /// EvaluatingDeclValue - This is the value being constructed for the
469 /// declaration whose initializer is being evaluated, if any.
470 APValue *EvaluatingDeclValue;
471
Richard Smith357362d2011-12-13 06:39:58 +0000472 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
473 /// notes attached to it will also be stored, otherwise they will not be.
474 bool HasActiveDiagnostic;
475
Richard Smith6d4c6582013-11-05 22:18:15 +0000476 enum EvaluationMode {
477 /// Evaluate as a constant expression. Stop if we find that the expression
478 /// is not a constant expression.
479 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000480
Richard Smith6d4c6582013-11-05 22:18:15 +0000481 /// Evaluate as a potential constant expression. Keep going if we hit a
482 /// construct that we can't evaluate yet (because we don't yet know the
483 /// value of something) but stop if we hit something that could never be
484 /// a constant expression.
485 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000486
Richard Smith6d4c6582013-11-05 22:18:15 +0000487 /// Fold the expression to a constant. Stop if we hit a side-effect that
488 /// we can't model.
489 EM_ConstantFold,
490
491 /// Evaluate the expression looking for integer overflow and similar
492 /// issues. Don't worry about side-effects, and try to visit all
493 /// subexpressions.
494 EM_EvaluateForOverflow,
495
496 /// Evaluate in any way we know how. Don't worry about side-effects that
497 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000498 EM_IgnoreSideEffects,
499
500 /// Evaluate as a constant expression. Stop if we find that the expression
501 /// is not a constant expression. Some expressions can be retried in the
502 /// optimizer if we don't constant fold them here, but in an unevaluated
503 /// context we try to fold them immediately since the optimizer never
504 /// gets a chance to look at it.
505 EM_ConstantExpressionUnevaluated,
506
507 /// Evaluate as a potential constant expression. Keep going if we hit a
508 /// construct that we can't evaluate yet (because we don't yet know the
509 /// value of something) but stop if we hit something that could never be
510 /// a constant expression. Some expressions can be retried in the
511 /// optimizer if we don't constant fold them here, but in an unevaluated
512 /// context we try to fold them immediately since the optimizer never
513 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000514 EM_PotentialConstantExpressionUnevaluated,
515
516 /// Evaluate as a constant expression. Continue evaluating if we find a
517 /// MemberExpr with a base that can't be evaluated.
518 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000519 } EvalMode;
520
521 /// Are we checking whether the expression is a potential constant
522 /// expression?
523 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000524 return EvalMode == EM_PotentialConstantExpression ||
525 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000526 }
527
528 /// Are we checking an expression for overflow?
529 // FIXME: We should check for any kind of undefined or suspicious behavior
530 // in such constructs, not just overflow.
531 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
532
533 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000534 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000535 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000536 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000537 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
538 EvaluatingDecl((const ValueDecl *)nullptr),
539 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
540 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000541
Richard Smith7525ff62013-05-09 07:14:00 +0000542 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
543 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000544 EvaluatingDeclValue = &Value;
545 }
546
David Blaikiebbafb8a2012-03-11 07:00:24 +0000547 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000548
Richard Smith357362d2011-12-13 06:39:58 +0000549 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000550 // Don't perform any constexpr calls (other than the call we're checking)
551 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000552 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000553 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000554 if (NextCallIndex == 0) {
555 // NextCallIndex has wrapped around.
556 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
557 return false;
558 }
Richard Smith357362d2011-12-13 06:39:58 +0000559 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
560 return true;
561 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
562 << getLangOpts().ConstexprCallDepth;
563 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000564 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000565
Richard Smithb228a862012-02-15 02:18:13 +0000566 CallStackFrame *getCallFrame(unsigned CallIndex) {
567 assert(CallIndex && "no call index in getCallFrame");
568 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
569 // be null in this loop.
570 CallStackFrame *Frame = CurrentCall;
571 while (Frame->Index > CallIndex)
572 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000573 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000574 }
575
Richard Smitha3d3bd22013-05-08 02:12:03 +0000576 bool nextStep(const Stmt *S) {
577 if (!StepsLeft) {
578 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
579 return false;
580 }
581 --StepsLeft;
582 return true;
583 }
584
Richard Smith357362d2011-12-13 06:39:58 +0000585 private:
586 /// Add a diagnostic to the diagnostics list.
587 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
588 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
589 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
590 return EvalStatus.Diag->back().second;
591 }
592
Richard Smithf6f003a2011-12-16 19:06:07 +0000593 /// Add notes containing a call stack to the current point of evaluation.
594 void addCallStack(unsigned Limit);
595
Richard Smith357362d2011-12-13 06:39:58 +0000596 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000597 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000598 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
599 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000600 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000601 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000602 // If we have a prior diagnostic, it will be noting that the expression
603 // isn't a constant expression. This diagnostic is more important,
604 // unless we require this evaluation to produce a constant expression.
605 //
606 // FIXME: We might want to show both diagnostics to the user in
607 // EM_ConstantFold mode.
608 if (!EvalStatus.Diag->empty()) {
609 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000610 case EM_ConstantFold:
611 case EM_IgnoreSideEffects:
612 case EM_EvaluateForOverflow:
613 if (!EvalStatus.HasSideEffects)
614 break;
615 // We've had side-effects; we want the diagnostic from them, not
616 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000617 case EM_ConstantExpression:
618 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000619 case EM_ConstantExpressionUnevaluated:
620 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000621 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000622 HasActiveDiagnostic = false;
623 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000624 }
625 }
626
Richard Smithf6f003a2011-12-16 19:06:07 +0000627 unsigned CallStackNotes = CallStackDepth - 1;
628 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
629 if (Limit)
630 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000631 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000632 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000633
Richard Smith357362d2011-12-13 06:39:58 +0000634 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000635 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000636 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
637 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000638 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000639 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000640 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000641 }
Richard Smith357362d2011-12-13 06:39:58 +0000642 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000643 return OptionalDiagnostic();
644 }
645
Richard Smithce1ec5e2012-03-15 04:53:45 +0000646 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
647 = diag::note_invalid_subexpr_in_const_expr,
648 unsigned ExtraNotes = 0) {
649 if (EvalStatus.Diag)
650 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
651 HasActiveDiagnostic = false;
652 return OptionalDiagnostic();
653 }
654
Richard Smith92b1ce02011-12-12 09:28:41 +0000655 /// Diagnose that the evaluation does not produce a C++11 core constant
656 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000657 ///
658 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
659 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000660 template<typename LocArg>
661 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000662 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000663 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000664 // Don't override a previous diagnostic. Don't bother collecting
665 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000666 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000667 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000668 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000669 }
Richard Smith357362d2011-12-13 06:39:58 +0000670 return Diag(Loc, DiagId, ExtraNotes);
671 }
672
673 /// Add a note to a prior diagnostic.
674 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
675 if (!HasActiveDiagnostic)
676 return OptionalDiagnostic();
677 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000678 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000679
680 /// Add a stack of notes to a prior diagnostic.
681 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
682 if (HasActiveDiagnostic) {
683 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
684 Diags.begin(), Diags.end());
685 }
686 }
Richard Smith253c2a32012-01-27 01:14:48 +0000687
Richard Smith6d4c6582013-11-05 22:18:15 +0000688 /// Should we continue evaluation after encountering a side-effect that we
689 /// couldn't model?
690 bool keepEvaluatingAfterSideEffect() {
691 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000692 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000693 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000694 case EM_EvaluateForOverflow:
695 case EM_IgnoreSideEffects:
696 return true;
697
Richard Smith6d4c6582013-11-05 22:18:15 +0000698 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000699 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000700 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000701 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000702 return false;
703 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000704 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000705 }
706
707 /// Note that we have had a side-effect, and determine whether we should
708 /// keep evaluating.
709 bool noteSideEffect() {
710 EvalStatus.HasSideEffects = true;
711 return keepEvaluatingAfterSideEffect();
712 }
713
Richard Smith253c2a32012-01-27 01:14:48 +0000714 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000715 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000716 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000717 if (!StepsLeft)
718 return false;
719
720 switch (EvalMode) {
721 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000722 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000723 case EM_EvaluateForOverflow:
724 return true;
725
726 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000727 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000728 case EM_ConstantFold:
729 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000730 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000731 return false;
732 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000733 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000734 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000735
736 bool allowInvalidBaseExpr() const {
737 return EvalMode == EM_DesignatorFold;
738 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000739 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000740
741 /// Object used to treat all foldable expressions as constant expressions.
742 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000743 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000744 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000745 bool HadNoPriorDiags;
746 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000747
Richard Smith6d4c6582013-11-05 22:18:15 +0000748 explicit FoldConstant(EvalInfo &Info, bool Enabled)
749 : Info(Info),
750 Enabled(Enabled),
751 HadNoPriorDiags(Info.EvalStatus.Diag &&
752 Info.EvalStatus.Diag->empty() &&
753 !Info.EvalStatus.HasSideEffects),
754 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000755 if (Enabled &&
756 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
757 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000758 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000759 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000760 void keepDiagnostics() { Enabled = false; }
761 ~FoldConstant() {
762 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000763 !Info.EvalStatus.HasSideEffects)
764 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000765 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000766 }
767 };
Richard Smith17100ba2012-02-16 02:46:34 +0000768
George Burgess IV3a03fab2015-09-04 21:28:13 +0000769 /// RAII object used to treat the current evaluation as the correct pointer
770 /// offset fold for the current EvalMode
771 struct FoldOffsetRAII {
772 EvalInfo &Info;
773 EvalInfo::EvaluationMode OldMode;
774 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
775 : Info(Info), OldMode(Info.EvalMode) {
776 if (!Info.checkingPotentialConstantExpression())
777 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
778 : EvalInfo::EM_ConstantFold;
779 }
780
781 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
782 };
783
Richard Smith17100ba2012-02-16 02:46:34 +0000784 /// RAII object used to suppress diagnostics and side-effects from a
785 /// speculative evaluation.
786 class SpeculativeEvaluationRAII {
787 EvalInfo &Info;
788 Expr::EvalStatus Old;
789
790 public:
791 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000792 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000793 : Info(Info), Old(Info.EvalStatus) {
794 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000795 // If we're speculatively evaluating, we may have skipped over some
796 // evaluations and missed out a side effect.
797 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000798 }
799 ~SpeculativeEvaluationRAII() {
800 Info.EvalStatus = Old;
801 }
802 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000803
804 /// RAII object wrapping a full-expression or block scope, and handling
805 /// the ending of the lifetime of temporaries created within it.
806 template<bool IsFullExpression>
807 class ScopeRAII {
808 EvalInfo &Info;
809 unsigned OldStackSize;
810 public:
811 ScopeRAII(EvalInfo &Info)
812 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
813 ~ScopeRAII() {
814 // Body moved to a static method to encourage the compiler to inline away
815 // instances of this class.
816 cleanup(Info, OldStackSize);
817 }
818 private:
819 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
820 unsigned NewEnd = OldStackSize;
821 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
822 I != N; ++I) {
823 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
824 // Full-expression cleanup of a lifetime-extended temporary: nothing
825 // to do, just move this cleanup to the right place in the stack.
826 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
827 ++NewEnd;
828 } else {
829 // End the lifetime of the object.
830 Info.CleanupStack[I].endLifetime();
831 }
832 }
833 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
834 Info.CleanupStack.end());
835 }
836 };
837 typedef ScopeRAII<false> BlockScopeRAII;
838 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000839}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000840
Richard Smitha8105bc2012-01-06 16:39:00 +0000841bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
842 CheckSubobjectKind CSK) {
843 if (Invalid)
844 return false;
845 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000846 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000847 << CSK;
848 setInvalid();
849 return false;
850 }
851 return true;
852}
853
854void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
855 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000856 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000857 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000858 << static_cast<int>(N) << /*array*/ 0
859 << static_cast<unsigned>(MostDerivedArraySize);
860 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000861 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000862 << static_cast<int>(N) << /*non-array*/ 1;
863 setInvalid();
864}
865
Richard Smithf6f003a2011-12-16 19:06:07 +0000866CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
867 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000868 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000869 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000870 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000871 Info.CurrentCall = this;
872 ++Info.CallStackDepth;
873}
874
875CallStackFrame::~CallStackFrame() {
876 assert(Info.CurrentCall == this && "calls retired out of order");
877 --Info.CallStackDepth;
878 Info.CurrentCall = Caller;
879}
880
Richard Smith08d6a2c2013-07-24 07:11:57 +0000881APValue &CallStackFrame::createTemporary(const void *Key,
882 bool IsLifetimeExtended) {
883 APValue &Result = Temporaries[Key];
884 assert(Result.isUninit() && "temporary created multiple times");
885 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
886 return Result;
887}
888
Richard Smith84401042013-06-03 05:03:02 +0000889static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000890
891void EvalInfo::addCallStack(unsigned Limit) {
892 // Determine which calls to skip, if any.
893 unsigned ActiveCalls = CallStackDepth - 1;
894 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
895 if (Limit && Limit < ActiveCalls) {
896 SkipStart = Limit / 2 + Limit % 2;
897 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000898 }
899
Richard Smithf6f003a2011-12-16 19:06:07 +0000900 // Walk the call stack and add the diagnostics.
901 unsigned CallIdx = 0;
902 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
903 Frame = Frame->Caller, ++CallIdx) {
904 // Skip this call?
905 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
906 if (CallIdx == SkipStart) {
907 // Note that we're skipping calls.
908 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
909 << unsigned(ActiveCalls - Limit);
910 }
911 continue;
912 }
913
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000914 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000915 llvm::raw_svector_ostream Out(Buffer);
916 describeCall(Frame, Out);
917 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
918 }
919}
920
921namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000922 struct ComplexValue {
923 private:
924 bool IsInt;
925
926 public:
927 APSInt IntReal, IntImag;
928 APFloat FloatReal, FloatImag;
929
930 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
931
932 void makeComplexFloat() { IsInt = false; }
933 bool isComplexFloat() const { return !IsInt; }
934 APFloat &getComplexFloatReal() { return FloatReal; }
935 APFloat &getComplexFloatImag() { return FloatImag; }
936
937 void makeComplexInt() { IsInt = true; }
938 bool isComplexInt() const { return IsInt; }
939 APSInt &getComplexIntReal() { return IntReal; }
940 APSInt &getComplexIntImag() { return IntImag; }
941
Richard Smith2e312c82012-03-03 22:46:17 +0000942 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000943 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000944 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000945 else
Richard Smith2e312c82012-03-03 22:46:17 +0000946 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000947 }
Richard Smith2e312c82012-03-03 22:46:17 +0000948 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000949 assert(v.isComplexFloat() || v.isComplexInt());
950 if (v.isComplexFloat()) {
951 makeComplexFloat();
952 FloatReal = v.getComplexFloatReal();
953 FloatImag = v.getComplexFloatImag();
954 } else {
955 makeComplexInt();
956 IntReal = v.getComplexIntReal();
957 IntImag = v.getComplexIntImag();
958 }
959 }
John McCall93d91dc2010-05-07 17:22:02 +0000960 };
John McCall45d55e42010-05-07 21:00:08 +0000961
962 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000963 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000964 CharUnits Offset;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000965 bool InvalidBase : 1;
966 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +0000967 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000968
Richard Smithce40ad62011-11-12 22:28:03 +0000969 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000970 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000971 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000972 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000973 SubobjectDesignator &getLValueDesignator() { return Designator; }
974 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000975
Richard Smith2e312c82012-03-03 22:46:17 +0000976 void moveInto(APValue &V) const {
977 if (Designator.Invalid)
978 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
979 else
980 V = APValue(Base, Offset, Designator.Entries,
981 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000982 }
Richard Smith2e312c82012-03-03 22:46:17 +0000983 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000984 assert(V.isLValue());
985 Base = V.getLValueBase();
986 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +0000987 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +0000988 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000989 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000990 }
991
George Burgess IV3a03fab2015-09-04 21:28:13 +0000992 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +0000993 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000994 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +0000995 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +0000996 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000997 Designator = SubobjectDesignator(getType(B));
998 }
999
George Burgess IV3a03fab2015-09-04 21:28:13 +00001000 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1001 set(B, I, true);
1002 }
1003
Richard Smitha8105bc2012-01-06 16:39:00 +00001004 // Check that this LValue is not based on a null pointer. If it is, produce
1005 // a diagnostic and mark the designator as invalid.
1006 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1007 CheckSubobjectKind CSK) {
1008 if (Designator.Invalid)
1009 return false;
1010 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001011 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001012 << CSK;
1013 Designator.setInvalid();
1014 return false;
1015 }
1016 return true;
1017 }
1018
1019 // Check this LValue refers to an object. If not, set the designator to be
1020 // invalid and emit a diagnostic.
1021 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001022 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001023 Designator.checkSubobject(Info, E, CSK);
1024 }
1025
1026 void addDecl(EvalInfo &Info, const Expr *E,
1027 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001028 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1029 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001030 }
1031 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001032 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1033 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001034 }
Richard Smith66c96992012-02-18 22:04:06 +00001035 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001036 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1037 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001038 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001039 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001040 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001041 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001042 }
John McCall45d55e42010-05-07 21:00:08 +00001043 };
Richard Smith027bf112011-11-17 22:56:20 +00001044
1045 struct MemberPtr {
1046 MemberPtr() {}
1047 explicit MemberPtr(const ValueDecl *Decl) :
1048 DeclAndIsDerivedMember(Decl, false), Path() {}
1049
1050 /// The member or (direct or indirect) field referred to by this member
1051 /// pointer, or 0 if this is a null member pointer.
1052 const ValueDecl *getDecl() const {
1053 return DeclAndIsDerivedMember.getPointer();
1054 }
1055 /// Is this actually a member of some type derived from the relevant class?
1056 bool isDerivedMember() const {
1057 return DeclAndIsDerivedMember.getInt();
1058 }
1059 /// Get the class which the declaration actually lives in.
1060 const CXXRecordDecl *getContainingRecord() const {
1061 return cast<CXXRecordDecl>(
1062 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1063 }
1064
Richard Smith2e312c82012-03-03 22:46:17 +00001065 void moveInto(APValue &V) const {
1066 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001067 }
Richard Smith2e312c82012-03-03 22:46:17 +00001068 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001069 assert(V.isMemberPointer());
1070 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1071 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1072 Path.clear();
1073 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1074 Path.insert(Path.end(), P.begin(), P.end());
1075 }
1076
1077 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1078 /// whether the member is a member of some class derived from the class type
1079 /// of the member pointer.
1080 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1081 /// Path - The path of base/derived classes from the member declaration's
1082 /// class (exclusive) to the class type of the member pointer (inclusive).
1083 SmallVector<const CXXRecordDecl*, 4> Path;
1084
1085 /// Perform a cast towards the class of the Decl (either up or down the
1086 /// hierarchy).
1087 bool castBack(const CXXRecordDecl *Class) {
1088 assert(!Path.empty());
1089 const CXXRecordDecl *Expected;
1090 if (Path.size() >= 2)
1091 Expected = Path[Path.size() - 2];
1092 else
1093 Expected = getContainingRecord();
1094 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1095 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1096 // if B does not contain the original member and is not a base or
1097 // derived class of the class containing the original member, the result
1098 // of the cast is undefined.
1099 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1100 // (D::*). We consider that to be a language defect.
1101 return false;
1102 }
1103 Path.pop_back();
1104 return true;
1105 }
1106 /// Perform a base-to-derived member pointer cast.
1107 bool castToDerived(const CXXRecordDecl *Derived) {
1108 if (!getDecl())
1109 return true;
1110 if (!isDerivedMember()) {
1111 Path.push_back(Derived);
1112 return true;
1113 }
1114 if (!castBack(Derived))
1115 return false;
1116 if (Path.empty())
1117 DeclAndIsDerivedMember.setInt(false);
1118 return true;
1119 }
1120 /// Perform a derived-to-base member pointer cast.
1121 bool castToBase(const CXXRecordDecl *Base) {
1122 if (!getDecl())
1123 return true;
1124 if (Path.empty())
1125 DeclAndIsDerivedMember.setInt(true);
1126 if (isDerivedMember()) {
1127 Path.push_back(Base);
1128 return true;
1129 }
1130 return castBack(Base);
1131 }
1132 };
Richard Smith357362d2011-12-13 06:39:58 +00001133
Richard Smith7bb00672012-02-01 01:42:44 +00001134 /// Compare two member pointers, which are assumed to be of the same type.
1135 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1136 if (!LHS.getDecl() || !RHS.getDecl())
1137 return !LHS.getDecl() && !RHS.getDecl();
1138 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1139 return false;
1140 return LHS.Path == RHS.Path;
1141 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001142}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001143
Richard Smith2e312c82012-03-03 22:46:17 +00001144static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001145static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1146 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001147 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001148static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1149static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001150static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1151 EvalInfo &Info);
1152static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001153static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001154static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001155 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001156static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001157static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001158static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001159
1160//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001161// Misc utilities
1162//===----------------------------------------------------------------------===//
1163
Richard Smith84401042013-06-03 05:03:02 +00001164/// Produce a string describing the given constexpr call.
1165static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1166 unsigned ArgIndex = 0;
1167 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1168 !isa<CXXConstructorDecl>(Frame->Callee) &&
1169 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1170
1171 if (!IsMemberCall)
1172 Out << *Frame->Callee << '(';
1173
1174 if (Frame->This && IsMemberCall) {
1175 APValue Val;
1176 Frame->This->moveInto(Val);
1177 Val.printPretty(Out, Frame->Info.Ctx,
1178 Frame->This->Designator.MostDerivedType);
1179 // FIXME: Add parens around Val if needed.
1180 Out << "->" << *Frame->Callee << '(';
1181 IsMemberCall = false;
1182 }
1183
1184 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1185 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1186 if (ArgIndex > (unsigned)IsMemberCall)
1187 Out << ", ";
1188
1189 const ParmVarDecl *Param = *I;
1190 const APValue &Arg = Frame->Arguments[ArgIndex];
1191 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1192
1193 if (ArgIndex == 0 && IsMemberCall)
1194 Out << "->" << *Frame->Callee << '(';
1195 }
1196
1197 Out << ')';
1198}
1199
Richard Smithd9f663b2013-04-22 15:31:51 +00001200/// Evaluate an expression to see if it had side-effects, and discard its
1201/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001202/// \return \c true if the caller should keep evaluating.
1203static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001204 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001205 if (!Evaluate(Scratch, Info, E))
1206 // We don't need the value, but we might have skipped a side effect here.
1207 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001208 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001209}
1210
Richard Smith861b5b52013-05-07 23:34:45 +00001211/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1212/// return its existing value.
1213static int64_t getExtValue(const APSInt &Value) {
1214 return Value.isSigned() ? Value.getSExtValue()
1215 : static_cast<int64_t>(Value.getZExtValue());
1216}
1217
Richard Smithd62306a2011-11-10 06:34:14 +00001218/// Should this call expression be treated as a string literal?
1219static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001220 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001221 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1222 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1223}
1224
Richard Smithce40ad62011-11-12 22:28:03 +00001225static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001226 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1227 // constant expression of pointer type that evaluates to...
1228
1229 // ... a null pointer value, or a prvalue core constant expression of type
1230 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001231 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001232
Richard Smithce40ad62011-11-12 22:28:03 +00001233 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1234 // ... the address of an object with static storage duration,
1235 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1236 return VD->hasGlobalStorage();
1237 // ... the address of a function,
1238 return isa<FunctionDecl>(D);
1239 }
1240
1241 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001242 switch (E->getStmtClass()) {
1243 default:
1244 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001245 case Expr::CompoundLiteralExprClass: {
1246 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1247 return CLE->isFileScope() && CLE->isLValue();
1248 }
Richard Smithe6c01442013-06-05 00:46:14 +00001249 case Expr::MaterializeTemporaryExprClass:
1250 // A materialized temporary might have been lifetime-extended to static
1251 // storage duration.
1252 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001253 // A string literal has static storage duration.
1254 case Expr::StringLiteralClass:
1255 case Expr::PredefinedExprClass:
1256 case Expr::ObjCStringLiteralClass:
1257 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001258 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001259 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001260 return true;
1261 case Expr::CallExprClass:
1262 return IsStringLiteralCall(cast<CallExpr>(E));
1263 // For GCC compatibility, &&label has static storage duration.
1264 case Expr::AddrLabelExprClass:
1265 return true;
1266 // A Block literal expression may be used as the initialization value for
1267 // Block variables at global or local static scope.
1268 case Expr::BlockExprClass:
1269 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001270 case Expr::ImplicitValueInitExprClass:
1271 // FIXME:
1272 // We can never form an lvalue with an implicit value initialization as its
1273 // base through expression evaluation, so these only appear in one case: the
1274 // implicit variable declaration we invent when checking whether a constexpr
1275 // constructor can produce a constant expression. We must assume that such
1276 // an expression might be a global lvalue.
1277 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001278 }
John McCall95007602010-05-10 23:27:23 +00001279}
1280
Richard Smithb228a862012-02-15 02:18:13 +00001281static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1282 assert(Base && "no location for a null lvalue");
1283 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1284 if (VD)
1285 Info.Note(VD->getLocation(), diag::note_declared_at);
1286 else
Ted Kremenek28831752012-08-23 20:46:57 +00001287 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001288 diag::note_constexpr_temporary_here);
1289}
1290
Richard Smith80815602011-11-07 05:07:52 +00001291/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001292/// value for an address or reference constant expression. Return true if we
1293/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001294static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1295 QualType Type, const LValue &LVal) {
1296 bool IsReferenceType = Type->isReferenceType();
1297
Richard Smith357362d2011-12-13 06:39:58 +00001298 APValue::LValueBase Base = LVal.getLValueBase();
1299 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1300
Richard Smith0dea49e2012-02-18 04:58:18 +00001301 // Check that the object is a global. Note that the fake 'this' object we
1302 // manufacture when checking potential constant expressions is conservatively
1303 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001304 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001305 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001306 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001307 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1308 << IsReferenceType << !Designator.Entries.empty()
1309 << !!VD << VD;
1310 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001311 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001312 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001313 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001314 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001315 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001316 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001317 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001318 LVal.getLValueCallIndex() == 0) &&
1319 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001320
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001321 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1322 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001323 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001324 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001325 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001326
Hans Wennborg82dd8772014-06-25 22:19:48 +00001327 // A dllimport variable never acts like a constant.
1328 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001329 return false;
1330 }
1331 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1332 // __declspec(dllimport) must be handled very carefully:
1333 // We must never initialize an expression with the thunk in C++.
1334 // Doing otherwise would allow the same id-expression to yield
1335 // different addresses for the same function in different translation
1336 // units. However, this means that we must dynamically initialize the
1337 // expression with the contents of the import address table at runtime.
1338 //
1339 // The C language has no notion of ODR; furthermore, it has no notion of
1340 // dynamic initialization. This means that we are permitted to
1341 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001342 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001343 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001344 }
1345 }
1346
Richard Smitha8105bc2012-01-06 16:39:00 +00001347 // Allow address constant expressions to be past-the-end pointers. This is
1348 // an extension: the standard requires them to point to an object.
1349 if (!IsReferenceType)
1350 return true;
1351
1352 // A reference constant expression must refer to an object.
1353 if (!Base) {
1354 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001355 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001356 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001357 }
1358
Richard Smith357362d2011-12-13 06:39:58 +00001359 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001360 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001361 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001362 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001363 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001364 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001365 }
1366
Richard Smith80815602011-11-07 05:07:52 +00001367 return true;
1368}
1369
Richard Smithfddd3842011-12-30 21:15:51 +00001370/// Check that this core constant expression is of literal type, and if not,
1371/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001372static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001373 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001374 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001375 return true;
1376
Richard Smith7525ff62013-05-09 07:14:00 +00001377 // C++1y: A constant initializer for an object o [...] may also invoke
1378 // constexpr constructors for o and its subobjects even if those objects
1379 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001380 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001381 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001382 return true;
1383
Richard Smithfddd3842011-12-30 21:15:51 +00001384 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001385 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001386 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001387 << E->getType();
1388 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001389 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001390 return false;
1391}
1392
Richard Smith0b0a0b62011-10-29 20:57:55 +00001393/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001394/// constant expression. If not, report an appropriate diagnostic. Does not
1395/// check that the expression is of literal type.
1396static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1397 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001398 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001399 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1400 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001401 return false;
1402 }
1403
Richard Smith77be48a2014-07-31 06:31:19 +00001404 // We allow _Atomic(T) to be initialized from anything that T can be
1405 // initialized from.
1406 if (const AtomicType *AT = Type->getAs<AtomicType>())
1407 Type = AT->getValueType();
1408
Richard Smithb228a862012-02-15 02:18:13 +00001409 // Core issue 1454: For a literal constant expression of array or class type,
1410 // each subobject of its value shall have been initialized by a constant
1411 // expression.
1412 if (Value.isArray()) {
1413 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1414 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1415 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1416 Value.getArrayInitializedElt(I)))
1417 return false;
1418 }
1419 if (!Value.hasArrayFiller())
1420 return true;
1421 return CheckConstantExpression(Info, DiagLoc, EltTy,
1422 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001423 }
Richard Smithb228a862012-02-15 02:18:13 +00001424 if (Value.isUnion() && Value.getUnionField()) {
1425 return CheckConstantExpression(Info, DiagLoc,
1426 Value.getUnionField()->getType(),
1427 Value.getUnionValue());
1428 }
1429 if (Value.isStruct()) {
1430 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1431 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1432 unsigned BaseIndex = 0;
1433 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1434 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1435 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1436 Value.getStructBase(BaseIndex)))
1437 return false;
1438 }
1439 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001440 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001441 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1442 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001443 return false;
1444 }
1445 }
1446
1447 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001448 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001449 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001450 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1451 }
1452
1453 // Everything else is fine.
1454 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001455}
1456
Benjamin Kramer8407df72015-03-09 16:47:52 +00001457static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001458 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001459}
1460
1461static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001462 if (Value.CallIndex)
1463 return false;
1464 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1465 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001466}
1467
Richard Smithcecf1842011-11-01 21:06:14 +00001468static bool IsWeakLValue(const LValue &Value) {
1469 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001470 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001471}
1472
David Majnemerb5116032014-12-09 23:32:34 +00001473static bool isZeroSized(const LValue &Value) {
1474 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001475 if (Decl && isa<VarDecl>(Decl)) {
1476 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001477 if (Ty->isArrayType())
1478 return Ty->isIncompleteType() ||
1479 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001480 }
1481 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001482}
1483
Richard Smith2e312c82012-03-03 22:46:17 +00001484static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001485 // A null base expression indicates a null pointer. These are always
1486 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001487 if (!Value.getLValueBase()) {
1488 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001489 return true;
1490 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001491
Richard Smith027bf112011-11-17 22:56:20 +00001492 // We have a non-null base. These are generally known to be true, but if it's
1493 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001494 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001495 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001496 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001497}
1498
Richard Smith2e312c82012-03-03 22:46:17 +00001499static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001500 switch (Val.getKind()) {
1501 case APValue::Uninitialized:
1502 return false;
1503 case APValue::Int:
1504 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001505 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001506 case APValue::Float:
1507 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001508 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001509 case APValue::ComplexInt:
1510 Result = Val.getComplexIntReal().getBoolValue() ||
1511 Val.getComplexIntImag().getBoolValue();
1512 return true;
1513 case APValue::ComplexFloat:
1514 Result = !Val.getComplexFloatReal().isZero() ||
1515 !Val.getComplexFloatImag().isZero();
1516 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001517 case APValue::LValue:
1518 return EvalPointerValueAsBool(Val, Result);
1519 case APValue::MemberPointer:
1520 Result = Val.getMemberPointerDecl();
1521 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001522 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001523 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001524 case APValue::Struct:
1525 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001526 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001527 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001528 }
1529
Richard Smith11562c52011-10-28 17:51:58 +00001530 llvm_unreachable("unknown APValue kind");
1531}
1532
1533static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1534 EvalInfo &Info) {
1535 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001536 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001537 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001538 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001539 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001540}
1541
Richard Smith357362d2011-12-13 06:39:58 +00001542template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001543static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001544 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001545 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001546 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001547}
1548
1549static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1550 QualType SrcType, const APFloat &Value,
1551 QualType DestType, APSInt &Result) {
1552 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001553 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001554 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001555
Richard Smith357362d2011-12-13 06:39:58 +00001556 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001557 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001558 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1559 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001560 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001561 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001562}
1563
Richard Smith357362d2011-12-13 06:39:58 +00001564static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1565 QualType SrcType, QualType DestType,
1566 APFloat &Result) {
1567 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001568 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001569 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1570 APFloat::rmNearestTiesToEven, &ignored)
1571 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001572 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001573 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001574}
1575
Richard Smith911e1422012-01-30 22:27:01 +00001576static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1577 QualType DestType, QualType SrcType,
1578 APSInt &Value) {
1579 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001580 APSInt Result = Value;
1581 // Figure out if this is a truncate, extend or noop cast.
1582 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001583 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001584 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001585 return Result;
1586}
1587
Richard Smith357362d2011-12-13 06:39:58 +00001588static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1589 QualType SrcType, const APSInt &Value,
1590 QualType DestType, APFloat &Result) {
1591 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1592 if (Result.convertFromAPInt(Value, Value.isSigned(),
1593 APFloat::rmNearestTiesToEven)
1594 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001595 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001596 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001597}
1598
Richard Smith49ca8aa2013-08-06 07:09:20 +00001599static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1600 APValue &Value, const FieldDecl *FD) {
1601 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1602
1603 if (!Value.isInt()) {
1604 // Trying to store a pointer-cast-to-integer into a bitfield.
1605 // FIXME: In this case, we should provide the diagnostic for casting
1606 // a pointer to an integer.
1607 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1608 Info.Diag(E);
1609 return false;
1610 }
1611
1612 APSInt &Int = Value.getInt();
1613 unsigned OldBitWidth = Int.getBitWidth();
1614 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1615 if (NewBitWidth < OldBitWidth)
1616 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1617 return true;
1618}
1619
Eli Friedman803acb32011-12-22 03:51:45 +00001620static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1621 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001622 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001623 if (!Evaluate(SVal, Info, E))
1624 return false;
1625 if (SVal.isInt()) {
1626 Res = SVal.getInt();
1627 return true;
1628 }
1629 if (SVal.isFloat()) {
1630 Res = SVal.getFloat().bitcastToAPInt();
1631 return true;
1632 }
1633 if (SVal.isVector()) {
1634 QualType VecTy = E->getType();
1635 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1636 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1637 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1638 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1639 Res = llvm::APInt::getNullValue(VecSize);
1640 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1641 APValue &Elt = SVal.getVectorElt(i);
1642 llvm::APInt EltAsInt;
1643 if (Elt.isInt()) {
1644 EltAsInt = Elt.getInt();
1645 } else if (Elt.isFloat()) {
1646 EltAsInt = Elt.getFloat().bitcastToAPInt();
1647 } else {
1648 // Don't try to handle vectors of anything other than int or float
1649 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001650 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001651 return false;
1652 }
1653 unsigned BaseEltSize = EltAsInt.getBitWidth();
1654 if (BigEndian)
1655 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1656 else
1657 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1658 }
1659 return true;
1660 }
1661 // Give up if the input isn't an int, float, or vector. For example, we
1662 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001663 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001664 return false;
1665}
1666
Richard Smith43e77732013-05-07 04:50:00 +00001667/// Perform the given integer operation, which is known to need at most BitWidth
1668/// bits, and check for overflow in the original type (if that type was not an
1669/// unsigned type).
1670template<typename Operation>
1671static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1672 const APSInt &LHS, const APSInt &RHS,
1673 unsigned BitWidth, Operation Op) {
1674 if (LHS.isUnsigned())
1675 return Op(LHS, RHS);
1676
1677 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1678 APSInt Result = Value.trunc(LHS.getBitWidth());
1679 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001680 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001681 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1682 diag::warn_integer_constant_overflow)
1683 << Result.toString(10) << E->getType();
1684 else
1685 HandleOverflow(Info, E, Value, E->getType());
1686 }
1687 return Result;
1688}
1689
1690/// Perform the given binary integer operation.
1691static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1692 BinaryOperatorKind Opcode, APSInt RHS,
1693 APSInt &Result) {
1694 switch (Opcode) {
1695 default:
1696 Info.Diag(E);
1697 return false;
1698 case BO_Mul:
1699 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1700 std::multiplies<APSInt>());
1701 return true;
1702 case BO_Add:
1703 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1704 std::plus<APSInt>());
1705 return true;
1706 case BO_Sub:
1707 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1708 std::minus<APSInt>());
1709 return true;
1710 case BO_And: Result = LHS & RHS; return true;
1711 case BO_Xor: Result = LHS ^ RHS; return true;
1712 case BO_Or: Result = LHS | RHS; return true;
1713 case BO_Div:
1714 case BO_Rem:
1715 if (RHS == 0) {
1716 Info.Diag(E, diag::note_expr_divide_by_zero);
1717 return false;
1718 }
1719 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1720 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1721 LHS.isSigned() && LHS.isMinSignedValue())
1722 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1723 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1724 return true;
1725 case BO_Shl: {
1726 if (Info.getLangOpts().OpenCL)
1727 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1728 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1729 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1730 RHS.isUnsigned());
1731 else if (RHS.isSigned() && RHS.isNegative()) {
1732 // During constant-folding, a negative shift is an opposite shift. Such
1733 // a shift is not a constant expression.
1734 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1735 RHS = -RHS;
1736 goto shift_right;
1737 }
1738 shift_left:
1739 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1740 // the shifted type.
1741 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1742 if (SA != RHS) {
1743 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1744 << RHS << E->getType() << LHS.getBitWidth();
1745 } else if (LHS.isSigned()) {
1746 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1747 // operand, and must not overflow the corresponding unsigned type.
1748 if (LHS.isNegative())
1749 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1750 else if (LHS.countLeadingZeros() < SA)
1751 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1752 }
1753 Result = LHS << SA;
1754 return true;
1755 }
1756 case BO_Shr: {
1757 if (Info.getLangOpts().OpenCL)
1758 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1759 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1760 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1761 RHS.isUnsigned());
1762 else if (RHS.isSigned() && RHS.isNegative()) {
1763 // During constant-folding, a negative shift is an opposite shift. Such a
1764 // shift is not a constant expression.
1765 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1766 RHS = -RHS;
1767 goto shift_left;
1768 }
1769 shift_right:
1770 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1771 // shifted type.
1772 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1773 if (SA != RHS)
1774 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1775 << RHS << E->getType() << LHS.getBitWidth();
1776 Result = LHS >> SA;
1777 return true;
1778 }
1779
1780 case BO_LT: Result = LHS < RHS; return true;
1781 case BO_GT: Result = LHS > RHS; return true;
1782 case BO_LE: Result = LHS <= RHS; return true;
1783 case BO_GE: Result = LHS >= RHS; return true;
1784 case BO_EQ: Result = LHS == RHS; return true;
1785 case BO_NE: Result = LHS != RHS; return true;
1786 }
1787}
1788
Richard Smith861b5b52013-05-07 23:34:45 +00001789/// Perform the given binary floating-point operation, in-place, on LHS.
1790static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1791 APFloat &LHS, BinaryOperatorKind Opcode,
1792 const APFloat &RHS) {
1793 switch (Opcode) {
1794 default:
1795 Info.Diag(E);
1796 return false;
1797 case BO_Mul:
1798 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1799 break;
1800 case BO_Add:
1801 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1802 break;
1803 case BO_Sub:
1804 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1805 break;
1806 case BO_Div:
1807 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1808 break;
1809 }
1810
1811 if (LHS.isInfinity() || LHS.isNaN())
1812 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1813 return true;
1814}
1815
Richard Smitha8105bc2012-01-06 16:39:00 +00001816/// Cast an lvalue referring to a base subobject to a derived class, by
1817/// truncating the lvalue's path to the given length.
1818static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1819 const RecordDecl *TruncatedType,
1820 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001821 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001822
1823 // Check we actually point to a derived class object.
1824 if (TruncatedElements == D.Entries.size())
1825 return true;
1826 assert(TruncatedElements >= D.MostDerivedPathLength &&
1827 "not casting to a derived class");
1828 if (!Result.checkSubobject(Info, E, CSK_Derived))
1829 return false;
1830
1831 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001832 const RecordDecl *RD = TruncatedType;
1833 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001834 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001835 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1836 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001837 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001838 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001839 else
Richard Smithd62306a2011-11-10 06:34:14 +00001840 Result.Offset -= Layout.getBaseClassOffset(Base);
1841 RD = Base;
1842 }
Richard Smith027bf112011-11-17 22:56:20 +00001843 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001844 return true;
1845}
1846
John McCalld7bca762012-05-01 00:38:49 +00001847static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001848 const CXXRecordDecl *Derived,
1849 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001850 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001851 if (!RL) {
1852 if (Derived->isInvalidDecl()) return false;
1853 RL = &Info.Ctx.getASTRecordLayout(Derived);
1854 }
1855
Richard Smithd62306a2011-11-10 06:34:14 +00001856 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001857 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001858 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001859}
1860
Richard Smitha8105bc2012-01-06 16:39:00 +00001861static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001862 const CXXRecordDecl *DerivedDecl,
1863 const CXXBaseSpecifier *Base) {
1864 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1865
John McCalld7bca762012-05-01 00:38:49 +00001866 if (!Base->isVirtual())
1867 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001868
Richard Smitha8105bc2012-01-06 16:39:00 +00001869 SubobjectDesignator &D = Obj.Designator;
1870 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001871 return false;
1872
Richard Smitha8105bc2012-01-06 16:39:00 +00001873 // Extract most-derived object and corresponding type.
1874 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1875 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1876 return false;
1877
1878 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001879 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001880 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1881 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001882 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001883 return true;
1884}
1885
Richard Smith84401042013-06-03 05:03:02 +00001886static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1887 QualType Type, LValue &Result) {
1888 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1889 PathE = E->path_end();
1890 PathI != PathE; ++PathI) {
1891 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1892 *PathI))
1893 return false;
1894 Type = (*PathI)->getType();
1895 }
1896 return true;
1897}
1898
Richard Smithd62306a2011-11-10 06:34:14 +00001899/// Update LVal to refer to the given field, which must be a member of the type
1900/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001901static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001902 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001903 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001904 if (!RL) {
1905 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001906 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001907 }
Richard Smithd62306a2011-11-10 06:34:14 +00001908
1909 unsigned I = FD->getFieldIndex();
1910 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001911 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001912 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001913}
1914
Richard Smith1b78b3d2012-01-25 22:15:11 +00001915/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001916static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001917 LValue &LVal,
1918 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001919 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001920 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001921 return false;
1922 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001923}
1924
Richard Smithd62306a2011-11-10 06:34:14 +00001925/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001926static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1927 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001928 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1929 // extension.
1930 if (Type->isVoidType() || Type->isFunctionType()) {
1931 Size = CharUnits::One();
1932 return true;
1933 }
1934
1935 if (!Type->isConstantSizeType()) {
1936 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001937 // FIXME: Better diagnostic.
1938 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001939 return false;
1940 }
1941
1942 Size = Info.Ctx.getTypeSizeInChars(Type);
1943 return true;
1944}
1945
1946/// Update a pointer value to model pointer arithmetic.
1947/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001948/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001949/// \param LVal - The pointer value to be updated.
1950/// \param EltTy - The pointee type represented by LVal.
1951/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001952static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1953 LValue &LVal, QualType EltTy,
1954 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001955 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001956 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001957 return false;
1958
1959 // Compute the new offset in the appropriate width.
1960 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001961 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001962 return true;
1963}
1964
Richard Smith66c96992012-02-18 22:04:06 +00001965/// Update an lvalue to refer to a component of a complex number.
1966/// \param Info - Information about the ongoing evaluation.
1967/// \param LVal - The lvalue to be updated.
1968/// \param EltTy - The complex number's component type.
1969/// \param Imag - False for the real component, true for the imaginary.
1970static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1971 LValue &LVal, QualType EltTy,
1972 bool Imag) {
1973 if (Imag) {
1974 CharUnits SizeOfComponent;
1975 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1976 return false;
1977 LVal.Offset += SizeOfComponent;
1978 }
1979 LVal.addComplex(Info, E, EltTy, Imag);
1980 return true;
1981}
1982
Richard Smith27908702011-10-24 17:54:18 +00001983/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001984///
1985/// \param Info Information about the ongoing evaluation.
1986/// \param E An expression to be used when printing diagnostics.
1987/// \param VD The variable whose initializer should be obtained.
1988/// \param Frame The frame in which the variable was created. Must be null
1989/// if this variable is not local to the evaluation.
1990/// \param Result Filled in with a pointer to the value of the variable.
1991static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1992 const VarDecl *VD, CallStackFrame *Frame,
1993 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001994 // If this is a parameter to an active constexpr function call, perform
1995 // argument substitution.
1996 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001997 // Assume arguments of a potential constant expression are unknown
1998 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001999 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002000 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002001 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002002 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002003 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002004 }
Richard Smith3229b742013-05-05 21:17:10 +00002005 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002006 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002007 }
Richard Smith27908702011-10-24 17:54:18 +00002008
Richard Smithd9f663b2013-04-22 15:31:51 +00002009 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002010 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002011 Result = Frame->getTemporary(VD);
2012 assert(Result && "missing value for local variable");
2013 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002014 }
2015
Richard Smithd0b4dd62011-12-19 06:19:21 +00002016 // Dig out the initializer, and use the declaration which it's attached to.
2017 const Expr *Init = VD->getAnyInitializer(VD);
2018 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002019 // If we're checking a potential constant expression, the variable could be
2020 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002021 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00002022 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002023 return false;
2024 }
2025
Richard Smithd62306a2011-11-10 06:34:14 +00002026 // If we're currently evaluating the initializer of this declaration, use that
2027 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002028 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002029 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002030 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002031 }
2032
Richard Smithcecf1842011-11-01 21:06:14 +00002033 // Never evaluate the initializer of a weak variable. We can't be sure that
2034 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002035 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002036 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002037 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002038 }
Richard Smithcecf1842011-11-01 21:06:14 +00002039
Richard Smithd0b4dd62011-12-19 06:19:21 +00002040 // Check that we can fold the initializer. In C++, we will have already done
2041 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002042 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002043 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002044 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002045 Notes.size() + 1) << VD;
2046 Info.Note(VD->getLocation(), diag::note_declared_at);
2047 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002048 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002049 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002050 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002051 Notes.size() + 1) << VD;
2052 Info.Note(VD->getLocation(), diag::note_declared_at);
2053 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002054 }
Richard Smith27908702011-10-24 17:54:18 +00002055
Richard Smith3229b742013-05-05 21:17:10 +00002056 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002057 return true;
Richard Smith27908702011-10-24 17:54:18 +00002058}
2059
Richard Smith11562c52011-10-28 17:51:58 +00002060static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002061 Qualifiers Quals = T.getQualifiers();
2062 return Quals.hasConst() && !Quals.hasVolatile();
2063}
2064
Richard Smithe97cbd72011-11-11 04:05:33 +00002065/// Get the base index of the given base class within an APValue representing
2066/// the given derived class.
2067static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2068 const CXXRecordDecl *Base) {
2069 Base = Base->getCanonicalDecl();
2070 unsigned Index = 0;
2071 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2072 E = Derived->bases_end(); I != E; ++I, ++Index) {
2073 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2074 return Index;
2075 }
2076
2077 llvm_unreachable("base class missing from derived class's bases list");
2078}
2079
Richard Smith3da88fa2013-04-26 14:36:30 +00002080/// Extract the value of a character from a string literal.
2081static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2082 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002083 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2084 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2085 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002086 const StringLiteral *S = cast<StringLiteral>(Lit);
2087 const ConstantArrayType *CAT =
2088 Info.Ctx.getAsConstantArrayType(S->getType());
2089 assert(CAT && "string literal isn't an array");
2090 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002091 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002092
2093 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002094 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002095 if (Index < S->getLength())
2096 Value = S->getCodeUnit(Index);
2097 return Value;
2098}
2099
Richard Smith3da88fa2013-04-26 14:36:30 +00002100// Expand a string literal into an array of characters.
2101static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2102 APValue &Result) {
2103 const StringLiteral *S = cast<StringLiteral>(Lit);
2104 const ConstantArrayType *CAT =
2105 Info.Ctx.getAsConstantArrayType(S->getType());
2106 assert(CAT && "string literal isn't an array");
2107 QualType CharType = CAT->getElementType();
2108 assert(CharType->isIntegerType() && "unexpected character type");
2109
2110 unsigned Elts = CAT->getSize().getZExtValue();
2111 Result = APValue(APValue::UninitArray(),
2112 std::min(S->getLength(), Elts), Elts);
2113 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2114 CharType->isUnsignedIntegerType());
2115 if (Result.hasArrayFiller())
2116 Result.getArrayFiller() = APValue(Value);
2117 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2118 Value = S->getCodeUnit(I);
2119 Result.getArrayInitializedElt(I) = APValue(Value);
2120 }
2121}
2122
2123// Expand an array so that it has more than Index filled elements.
2124static void expandArray(APValue &Array, unsigned Index) {
2125 unsigned Size = Array.getArraySize();
2126 assert(Index < Size);
2127
2128 // Always at least double the number of elements for which we store a value.
2129 unsigned OldElts = Array.getArrayInitializedElts();
2130 unsigned NewElts = std::max(Index+1, OldElts * 2);
2131 NewElts = std::min(Size, std::max(NewElts, 8u));
2132
2133 // Copy the data across.
2134 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2135 for (unsigned I = 0; I != OldElts; ++I)
2136 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2137 for (unsigned I = OldElts; I != NewElts; ++I)
2138 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2139 if (NewValue.hasArrayFiller())
2140 NewValue.getArrayFiller() = Array.getArrayFiller();
2141 Array.swap(NewValue);
2142}
2143
Richard Smithb01fe402014-09-16 01:24:02 +00002144/// Determine whether a type would actually be read by an lvalue-to-rvalue
2145/// conversion. If it's of class type, we may assume that the copy operation
2146/// is trivial. Note that this is never true for a union type with fields
2147/// (because the copy always "reads" the active member) and always true for
2148/// a non-class type.
2149static bool isReadByLvalueToRvalueConversion(QualType T) {
2150 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2151 if (!RD || (RD->isUnion() && !RD->field_empty()))
2152 return true;
2153 if (RD->isEmpty())
2154 return false;
2155
2156 for (auto *Field : RD->fields())
2157 if (isReadByLvalueToRvalueConversion(Field->getType()))
2158 return true;
2159
2160 for (auto &BaseSpec : RD->bases())
2161 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2162 return true;
2163
2164 return false;
2165}
2166
2167/// Diagnose an attempt to read from any unreadable field within the specified
2168/// type, which might be a class type.
2169static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2170 QualType T) {
2171 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2172 if (!RD)
2173 return false;
2174
2175 if (!RD->hasMutableFields())
2176 return false;
2177
2178 for (auto *Field : RD->fields()) {
2179 // If we're actually going to read this field in some way, then it can't
2180 // be mutable. If we're in a union, then assigning to a mutable field
2181 // (even an empty one) can change the active member, so that's not OK.
2182 // FIXME: Add core issue number for the union case.
2183 if (Field->isMutable() &&
2184 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2185 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2186 Info.Note(Field->getLocation(), diag::note_declared_at);
2187 return true;
2188 }
2189
2190 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2191 return true;
2192 }
2193
2194 for (auto &BaseSpec : RD->bases())
2195 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2196 return true;
2197
2198 // All mutable fields were empty, and thus not actually read.
2199 return false;
2200}
2201
Richard Smith861b5b52013-05-07 23:34:45 +00002202/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002203enum AccessKinds {
2204 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002205 AK_Assign,
2206 AK_Increment,
2207 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002208};
2209
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002210namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002211/// A handle to a complete object (an object that is not a subobject of
2212/// another object).
2213struct CompleteObject {
2214 /// The value of the complete object.
2215 APValue *Value;
2216 /// The type of the complete object.
2217 QualType Type;
2218
Craig Topper36250ad2014-05-12 05:36:57 +00002219 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002220 CompleteObject(APValue *Value, QualType Type)
2221 : Value(Value), Type(Type) {
2222 assert(Value && "missing value for complete object");
2223 }
2224
Aaron Ballman67347662015-02-15 22:00:28 +00002225 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002226};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002227} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002228
Richard Smith3da88fa2013-04-26 14:36:30 +00002229/// Find the designated sub-object of an rvalue.
2230template<typename SubobjectHandler>
2231typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002232findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002233 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002234 if (Sub.Invalid)
2235 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002236 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002237 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002238 if (Info.getLangOpts().CPlusPlus11)
2239 Info.Diag(E, diag::note_constexpr_access_past_end)
2240 << handler.AccessKind;
2241 else
2242 Info.Diag(E);
2243 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002244 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002245
Richard Smith3229b742013-05-05 21:17:10 +00002246 APValue *O = Obj.Value;
2247 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002248 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002249
Richard Smithd62306a2011-11-10 06:34:14 +00002250 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002251 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2252 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002253 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002254 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2255 return handler.failed();
2256 }
2257
Richard Smith49ca8aa2013-08-06 07:09:20 +00002258 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002259 // If we are reading an object of class type, there may still be more
2260 // things we need to check: if there are any mutable subobjects, we
2261 // cannot perform this read. (This only happens when performing a trivial
2262 // copy or assignment.)
2263 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2264 diagnoseUnreadableFields(Info, E, ObjType))
2265 return handler.failed();
2266
Richard Smith49ca8aa2013-08-06 07:09:20 +00002267 if (!handler.found(*O, ObjType))
2268 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002269
Richard Smith49ca8aa2013-08-06 07:09:20 +00002270 // If we modified a bit-field, truncate it to the right width.
2271 if (handler.AccessKind != AK_Read &&
2272 LastField && LastField->isBitField() &&
2273 !truncateBitfieldValue(Info, E, *O, LastField))
2274 return false;
2275
2276 return true;
2277 }
2278
Craig Topper36250ad2014-05-12 05:36:57 +00002279 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002280 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002281 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002282 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002283 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002284 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002285 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002286 // Note, it should not be possible to form a pointer with a valid
2287 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002288 if (Info.getLangOpts().CPlusPlus11)
2289 Info.Diag(E, diag::note_constexpr_access_past_end)
2290 << handler.AccessKind;
2291 else
2292 Info.Diag(E);
2293 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002294 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002295
2296 ObjType = CAT->getElementType();
2297
Richard Smith14a94132012-02-17 03:35:37 +00002298 // An array object is represented as either an Array APValue or as an
2299 // LValue which refers to a string literal.
2300 if (O->isLValue()) {
2301 assert(I == N - 1 && "extracting subobject of character?");
2302 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002303 if (handler.AccessKind != AK_Read)
2304 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2305 *O);
2306 else
2307 return handler.foundString(*O, ObjType, Index);
2308 }
2309
2310 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002311 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002312 else if (handler.AccessKind != AK_Read) {
2313 expandArray(*O, Index);
2314 O = &O->getArrayInitializedElt(Index);
2315 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002316 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002317 } else if (ObjType->isAnyComplexType()) {
2318 // Next subobject is a complex number.
2319 uint64_t Index = Sub.Entries[I].ArrayIndex;
2320 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002321 if (Info.getLangOpts().CPlusPlus11)
2322 Info.Diag(E, diag::note_constexpr_access_past_end)
2323 << handler.AccessKind;
2324 else
2325 Info.Diag(E);
2326 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002327 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002328
2329 bool WasConstQualified = ObjType.isConstQualified();
2330 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2331 if (WasConstQualified)
2332 ObjType.addConst();
2333
Richard Smith66c96992012-02-18 22:04:06 +00002334 assert(I == N - 1 && "extracting subobject of scalar?");
2335 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002336 return handler.found(Index ? O->getComplexIntImag()
2337 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002338 } else {
2339 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002340 return handler.found(Index ? O->getComplexFloatImag()
2341 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002342 }
Richard Smithd62306a2011-11-10 06:34:14 +00002343 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002344 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002345 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002346 << Field;
2347 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002348 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002349 }
2350
Richard Smithd62306a2011-11-10 06:34:14 +00002351 // Next subobject is a class, struct or union field.
2352 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2353 if (RD->isUnion()) {
2354 const FieldDecl *UnionField = O->getUnionField();
2355 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002356 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002357 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2358 << handler.AccessKind << Field << !UnionField << UnionField;
2359 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002360 }
Richard Smithd62306a2011-11-10 06:34:14 +00002361 O = &O->getUnionValue();
2362 } else
2363 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002364
2365 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002366 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002367 if (WasConstQualified && !Field->isMutable())
2368 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002369
2370 if (ObjType.isVolatileQualified()) {
2371 if (Info.getLangOpts().CPlusPlus) {
2372 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002373 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2374 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002375 Info.Note(Field->getLocation(), diag::note_declared_at);
2376 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002377 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002378 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002379 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002380 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002381
2382 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002383 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002384 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002385 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2386 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2387 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002388
2389 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002390 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002391 if (WasConstQualified)
2392 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002393 }
2394 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002395}
2396
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002397namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002398struct ExtractSubobjectHandler {
2399 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002400 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002401
2402 static const AccessKinds AccessKind = AK_Read;
2403
2404 typedef bool result_type;
2405 bool failed() { return false; }
2406 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002407 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002408 return true;
2409 }
2410 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002411 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002412 return true;
2413 }
2414 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002415 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002416 return true;
2417 }
2418 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002419 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002420 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2421 return true;
2422 }
2423};
Richard Smith3229b742013-05-05 21:17:10 +00002424} // end anonymous namespace
2425
Richard Smith3da88fa2013-04-26 14:36:30 +00002426const AccessKinds ExtractSubobjectHandler::AccessKind;
2427
2428/// Extract the designated sub-object of an rvalue.
2429static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002430 const CompleteObject &Obj,
2431 const SubobjectDesignator &Sub,
2432 APValue &Result) {
2433 ExtractSubobjectHandler Handler = { Info, Result };
2434 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002435}
2436
Richard Smith3229b742013-05-05 21:17:10 +00002437namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002438struct ModifySubobjectHandler {
2439 EvalInfo &Info;
2440 APValue &NewVal;
2441 const Expr *E;
2442
2443 typedef bool result_type;
2444 static const AccessKinds AccessKind = AK_Assign;
2445
2446 bool checkConst(QualType QT) {
2447 // Assigning to a const object has undefined behavior.
2448 if (QT.isConstQualified()) {
2449 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2450 return false;
2451 }
2452 return true;
2453 }
2454
2455 bool failed() { return false; }
2456 bool found(APValue &Subobj, QualType SubobjType) {
2457 if (!checkConst(SubobjType))
2458 return false;
2459 // We've been given ownership of NewVal, so just swap it in.
2460 Subobj.swap(NewVal);
2461 return true;
2462 }
2463 bool found(APSInt &Value, QualType SubobjType) {
2464 if (!checkConst(SubobjType))
2465 return false;
2466 if (!NewVal.isInt()) {
2467 // Maybe trying to write a cast pointer value into a complex?
2468 Info.Diag(E);
2469 return false;
2470 }
2471 Value = NewVal.getInt();
2472 return true;
2473 }
2474 bool found(APFloat &Value, QualType SubobjType) {
2475 if (!checkConst(SubobjType))
2476 return false;
2477 Value = NewVal.getFloat();
2478 return true;
2479 }
2480 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2481 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2482 }
2483};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002484} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002485
Richard Smith3229b742013-05-05 21:17:10 +00002486const AccessKinds ModifySubobjectHandler::AccessKind;
2487
Richard Smith3da88fa2013-04-26 14:36:30 +00002488/// Update the designated sub-object of an rvalue to the given value.
2489static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002490 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002491 const SubobjectDesignator &Sub,
2492 APValue &NewVal) {
2493 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002494 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002495}
2496
Richard Smith84f6dcf2012-02-02 01:16:57 +00002497/// Find the position where two subobject designators diverge, or equivalently
2498/// the length of the common initial subsequence.
2499static unsigned FindDesignatorMismatch(QualType ObjType,
2500 const SubobjectDesignator &A,
2501 const SubobjectDesignator &B,
2502 bool &WasArrayIndex) {
2503 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2504 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002505 if (!ObjType.isNull() &&
2506 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002507 // Next subobject is an array element.
2508 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2509 WasArrayIndex = true;
2510 return I;
2511 }
Richard Smith66c96992012-02-18 22:04:06 +00002512 if (ObjType->isAnyComplexType())
2513 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2514 else
2515 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002516 } else {
2517 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2518 WasArrayIndex = false;
2519 return I;
2520 }
2521 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2522 // Next subobject is a field.
2523 ObjType = FD->getType();
2524 else
2525 // Next subobject is a base class.
2526 ObjType = QualType();
2527 }
2528 }
2529 WasArrayIndex = false;
2530 return I;
2531}
2532
2533/// Determine whether the given subobject designators refer to elements of the
2534/// same array object.
2535static bool AreElementsOfSameArray(QualType ObjType,
2536 const SubobjectDesignator &A,
2537 const SubobjectDesignator &B) {
2538 if (A.Entries.size() != B.Entries.size())
2539 return false;
2540
George Burgess IVa51c4072015-10-16 01:49:01 +00002541 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002542 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2543 // A is a subobject of the array element.
2544 return false;
2545
2546 // If A (and B) designates an array element, the last entry will be the array
2547 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2548 // of length 1' case, and the entire path must match.
2549 bool WasArrayIndex;
2550 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2551 return CommonLength >= A.Entries.size() - IsArray;
2552}
2553
Richard Smith3229b742013-05-05 21:17:10 +00002554/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002555static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2556 AccessKinds AK, const LValue &LVal,
2557 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002558 if (!LVal.Base) {
2559 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2560 return CompleteObject();
2561 }
2562
Craig Topper36250ad2014-05-12 05:36:57 +00002563 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002564 if (LVal.CallIndex) {
2565 Frame = Info.getCallFrame(LVal.CallIndex);
2566 if (!Frame) {
2567 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2568 << AK << LVal.Base.is<const ValueDecl*>();
2569 NoteLValueLocation(Info, LVal.Base);
2570 return CompleteObject();
2571 }
Richard Smith3229b742013-05-05 21:17:10 +00002572 }
2573
2574 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2575 // is not a constant expression (even if the object is non-volatile). We also
2576 // apply this rule to C++98, in order to conform to the expected 'volatile'
2577 // semantics.
2578 if (LValType.isVolatileQualified()) {
2579 if (Info.getLangOpts().CPlusPlus)
2580 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2581 << AK << LValType;
2582 else
2583 Info.Diag(E);
2584 return CompleteObject();
2585 }
2586
2587 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002588 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002589 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002590
2591 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2592 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2593 // In C++11, constexpr, non-volatile variables initialized with constant
2594 // expressions are constant expressions too. Inside constexpr functions,
2595 // parameters are constant expressions even if they're non-const.
2596 // In C++1y, objects local to a constant expression (those with a Frame) are
2597 // both readable and writable inside constant expressions.
2598 // In C, such things can also be folded, although they are not ICEs.
2599 const VarDecl *VD = dyn_cast<VarDecl>(D);
2600 if (VD) {
2601 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2602 VD = VDef;
2603 }
2604 if (!VD || VD->isInvalidDecl()) {
2605 Info.Diag(E);
2606 return CompleteObject();
2607 }
2608
2609 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002610 if (BaseType.isVolatileQualified()) {
2611 if (Info.getLangOpts().CPlusPlus) {
2612 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2613 << AK << 1 << VD;
2614 Info.Note(VD->getLocation(), diag::note_declared_at);
2615 } else {
2616 Info.Diag(E);
2617 }
2618 return CompleteObject();
2619 }
2620
2621 // Unless we're looking at a local variable or argument in a constexpr call,
2622 // the variable we're reading must be const.
2623 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002624 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002625 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2626 // OK, we can read and modify an object if we're in the process of
2627 // evaluating its initializer, because its lifetime began in this
2628 // evaluation.
2629 } else if (AK != AK_Read) {
2630 // All the remaining cases only permit reading.
2631 Info.Diag(E, diag::note_constexpr_modify_global);
2632 return CompleteObject();
2633 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002634 // OK, we can read this variable.
2635 } else if (BaseType->isIntegralOrEnumerationType()) {
2636 if (!BaseType.isConstQualified()) {
2637 if (Info.getLangOpts().CPlusPlus) {
2638 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2639 Info.Note(VD->getLocation(), diag::note_declared_at);
2640 } else {
2641 Info.Diag(E);
2642 }
2643 return CompleteObject();
2644 }
2645 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2646 // We support folding of const floating-point types, in order to make
2647 // static const data members of such types (supported as an extension)
2648 // more useful.
2649 if (Info.getLangOpts().CPlusPlus11) {
2650 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2651 Info.Note(VD->getLocation(), diag::note_declared_at);
2652 } else {
2653 Info.CCEDiag(E);
2654 }
2655 } else {
2656 // FIXME: Allow folding of values of any literal type in all languages.
2657 if (Info.getLangOpts().CPlusPlus11) {
2658 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2659 Info.Note(VD->getLocation(), diag::note_declared_at);
2660 } else {
2661 Info.Diag(E);
2662 }
2663 return CompleteObject();
2664 }
2665 }
2666
2667 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2668 return CompleteObject();
2669 } else {
2670 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2671
2672 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002673 if (const MaterializeTemporaryExpr *MTE =
2674 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2675 assert(MTE->getStorageDuration() == SD_Static &&
2676 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002677
Richard Smithe6c01442013-06-05 00:46:14 +00002678 // Per C++1y [expr.const]p2:
2679 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2680 // - a [...] glvalue of integral or enumeration type that refers to
2681 // a non-volatile const object [...]
2682 // [...]
2683 // - a [...] glvalue of literal type that refers to a non-volatile
2684 // object whose lifetime began within the evaluation of e.
2685 //
2686 // C++11 misses the 'began within the evaluation of e' check and
2687 // instead allows all temporaries, including things like:
2688 // int &&r = 1;
2689 // int x = ++r;
2690 // constexpr int k = r;
2691 // Therefore we use the C++1y rules in C++11 too.
2692 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2693 const ValueDecl *ED = MTE->getExtendingDecl();
2694 if (!(BaseType.isConstQualified() &&
2695 BaseType->isIntegralOrEnumerationType()) &&
2696 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2697 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2698 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2699 return CompleteObject();
2700 }
2701
2702 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2703 assert(BaseVal && "got reference to unevaluated temporary");
2704 } else {
2705 Info.Diag(E);
2706 return CompleteObject();
2707 }
2708 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002709 BaseVal = Frame->getTemporary(Base);
2710 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002711 }
Richard Smith3229b742013-05-05 21:17:10 +00002712
2713 // Volatile temporary objects cannot be accessed in constant expressions.
2714 if (BaseType.isVolatileQualified()) {
2715 if (Info.getLangOpts().CPlusPlus) {
2716 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2717 << AK << 0;
2718 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2719 } else {
2720 Info.Diag(E);
2721 }
2722 return CompleteObject();
2723 }
2724 }
2725
Richard Smith7525ff62013-05-09 07:14:00 +00002726 // During the construction of an object, it is not yet 'const'.
2727 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2728 // and this doesn't do quite the right thing for const subobjects of the
2729 // object under construction.
2730 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2731 BaseType = Info.Ctx.getCanonicalType(BaseType);
2732 BaseType.removeLocalConst();
2733 }
2734
Richard Smith6d4c6582013-11-05 22:18:15 +00002735 // In C++1y, we can't safely access any mutable state when we might be
2736 // evaluating after an unmodeled side effect or an evaluation failure.
2737 //
2738 // FIXME: Not all local state is mutable. Allow local constant subobjects
2739 // to be read here (but take care with 'mutable' fields).
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002740 if (Frame && Info.getLangOpts().CPlusPlus14 &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002741 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002742 return CompleteObject();
2743
2744 return CompleteObject(BaseVal, BaseType);
2745}
2746
Richard Smith243ef902013-05-05 23:31:59 +00002747/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2748/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2749/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002750///
2751/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002752/// \param Conv - The expression for which we are performing the conversion.
2753/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002754/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2755/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002756/// \param LVal - The glvalue on which we are attempting to perform this action.
2757/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002758static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002759 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002760 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002761 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002762 return false;
2763
Richard Smith3229b742013-05-05 21:17:10 +00002764 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002765 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002766 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002767 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2768 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2769 // initializer until now for such expressions. Such an expression can't be
2770 // an ICE in C, so this only matters for fold.
2771 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2772 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002773 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002774 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002775 }
Richard Smith3229b742013-05-05 21:17:10 +00002776 APValue Lit;
2777 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2778 return false;
2779 CompleteObject LitObj(&Lit, Base->getType());
2780 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002781 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002782 // We represent a string literal array as an lvalue pointing at the
2783 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002784 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002785 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2786 CompleteObject StrObj(&Str, Base->getType());
2787 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002788 }
Richard Smith11562c52011-10-28 17:51:58 +00002789 }
2790
Richard Smith3229b742013-05-05 21:17:10 +00002791 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2792 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002793}
2794
2795/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002796static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002797 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002798 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002799 return false;
2800
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002801 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002802 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002803 return false;
2804 }
2805
Richard Smith3229b742013-05-05 21:17:10 +00002806 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2807 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002808}
2809
Richard Smith243ef902013-05-05 23:31:59 +00002810static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2811 return T->isSignedIntegerType() &&
2812 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2813}
2814
2815namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002816struct CompoundAssignSubobjectHandler {
2817 EvalInfo &Info;
2818 const Expr *E;
2819 QualType PromotedLHSType;
2820 BinaryOperatorKind Opcode;
2821 const APValue &RHS;
2822
2823 static const AccessKinds AccessKind = AK_Assign;
2824
2825 typedef bool result_type;
2826
2827 bool checkConst(QualType QT) {
2828 // Assigning to a const object has undefined behavior.
2829 if (QT.isConstQualified()) {
2830 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2831 return false;
2832 }
2833 return true;
2834 }
2835
2836 bool failed() { return false; }
2837 bool found(APValue &Subobj, QualType SubobjType) {
2838 switch (Subobj.getKind()) {
2839 case APValue::Int:
2840 return found(Subobj.getInt(), SubobjType);
2841 case APValue::Float:
2842 return found(Subobj.getFloat(), SubobjType);
2843 case APValue::ComplexInt:
2844 case APValue::ComplexFloat:
2845 // FIXME: Implement complex compound assignment.
2846 Info.Diag(E);
2847 return false;
2848 case APValue::LValue:
2849 return foundPointer(Subobj, SubobjType);
2850 default:
2851 // FIXME: can this happen?
2852 Info.Diag(E);
2853 return false;
2854 }
2855 }
2856 bool found(APSInt &Value, QualType SubobjType) {
2857 if (!checkConst(SubobjType))
2858 return false;
2859
2860 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2861 // We don't support compound assignment on integer-cast-to-pointer
2862 // values.
2863 Info.Diag(E);
2864 return false;
2865 }
2866
2867 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2868 SubobjType, Value);
2869 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2870 return false;
2871 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2872 return true;
2873 }
2874 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002875 return checkConst(SubobjType) &&
2876 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2877 Value) &&
2878 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2879 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002880 }
2881 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2882 if (!checkConst(SubobjType))
2883 return false;
2884
2885 QualType PointeeType;
2886 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2887 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002888
2889 if (PointeeType.isNull() || !RHS.isInt() ||
2890 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002891 Info.Diag(E);
2892 return false;
2893 }
2894
Richard Smith861b5b52013-05-07 23:34:45 +00002895 int64_t Offset = getExtValue(RHS.getInt());
2896 if (Opcode == BO_Sub)
2897 Offset = -Offset;
2898
2899 LValue LVal;
2900 LVal.setFrom(Info.Ctx, Subobj);
2901 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2902 return false;
2903 LVal.moveInto(Subobj);
2904 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002905 }
2906 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2907 llvm_unreachable("shouldn't encounter string elements here");
2908 }
2909};
2910} // end anonymous namespace
2911
2912const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2913
2914/// Perform a compound assignment of LVal <op>= RVal.
2915static bool handleCompoundAssignment(
2916 EvalInfo &Info, const Expr *E,
2917 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2918 BinaryOperatorKind Opcode, const APValue &RVal) {
2919 if (LVal.Designator.Invalid)
2920 return false;
2921
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002922 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00002923 Info.Diag(E);
2924 return false;
2925 }
2926
2927 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2928 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2929 RVal };
2930 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2931}
2932
2933namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002934struct IncDecSubobjectHandler {
2935 EvalInfo &Info;
2936 const Expr *E;
2937 AccessKinds AccessKind;
2938 APValue *Old;
2939
2940 typedef bool result_type;
2941
2942 bool checkConst(QualType QT) {
2943 // Assigning to a const object has undefined behavior.
2944 if (QT.isConstQualified()) {
2945 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2946 return false;
2947 }
2948 return true;
2949 }
2950
2951 bool failed() { return false; }
2952 bool found(APValue &Subobj, QualType SubobjType) {
2953 // Stash the old value. Also clear Old, so we don't clobber it later
2954 // if we're post-incrementing a complex.
2955 if (Old) {
2956 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002957 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002958 }
2959
2960 switch (Subobj.getKind()) {
2961 case APValue::Int:
2962 return found(Subobj.getInt(), SubobjType);
2963 case APValue::Float:
2964 return found(Subobj.getFloat(), SubobjType);
2965 case APValue::ComplexInt:
2966 return found(Subobj.getComplexIntReal(),
2967 SubobjType->castAs<ComplexType>()->getElementType()
2968 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2969 case APValue::ComplexFloat:
2970 return found(Subobj.getComplexFloatReal(),
2971 SubobjType->castAs<ComplexType>()->getElementType()
2972 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2973 case APValue::LValue:
2974 return foundPointer(Subobj, SubobjType);
2975 default:
2976 // FIXME: can this happen?
2977 Info.Diag(E);
2978 return false;
2979 }
2980 }
2981 bool found(APSInt &Value, QualType SubobjType) {
2982 if (!checkConst(SubobjType))
2983 return false;
2984
2985 if (!SubobjType->isIntegerType()) {
2986 // We don't support increment / decrement on integer-cast-to-pointer
2987 // values.
2988 Info.Diag(E);
2989 return false;
2990 }
2991
2992 if (Old) *Old = APValue(Value);
2993
2994 // bool arithmetic promotes to int, and the conversion back to bool
2995 // doesn't reduce mod 2^n, so special-case it.
2996 if (SubobjType->isBooleanType()) {
2997 if (AccessKind == AK_Increment)
2998 Value = 1;
2999 else
3000 Value = !Value;
3001 return true;
3002 }
3003
3004 bool WasNegative = Value.isNegative();
3005 if (AccessKind == AK_Increment) {
3006 ++Value;
3007
3008 if (!WasNegative && Value.isNegative() &&
3009 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3010 APSInt ActualValue(Value, /*IsUnsigned*/true);
3011 HandleOverflow(Info, E, ActualValue, SubobjType);
3012 }
3013 } else {
3014 --Value;
3015
3016 if (WasNegative && !Value.isNegative() &&
3017 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3018 unsigned BitWidth = Value.getBitWidth();
3019 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3020 ActualValue.setBit(BitWidth);
3021 HandleOverflow(Info, E, ActualValue, SubobjType);
3022 }
3023 }
3024 return true;
3025 }
3026 bool found(APFloat &Value, QualType SubobjType) {
3027 if (!checkConst(SubobjType))
3028 return false;
3029
3030 if (Old) *Old = APValue(Value);
3031
3032 APFloat One(Value.getSemantics(), 1);
3033 if (AccessKind == AK_Increment)
3034 Value.add(One, APFloat::rmNearestTiesToEven);
3035 else
3036 Value.subtract(One, APFloat::rmNearestTiesToEven);
3037 return true;
3038 }
3039 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3040 if (!checkConst(SubobjType))
3041 return false;
3042
3043 QualType PointeeType;
3044 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3045 PointeeType = PT->getPointeeType();
3046 else {
3047 Info.Diag(E);
3048 return false;
3049 }
3050
3051 LValue LVal;
3052 LVal.setFrom(Info.Ctx, Subobj);
3053 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3054 AccessKind == AK_Increment ? 1 : -1))
3055 return false;
3056 LVal.moveInto(Subobj);
3057 return true;
3058 }
3059 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3060 llvm_unreachable("shouldn't encounter string elements here");
3061 }
3062};
3063} // end anonymous namespace
3064
3065/// Perform an increment or decrement on LVal.
3066static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3067 QualType LValType, bool IsIncrement, APValue *Old) {
3068 if (LVal.Designator.Invalid)
3069 return false;
3070
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003071 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003072 Info.Diag(E);
3073 return false;
3074 }
3075
3076 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3077 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3078 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3079 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3080}
3081
Richard Smithe97cbd72011-11-11 04:05:33 +00003082/// Build an lvalue for the object argument of a member function call.
3083static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3084 LValue &This) {
3085 if (Object->getType()->isPointerType())
3086 return EvaluatePointer(Object, This, Info);
3087
3088 if (Object->isGLValue())
3089 return EvaluateLValue(Object, This, Info);
3090
Richard Smithd9f663b2013-04-22 15:31:51 +00003091 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003092 return EvaluateTemporary(Object, This, Info);
3093
Richard Smith3e79a572014-06-11 19:53:12 +00003094 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003095 return false;
3096}
3097
3098/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3099/// lvalue referring to the result.
3100///
3101/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003102/// \param LV - An lvalue referring to the base of the member pointer.
3103/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003104/// \param IncludeMember - Specifies whether the member itself is included in
3105/// the resulting LValue subobject designator. This is not possible when
3106/// creating a bound member function.
3107/// \return The field or method declaration to which the member pointer refers,
3108/// or 0 if evaluation fails.
3109static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003110 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003111 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003112 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003113 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003114 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003115 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003116 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003117
3118 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3119 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003120 if (!MemPtr.getDecl()) {
3121 // FIXME: Specific diagnostic.
3122 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003123 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003124 }
Richard Smith253c2a32012-01-27 01:14:48 +00003125
Richard Smith027bf112011-11-17 22:56:20 +00003126 if (MemPtr.isDerivedMember()) {
3127 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003128 // The end of the derived-to-base path for the base object must match the
3129 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003130 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003131 LV.Designator.Entries.size()) {
3132 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003133 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003134 }
Richard Smith027bf112011-11-17 22:56:20 +00003135 unsigned PathLengthToMember =
3136 LV.Designator.Entries.size() - MemPtr.Path.size();
3137 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3138 const CXXRecordDecl *LVDecl = getAsBaseClass(
3139 LV.Designator.Entries[PathLengthToMember + I]);
3140 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003141 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3142 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003143 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003144 }
Richard Smith027bf112011-11-17 22:56:20 +00003145 }
3146
3147 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003148 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003149 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003150 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003151 } else if (!MemPtr.Path.empty()) {
3152 // Extend the LValue path with the member pointer's path.
3153 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3154 MemPtr.Path.size() + IncludeMember);
3155
3156 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003157 if (const PointerType *PT = LVType->getAs<PointerType>())
3158 LVType = PT->getPointeeType();
3159 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3160 assert(RD && "member pointer access on non-class-type expression");
3161 // The first class in the path is that of the lvalue.
3162 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3163 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003164 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003165 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003166 RD = Base;
3167 }
3168 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003169 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3170 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003171 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003172 }
3173
3174 // Add the member. Note that we cannot build bound member functions here.
3175 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003176 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003177 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003178 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003179 } else if (const IndirectFieldDecl *IFD =
3180 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003181 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003182 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003183 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003184 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003185 }
Richard Smith027bf112011-11-17 22:56:20 +00003186 }
3187
3188 return MemPtr.getDecl();
3189}
3190
Richard Smith84401042013-06-03 05:03:02 +00003191static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3192 const BinaryOperator *BO,
3193 LValue &LV,
3194 bool IncludeMember = true) {
3195 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3196
3197 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3198 if (Info.keepEvaluatingAfterFailure()) {
3199 MemberPtr MemPtr;
3200 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3201 }
Craig Topper36250ad2014-05-12 05:36:57 +00003202 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003203 }
3204
3205 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3206 BO->getRHS(), IncludeMember);
3207}
3208
Richard Smith027bf112011-11-17 22:56:20 +00003209/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3210/// the provided lvalue, which currently refers to the base object.
3211static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3212 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003213 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003214 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003215 return false;
3216
Richard Smitha8105bc2012-01-06 16:39:00 +00003217 QualType TargetQT = E->getType();
3218 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3219 TargetQT = PT->getPointeeType();
3220
3221 // Check this cast lands within the final derived-to-base subobject path.
3222 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003223 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003224 << D.MostDerivedType << TargetQT;
3225 return false;
3226 }
3227
Richard Smith027bf112011-11-17 22:56:20 +00003228 // Check the type of the final cast. We don't need to check the path,
3229 // since a cast can only be formed if the path is unique.
3230 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003231 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3232 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003233 if (NewEntriesSize == D.MostDerivedPathLength)
3234 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3235 else
Richard Smith027bf112011-11-17 22:56:20 +00003236 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003237 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003238 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003239 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003240 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003241 }
Richard Smith027bf112011-11-17 22:56:20 +00003242
3243 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003244 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003245}
3246
Mike Stump876387b2009-10-27 22:09:17 +00003247namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003248enum EvalStmtResult {
3249 /// Evaluation failed.
3250 ESR_Failed,
3251 /// Hit a 'return' statement.
3252 ESR_Returned,
3253 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003254 ESR_Succeeded,
3255 /// Hit a 'continue' statement.
3256 ESR_Continue,
3257 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003258 ESR_Break,
3259 /// Still scanning for 'case' or 'default' statement.
3260 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003261};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003262}
Richard Smith254a73d2011-10-28 22:34:42 +00003263
Richard Smithd9f663b2013-04-22 15:31:51 +00003264static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3265 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3266 // We don't need to evaluate the initializer for a static local.
3267 if (!VD->hasLocalStorage())
3268 return true;
3269
3270 LValue Result;
3271 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003272 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003273
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003274 const Expr *InitE = VD->getInit();
3275 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003276 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3277 << false << VD->getType();
3278 Val = APValue();
3279 return false;
3280 }
3281
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003282 if (InitE->isValueDependent())
3283 return false;
3284
3285 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003286 // Wipe out any partially-computed value, to allow tracking that this
3287 // evaluation failed.
3288 Val = APValue();
3289 return false;
3290 }
3291 }
3292
3293 return true;
3294}
3295
Richard Smith4e18ca52013-05-06 05:56:11 +00003296/// Evaluate a condition (either a variable declaration or an expression).
3297static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3298 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003299 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003300 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3301 return false;
3302 return EvaluateAsBooleanCondition(Cond, Result, Info);
3303}
3304
Richard Smith52a980a2015-08-28 02:43:42 +00003305/// \brief A location where the result (returned value) of evaluating a
3306/// statement should be stored.
3307struct StmtResult {
3308 /// The APValue that should be filled in with the returned value.
3309 APValue &Value;
3310 /// The location containing the result, if any (used to support RVO).
3311 const LValue *Slot;
3312};
3313
3314static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003315 const Stmt *S,
3316 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003317
3318/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003319static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003320 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003321 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003322 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003323 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003324 case ESR_Break:
3325 return ESR_Succeeded;
3326 case ESR_Succeeded:
3327 case ESR_Continue:
3328 return ESR_Continue;
3329 case ESR_Failed:
3330 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003331 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003332 return ESR;
3333 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003334 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003335}
3336
Richard Smith496ddcf2013-05-12 17:32:42 +00003337/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003338static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003339 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003340 BlockScopeRAII Scope(Info);
3341
Richard Smith496ddcf2013-05-12 17:32:42 +00003342 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003343 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003344 {
3345 FullExpressionRAII Scope(Info);
3346 if (SS->getConditionVariable() &&
3347 !EvaluateDecl(Info, SS->getConditionVariable()))
3348 return ESR_Failed;
3349 if (!EvaluateInteger(SS->getCond(), Value, Info))
3350 return ESR_Failed;
3351 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003352
3353 // Find the switch case corresponding to the value of the condition.
3354 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003355 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003356 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3357 SC = SC->getNextSwitchCase()) {
3358 if (isa<DefaultStmt>(SC)) {
3359 Found = SC;
3360 continue;
3361 }
3362
3363 const CaseStmt *CS = cast<CaseStmt>(SC);
3364 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3365 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3366 : LHS;
3367 if (LHS <= Value && Value <= RHS) {
3368 Found = SC;
3369 break;
3370 }
3371 }
3372
3373 if (!Found)
3374 return ESR_Succeeded;
3375
3376 // Search the switch body for the switch case and evaluate it from there.
3377 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3378 case ESR_Break:
3379 return ESR_Succeeded;
3380 case ESR_Succeeded:
3381 case ESR_Continue:
3382 case ESR_Failed:
3383 case ESR_Returned:
3384 return ESR;
3385 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003386 // This can only happen if the switch case is nested within a statement
3387 // expression. We have no intention of supporting that.
3388 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3389 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003390 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003391 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003392}
3393
Richard Smith254a73d2011-10-28 22:34:42 +00003394// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003395static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003396 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003397 if (!Info.nextStep(S))
3398 return ESR_Failed;
3399
Richard Smith496ddcf2013-05-12 17:32:42 +00003400 // If we're hunting down a 'case' or 'default' label, recurse through
3401 // substatements until we hit the label.
3402 if (Case) {
3403 // FIXME: We don't start the lifetime of objects whose initialization we
3404 // jump over. However, such objects must be of class type with a trivial
3405 // default constructor that initialize all subobjects, so must be empty,
3406 // so this almost never matters.
3407 switch (S->getStmtClass()) {
3408 case Stmt::CompoundStmtClass:
3409 // FIXME: Precompute which substatement of a compound statement we
3410 // would jump to, and go straight there rather than performing a
3411 // linear scan each time.
3412 case Stmt::LabelStmtClass:
3413 case Stmt::AttributedStmtClass:
3414 case Stmt::DoStmtClass:
3415 break;
3416
3417 case Stmt::CaseStmtClass:
3418 case Stmt::DefaultStmtClass:
3419 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003420 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003421 break;
3422
3423 case Stmt::IfStmtClass: {
3424 // FIXME: Precompute which side of an 'if' we would jump to, and go
3425 // straight there rather than scanning both sides.
3426 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003427
3428 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3429 // preceded by our switch label.
3430 BlockScopeRAII Scope(Info);
3431
Richard Smith496ddcf2013-05-12 17:32:42 +00003432 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3433 if (ESR != ESR_CaseNotFound || !IS->getElse())
3434 return ESR;
3435 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3436 }
3437
3438 case Stmt::WhileStmtClass: {
3439 EvalStmtResult ESR =
3440 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3441 if (ESR != ESR_Continue)
3442 return ESR;
3443 break;
3444 }
3445
3446 case Stmt::ForStmtClass: {
3447 const ForStmt *FS = cast<ForStmt>(S);
3448 EvalStmtResult ESR =
3449 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3450 if (ESR != ESR_Continue)
3451 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003452 if (FS->getInc()) {
3453 FullExpressionRAII IncScope(Info);
3454 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3455 return ESR_Failed;
3456 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003457 break;
3458 }
3459
3460 case Stmt::DeclStmtClass:
3461 // FIXME: If the variable has initialization that can't be jumped over,
3462 // bail out of any immediately-surrounding compound-statement too.
3463 default:
3464 return ESR_CaseNotFound;
3465 }
3466 }
3467
Richard Smith254a73d2011-10-28 22:34:42 +00003468 switch (S->getStmtClass()) {
3469 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003470 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003471 // Don't bother evaluating beyond an expression-statement which couldn't
3472 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003473 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003474 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003475 return ESR_Failed;
3476 return ESR_Succeeded;
3477 }
3478
3479 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003480 return ESR_Failed;
3481
3482 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003483 return ESR_Succeeded;
3484
Richard Smithd9f663b2013-04-22 15:31:51 +00003485 case Stmt::DeclStmtClass: {
3486 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003487 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003488 // Each declaration initialization is its own full-expression.
3489 // FIXME: This isn't quite right; if we're performing aggregate
3490 // initialization, each braced subexpression is its own full-expression.
3491 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003492 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003493 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003494 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003495 return ESR_Succeeded;
3496 }
3497
Richard Smith357362d2011-12-13 06:39:58 +00003498 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003499 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003500 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003501 if (RetExpr &&
3502 !(Result.Slot
3503 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3504 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003505 return ESR_Failed;
3506 return ESR_Returned;
3507 }
Richard Smith254a73d2011-10-28 22:34:42 +00003508
3509 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003510 BlockScopeRAII Scope(Info);
3511
Richard Smith254a73d2011-10-28 22:34:42 +00003512 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003513 for (const auto *BI : CS->body()) {
3514 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003515 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003516 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003517 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003518 return ESR;
3519 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003520 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003521 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003522
3523 case Stmt::IfStmtClass: {
3524 const IfStmt *IS = cast<IfStmt>(S);
3525
3526 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003527 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003528 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003529 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003530 return ESR_Failed;
3531
3532 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3533 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3534 if (ESR != ESR_Succeeded)
3535 return ESR;
3536 }
3537 return ESR_Succeeded;
3538 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003539
3540 case Stmt::WhileStmtClass: {
3541 const WhileStmt *WS = cast<WhileStmt>(S);
3542 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003543 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003544 bool Continue;
3545 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3546 Continue))
3547 return ESR_Failed;
3548 if (!Continue)
3549 break;
3550
3551 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3552 if (ESR != ESR_Continue)
3553 return ESR;
3554 }
3555 return ESR_Succeeded;
3556 }
3557
3558 case Stmt::DoStmtClass: {
3559 const DoStmt *DS = cast<DoStmt>(S);
3560 bool Continue;
3561 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003562 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003563 if (ESR != ESR_Continue)
3564 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003565 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003566
Richard Smith08d6a2c2013-07-24 07:11:57 +00003567 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003568 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3569 return ESR_Failed;
3570 } while (Continue);
3571 return ESR_Succeeded;
3572 }
3573
3574 case Stmt::ForStmtClass: {
3575 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003576 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003577 if (FS->getInit()) {
3578 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3579 if (ESR != ESR_Succeeded)
3580 return ESR;
3581 }
3582 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003583 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003584 bool Continue = true;
3585 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3586 FS->getCond(), Continue))
3587 return ESR_Failed;
3588 if (!Continue)
3589 break;
3590
3591 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3592 if (ESR != ESR_Continue)
3593 return ESR;
3594
Richard Smith08d6a2c2013-07-24 07:11:57 +00003595 if (FS->getInc()) {
3596 FullExpressionRAII IncScope(Info);
3597 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3598 return ESR_Failed;
3599 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003600 }
3601 return ESR_Succeeded;
3602 }
3603
Richard Smith896e0d72013-05-06 06:51:17 +00003604 case Stmt::CXXForRangeStmtClass: {
3605 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003606 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003607
3608 // Initialize the __range variable.
3609 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3610 if (ESR != ESR_Succeeded)
3611 return ESR;
3612
3613 // Create the __begin and __end iterators.
3614 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3615 if (ESR != ESR_Succeeded)
3616 return ESR;
3617
3618 while (true) {
3619 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003620 {
3621 bool Continue = true;
3622 FullExpressionRAII CondExpr(Info);
3623 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3624 return ESR_Failed;
3625 if (!Continue)
3626 break;
3627 }
Richard Smith896e0d72013-05-06 06:51:17 +00003628
3629 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003630 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003631 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3632 if (ESR != ESR_Succeeded)
3633 return ESR;
3634
3635 // Loop body.
3636 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3637 if (ESR != ESR_Continue)
3638 return ESR;
3639
3640 // Increment: ++__begin
3641 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3642 return ESR_Failed;
3643 }
3644
3645 return ESR_Succeeded;
3646 }
3647
Richard Smith496ddcf2013-05-12 17:32:42 +00003648 case Stmt::SwitchStmtClass:
3649 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3650
Richard Smith4e18ca52013-05-06 05:56:11 +00003651 case Stmt::ContinueStmtClass:
3652 return ESR_Continue;
3653
3654 case Stmt::BreakStmtClass:
3655 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003656
3657 case Stmt::LabelStmtClass:
3658 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3659
3660 case Stmt::AttributedStmtClass:
3661 // As a general principle, C++11 attributes can be ignored without
3662 // any semantic impact.
3663 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3664 Case);
3665
3666 case Stmt::CaseStmtClass:
3667 case Stmt::DefaultStmtClass:
3668 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003669 }
3670}
3671
Richard Smithcc36f692011-12-22 02:22:31 +00003672/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3673/// default constructor. If so, we'll fold it whether or not it's marked as
3674/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3675/// so we need special handling.
3676static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003677 const CXXConstructorDecl *CD,
3678 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003679 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3680 return false;
3681
Richard Smith66e05fe2012-01-18 05:21:49 +00003682 // Value-initialization does not call a trivial default constructor, so such a
3683 // call is a core constant expression whether or not the constructor is
3684 // constexpr.
3685 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003686 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003687 // FIXME: If DiagDecl is an implicitly-declared special member function,
3688 // we should be much more explicit about why it's not constexpr.
3689 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3690 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3691 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003692 } else {
3693 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3694 }
3695 }
3696 return true;
3697}
3698
Richard Smith357362d2011-12-13 06:39:58 +00003699/// CheckConstexprFunction - Check that a function can be called in a constant
3700/// expression.
3701static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3702 const FunctionDecl *Declaration,
3703 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003704 // Potential constant expressions can contain calls to declared, but not yet
3705 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003706 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003707 Declaration->isConstexpr())
3708 return false;
3709
Richard Smith0838f3a2013-05-14 05:18:44 +00003710 // Bail out with no diagnostic if the function declaration itself is invalid.
3711 // We will have produced a relevant diagnostic while parsing it.
3712 if (Declaration->isInvalidDecl())
3713 return false;
3714
Richard Smith357362d2011-12-13 06:39:58 +00003715 // Can we evaluate this function call?
3716 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3717 return true;
3718
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003719 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003720 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003721 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3722 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003723 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3724 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3725 << DiagDecl;
3726 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3727 } else {
3728 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3729 }
3730 return false;
3731}
3732
Richard Smithbe6dd812014-11-19 21:27:17 +00003733/// Determine if a class has any fields that might need to be copied by a
3734/// trivial copy or move operation.
3735static bool hasFields(const CXXRecordDecl *RD) {
3736 if (!RD || RD->isEmpty())
3737 return false;
3738 for (auto *FD : RD->fields()) {
3739 if (FD->isUnnamedBitfield())
3740 continue;
3741 return true;
3742 }
3743 for (auto &Base : RD->bases())
3744 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3745 return true;
3746 return false;
3747}
3748
Richard Smithd62306a2011-11-10 06:34:14 +00003749namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003750typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003751}
3752
3753/// EvaluateArgs - Evaluate the arguments to a function call.
3754static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3755 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003756 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003757 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003758 I != E; ++I) {
3759 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3760 // If we're checking for a potential constant expression, evaluate all
3761 // initializers even if some of them fail.
3762 if (!Info.keepEvaluatingAfterFailure())
3763 return false;
3764 Success = false;
3765 }
3766 }
3767 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003768}
3769
Richard Smith254a73d2011-10-28 22:34:42 +00003770/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003771static bool HandleFunctionCall(SourceLocation CallLoc,
3772 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003773 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003774 EvalInfo &Info, APValue &Result,
3775 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003776 ArgVector ArgValues(Args.size());
3777 if (!EvaluateArgs(Args, ArgValues, Info))
3778 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003779
Richard Smith253c2a32012-01-27 01:14:48 +00003780 if (!Info.CheckCallLimit(CallLoc))
3781 return false;
3782
3783 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003784
3785 // For a trivial copy or move assignment, perform an APValue copy. This is
3786 // essential for unions, where the operations performed by the assignment
3787 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003788 //
3789 // Skip this for non-union classes with no fields; in that case, the defaulted
3790 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003791 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003792 if (MD && MD->isDefaulted() &&
3793 (MD->getParent()->isUnion() ||
3794 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003795 assert(This &&
3796 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3797 LValue RHS;
3798 RHS.setFrom(Info.Ctx, ArgValues[0]);
3799 APValue RHSValue;
3800 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3801 RHS, RHSValue))
3802 return false;
3803 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3804 RHSValue))
3805 return false;
3806 This->moveInto(Result);
3807 return true;
3808 }
3809
Richard Smith52a980a2015-08-28 02:43:42 +00003810 StmtResult Ret = {Result, ResultSlot};
3811 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003812 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003813 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003814 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003815 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003816 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003817 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003818}
3819
Richard Smithd62306a2011-11-10 06:34:14 +00003820/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003821static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003822 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003823 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003824 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003825 ArgVector ArgValues(Args.size());
3826 if (!EvaluateArgs(Args, ArgValues, Info))
3827 return false;
3828
Richard Smith253c2a32012-01-27 01:14:48 +00003829 if (!Info.CheckCallLimit(CallLoc))
3830 return false;
3831
Richard Smith3607ffe2012-02-13 03:54:03 +00003832 const CXXRecordDecl *RD = Definition->getParent();
3833 if (RD->getNumVBases()) {
3834 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3835 return false;
3836 }
3837
Richard Smith253c2a32012-01-27 01:14:48 +00003838 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003839
Richard Smith52a980a2015-08-28 02:43:42 +00003840 // FIXME: Creating an APValue just to hold a nonexistent return value is
3841 // wasteful.
3842 APValue RetVal;
3843 StmtResult Ret = {RetVal, nullptr};
3844
Richard Smithd62306a2011-11-10 06:34:14 +00003845 // If it's a delegating constructor, just delegate.
3846 if (Definition->isDelegatingConstructor()) {
3847 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003848 {
3849 FullExpressionRAII InitScope(Info);
3850 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3851 return false;
3852 }
Richard Smith52a980a2015-08-28 02:43:42 +00003853 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003854 }
3855
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003856 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003857 // essential for unions (or classes with anonymous union members), where the
3858 // operations performed by the constructor cannot be represented by
3859 // ctor-initializers.
3860 //
3861 // Skip this for empty non-union classes; we should not perform an
3862 // lvalue-to-rvalue conversion on them because their copy constructor does not
3863 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003864 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003865 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003866 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003867 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003868 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003869 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003870 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003871 }
3872
3873 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003874 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003875 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003876 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003877
John McCalld7bca762012-05-01 00:38:49 +00003878 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003879 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3880
Richard Smith08d6a2c2013-07-24 07:11:57 +00003881 // A scope for temporaries lifetime-extended by reference members.
3882 BlockScopeRAII LifetimeExtendedScope(Info);
3883
Richard Smith253c2a32012-01-27 01:14:48 +00003884 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003885 unsigned BasesSeen = 0;
3886#ifndef NDEBUG
3887 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3888#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003889 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003890 LValue Subobject = This;
3891 APValue *Value = &Result;
3892
3893 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003894 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003895 if (I->isBaseInitializer()) {
3896 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003897#ifndef NDEBUG
3898 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003899 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003900 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3901 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3902 "base class initializers not in expected order");
3903 ++BaseIt;
3904#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003905 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003906 BaseType->getAsCXXRecordDecl(), &Layout))
3907 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003908 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003909 } else if ((FD = I->getMember())) {
3910 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003911 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003912 if (RD->isUnion()) {
3913 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003914 Value = &Result.getUnionValue();
3915 } else {
3916 Value = &Result.getStructField(FD->getFieldIndex());
3917 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003918 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003919 // Walk the indirect field decl's chain to find the object to initialize,
3920 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003921 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003922 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003923 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3924 // Switch the union field if it differs. This happens if we had
3925 // preceding zero-initialization, and we're now initializing a union
3926 // subobject other than the first.
3927 // FIXME: In this case, the values of the other subobjects are
3928 // specified, since zero-initialization sets all padding bits to zero.
3929 if (Value->isUninit() ||
3930 (Value->isUnion() && Value->getUnionField() != FD)) {
3931 if (CD->isUnion())
3932 *Value = APValue(FD);
3933 else
3934 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003935 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003936 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003937 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003938 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003939 if (CD->isUnion())
3940 Value = &Value->getUnionValue();
3941 else
3942 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003943 }
Richard Smithd62306a2011-11-10 06:34:14 +00003944 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003945 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003946 }
Richard Smith253c2a32012-01-27 01:14:48 +00003947
Richard Smith08d6a2c2013-07-24 07:11:57 +00003948 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003949 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3950 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003951 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003952 // If we're checking for a potential constant expression, evaluate all
3953 // initializers even if some of them fail.
3954 if (!Info.keepEvaluatingAfterFailure())
3955 return false;
3956 Success = false;
3957 }
Richard Smithd62306a2011-11-10 06:34:14 +00003958 }
3959
Richard Smithd9f663b2013-04-22 15:31:51 +00003960 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00003961 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003962}
3963
Eli Friedman9a156e52008-11-12 09:44:48 +00003964//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003965// Generic Evaluation
3966//===----------------------------------------------------------------------===//
3967namespace {
3968
Aaron Ballman68af21c2014-01-03 19:26:43 +00003969template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003970class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003971 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003972private:
Richard Smith52a980a2015-08-28 02:43:42 +00003973 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003974 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00003975 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003976 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003977 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00003978 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003979 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003980
Richard Smith17100ba2012-02-16 02:46:34 +00003981 // Check whether a conditional operator with a non-constant condition is a
3982 // potential constant expression. If neither arm is a potential constant
3983 // expression, then the conditional operator is not either.
3984 template<typename ConditionalOperator>
3985 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003986 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003987
3988 // Speculatively evaluate both arms.
3989 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003990 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003991 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3992
3993 StmtVisitorTy::Visit(E->getFalseExpr());
3994 if (Diag.empty())
3995 return;
3996
3997 Diag.clear();
3998 StmtVisitorTy::Visit(E->getTrueExpr());
3999 if (Diag.empty())
4000 return;
4001 }
4002
4003 Error(E, diag::note_constexpr_conditional_never_const);
4004 }
4005
4006
4007 template<typename ConditionalOperator>
4008 bool HandleConditionalOperator(const ConditionalOperator *E) {
4009 bool BoolResult;
4010 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004011 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00004012 CheckPotentialConstantConditional(E);
4013 return false;
4014 }
4015
4016 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4017 return StmtVisitorTy::Visit(EvalExpr);
4018 }
4019
Peter Collingbournee9200682011-05-13 03:29:01 +00004020protected:
4021 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004022 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004023 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4024
Richard Smith92b1ce02011-12-12 09:28:41 +00004025 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004026 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004027 }
4028
Aaron Ballman68af21c2014-01-03 19:26:43 +00004029 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004030
4031public:
4032 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4033
4034 EvalInfo &getEvalInfo() { return Info; }
4035
Richard Smithf57d8cb2011-12-09 22:58:01 +00004036 /// Report an evaluation error. This should only be called when an error is
4037 /// first discovered. When propagating an error, just return false.
4038 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004039 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004040 return false;
4041 }
4042 bool Error(const Expr *E) {
4043 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4044 }
4045
Aaron Ballman68af21c2014-01-03 19:26:43 +00004046 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004047 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004048 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004049 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004050 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004051 }
4052
Aaron Ballman68af21c2014-01-03 19:26:43 +00004053 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004054 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004055 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004056 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004057 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004058 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004059 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004060 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004061 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004062 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004063 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004064 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004065 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004066 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004067 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004068 // The initializer may not have been parsed yet, or might be erroneous.
4069 if (!E->getExpr())
4070 return Error(E);
4071 return StmtVisitorTy::Visit(E->getExpr());
4072 }
Richard Smith5894a912011-12-19 22:12:41 +00004073 // We cannot create any objects for which cleanups are required, so there is
4074 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004075 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004076 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004077
Aaron Ballman68af21c2014-01-03 19:26:43 +00004078 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004079 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4080 return static_cast<Derived*>(this)->VisitCastExpr(E);
4081 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004082 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004083 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4084 return static_cast<Derived*>(this)->VisitCastExpr(E);
4085 }
4086
Aaron Ballman68af21c2014-01-03 19:26:43 +00004087 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004088 switch (E->getOpcode()) {
4089 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004090 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004091
4092 case BO_Comma:
4093 VisitIgnoredValue(E->getLHS());
4094 return StmtVisitorTy::Visit(E->getRHS());
4095
4096 case BO_PtrMemD:
4097 case BO_PtrMemI: {
4098 LValue Obj;
4099 if (!HandleMemberPointerAccess(Info, E, Obj))
4100 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004101 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004102 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004103 return false;
4104 return DerivedSuccess(Result, E);
4105 }
4106 }
4107 }
4108
Aaron Ballman68af21c2014-01-03 19:26:43 +00004109 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004110 // Evaluate and cache the common expression. We treat it as a temporary,
4111 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004112 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004113 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004114 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004115
Richard Smith17100ba2012-02-16 02:46:34 +00004116 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004117 }
4118
Aaron Ballman68af21c2014-01-03 19:26:43 +00004119 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004120 bool IsBcpCall = false;
4121 // If the condition (ignoring parens) is a __builtin_constant_p call,
4122 // the result is a constant expression if it can be folded without
4123 // side-effects. This is an important GNU extension. See GCC PR38377
4124 // for discussion.
4125 if (const CallExpr *CallCE =
4126 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004127 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004128 IsBcpCall = true;
4129
4130 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4131 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004132 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004133 return false;
4134
Richard Smith6d4c6582013-11-05 22:18:15 +00004135 FoldConstant Fold(Info, IsBcpCall);
4136 if (!HandleConditionalOperator(E)) {
4137 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004138 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004139 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004140
4141 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004142 }
4143
Aaron Ballman68af21c2014-01-03 19:26:43 +00004144 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004145 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4146 return DerivedSuccess(*Value, E);
4147
4148 const Expr *Source = E->getSourceExpr();
4149 if (!Source)
4150 return Error(E);
4151 if (Source == E) { // sanity checking.
4152 assert(0 && "OpaqueValueExpr recursively refers to itself");
4153 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004154 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004155 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004156 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004157
Aaron Ballman68af21c2014-01-03 19:26:43 +00004158 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004159 APValue Result;
4160 if (!handleCallExpr(E, Result, nullptr))
4161 return false;
4162 return DerivedSuccess(Result, E);
4163 }
4164
4165 bool handleCallExpr(const CallExpr *E, APValue &Result,
4166 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004167 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004168 QualType CalleeType = Callee->getType();
4169
Craig Topper36250ad2014-05-12 05:36:57 +00004170 const FunctionDecl *FD = nullptr;
4171 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004172 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004173 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004174
Richard Smithe97cbd72011-11-11 04:05:33 +00004175 // Extract function decl and 'this' pointer from the callee.
4176 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004177 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004178 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4179 // Explicit bound member calls, such as x.f() or p->g();
4180 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004181 return false;
4182 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004183 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004184 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004185 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4186 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004187 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4188 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004189 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004190 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004191 return Error(Callee);
4192
4193 FD = dyn_cast<FunctionDecl>(Member);
4194 if (!FD)
4195 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004196 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004197 LValue Call;
4198 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004199 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004200
Richard Smitha8105bc2012-01-06 16:39:00 +00004201 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004202 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004203 FD = dyn_cast_or_null<FunctionDecl>(
4204 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004205 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004206 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004207
4208 // Overloaded operator calls to member functions are represented as normal
4209 // calls with '*this' as the first argument.
4210 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4211 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004212 // FIXME: When selecting an implicit conversion for an overloaded
4213 // operator delete, we sometimes try to evaluate calls to conversion
4214 // operators without a 'this' parameter!
4215 if (Args.empty())
4216 return Error(E);
4217
Richard Smithe97cbd72011-11-11 04:05:33 +00004218 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4219 return false;
4220 This = &ThisVal;
4221 Args = Args.slice(1);
4222 }
4223
4224 // Don't call function pointers which have been cast to some other type.
4225 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004226 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004227 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004228 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004229
Richard Smith47b34932012-02-01 02:39:43 +00004230 if (This && !This->checkSubobject(Info, E, CSK_This))
4231 return false;
4232
Richard Smith3607ffe2012-02-13 03:54:03 +00004233 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4234 // calls to such functions in constant expressions.
4235 if (This && !HasQualifier &&
4236 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4237 return Error(E, diag::note_constexpr_virtual_call);
4238
Craig Topper36250ad2014-05-12 05:36:57 +00004239 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004240 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004241
Richard Smith357362d2011-12-13 06:39:58 +00004242 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004243 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4244 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004245 return false;
4246
Richard Smith52a980a2015-08-28 02:43:42 +00004247 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004248 }
4249
Aaron Ballman68af21c2014-01-03 19:26:43 +00004250 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004251 return StmtVisitorTy::Visit(E->getInitializer());
4252 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004253 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004254 if (E->getNumInits() == 0)
4255 return DerivedZeroInitialization(E);
4256 if (E->getNumInits() == 1)
4257 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004258 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004259 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004260 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004261 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004262 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004263 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004264 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004265 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004266 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004267 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004268 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004269
Richard Smithd62306a2011-11-10 06:34:14 +00004270 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004271 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004272 assert(!E->isArrow() && "missing call to bound member function?");
4273
Richard Smith2e312c82012-03-03 22:46:17 +00004274 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004275 if (!Evaluate(Val, Info, E->getBase()))
4276 return false;
4277
4278 QualType BaseTy = E->getBase()->getType();
4279
4280 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004281 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004282 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004283 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004284 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4285
Richard Smith3229b742013-05-05 21:17:10 +00004286 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004287 SubobjectDesignator Designator(BaseTy);
4288 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004289
Richard Smith3229b742013-05-05 21:17:10 +00004290 APValue Result;
4291 return extractSubobject(Info, E, Obj, Designator, Result) &&
4292 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004293 }
4294
Aaron Ballman68af21c2014-01-03 19:26:43 +00004295 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004296 switch (E->getCastKind()) {
4297 default:
4298 break;
4299
Richard Smitha23ab512013-05-23 00:30:41 +00004300 case CK_AtomicToNonAtomic: {
4301 APValue AtomicVal;
4302 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4303 return false;
4304 return DerivedSuccess(AtomicVal, E);
4305 }
4306
Richard Smith11562c52011-10-28 17:51:58 +00004307 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004308 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004309 return StmtVisitorTy::Visit(E->getSubExpr());
4310
4311 case CK_LValueToRValue: {
4312 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004313 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4314 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004315 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004316 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004317 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004318 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004319 return false;
4320 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004321 }
4322 }
4323
Richard Smithf57d8cb2011-12-09 22:58:01 +00004324 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004325 }
4326
Aaron Ballman68af21c2014-01-03 19:26:43 +00004327 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004328 return VisitUnaryPostIncDec(UO);
4329 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004330 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004331 return VisitUnaryPostIncDec(UO);
4332 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004333 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004334 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004335 return Error(UO);
4336
4337 LValue LVal;
4338 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4339 return false;
4340 APValue RVal;
4341 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4342 UO->isIncrementOp(), &RVal))
4343 return false;
4344 return DerivedSuccess(RVal, UO);
4345 }
4346
Aaron Ballman68af21c2014-01-03 19:26:43 +00004347 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004348 // We will have checked the full-expressions inside the statement expression
4349 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004350 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004351 return Error(E);
4352
Richard Smith08d6a2c2013-07-24 07:11:57 +00004353 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004354 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004355 if (CS->body_empty())
4356 return true;
4357
Richard Smith51f03172013-06-20 03:00:05 +00004358 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4359 BE = CS->body_end();
4360 /**/; ++BI) {
4361 if (BI + 1 == BE) {
4362 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4363 if (!FinalExpr) {
4364 Info.Diag((*BI)->getLocStart(),
4365 diag::note_constexpr_stmt_expr_unsupported);
4366 return false;
4367 }
4368 return this->Visit(FinalExpr);
4369 }
4370
4371 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004372 StmtResult Result = { ReturnValue, nullptr };
4373 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004374 if (ESR != ESR_Succeeded) {
4375 // FIXME: If the statement-expression terminated due to 'return',
4376 // 'break', or 'continue', it would be nice to propagate that to
4377 // the outer statement evaluation rather than bailing out.
4378 if (ESR != ESR_Failed)
4379 Info.Diag((*BI)->getLocStart(),
4380 diag::note_constexpr_stmt_expr_unsupported);
4381 return false;
4382 }
4383 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004384
4385 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004386 }
4387
Richard Smith4a678122011-10-24 18:44:57 +00004388 /// Visit a value which is evaluated, but whose value is ignored.
4389 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004390 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004391 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004392};
4393
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004394}
Peter Collingbournee9200682011-05-13 03:29:01 +00004395
4396//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004397// Common base class for lvalue and temporary evaluation.
4398//===----------------------------------------------------------------------===//
4399namespace {
4400template<class Derived>
4401class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004402 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004403protected:
4404 LValue &Result;
4405 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004406 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004407
4408 bool Success(APValue::LValueBase B) {
4409 Result.set(B);
4410 return true;
4411 }
4412
4413public:
4414 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4415 ExprEvaluatorBaseTy(Info), Result(Result) {}
4416
Richard Smith2e312c82012-03-03 22:46:17 +00004417 bool Success(const APValue &V, const Expr *E) {
4418 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004419 return true;
4420 }
Richard Smith027bf112011-11-17 22:56:20 +00004421
Richard Smith027bf112011-11-17 22:56:20 +00004422 bool VisitMemberExpr(const MemberExpr *E) {
4423 // Handle non-static data members.
4424 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004425 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004426 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004427 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004428 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004429 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004430 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004431 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004432 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004433 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004434 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004435 BaseTy = E->getBase()->getType();
4436 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004437 if (!EvalOK) {
4438 if (!this->Info.allowInvalidBaseExpr())
4439 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004440 Result.setInvalid(E);
4441 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004442 }
Richard Smith027bf112011-11-17 22:56:20 +00004443
Richard Smith1b78b3d2012-01-25 22:15:11 +00004444 const ValueDecl *MD = E->getMemberDecl();
4445 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4446 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4447 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4448 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004449 if (!HandleLValueMember(this->Info, E, Result, FD))
4450 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004451 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004452 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4453 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004454 } else
4455 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004456
Richard Smith1b78b3d2012-01-25 22:15:11 +00004457 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004458 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004459 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004460 RefValue))
4461 return false;
4462 return Success(RefValue, E);
4463 }
4464 return true;
4465 }
4466
4467 bool VisitBinaryOperator(const BinaryOperator *E) {
4468 switch (E->getOpcode()) {
4469 default:
4470 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4471
4472 case BO_PtrMemD:
4473 case BO_PtrMemI:
4474 return HandleMemberPointerAccess(this->Info, E, Result);
4475 }
4476 }
4477
4478 bool VisitCastExpr(const CastExpr *E) {
4479 switch (E->getCastKind()) {
4480 default:
4481 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4482
4483 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004484 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004485 if (!this->Visit(E->getSubExpr()))
4486 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004487
4488 // Now figure out the necessary offset to add to the base LV to get from
4489 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004490 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4491 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004492 }
4493 }
4494};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004495}
Richard Smith027bf112011-11-17 22:56:20 +00004496
4497//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004498// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004499//
4500// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4501// function designators (in C), decl references to void objects (in C), and
4502// temporaries (if building with -Wno-address-of-temporary).
4503//
4504// LValue evaluation produces values comprising a base expression of one of the
4505// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004506// - Declarations
4507// * VarDecl
4508// * FunctionDecl
4509// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004510// * CompoundLiteralExpr in C
4511// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004512// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004513// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004514// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004515// * ObjCEncodeExpr
4516// * AddrLabelExpr
4517// * BlockExpr
4518// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004519// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004520// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004521// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004522// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4523// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004524// * A MaterializeTemporaryExpr that has static storage duration, with no
4525// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004526// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004527//===----------------------------------------------------------------------===//
4528namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004529class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004530 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004531public:
Richard Smith027bf112011-11-17 22:56:20 +00004532 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4533 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004534
Richard Smith11562c52011-10-28 17:51:58 +00004535 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004536 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004537
Peter Collingbournee9200682011-05-13 03:29:01 +00004538 bool VisitDeclRefExpr(const DeclRefExpr *E);
4539 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004540 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004541 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4542 bool VisitMemberExpr(const MemberExpr *E);
4543 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4544 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004545 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004546 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004547 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4548 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004549 bool VisitUnaryReal(const UnaryOperator *E);
4550 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004551 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4552 return VisitUnaryPreIncDec(UO);
4553 }
4554 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4555 return VisitUnaryPreIncDec(UO);
4556 }
Richard Smith3229b742013-05-05 21:17:10 +00004557 bool VisitBinAssign(const BinaryOperator *BO);
4558 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004559
Peter Collingbournee9200682011-05-13 03:29:01 +00004560 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004561 switch (E->getCastKind()) {
4562 default:
Richard Smith027bf112011-11-17 22:56:20 +00004563 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004564
Eli Friedmance3e02a2011-10-11 00:13:24 +00004565 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004566 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004567 if (!Visit(E->getSubExpr()))
4568 return false;
4569 Result.Designator.setInvalid();
4570 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004571
Richard Smith027bf112011-11-17 22:56:20 +00004572 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004573 if (!Visit(E->getSubExpr()))
4574 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004575 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004576 }
4577 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004578};
4579} // end anonymous namespace
4580
Richard Smith11562c52011-10-28 17:51:58 +00004581/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004582/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004583/// * function designators in C, and
4584/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004585/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004586static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4587 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004588 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004589 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004590}
4591
Peter Collingbournee9200682011-05-13 03:29:01 +00004592bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004593 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004594 return Success(FD);
4595 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004596 return VisitVarDecl(E, VD);
4597 return Error(E);
4598}
Richard Smith733237d2011-10-24 23:14:33 +00004599
Richard Smith11562c52011-10-28 17:51:58 +00004600bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004601 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004602 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4603 Frame = Info.CurrentCall;
4604
Richard Smithfec09922011-11-01 16:57:24 +00004605 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004606 if (Frame) {
4607 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004608 return true;
4609 }
Richard Smithce40ad62011-11-12 22:28:03 +00004610 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004611 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004612
Richard Smith3229b742013-05-05 21:17:10 +00004613 APValue *V;
4614 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004615 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004616 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004617 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004618 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4619 return false;
4620 }
Richard Smith3229b742013-05-05 21:17:10 +00004621 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004622}
4623
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004624bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4625 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004626 // Walk through the expression to find the materialized temporary itself.
4627 SmallVector<const Expr *, 2> CommaLHSs;
4628 SmallVector<SubobjectAdjustment, 2> Adjustments;
4629 const Expr *Inner = E->GetTemporaryExpr()->
4630 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004631
Richard Smith84401042013-06-03 05:03:02 +00004632 // If we passed any comma operators, evaluate their LHSs.
4633 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4634 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4635 return false;
4636
Richard Smithe6c01442013-06-05 00:46:14 +00004637 // A materialized temporary with static storage duration can appear within the
4638 // result of a constant expression evaluation, so we need to preserve its
4639 // value for use outside this evaluation.
4640 APValue *Value;
4641 if (E->getStorageDuration() == SD_Static) {
4642 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004643 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004644 Result.set(E);
4645 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004646 Value = &Info.CurrentCall->
4647 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004648 Result.set(E, Info.CurrentCall->Index);
4649 }
4650
Richard Smithea4ad5d2013-06-06 08:19:16 +00004651 QualType Type = Inner->getType();
4652
Richard Smith84401042013-06-03 05:03:02 +00004653 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004654 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4655 (E->getStorageDuration() == SD_Static &&
4656 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4657 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004658 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004659 }
Richard Smith84401042013-06-03 05:03:02 +00004660
4661 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004662 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4663 --I;
4664 switch (Adjustments[I].Kind) {
4665 case SubobjectAdjustment::DerivedToBaseAdjustment:
4666 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4667 Type, Result))
4668 return false;
4669 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4670 break;
4671
4672 case SubobjectAdjustment::FieldAdjustment:
4673 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4674 return false;
4675 Type = Adjustments[I].Field->getType();
4676 break;
4677
4678 case SubobjectAdjustment::MemberPointerAdjustment:
4679 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4680 Adjustments[I].Ptr.RHS))
4681 return false;
4682 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4683 break;
4684 }
4685 }
4686
4687 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004688}
4689
Peter Collingbournee9200682011-05-13 03:29:01 +00004690bool
4691LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004692 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4693 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4694 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004695 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004696}
4697
Richard Smith6e525142011-12-27 12:18:28 +00004698bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004699 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004700 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004701
4702 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4703 << E->getExprOperand()->getType()
4704 << E->getExprOperand()->getSourceRange();
4705 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004706}
4707
Francois Pichet0066db92012-04-16 04:08:35 +00004708bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4709 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004710}
Francois Pichet0066db92012-04-16 04:08:35 +00004711
Peter Collingbournee9200682011-05-13 03:29:01 +00004712bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004713 // Handle static data members.
4714 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4715 VisitIgnoredValue(E->getBase());
4716 return VisitVarDecl(E, VD);
4717 }
4718
Richard Smith254a73d2011-10-28 22:34:42 +00004719 // Handle static member functions.
4720 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4721 if (MD->isStatic()) {
4722 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004723 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004724 }
4725 }
4726
Richard Smithd62306a2011-11-10 06:34:14 +00004727 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004728 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004729}
4730
Peter Collingbournee9200682011-05-13 03:29:01 +00004731bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004732 // FIXME: Deal with vectors as array subscript bases.
4733 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004734 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004735
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004736 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004737 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004738
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004739 APSInt Index;
4740 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004741 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004742
Richard Smith861b5b52013-05-07 23:34:45 +00004743 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4744 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004745}
Eli Friedman9a156e52008-11-12 09:44:48 +00004746
Peter Collingbournee9200682011-05-13 03:29:01 +00004747bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004748 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004749}
4750
Richard Smith66c96992012-02-18 22:04:06 +00004751bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4752 if (!Visit(E->getSubExpr()))
4753 return false;
4754 // __real is a no-op on scalar lvalues.
4755 if (E->getSubExpr()->getType()->isAnyComplexType())
4756 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4757 return true;
4758}
4759
4760bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4761 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4762 "lvalue __imag__ on scalar?");
4763 if (!Visit(E->getSubExpr()))
4764 return false;
4765 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4766 return true;
4767}
4768
Richard Smith243ef902013-05-05 23:31:59 +00004769bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004770 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004771 return Error(UO);
4772
4773 if (!this->Visit(UO->getSubExpr()))
4774 return false;
4775
Richard Smith243ef902013-05-05 23:31:59 +00004776 return handleIncDec(
4777 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004778 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004779}
4780
4781bool LValueExprEvaluator::VisitCompoundAssignOperator(
4782 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004783 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004784 return Error(CAO);
4785
Richard Smith3229b742013-05-05 21:17:10 +00004786 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004787
4788 // The overall lvalue result is the result of evaluating the LHS.
4789 if (!this->Visit(CAO->getLHS())) {
4790 if (Info.keepEvaluatingAfterFailure())
4791 Evaluate(RHS, this->Info, CAO->getRHS());
4792 return false;
4793 }
4794
Richard Smith3229b742013-05-05 21:17:10 +00004795 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4796 return false;
4797
Richard Smith43e77732013-05-07 04:50:00 +00004798 return handleCompoundAssignment(
4799 this->Info, CAO,
4800 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4801 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004802}
4803
4804bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004805 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004806 return Error(E);
4807
Richard Smith3229b742013-05-05 21:17:10 +00004808 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004809
4810 if (!this->Visit(E->getLHS())) {
4811 if (Info.keepEvaluatingAfterFailure())
4812 Evaluate(NewVal, this->Info, E->getRHS());
4813 return false;
4814 }
4815
Richard Smith3229b742013-05-05 21:17:10 +00004816 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4817 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004818
4819 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004820 NewVal);
4821}
4822
Eli Friedman9a156e52008-11-12 09:44:48 +00004823//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004824// Pointer Evaluation
4825//===----------------------------------------------------------------------===//
4826
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004827namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004828class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004829 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004830 LValue &Result;
4831
Peter Collingbournee9200682011-05-13 03:29:01 +00004832 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004833 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004834 return true;
4835 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004836public:
Mike Stump11289f42009-09-09 15:08:12 +00004837
John McCall45d55e42010-05-07 21:00:08 +00004838 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004839 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004840
Richard Smith2e312c82012-03-03 22:46:17 +00004841 bool Success(const APValue &V, const Expr *E) {
4842 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004843 return true;
4844 }
Richard Smithfddd3842011-12-30 21:15:51 +00004845 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004846 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004847 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004848
John McCall45d55e42010-05-07 21:00:08 +00004849 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004850 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004851 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004852 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004853 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004854 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004855 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004856 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004857 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004858 bool VisitCallExpr(const CallExpr *E);
4859 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004860 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004861 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004862 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004863 }
Richard Smithd62306a2011-11-10 06:34:14 +00004864 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004865 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004866 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004867 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004868 if (!Info.CurrentCall->This) {
4869 if (Info.getLangOpts().CPlusPlus11)
4870 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4871 else
4872 Info.Diag(E);
4873 return false;
4874 }
Richard Smithd62306a2011-11-10 06:34:14 +00004875 Result = *Info.CurrentCall->This;
4876 return true;
4877 }
John McCallc07a0c72011-02-17 10:25:35 +00004878
Eli Friedman449fe542009-03-23 04:56:01 +00004879 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004880};
Chris Lattner05706e882008-07-11 18:11:29 +00004881} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004882
John McCall45d55e42010-05-07 21:00:08 +00004883static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004884 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004885 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004886}
4887
John McCall45d55e42010-05-07 21:00:08 +00004888bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004889 if (E->getOpcode() != BO_Add &&
4890 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004891 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004892
Chris Lattner05706e882008-07-11 18:11:29 +00004893 const Expr *PExp = E->getLHS();
4894 const Expr *IExp = E->getRHS();
4895 if (IExp->getType()->isPointerType())
4896 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004897
Richard Smith253c2a32012-01-27 01:14:48 +00004898 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4899 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004900 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004901
John McCall45d55e42010-05-07 21:00:08 +00004902 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004903 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004904 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004905
4906 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004907 if (E->getOpcode() == BO_Sub)
4908 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004909
Ted Kremenek28831752012-08-23 20:46:57 +00004910 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004911 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4912 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004913}
Eli Friedman9a156e52008-11-12 09:44:48 +00004914
John McCall45d55e42010-05-07 21:00:08 +00004915bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4916 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004917}
Mike Stump11289f42009-09-09 15:08:12 +00004918
Peter Collingbournee9200682011-05-13 03:29:01 +00004919bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4920 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004921
Eli Friedman847a2bc2009-12-27 05:43:15 +00004922 switch (E->getCastKind()) {
4923 default:
4924 break;
4925
John McCalle3027922010-08-25 11:45:40 +00004926 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004927 case CK_CPointerToObjCPointerCast:
4928 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004929 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00004930 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004931 if (!Visit(SubExpr))
4932 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004933 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4934 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4935 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004936 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004937 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004938 if (SubExpr->getType()->isVoidPointerType())
4939 CCEDiag(E, diag::note_constexpr_invalid_cast)
4940 << 3 << SubExpr->getType();
4941 else
4942 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4943 }
Richard Smith96e0c102011-11-04 02:25:55 +00004944 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004945
Anders Carlsson18275092010-10-31 20:41:46 +00004946 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004947 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004948 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004949 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004950 if (!Result.Base && Result.Offset.isZero())
4951 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004952
Richard Smithd62306a2011-11-10 06:34:14 +00004953 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004954 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004955 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4956 castAs<PointerType>()->getPointeeType(),
4957 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004958
Richard Smith027bf112011-11-17 22:56:20 +00004959 case CK_BaseToDerived:
4960 if (!Visit(E->getSubExpr()))
4961 return false;
4962 if (!Result.Base && Result.Offset.isZero())
4963 return true;
4964 return HandleBaseToDerivedCast(Info, E, Result);
4965
Richard Smith0b0a0b62011-10-29 20:57:55 +00004966 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004967 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004968 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004969
John McCalle3027922010-08-25 11:45:40 +00004970 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004971 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4972
Richard Smith2e312c82012-03-03 22:46:17 +00004973 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004974 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004975 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004976
John McCall45d55e42010-05-07 21:00:08 +00004977 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004978 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4979 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004980 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004981 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004982 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004983 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004984 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004985 return true;
4986 } else {
4987 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004988 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004989 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004990 }
4991 }
John McCalle3027922010-08-25 11:45:40 +00004992 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004993 if (SubExpr->isGLValue()) {
4994 if (!EvaluateLValue(SubExpr, Result, Info))
4995 return false;
4996 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004997 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004998 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004999 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005000 return false;
5001 }
Richard Smith96e0c102011-11-04 02:25:55 +00005002 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005003 if (const ConstantArrayType *CAT
5004 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5005 Result.addArray(Info, E, CAT);
5006 else
5007 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005008 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005009
John McCalle3027922010-08-25 11:45:40 +00005010 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005011 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005012 }
5013
Richard Smith11562c52011-10-28 17:51:58 +00005014 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005015}
Chris Lattner05706e882008-07-11 18:11:29 +00005016
Hal Finkel0dd05d42014-10-03 17:18:37 +00005017static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5018 // C++ [expr.alignof]p3:
5019 // When alignof is applied to a reference type, the result is the
5020 // alignment of the referenced type.
5021 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5022 T = Ref->getPointeeType();
5023
5024 // __alignof is defined to return the preferred alignment.
5025 return Info.Ctx.toCharUnitsFromBits(
5026 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5027}
5028
5029static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5030 E = E->IgnoreParens();
5031
5032 // The kinds of expressions that we have special-case logic here for
5033 // should be kept up to date with the special checks for those
5034 // expressions in Sema.
5035
5036 // alignof decl is always accepted, even if it doesn't make sense: we default
5037 // to 1 in those cases.
5038 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5039 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5040 /*RefAsPointee*/true);
5041
5042 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5043 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5044 /*RefAsPointee*/true);
5045
5046 return GetAlignOfType(Info, E->getType());
5047}
5048
Peter Collingbournee9200682011-05-13 03:29:01 +00005049bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005050 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005051 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005052
Alp Tokera724cff2013-12-28 21:59:02 +00005053 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005054 case Builtin::BI__builtin_addressof:
5055 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005056 case Builtin::BI__builtin_assume_aligned: {
5057 // We need to be very careful here because: if the pointer does not have the
5058 // asserted alignment, then the behavior is undefined, and undefined
5059 // behavior is non-constant.
5060 if (!EvaluatePointer(E->getArg(0), Result, Info))
5061 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005062
Hal Finkel0dd05d42014-10-03 17:18:37 +00005063 LValue OffsetResult(Result);
5064 APSInt Alignment;
5065 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5066 return false;
5067 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5068
5069 if (E->getNumArgs() > 2) {
5070 APSInt Offset;
5071 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5072 return false;
5073
5074 int64_t AdditionalOffset = -getExtValue(Offset);
5075 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5076 }
5077
5078 // If there is a base object, then it must have the correct alignment.
5079 if (OffsetResult.Base) {
5080 CharUnits BaseAlignment;
5081 if (const ValueDecl *VD =
5082 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5083 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5084 } else {
5085 BaseAlignment =
5086 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5087 }
5088
5089 if (BaseAlignment < Align) {
5090 Result.Designator.setInvalid();
5091 // FIXME: Quantities here cast to integers because the plural modifier
5092 // does not work on APSInts yet.
5093 CCEDiag(E->getArg(0),
5094 diag::note_constexpr_baa_insufficient_alignment) << 0
5095 << (int) BaseAlignment.getQuantity()
5096 << (unsigned) getExtValue(Alignment);
5097 return false;
5098 }
5099 }
5100
5101 // The offset must also have the correct alignment.
5102 if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5103 Result.Designator.setInvalid();
5104 APSInt Offset(64, false);
5105 Offset = OffsetResult.Offset.getQuantity();
5106
5107 if (OffsetResult.Base)
5108 CCEDiag(E->getArg(0),
5109 diag::note_constexpr_baa_insufficient_alignment) << 1
5110 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5111 else
5112 CCEDiag(E->getArg(0),
5113 diag::note_constexpr_baa_value_insufficient_alignment)
5114 << Offset << (unsigned) getExtValue(Alignment);
5115
5116 return false;
5117 }
5118
5119 return true;
5120 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005121 default:
5122 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5123 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005124}
Chris Lattner05706e882008-07-11 18:11:29 +00005125
5126//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005127// Member Pointer Evaluation
5128//===----------------------------------------------------------------------===//
5129
5130namespace {
5131class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005132 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005133 MemberPtr &Result;
5134
5135 bool Success(const ValueDecl *D) {
5136 Result = MemberPtr(D);
5137 return true;
5138 }
5139public:
5140
5141 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5142 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5143
Richard Smith2e312c82012-03-03 22:46:17 +00005144 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005145 Result.setFrom(V);
5146 return true;
5147 }
Richard Smithfddd3842011-12-30 21:15:51 +00005148 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005149 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005150 }
5151
5152 bool VisitCastExpr(const CastExpr *E);
5153 bool VisitUnaryAddrOf(const UnaryOperator *E);
5154};
5155} // end anonymous namespace
5156
5157static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5158 EvalInfo &Info) {
5159 assert(E->isRValue() && E->getType()->isMemberPointerType());
5160 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5161}
5162
5163bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5164 switch (E->getCastKind()) {
5165 default:
5166 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5167
5168 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005169 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005170 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005171
5172 case CK_BaseToDerivedMemberPointer: {
5173 if (!Visit(E->getSubExpr()))
5174 return false;
5175 if (E->path_empty())
5176 return true;
5177 // Base-to-derived member pointer casts store the path in derived-to-base
5178 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5179 // the wrong end of the derived->base arc, so stagger the path by one class.
5180 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5181 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5182 PathI != PathE; ++PathI) {
5183 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5184 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5185 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005186 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005187 }
5188 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5189 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005190 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005191 return true;
5192 }
5193
5194 case CK_DerivedToBaseMemberPointer:
5195 if (!Visit(E->getSubExpr()))
5196 return false;
5197 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5198 PathE = E->path_end(); PathI != PathE; ++PathI) {
5199 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5200 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5201 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005202 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005203 }
5204 return true;
5205 }
5206}
5207
5208bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5209 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5210 // member can be formed.
5211 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5212}
5213
5214//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005215// Record Evaluation
5216//===----------------------------------------------------------------------===//
5217
5218namespace {
5219 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005220 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005221 const LValue &This;
5222 APValue &Result;
5223 public:
5224
5225 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5226 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5227
Richard Smith2e312c82012-03-03 22:46:17 +00005228 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005229 Result = V;
5230 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005231 }
Richard Smithfddd3842011-12-30 21:15:51 +00005232 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005233
Richard Smith52a980a2015-08-28 02:43:42 +00005234 bool VisitCallExpr(const CallExpr *E) {
5235 return handleCallExpr(E, Result, &This);
5236 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005237 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005238 bool VisitInitListExpr(const InitListExpr *E);
5239 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005240 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005241 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005242}
Richard Smithd62306a2011-11-10 06:34:14 +00005243
Richard Smithfddd3842011-12-30 21:15:51 +00005244/// Perform zero-initialization on an object of non-union class type.
5245/// C++11 [dcl.init]p5:
5246/// To zero-initialize an object or reference of type T means:
5247/// [...]
5248/// -- if T is a (possibly cv-qualified) non-union class type,
5249/// each non-static data member and each base-class subobject is
5250/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005251static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5252 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005253 const LValue &This, APValue &Result) {
5254 assert(!RD->isUnion() && "Expected non-union class type");
5255 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5256 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005257 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005258
John McCalld7bca762012-05-01 00:38:49 +00005259 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005260 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5261
5262 if (CD) {
5263 unsigned Index = 0;
5264 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005265 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005266 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5267 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005268 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5269 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005270 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005271 Result.getStructBase(Index)))
5272 return false;
5273 }
5274 }
5275
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005276 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005277 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005278 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005279 continue;
5280
5281 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005282 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005283 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005284
David Blaikie2d7c57e2012-04-30 02:36:29 +00005285 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005286 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005287 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005288 return false;
5289 }
5290
5291 return true;
5292}
5293
5294bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5295 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005296 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005297 if (RD->isUnion()) {
5298 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5299 // object's first non-static named data member is zero-initialized
5300 RecordDecl::field_iterator I = RD->field_begin();
5301 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005302 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005303 return true;
5304 }
5305
5306 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005307 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005308 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005309 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005310 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005311 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005312 }
5313
Richard Smith5d108602012-02-17 00:44:16 +00005314 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005315 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005316 return false;
5317 }
5318
Richard Smitha8105bc2012-01-06 16:39:00 +00005319 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005320}
5321
Richard Smithe97cbd72011-11-11 04:05:33 +00005322bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5323 switch (E->getCastKind()) {
5324 default:
5325 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5326
5327 case CK_ConstructorConversion:
5328 return Visit(E->getSubExpr());
5329
5330 case CK_DerivedToBase:
5331 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005332 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005333 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005334 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005335 if (!DerivedObject.isStruct())
5336 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005337
5338 // Derived-to-base rvalue conversion: just slice off the derived part.
5339 APValue *Value = &DerivedObject;
5340 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5341 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5342 PathE = E->path_end(); PathI != PathE; ++PathI) {
5343 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5344 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5345 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5346 RD = Base;
5347 }
5348 Result = *Value;
5349 return true;
5350 }
5351 }
5352}
5353
Richard Smithd62306a2011-11-10 06:34:14 +00005354bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5355 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005356 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005357 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5358
5359 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005360 const FieldDecl *Field = E->getInitializedFieldInUnion();
5361 Result = APValue(Field);
5362 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005363 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005364
5365 // If the initializer list for a union does not contain any elements, the
5366 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005367 // FIXME: The element should be initialized from an initializer list.
5368 // Is this difference ever observable for initializer lists which
5369 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005370 ImplicitValueInitExpr VIE(Field->getType());
5371 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5372
Richard Smithd62306a2011-11-10 06:34:14 +00005373 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005374 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5375 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005376
5377 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5378 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5379 isa<CXXDefaultInitExpr>(InitExpr));
5380
Richard Smithb228a862012-02-15 02:18:13 +00005381 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005382 }
5383
5384 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5385 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005386 Result = APValue(APValue::UninitStruct(), 0,
5387 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005388 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005389 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005390 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005391 // Anonymous bit-fields are not considered members of the class for
5392 // purposes of aggregate initialization.
5393 if (Field->isUnnamedBitfield())
5394 continue;
5395
5396 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005397
Richard Smith253c2a32012-01-27 01:14:48 +00005398 bool HaveInit = ElementNo < E->getNumInits();
5399
5400 // FIXME: Diagnostics here should point to the end of the initializer
5401 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005402 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005403 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005404 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005405
5406 // Perform an implicit value-initialization for members beyond the end of
5407 // the initializer list.
5408 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005409 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005410
Richard Smith852c9db2013-04-20 22:23:05 +00005411 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5412 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5413 isa<CXXDefaultInitExpr>(Init));
5414
Richard Smith49ca8aa2013-08-06 07:09:20 +00005415 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5416 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5417 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005418 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005419 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005420 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005421 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005422 }
5423 }
5424
Richard Smith253c2a32012-01-27 01:14:48 +00005425 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005426}
5427
5428bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5429 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005430 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5431
Richard Smithfddd3842011-12-30 21:15:51 +00005432 bool ZeroInit = E->requiresZeroInitialization();
5433 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005434 // If we've already performed zero-initialization, we're already done.
5435 if (!Result.isUninit())
5436 return true;
5437
Richard Smithda3f4fd2014-03-05 23:32:50 +00005438 // We can get here in two different ways:
5439 // 1) We're performing value-initialization, and should zero-initialize
5440 // the object, or
5441 // 2) We're performing default-initialization of an object with a trivial
5442 // constexpr default constructor, in which case we should start the
5443 // lifetimes of all the base subobjects (there can be no data member
5444 // subobjects in this case) per [basic.life]p1.
5445 // Either way, ZeroInitialization is appropriate.
5446 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005447 }
5448
Craig Topper36250ad2014-05-12 05:36:57 +00005449 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005450 FD->getBody(Definition);
5451
Richard Smith357362d2011-12-13 06:39:58 +00005452 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5453 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005454
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005455 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005456 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005457 if (const MaterializeTemporaryExpr *ME
5458 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5459 return Visit(ME->GetTemporaryExpr());
5460
Richard Smithfddd3842011-12-30 21:15:51 +00005461 if (ZeroInit && !ZeroInitialization(E))
5462 return false;
5463
Craig Topper5fc8fc22014-08-27 06:28:36 +00005464 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005465 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005466 cast<CXXConstructorDecl>(Definition), Info,
5467 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005468}
5469
Richard Smithcc1b96d2013-06-12 22:31:48 +00005470bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5471 const CXXStdInitializerListExpr *E) {
5472 const ConstantArrayType *ArrayType =
5473 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5474
5475 LValue Array;
5476 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5477 return false;
5478
5479 // Get a pointer to the first element of the array.
5480 Array.addArray(Info, E, ArrayType);
5481
5482 // FIXME: Perform the checks on the field types in SemaInit.
5483 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5484 RecordDecl::field_iterator Field = Record->field_begin();
5485 if (Field == Record->field_end())
5486 return Error(E);
5487
5488 // Start pointer.
5489 if (!Field->getType()->isPointerType() ||
5490 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5491 ArrayType->getElementType()))
5492 return Error(E);
5493
5494 // FIXME: What if the initializer_list type has base classes, etc?
5495 Result = APValue(APValue::UninitStruct(), 0, 2);
5496 Array.moveInto(Result.getStructField(0));
5497
5498 if (++Field == Record->field_end())
5499 return Error(E);
5500
5501 if (Field->getType()->isPointerType() &&
5502 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5503 ArrayType->getElementType())) {
5504 // End pointer.
5505 if (!HandleLValueArrayAdjustment(Info, E, Array,
5506 ArrayType->getElementType(),
5507 ArrayType->getSize().getZExtValue()))
5508 return false;
5509 Array.moveInto(Result.getStructField(1));
5510 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5511 // Length.
5512 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5513 else
5514 return Error(E);
5515
5516 if (++Field != Record->field_end())
5517 return Error(E);
5518
5519 return true;
5520}
5521
Richard Smithd62306a2011-11-10 06:34:14 +00005522static bool EvaluateRecord(const Expr *E, const LValue &This,
5523 APValue &Result, EvalInfo &Info) {
5524 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005525 "can't evaluate expression as a record rvalue");
5526 return RecordExprEvaluator(Info, This, Result).Visit(E);
5527}
5528
5529//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005530// Temporary Evaluation
5531//
5532// Temporaries are represented in the AST as rvalues, but generally behave like
5533// lvalues. The full-object of which the temporary is a subobject is implicitly
5534// materialized so that a reference can bind to it.
5535//===----------------------------------------------------------------------===//
5536namespace {
5537class TemporaryExprEvaluator
5538 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5539public:
5540 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5541 LValueExprEvaluatorBaseTy(Info, Result) {}
5542
5543 /// Visit an expression which constructs the value of this temporary.
5544 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005545 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005546 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5547 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005548 }
5549
5550 bool VisitCastExpr(const CastExpr *E) {
5551 switch (E->getCastKind()) {
5552 default:
5553 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5554
5555 case CK_ConstructorConversion:
5556 return VisitConstructExpr(E->getSubExpr());
5557 }
5558 }
5559 bool VisitInitListExpr(const InitListExpr *E) {
5560 return VisitConstructExpr(E);
5561 }
5562 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5563 return VisitConstructExpr(E);
5564 }
5565 bool VisitCallExpr(const CallExpr *E) {
5566 return VisitConstructExpr(E);
5567 }
Richard Smith513955c2014-12-17 19:24:30 +00005568 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5569 return VisitConstructExpr(E);
5570 }
Richard Smith027bf112011-11-17 22:56:20 +00005571};
5572} // end anonymous namespace
5573
5574/// Evaluate an expression of record type as a temporary.
5575static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005576 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005577 return TemporaryExprEvaluator(Info, Result).Visit(E);
5578}
5579
5580//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005581// Vector Evaluation
5582//===----------------------------------------------------------------------===//
5583
5584namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005585 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005586 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005587 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005588 public:
Mike Stump11289f42009-09-09 15:08:12 +00005589
Richard Smith2d406342011-10-22 21:10:00 +00005590 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5591 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005592
Craig Topper9798b932015-09-29 04:30:05 +00005593 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005594 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5595 // FIXME: remove this APValue copy.
5596 Result = APValue(V.data(), V.size());
5597 return true;
5598 }
Richard Smith2e312c82012-03-03 22:46:17 +00005599 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005600 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005601 Result = V;
5602 return true;
5603 }
Richard Smithfddd3842011-12-30 21:15:51 +00005604 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005605
Richard Smith2d406342011-10-22 21:10:00 +00005606 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005607 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005608 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005609 bool VisitInitListExpr(const InitListExpr *E);
5610 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005611 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005612 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005613 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005614 };
5615} // end anonymous namespace
5616
5617static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005618 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005619 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005620}
5621
Richard Smith2d406342011-10-22 21:10:00 +00005622bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5623 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005624 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005625
Richard Smith161f09a2011-12-06 22:44:34 +00005626 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005627 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005628
Eli Friedmanc757de22011-03-25 00:43:55 +00005629 switch (E->getCastKind()) {
5630 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005631 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005632 if (SETy->isIntegerType()) {
5633 APSInt IntResult;
5634 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005635 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005636 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005637 } else if (SETy->isRealFloatingType()) {
5638 APFloat F(0.0);
5639 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005640 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005641 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005642 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005643 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005644 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005645
5646 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005647 SmallVector<APValue, 4> Elts(NElts, Val);
5648 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005649 }
Eli Friedman803acb32011-12-22 03:51:45 +00005650 case CK_BitCast: {
5651 // Evaluate the operand into an APInt we can extract from.
5652 llvm::APInt SValInt;
5653 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5654 return false;
5655 // Extract the elements
5656 QualType EltTy = VTy->getElementType();
5657 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5658 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5659 SmallVector<APValue, 4> Elts;
5660 if (EltTy->isRealFloatingType()) {
5661 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005662 unsigned FloatEltSize = EltSize;
5663 if (&Sem == &APFloat::x87DoubleExtended)
5664 FloatEltSize = 80;
5665 for (unsigned i = 0; i < NElts; i++) {
5666 llvm::APInt Elt;
5667 if (BigEndian)
5668 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5669 else
5670 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005671 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005672 }
5673 } else if (EltTy->isIntegerType()) {
5674 for (unsigned i = 0; i < NElts; i++) {
5675 llvm::APInt Elt;
5676 if (BigEndian)
5677 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5678 else
5679 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5680 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5681 }
5682 } else {
5683 return Error(E);
5684 }
5685 return Success(Elts, E);
5686 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005687 default:
Richard Smith11562c52011-10-28 17:51:58 +00005688 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005689 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005690}
5691
Richard Smith2d406342011-10-22 21:10:00 +00005692bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005693VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005694 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005695 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005696 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005697
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005698 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005699 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005700
Eli Friedmanb9c71292012-01-03 23:24:20 +00005701 // The number of initializers can be less than the number of
5702 // vector elements. For OpenCL, this can be due to nested vector
5703 // initialization. For GCC compatibility, missing trailing elements
5704 // should be initialized with zeroes.
5705 unsigned CountInits = 0, CountElts = 0;
5706 while (CountElts < NumElements) {
5707 // Handle nested vector initialization.
5708 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005709 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005710 APValue v;
5711 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5712 return Error(E);
5713 unsigned vlen = v.getVectorLength();
5714 for (unsigned j = 0; j < vlen; j++)
5715 Elements.push_back(v.getVectorElt(j));
5716 CountElts += vlen;
5717 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005718 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005719 if (CountInits < NumInits) {
5720 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005721 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005722 } else // trailing integer zero.
5723 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5724 Elements.push_back(APValue(sInt));
5725 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005726 } else {
5727 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005728 if (CountInits < NumInits) {
5729 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005730 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005731 } else // trailing float zero.
5732 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5733 Elements.push_back(APValue(f));
5734 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005735 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005736 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005737 }
Richard Smith2d406342011-10-22 21:10:00 +00005738 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005739}
5740
Richard Smith2d406342011-10-22 21:10:00 +00005741bool
Richard Smithfddd3842011-12-30 21:15:51 +00005742VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005743 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005744 QualType EltTy = VT->getElementType();
5745 APValue ZeroElement;
5746 if (EltTy->isIntegerType())
5747 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5748 else
5749 ZeroElement =
5750 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5751
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005752 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005753 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005754}
5755
Richard Smith2d406342011-10-22 21:10:00 +00005756bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005757 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005758 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005759}
5760
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005761//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005762// Array Evaluation
5763//===----------------------------------------------------------------------===//
5764
5765namespace {
5766 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005767 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005768 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005769 APValue &Result;
5770 public:
5771
Richard Smithd62306a2011-11-10 06:34:14 +00005772 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5773 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005774
5775 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005776 assert((V.isArray() || V.isLValue()) &&
5777 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005778 Result = V;
5779 return true;
5780 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005781
Richard Smithfddd3842011-12-30 21:15:51 +00005782 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005783 const ConstantArrayType *CAT =
5784 Info.Ctx.getAsConstantArrayType(E->getType());
5785 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005786 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005787
5788 Result = APValue(APValue::UninitArray(), 0,
5789 CAT->getSize().getZExtValue());
5790 if (!Result.hasArrayFiller()) return true;
5791
Richard Smithfddd3842011-12-30 21:15:51 +00005792 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005793 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005794 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005795 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005796 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005797 }
5798
Richard Smith52a980a2015-08-28 02:43:42 +00005799 bool VisitCallExpr(const CallExpr *E) {
5800 return handleCallExpr(E, Result, &This);
5801 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005802 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005803 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005804 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5805 const LValue &Subobject,
5806 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005807 };
5808} // end anonymous namespace
5809
Richard Smithd62306a2011-11-10 06:34:14 +00005810static bool EvaluateArray(const Expr *E, const LValue &This,
5811 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005812 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005813 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005814}
5815
5816bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5817 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5818 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005819 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005820
Richard Smithca2cfbf2011-12-22 01:07:19 +00005821 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5822 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005823 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005824 LValue LV;
5825 if (!EvaluateLValue(E->getInit(0), LV, Info))
5826 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005827 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005828 LV.moveInto(Val);
5829 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005830 }
5831
Richard Smith253c2a32012-01-27 01:14:48 +00005832 bool Success = true;
5833
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005834 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5835 "zero-initialized array shouldn't have any initialized elts");
5836 APValue Filler;
5837 if (Result.isArray() && Result.hasArrayFiller())
5838 Filler = Result.getArrayFiller();
5839
Richard Smith9543c5e2013-04-22 14:44:29 +00005840 unsigned NumEltsToInit = E->getNumInits();
5841 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005842 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005843
5844 // If the initializer might depend on the array index, run it for each
5845 // array element. For now, just whitelist non-class value-initialization.
5846 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5847 NumEltsToInit = NumElts;
5848
5849 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005850
5851 // If the array was previously zero-initialized, preserve the
5852 // zero-initialized values.
5853 if (!Filler.isUninit()) {
5854 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5855 Result.getArrayInitializedElt(I) = Filler;
5856 if (Result.hasArrayFiller())
5857 Result.getArrayFiller() = Filler;
5858 }
5859
Richard Smithd62306a2011-11-10 06:34:14 +00005860 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005861 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005862 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5863 const Expr *Init =
5864 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005865 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005866 Info, Subobject, Init) ||
5867 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005868 CAT->getElementType(), 1)) {
5869 if (!Info.keepEvaluatingAfterFailure())
5870 return false;
5871 Success = false;
5872 }
Richard Smithd62306a2011-11-10 06:34:14 +00005873 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005874
Richard Smith9543c5e2013-04-22 14:44:29 +00005875 if (!Result.hasArrayFiller())
5876 return Success;
5877
5878 // If we get here, we have a trivial filler, which we can just evaluate
5879 // once and splat over the rest of the array elements.
5880 assert(FillerExpr && "no array filler for incomplete init list");
5881 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5882 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005883}
5884
Richard Smith027bf112011-11-17 22:56:20 +00005885bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005886 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5887}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005888
Richard Smith9543c5e2013-04-22 14:44:29 +00005889bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5890 const LValue &Subobject,
5891 APValue *Value,
5892 QualType Type) {
5893 bool HadZeroInit = !Value->isUninit();
5894
5895 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5896 unsigned N = CAT->getSize().getZExtValue();
5897
5898 // Preserve the array filler if we had prior zero-initialization.
5899 APValue Filler =
5900 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5901 : APValue();
5902
5903 *Value = APValue(APValue::UninitArray(), N, N);
5904
5905 if (HadZeroInit)
5906 for (unsigned I = 0; I != N; ++I)
5907 Value->getArrayInitializedElt(I) = Filler;
5908
5909 // Initialize the elements.
5910 LValue ArrayElt = Subobject;
5911 ArrayElt.addArray(Info, E, CAT);
5912 for (unsigned I = 0; I != N; ++I)
5913 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5914 CAT->getElementType()) ||
5915 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5916 CAT->getElementType(), 1))
5917 return false;
5918
5919 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005920 }
Richard Smith027bf112011-11-17 22:56:20 +00005921
Richard Smith9543c5e2013-04-22 14:44:29 +00005922 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005923 return Error(E);
5924
Richard Smith027bf112011-11-17 22:56:20 +00005925 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005926
Richard Smithfddd3842011-12-30 21:15:51 +00005927 bool ZeroInit = E->requiresZeroInitialization();
5928 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005929 if (HadZeroInit)
5930 return true;
5931
Richard Smithda3f4fd2014-03-05 23:32:50 +00005932 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5933 ImplicitValueInitExpr VIE(Type);
5934 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005935 }
5936
Craig Topper36250ad2014-05-12 05:36:57 +00005937 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005938 FD->getBody(Definition);
5939
Richard Smith357362d2011-12-13 06:39:58 +00005940 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5941 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005942
Richard Smith9eae7232012-01-12 18:54:33 +00005943 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005944 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005945 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005946 return false;
5947 }
5948
Craig Topper5fc8fc22014-08-27 06:28:36 +00005949 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005950 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005951 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005952 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005953}
5954
Richard Smithf3e9e432011-11-07 09:22:26 +00005955//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005956// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005957//
5958// As a GNU extension, we support casting pointers to sufficiently-wide integer
5959// types and back in constant folding. Integer values are thus represented
5960// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005961//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005962
5963namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005964class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005965 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005966 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005967public:
Richard Smith2e312c82012-03-03 22:46:17 +00005968 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005969 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005970
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005971 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005972 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005973 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005974 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005975 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005976 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005977 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005978 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005979 return true;
5980 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005981 bool Success(const llvm::APSInt &SI, const Expr *E) {
5982 return Success(SI, E, Result);
5983 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005984
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005985 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005986 assert(E->getType()->isIntegralOrEnumerationType() &&
5987 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005988 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005989 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005990 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005991 Result.getInt().setIsUnsigned(
5992 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005993 return true;
5994 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005995 bool Success(const llvm::APInt &I, const Expr *E) {
5996 return Success(I, E, Result);
5997 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005998
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005999 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006000 assert(E->getType()->isIntegralOrEnumerationType() &&
6001 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006002 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006003 return true;
6004 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006005 bool Success(uint64_t Value, const Expr *E) {
6006 return Success(Value, E, Result);
6007 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006008
Ken Dyckdbc01912011-03-11 02:13:43 +00006009 bool Success(CharUnits Size, const Expr *E) {
6010 return Success(Size.getQuantity(), E);
6011 }
6012
Richard Smith2e312c82012-03-03 22:46:17 +00006013 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006014 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006015 Result = V;
6016 return true;
6017 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006018 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006019 }
Mike Stump11289f42009-09-09 15:08:12 +00006020
Richard Smithfddd3842011-12-30 21:15:51 +00006021 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006022
Peter Collingbournee9200682011-05-13 03:29:01 +00006023 //===--------------------------------------------------------------------===//
6024 // Visitor Methods
6025 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006026
Chris Lattner7174bf32008-07-12 00:38:25 +00006027 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006028 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006029 }
6030 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006031 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006032 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006033
6034 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6035 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006036 if (CheckReferencedDecl(E, E->getDecl()))
6037 return true;
6038
6039 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006040 }
6041 bool VisitMemberExpr(const MemberExpr *E) {
6042 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00006043 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006044 return true;
6045 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006046
6047 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006048 }
6049
Peter Collingbournee9200682011-05-13 03:29:01 +00006050 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006051 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006052 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006053 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006054
Peter Collingbournee9200682011-05-13 03:29:01 +00006055 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006056 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006057
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006058 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006059 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006060 }
Mike Stump11289f42009-09-09 15:08:12 +00006061
Ted Kremeneke65b0862012-03-06 20:05:56 +00006062 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6063 return Success(E->getValue(), E);
6064 }
6065
Richard Smith4ce706a2011-10-11 21:43:33 +00006066 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006067 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006068 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006069 }
6070
Douglas Gregor29c42f22012-02-24 07:38:34 +00006071 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6072 return Success(E->getValue(), E);
6073 }
6074
John Wiegley6242b6a2011-04-28 00:16:57 +00006075 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6076 return Success(E->getValue(), E);
6077 }
6078
John Wiegleyf9f65842011-04-25 06:54:41 +00006079 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6080 return Success(E->getValue(), E);
6081 }
6082
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006083 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006084 bool VisitUnaryImag(const UnaryOperator *E);
6085
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006086 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006087 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006088
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006089private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006090 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006091 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006092};
Chris Lattner05706e882008-07-11 18:11:29 +00006093} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006094
Richard Smith11562c52011-10-28 17:51:58 +00006095/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6096/// produce either the integer value or a pointer.
6097///
6098/// GCC has a heinous extension which folds casts between pointer types and
6099/// pointer-sized integral types. We support this by allowing the evaluation of
6100/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6101/// Some simple arithmetic on such values is supported (they are treated much
6102/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006103static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006104 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006105 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006106 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006107}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006108
Richard Smithf57d8cb2011-12-09 22:58:01 +00006109static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006110 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006111 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006112 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006113 if (!Val.isInt()) {
6114 // FIXME: It would be better to produce the diagnostic for casting
6115 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006116 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006117 return false;
6118 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006119 Result = Val.getInt();
6120 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006121}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006122
Richard Smithf57d8cb2011-12-09 22:58:01 +00006123/// Check whether the given declaration can be directly converted to an integral
6124/// rvalue. If not, no diagnostic is produced; there are other things we can
6125/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006126bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006127 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006128 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006129 // Check for signedness/width mismatches between E type and ECD value.
6130 bool SameSign = (ECD->getInitVal().isSigned()
6131 == E->getType()->isSignedIntegerOrEnumerationType());
6132 bool SameWidth = (ECD->getInitVal().getBitWidth()
6133 == Info.Ctx.getIntWidth(E->getType()));
6134 if (SameSign && SameWidth)
6135 return Success(ECD->getInitVal(), E);
6136 else {
6137 // Get rid of mismatch (otherwise Success assertions will fail)
6138 // by computing a new value matching the type of E.
6139 llvm::APSInt Val = ECD->getInitVal();
6140 if (!SameSign)
6141 Val.setIsSigned(!ECD->getInitVal().isSigned());
6142 if (!SameWidth)
6143 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6144 return Success(Val, E);
6145 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006146 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006147 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006148}
6149
Chris Lattner86ee2862008-10-06 06:40:35 +00006150/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6151/// as GCC.
6152static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6153 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006154 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006155 enum gcc_type_class {
6156 no_type_class = -1,
6157 void_type_class, integer_type_class, char_type_class,
6158 enumeral_type_class, boolean_type_class,
6159 pointer_type_class, reference_type_class, offset_type_class,
6160 real_type_class, complex_type_class,
6161 function_type_class, method_type_class,
6162 record_type_class, union_type_class,
6163 array_type_class, string_type_class,
6164 lang_type_class
6165 };
Mike Stump11289f42009-09-09 15:08:12 +00006166
6167 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006168 // ideal, however it is what gcc does.
6169 if (E->getNumArgs() == 0)
6170 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006171
Chris Lattner86ee2862008-10-06 06:40:35 +00006172 QualType ArgTy = E->getArg(0)->getType();
6173 if (ArgTy->isVoidType())
6174 return void_type_class;
6175 else if (ArgTy->isEnumeralType())
6176 return enumeral_type_class;
6177 else if (ArgTy->isBooleanType())
6178 return boolean_type_class;
6179 else if (ArgTy->isCharType())
6180 return string_type_class; // gcc doesn't appear to use char_type_class
6181 else if (ArgTy->isIntegerType())
6182 return integer_type_class;
6183 else if (ArgTy->isPointerType())
6184 return pointer_type_class;
6185 else if (ArgTy->isReferenceType())
6186 return reference_type_class;
6187 else if (ArgTy->isRealType())
6188 return real_type_class;
6189 else if (ArgTy->isComplexType())
6190 return complex_type_class;
6191 else if (ArgTy->isFunctionType())
6192 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00006193 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00006194 return record_type_class;
6195 else if (ArgTy->isUnionType())
6196 return union_type_class;
6197 else if (ArgTy->isArrayType())
6198 return array_type_class;
6199 else if (ArgTy->isUnionType())
6200 return union_type_class;
6201 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00006202 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006203}
6204
Richard Smith5fab0c92011-12-28 19:48:30 +00006205/// EvaluateBuiltinConstantPForLValue - Determine the result of
6206/// __builtin_constant_p when applied to the given lvalue.
6207///
6208/// An lvalue is only "constant" if it is a pointer or reference to the first
6209/// character of a string literal.
6210template<typename LValue>
6211static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006212 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006213 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6214}
6215
6216/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6217/// GCC as we can manage.
6218static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6219 QualType ArgType = Arg->getType();
6220
6221 // __builtin_constant_p always has one operand. The rules which gcc follows
6222 // are not precisely documented, but are as follows:
6223 //
6224 // - If the operand is of integral, floating, complex or enumeration type,
6225 // and can be folded to a known value of that type, it returns 1.
6226 // - If the operand and can be folded to a pointer to the first character
6227 // of a string literal (or such a pointer cast to an integral type), it
6228 // returns 1.
6229 //
6230 // Otherwise, it returns 0.
6231 //
6232 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6233 // its support for this does not currently work.
6234 if (ArgType->isIntegralOrEnumerationType()) {
6235 Expr::EvalResult Result;
6236 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6237 return false;
6238
6239 APValue &V = Result.Val;
6240 if (V.getKind() == APValue::Int)
6241 return true;
6242
6243 return EvaluateBuiltinConstantPForLValue(V);
6244 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6245 return Arg->isEvaluatable(Ctx);
6246 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6247 LValue LV;
6248 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006249 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006250 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6251 : EvaluatePointer(Arg, LV, Info)) &&
6252 !Status.HasSideEffects)
6253 return EvaluateBuiltinConstantPForLValue(LV);
6254 }
6255
6256 // Anything else isn't considered to be sufficiently constant.
6257 return false;
6258}
6259
John McCall95007602010-05-10 23:27:23 +00006260/// Retrieves the "underlying object type" of the given expression,
6261/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006262static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006263 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6264 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006265 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006266 } else if (const Expr *E = B.get<const Expr*>()) {
6267 if (isa<CompoundLiteralExpr>(E))
6268 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006269 }
6270
6271 return QualType();
6272}
6273
George Burgess IV3a03fab2015-09-04 21:28:13 +00006274/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006275/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6276/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006277/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6278///
6279/// Always returns an RValue with a pointer representation.
6280static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6281 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6282
6283 auto *NoParens = E->IgnoreParens();
6284 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006285 if (Cast == nullptr)
6286 return NoParens;
6287
6288 // We only conservatively allow a few kinds of casts, because this code is
6289 // inherently a simple solution that seeks to support the common case.
6290 auto CastKind = Cast->getCastKind();
6291 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6292 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006293 return NoParens;
6294
6295 auto *SubExpr = Cast->getSubExpr();
6296 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6297 return NoParens;
6298 return ignorePointerCastsAndParens(SubExpr);
6299}
6300
George Burgess IVa51c4072015-10-16 01:49:01 +00006301/// Checks to see if the given LValue's Designator is at the end of the LValue's
6302/// record layout. e.g.
6303/// struct { struct { int a, b; } fst, snd; } obj;
6304/// obj.fst // no
6305/// obj.snd // yes
6306/// obj.fst.a // no
6307/// obj.fst.b // no
6308/// obj.snd.a // no
6309/// obj.snd.b // yes
6310///
6311/// Please note: this function is specialized for how __builtin_object_size
6312/// views "objects".
6313static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6314 assert(!LVal.Designator.Invalid);
6315
6316 auto IsLastFieldDecl = [&Ctx](const FieldDecl *FD) {
6317 if (FD->getParent()->isUnion())
6318 return true;
6319 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
6320 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6321 };
6322
6323 auto &Base = LVal.getLValueBase();
6324 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6325 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
6326 if (!IsLastFieldDecl(FD))
6327 return false;
6328 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
6329 for (auto *FD : IFD->chain())
6330 if (!IsLastFieldDecl(cast<FieldDecl>(FD)))
6331 return false;
6332 }
6333 }
6334
6335 QualType BaseType = getType(Base);
6336 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6337 if (BaseType->isArrayType()) {
6338 // Because __builtin_object_size treats arrays as objects, we can ignore
6339 // the index iff this is the last array in the Designator.
6340 if (I + 1 == E)
6341 return true;
6342 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6343 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6344 if (Index + 1 != CAT->getSize())
6345 return false;
6346 BaseType = CAT->getElementType();
6347 } else if (BaseType->isAnyComplexType()) {
6348 auto *CT = BaseType->castAs<ComplexType>();
6349 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6350 if (Index != 1)
6351 return false;
6352 BaseType = CT->getElementType();
6353 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
6354 if (!IsLastFieldDecl(FD))
6355 return false;
6356 BaseType = FD->getType();
6357 } else {
6358 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6359 "Expecting cast to a base class");
6360 return false;
6361 }
6362 }
6363 return true;
6364}
6365
6366/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6367static bool refersToCompleteObject(const LValue &LVal) {
6368 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6369 return false;
6370
6371 if (!LVal.InvalidBase)
6372 return true;
6373
6374 auto *E = LVal.Base.dyn_cast<const Expr *>();
6375 (void)E;
6376 assert(E != nullptr && isa<MemberExpr>(E));
6377 return false;
6378}
6379
George Burgess IVbdb5b262015-08-19 02:19:07 +00006380bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6381 unsigned Type) {
6382 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006383 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006384 {
6385 // The operand of __builtin_object_size is never evaluated for side-effects.
6386 // If there are any, but we can determine the pointed-to object anyway, then
6387 // ignore the side-effects.
6388 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006389 FoldOffsetRAII Fold(Info, Type & 1);
6390 const Expr *Ptr = ignorePointerCastsAndParens(E->getArg(0));
6391 if (!EvaluatePointer(Ptr, Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006392 return false;
6393 }
John McCall95007602010-05-10 23:27:23 +00006394
George Burgess IVbdb5b262015-08-19 02:19:07 +00006395 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006396 // If we point to before the start of the object, there are no accessible
6397 // bytes.
6398 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006399 return Success(0, E);
6400
George Burgess IV3a03fab2015-09-04 21:28:13 +00006401 // In the case where we're not dealing with a subobject, we discard the
6402 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006403 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006404
6405 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6406 // exist. If we can't verify the base, then we can't do that.
6407 //
6408 // As a special case, we produce a valid object size for an unknown object
6409 // with a known designator if Type & 1 is 1. For instance:
6410 //
6411 // extern struct X { char buff[32]; int a, b, c; } *p;
6412 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6413 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6414 //
6415 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006416 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006417 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006418
George Burgess IVa51c4072015-10-16 01:49:01 +00006419 // If we're not examining only the subobject, then we reset to a complete
6420 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006421 //
6422 // If Type is 1 and we've lost track of the subobject, just find the complete
6423 // object instead. (If Type is 3, that's not correct behavior and we should
6424 // return 0 instead.)
6425 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006426 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006427 QualType T = getObjectType(End.getLValueBase());
6428 if (T.isNull())
6429 End.Designator.setInvalid();
6430 else {
6431 End.Designator = SubobjectDesignator(T);
6432 End.Offset = CharUnits::Zero();
6433 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006434 }
John McCall95007602010-05-10 23:27:23 +00006435
George Burgess IVbdb5b262015-08-19 02:19:07 +00006436 // If it is not possible to determine which objects ptr points to at compile
6437 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6438 // and (size_t) 0 for type 2 or 3.
6439 if (End.Designator.Invalid)
6440 return false;
6441
6442 // According to the GCC documentation, we want the size of the subobject
6443 // denoted by the pointer. But that's not quite right -- what we actually
6444 // want is the size of the immediately-enclosing array, if there is one.
6445 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006446 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006447 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6448 // We got a pointer to an array. Step to its end.
6449 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3a03fab2015-09-04 21:28:13 +00006450 End.Designator.Entries.back().ArrayIndex;
6451 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006452 // We're already pointing at the end of the object.
6453 AmountToAdd = 0;
6454 }
6455
George Burgess IV3a03fab2015-09-04 21:28:13 +00006456 QualType PointeeType = End.Designator.MostDerivedType;
6457 assert(!PointeeType.isNull());
6458 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006459 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006460
George Burgess IVbdb5b262015-08-19 02:19:07 +00006461 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6462 AmountToAdd))
6463 return false;
John McCall95007602010-05-10 23:27:23 +00006464
George Burgess IVbdb5b262015-08-19 02:19:07 +00006465 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006466
6467 // The following is a moderately common idiom in C:
6468 //
6469 // struct Foo { int a; char c[1]; };
6470 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6471 // strcpy(&F->c[0], Bar);
6472 //
6473 // So, if we see that we're examining a 1-length (or 0-length) array at the
6474 // end of a struct with an unknown base, we give up instead of breaking code
6475 // that behaves this way. Note that we only do this when Type=1, because
6476 // Type=3 is a lower bound, so answering conservatively is fine.
6477 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6478 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6479 End.Designator.MostDerivedIsArrayElement &&
6480 End.Designator.MostDerivedArraySize < 2 &&
6481 isDesignatorAtObjectEnd(Info.Ctx, End))
6482 return false;
6483
George Burgess IVbdb5b262015-08-19 02:19:07 +00006484 if (BaseOffset > EndOffset)
6485 return Success(0, E);
6486
6487 return Success(EndOffset - BaseOffset, E);
John McCall95007602010-05-10 23:27:23 +00006488}
6489
Peter Collingbournee9200682011-05-13 03:29:01 +00006490bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006491 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006492 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006493 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006494
6495 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006496 // The type was checked when we built the expression.
6497 unsigned Type =
6498 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6499 assert(Type <= 3 && "unexpected type");
6500
6501 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006502 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006503
Richard Smith0421ce72012-08-07 04:16:51 +00006504 // If evaluating the argument has side-effects, we can't determine the size
6505 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6506 // handle all cases where the expression has side-effects.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006507 // Likewise, if Type is 3, we must handle this because CodeGen cannot give a
6508 // conservatively correct answer in that case.
6509 if (E->getArg(0)->HasSideEffects(Info.Ctx) || Type == 3)
6510 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006511
Richard Smith01ade172012-05-23 04:13:20 +00006512 // Expression had no side effects, but we couldn't statically determine the
6513 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006514 switch (Info.EvalMode) {
6515 case EvalInfo::EM_ConstantExpression:
6516 case EvalInfo::EM_PotentialConstantExpression:
6517 case EvalInfo::EM_ConstantFold:
6518 case EvalInfo::EM_EvaluateForOverflow:
6519 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006520 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006521 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006522 return Error(E);
6523 case EvalInfo::EM_ConstantExpressionUnevaluated:
6524 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006525 // Reduce it to a constant now.
6526 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006527 }
Mike Stump722cedf2009-10-26 18:35:08 +00006528 }
6529
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006530 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006531 case Builtin::BI__builtin_bswap32:
6532 case Builtin::BI__builtin_bswap64: {
6533 APSInt Val;
6534 if (!EvaluateInteger(E->getArg(0), Val, Info))
6535 return false;
6536
6537 return Success(Val.byteSwap(), E);
6538 }
6539
Richard Smith8889a3d2013-06-13 06:26:32 +00006540 case Builtin::BI__builtin_classify_type:
6541 return Success(EvaluateBuiltinClassifyType(E), E);
6542
6543 // FIXME: BI__builtin_clrsb
6544 // FIXME: BI__builtin_clrsbl
6545 // FIXME: BI__builtin_clrsbll
6546
Richard Smith80b3c8e2013-06-13 05:04:16 +00006547 case Builtin::BI__builtin_clz:
6548 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006549 case Builtin::BI__builtin_clzll:
6550 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006551 APSInt Val;
6552 if (!EvaluateInteger(E->getArg(0), Val, Info))
6553 return false;
6554 if (!Val)
6555 return Error(E);
6556
6557 return Success(Val.countLeadingZeros(), E);
6558 }
6559
Richard Smith8889a3d2013-06-13 06:26:32 +00006560 case Builtin::BI__builtin_constant_p:
6561 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6562
Richard Smith80b3c8e2013-06-13 05:04:16 +00006563 case Builtin::BI__builtin_ctz:
6564 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006565 case Builtin::BI__builtin_ctzll:
6566 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006567 APSInt Val;
6568 if (!EvaluateInteger(E->getArg(0), Val, Info))
6569 return false;
6570 if (!Val)
6571 return Error(E);
6572
6573 return Success(Val.countTrailingZeros(), E);
6574 }
6575
Richard Smith8889a3d2013-06-13 06:26:32 +00006576 case Builtin::BI__builtin_eh_return_data_regno: {
6577 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6578 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6579 return Success(Operand, E);
6580 }
6581
6582 case Builtin::BI__builtin_expect:
6583 return Visit(E->getArg(0));
6584
6585 case Builtin::BI__builtin_ffs:
6586 case Builtin::BI__builtin_ffsl:
6587 case Builtin::BI__builtin_ffsll: {
6588 APSInt Val;
6589 if (!EvaluateInteger(E->getArg(0), Val, Info))
6590 return false;
6591
6592 unsigned N = Val.countTrailingZeros();
6593 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6594 }
6595
6596 case Builtin::BI__builtin_fpclassify: {
6597 APFloat Val(0.0);
6598 if (!EvaluateFloat(E->getArg(5), Val, Info))
6599 return false;
6600 unsigned Arg;
6601 switch (Val.getCategory()) {
6602 case APFloat::fcNaN: Arg = 0; break;
6603 case APFloat::fcInfinity: Arg = 1; break;
6604 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6605 case APFloat::fcZero: Arg = 4; break;
6606 }
6607 return Visit(E->getArg(Arg));
6608 }
6609
6610 case Builtin::BI__builtin_isinf_sign: {
6611 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006612 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006613 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6614 }
6615
Richard Smithea3019d2013-10-15 19:07:14 +00006616 case Builtin::BI__builtin_isinf: {
6617 APFloat Val(0.0);
6618 return EvaluateFloat(E->getArg(0), Val, Info) &&
6619 Success(Val.isInfinity() ? 1 : 0, E);
6620 }
6621
6622 case Builtin::BI__builtin_isfinite: {
6623 APFloat Val(0.0);
6624 return EvaluateFloat(E->getArg(0), Val, Info) &&
6625 Success(Val.isFinite() ? 1 : 0, E);
6626 }
6627
6628 case Builtin::BI__builtin_isnan: {
6629 APFloat Val(0.0);
6630 return EvaluateFloat(E->getArg(0), Val, Info) &&
6631 Success(Val.isNaN() ? 1 : 0, E);
6632 }
6633
6634 case Builtin::BI__builtin_isnormal: {
6635 APFloat Val(0.0);
6636 return EvaluateFloat(E->getArg(0), Val, Info) &&
6637 Success(Val.isNormal() ? 1 : 0, E);
6638 }
6639
Richard Smith8889a3d2013-06-13 06:26:32 +00006640 case Builtin::BI__builtin_parity:
6641 case Builtin::BI__builtin_parityl:
6642 case Builtin::BI__builtin_parityll: {
6643 APSInt Val;
6644 if (!EvaluateInteger(E->getArg(0), Val, Info))
6645 return false;
6646
6647 return Success(Val.countPopulation() % 2, E);
6648 }
6649
Richard Smith80b3c8e2013-06-13 05:04:16 +00006650 case Builtin::BI__builtin_popcount:
6651 case Builtin::BI__builtin_popcountl:
6652 case Builtin::BI__builtin_popcountll: {
6653 APSInt Val;
6654 if (!EvaluateInteger(E->getArg(0), Val, Info))
6655 return false;
6656
6657 return Success(Val.countPopulation(), E);
6658 }
6659
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006660 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006661 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006662 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006663 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006664 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6665 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006666 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006667 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006668 case Builtin::BI__builtin_strlen: {
6669 // As an extension, we support __builtin_strlen() as a constant expression,
6670 // and support folding strlen() to a constant.
6671 LValue String;
6672 if (!EvaluatePointer(E->getArg(0), String, Info))
6673 return false;
6674
6675 // Fast path: if it's a string literal, search the string value.
6676 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6677 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006678 // The string literal may have embedded null characters. Find the first
6679 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006680 StringRef Str = S->getBytes();
6681 int64_t Off = String.Offset.getQuantity();
6682 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6683 S->getCharByteWidth() == 1) {
6684 Str = Str.substr(Off);
6685
6686 StringRef::size_type Pos = Str.find(0);
6687 if (Pos != StringRef::npos)
6688 Str = Str.substr(0, Pos);
6689
6690 return Success(Str.size(), E);
6691 }
6692
6693 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006694 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006695
6696 // Slow path: scan the bytes of the string looking for the terminating 0.
6697 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6698 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6699 APValue Char;
6700 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6701 !Char.isInt())
6702 return false;
6703 if (!Char.getInt())
6704 return Success(Strlen, E);
6705 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6706 return false;
6707 }
6708 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006709
Richard Smith01ba47d2012-04-13 00:45:38 +00006710 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006711 case Builtin::BI__atomic_is_lock_free:
6712 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006713 APSInt SizeVal;
6714 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6715 return false;
6716
6717 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6718 // of two less than the maximum inline atomic width, we know it is
6719 // lock-free. If the size isn't a power of two, or greater than the
6720 // maximum alignment where we promote atomics, we know it is not lock-free
6721 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6722 // the answer can only be determined at runtime; for example, 16-byte
6723 // atomics have lock-free implementations on some, but not all,
6724 // x86-64 processors.
6725
6726 // Check power-of-two.
6727 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006728 if (Size.isPowerOfTwo()) {
6729 // Check against inlining width.
6730 unsigned InlineWidthBits =
6731 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6732 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6733 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6734 Size == CharUnits::One() ||
6735 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6736 Expr::NPC_NeverValueDependent))
6737 // OK, we will inline appropriately-aligned operations of this size,
6738 // and _Atomic(T) is appropriately-aligned.
6739 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006740
Richard Smith01ba47d2012-04-13 00:45:38 +00006741 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6742 castAs<PointerType>()->getPointeeType();
6743 if (!PointeeType->isIncompleteType() &&
6744 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6745 // OK, we will inline operations on this object.
6746 return Success(1, E);
6747 }
6748 }
6749 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006750
Richard Smith01ba47d2012-04-13 00:45:38 +00006751 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6752 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006753 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006754 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006755}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006756
Richard Smith8b3497e2011-10-31 01:37:14 +00006757static bool HasSameBase(const LValue &A, const LValue &B) {
6758 if (!A.getLValueBase())
6759 return !B.getLValueBase();
6760 if (!B.getLValueBase())
6761 return false;
6762
Richard Smithce40ad62011-11-12 22:28:03 +00006763 if (A.getLValueBase().getOpaqueValue() !=
6764 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006765 const Decl *ADecl = GetLValueBaseDecl(A);
6766 if (!ADecl)
6767 return false;
6768 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006769 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006770 return false;
6771 }
6772
6773 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006774 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006775}
6776
Richard Smithd20f1e62014-10-21 23:01:04 +00006777/// \brief Determine whether this is a pointer past the end of the complete
6778/// object referred to by the lvalue.
6779static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6780 const LValue &LV) {
6781 // A null pointer can be viewed as being "past the end" but we don't
6782 // choose to look at it that way here.
6783 if (!LV.getLValueBase())
6784 return false;
6785
6786 // If the designator is valid and refers to a subobject, we're not pointing
6787 // past the end.
6788 if (!LV.getLValueDesignator().Invalid &&
6789 !LV.getLValueDesignator().isOnePastTheEnd())
6790 return false;
6791
David Majnemerc378ca52015-08-29 08:32:55 +00006792 // A pointer to an incomplete type might be past-the-end if the type's size is
6793 // zero. We cannot tell because the type is incomplete.
6794 QualType Ty = getType(LV.getLValueBase());
6795 if (Ty->isIncompleteType())
6796 return true;
6797
Richard Smithd20f1e62014-10-21 23:01:04 +00006798 // We're a past-the-end pointer if we point to the byte after the object,
6799 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00006800 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00006801 return LV.getLValueOffset() == Size;
6802}
6803
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006804namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006805
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006806/// \brief Data recursive integer evaluator of certain binary operators.
6807///
6808/// We use a data recursive algorithm for binary operators so that we are able
6809/// to handle extreme cases of chained binary operators without causing stack
6810/// overflow.
6811class DataRecursiveIntBinOpEvaluator {
6812 struct EvalResult {
6813 APValue Val;
6814 bool Failed;
6815
6816 EvalResult() : Failed(false) { }
6817
6818 void swap(EvalResult &RHS) {
6819 Val.swap(RHS.Val);
6820 Failed = RHS.Failed;
6821 RHS.Failed = false;
6822 }
6823 };
6824
6825 struct Job {
6826 const Expr *E;
6827 EvalResult LHSResult; // meaningful only for binary operator expression.
6828 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006829
David Blaikie73726062015-08-12 23:09:24 +00006830 Job() = default;
6831 Job(Job &&J)
6832 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
6833 StoredInfo(J.StoredInfo), OldEvalStatus(J.OldEvalStatus) {
6834 J.StoredInfo = nullptr;
6835 }
6836
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006837 void startSpeculativeEval(EvalInfo &Info) {
6838 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006839 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006840 StoredInfo = &Info;
6841 }
6842 ~Job() {
6843 if (StoredInfo) {
6844 StoredInfo->EvalStatus = OldEvalStatus;
6845 }
6846 }
6847 private:
David Blaikie73726062015-08-12 23:09:24 +00006848 EvalInfo *StoredInfo = nullptr; // non-null if status changed.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006849 Expr::EvalStatus OldEvalStatus;
6850 };
6851
6852 SmallVector<Job, 16> Queue;
6853
6854 IntExprEvaluator &IntEval;
6855 EvalInfo &Info;
6856 APValue &FinalResult;
6857
6858public:
6859 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6860 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6861
6862 /// \brief True if \param E is a binary operator that we are going to handle
6863 /// data recursively.
6864 /// We handle binary operators that are comma, logical, or that have operands
6865 /// with integral or enumeration type.
6866 static bool shouldEnqueue(const BinaryOperator *E) {
6867 return E->getOpcode() == BO_Comma ||
6868 E->isLogicalOp() ||
6869 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6870 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006871 }
6872
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006873 bool Traverse(const BinaryOperator *E) {
6874 enqueue(E);
6875 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006876 while (!Queue.empty())
6877 process(PrevResult);
6878
6879 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006880
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006881 FinalResult.swap(PrevResult.Val);
6882 return true;
6883 }
6884
6885private:
6886 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6887 return IntEval.Success(Value, E, Result);
6888 }
6889 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6890 return IntEval.Success(Value, E, Result);
6891 }
6892 bool Error(const Expr *E) {
6893 return IntEval.Error(E);
6894 }
6895 bool Error(const Expr *E, diag::kind D) {
6896 return IntEval.Error(E, D);
6897 }
6898
6899 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6900 return Info.CCEDiag(E, D);
6901 }
6902
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006903 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6904 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006905 bool &SuppressRHSDiags);
6906
6907 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6908 const BinaryOperator *E, APValue &Result);
6909
6910 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6911 Result.Failed = !Evaluate(Result.Val, Info, E);
6912 if (Result.Failed)
6913 Result.Val = APValue();
6914 }
6915
Richard Trieuba4d0872012-03-21 23:30:30 +00006916 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006917
6918 void enqueue(const Expr *E) {
6919 E = E->IgnoreParens();
6920 Queue.resize(Queue.size()+1);
6921 Queue.back().E = E;
6922 Queue.back().Kind = Job::AnyExprKind;
6923 }
6924};
6925
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006926}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006927
6928bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006929 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006930 bool &SuppressRHSDiags) {
6931 if (E->getOpcode() == BO_Comma) {
6932 // Ignore LHS but note if we could not evaluate it.
6933 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006934 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006935 return true;
6936 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006937
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006938 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006939 bool LHSAsBool;
6940 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006941 // We were able to evaluate the LHS, see if we can get away with not
6942 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006943 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6944 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006945 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006946 }
6947 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006948 LHSResult.Failed = true;
6949
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006950 // Since we weren't able to evaluate the left hand side, it
6951 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006952 if (!Info.noteSideEffect())
6953 return false;
6954
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006955 // We can't evaluate the LHS; however, sometimes the result
6956 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6957 // Don't ignore RHS and suppress diagnostics from this arm.
6958 SuppressRHSDiags = true;
6959 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006960
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006961 return true;
6962 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006963
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006964 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6965 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006966
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006967 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006968 return false; // Ignore RHS;
6969
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006970 return true;
6971}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006972
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006973bool DataRecursiveIntBinOpEvaluator::
6974 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6975 const BinaryOperator *E, APValue &Result) {
6976 if (E->getOpcode() == BO_Comma) {
6977 if (RHSResult.Failed)
6978 return false;
6979 Result = RHSResult.Val;
6980 return true;
6981 }
6982
6983 if (E->isLogicalOp()) {
6984 bool lhsResult, rhsResult;
6985 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6986 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6987
6988 if (LHSIsOK) {
6989 if (RHSIsOK) {
6990 if (E->getOpcode() == BO_LOr)
6991 return Success(lhsResult || rhsResult, E, Result);
6992 else
6993 return Success(lhsResult && rhsResult, E, Result);
6994 }
6995 } else {
6996 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006997 // We can't evaluate the LHS; however, sometimes the result
6998 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6999 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007000 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007001 }
7002 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007003
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007004 return false;
7005 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007006
7007 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7008 E->getRHS()->getType()->isIntegralOrEnumerationType());
7009
7010 if (LHSResult.Failed || RHSResult.Failed)
7011 return false;
7012
7013 const APValue &LHSVal = LHSResult.Val;
7014 const APValue &RHSVal = RHSResult.Val;
7015
7016 // Handle cases like (unsigned long)&a + 4.
7017 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7018 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007019 CharUnits AdditionalOffset =
7020 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007021 if (E->getOpcode() == BO_Add)
7022 Result.getLValueOffset() += AdditionalOffset;
7023 else
7024 Result.getLValueOffset() -= AdditionalOffset;
7025 return true;
7026 }
7027
7028 // Handle cases like 4 + (unsigned long)&a
7029 if (E->getOpcode() == BO_Add &&
7030 RHSVal.isLValue() && LHSVal.isInt()) {
7031 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007032 Result.getLValueOffset() +=
7033 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007034 return true;
7035 }
7036
7037 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7038 // Handle (intptr_t)&&A - (intptr_t)&&B.
7039 if (!LHSVal.getLValueOffset().isZero() ||
7040 !RHSVal.getLValueOffset().isZero())
7041 return false;
7042 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7043 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7044 if (!LHSExpr || !RHSExpr)
7045 return false;
7046 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7047 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7048 if (!LHSAddrExpr || !RHSAddrExpr)
7049 return false;
7050 // Make sure both labels come from the same function.
7051 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7052 RHSAddrExpr->getLabel()->getDeclContext())
7053 return false;
7054 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7055 return true;
7056 }
Richard Smith43e77732013-05-07 04:50:00 +00007057
7058 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007059 if (!LHSVal.isInt() || !RHSVal.isInt())
7060 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007061
7062 // Set up the width and signedness manually, in case it can't be deduced
7063 // from the operation we're performing.
7064 // FIXME: Don't do this in the cases where we can deduce it.
7065 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7066 E->getType()->isUnsignedIntegerOrEnumerationType());
7067 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7068 RHSVal.getInt(), Value))
7069 return false;
7070 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007071}
7072
Richard Trieuba4d0872012-03-21 23:30:30 +00007073void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007074 Job &job = Queue.back();
7075
7076 switch (job.Kind) {
7077 case Job::AnyExprKind: {
7078 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7079 if (shouldEnqueue(Bop)) {
7080 job.Kind = Job::BinOpKind;
7081 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007082 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007083 }
7084 }
7085
7086 EvaluateExpr(job.E, Result);
7087 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007088 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007089 }
7090
7091 case Job::BinOpKind: {
7092 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007093 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007094 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007095 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007096 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007097 }
7098 if (SuppressRHSDiags)
7099 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007100 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007101 job.Kind = Job::BinOpVisitedLHSKind;
7102 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007103 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007104 }
7105
7106 case Job::BinOpVisitedLHSKind: {
7107 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7108 EvalResult RHS;
7109 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007110 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007111 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007112 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007113 }
7114 }
7115
7116 llvm_unreachable("Invalid Job::Kind!");
7117}
7118
7119bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Josh Magee4d1a79b2015-02-04 21:50:20 +00007120 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007121 return Error(E);
7122
7123 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7124 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007125
Anders Carlssonacc79812008-11-16 07:17:21 +00007126 QualType LHSTy = E->getLHS()->getType();
7127 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007128
Chandler Carruthb29a7432014-10-11 11:03:30 +00007129 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007130 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007131 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007132 if (E->isAssignmentOp()) {
7133 LValue LV;
7134 EvaluateLValue(E->getLHS(), LV, Info);
7135 LHSOK = false;
7136 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007137 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7138 if (LHSOK) {
7139 LHS.makeComplexFloat();
7140 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7141 }
7142 } else {
7143 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7144 }
Richard Smith253c2a32012-01-27 01:14:48 +00007145 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007146 return false;
7147
Chandler Carruthb29a7432014-10-11 11:03:30 +00007148 if (E->getRHS()->getType()->isRealFloatingType()) {
7149 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7150 return false;
7151 RHS.makeComplexFloat();
7152 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7153 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007154 return false;
7155
7156 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007157 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007158 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007159 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007160 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7161
John McCalle3027922010-08-25 11:45:40 +00007162 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007163 return Success((CR_r == APFloat::cmpEqual &&
7164 CR_i == APFloat::cmpEqual), E);
7165 else {
John McCalle3027922010-08-25 11:45:40 +00007166 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007167 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007168 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007169 CR_r == APFloat::cmpLessThan ||
7170 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007171 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007172 CR_i == APFloat::cmpLessThan ||
7173 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007174 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007175 } else {
John McCalle3027922010-08-25 11:45:40 +00007176 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007177 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7178 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7179 else {
John McCalle3027922010-08-25 11:45:40 +00007180 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007181 "Invalid compex comparison.");
7182 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7183 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7184 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007185 }
7186 }
Mike Stump11289f42009-09-09 15:08:12 +00007187
Anders Carlssonacc79812008-11-16 07:17:21 +00007188 if (LHSTy->isRealFloatingType() &&
7189 RHSTy->isRealFloatingType()) {
7190 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007191
Richard Smith253c2a32012-01-27 01:14:48 +00007192 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7193 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007194 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007195
Richard Smith253c2a32012-01-27 01:14:48 +00007196 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007197 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007198
Anders Carlssonacc79812008-11-16 07:17:21 +00007199 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007200
Anders Carlssonacc79812008-11-16 07:17:21 +00007201 switch (E->getOpcode()) {
7202 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007203 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007204 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007205 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007206 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007207 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007208 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007209 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007210 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007211 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007212 E);
John McCalle3027922010-08-25 11:45:40 +00007213 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007214 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007215 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007216 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007217 || CR == APFloat::cmpLessThan
7218 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007219 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007220 }
Mike Stump11289f42009-09-09 15:08:12 +00007221
Eli Friedmana38da572009-04-28 19:17:36 +00007222 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007223 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007224 LValue LHSValue, RHSValue;
7225
7226 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
7227 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007228 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007229
Richard Smith253c2a32012-01-27 01:14:48 +00007230 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007231 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007232
Richard Smith8b3497e2011-10-31 01:37:14 +00007233 // Reject differing bases from the normal codepath; we special-case
7234 // comparisons to null.
7235 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007236 if (E->getOpcode() == BO_Sub) {
7237 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007238 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
7239 return false;
7240 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007241 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007242 if (!LHSExpr || !RHSExpr)
7243 return false;
7244 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7245 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7246 if (!LHSAddrExpr || !RHSAddrExpr)
7247 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007248 // Make sure both labels come from the same function.
7249 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7250 RHSAddrExpr->getLabel()->getDeclContext())
7251 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007252 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007253 return true;
7254 }
Richard Smith83c68212011-10-31 05:11:32 +00007255 // Inequalities and subtractions between unrelated pointers have
7256 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007257 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007258 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007259 // A constant address may compare equal to the address of a symbol.
7260 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007261 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007262 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7263 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007264 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007265 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007266 // distinct addresses. In clang, the result of such a comparison is
7267 // unspecified, so it is not a constant expression. However, we do know
7268 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007269 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7270 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007271 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007272 // We can't tell whether weak symbols will end up pointing to the same
7273 // object.
7274 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007275 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007276 // We can't compare the address of the start of one object with the
7277 // past-the-end address of another object, per C++ DR1652.
7278 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7279 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7280 (RHSValue.Base && RHSValue.Offset.isZero() &&
7281 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7282 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007283 // We can't tell whether an object is at the same address as another
7284 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007285 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7286 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007287 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007288 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007289 // (Note that clang defaults to -fmerge-all-constants, which can
7290 // lead to inconsistent results for comparisons involving the address
7291 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007292 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007293 }
Eli Friedman64004332009-03-23 04:38:34 +00007294
Richard Smith1b470412012-02-01 08:10:20 +00007295 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7296 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7297
Richard Smith84f6dcf2012-02-02 01:16:57 +00007298 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7299 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7300
John McCalle3027922010-08-25 11:45:40 +00007301 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007302 // C++11 [expr.add]p6:
7303 // Unless both pointers point to elements of the same array object, or
7304 // one past the last element of the array object, the behavior is
7305 // undefined.
7306 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7307 !AreElementsOfSameArray(getType(LHSValue.Base),
7308 LHSDesignator, RHSDesignator))
7309 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7310
Chris Lattner882bdf22010-04-20 17:13:14 +00007311 QualType Type = E->getLHS()->getType();
7312 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007313
Richard Smithd62306a2011-11-10 06:34:14 +00007314 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007315 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007316 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007317
Richard Smith84c6b3d2013-09-10 21:34:14 +00007318 // As an extension, a type may have zero size (empty struct or union in
7319 // C, array of zero length). Pointer subtraction in such cases has
7320 // undefined behavior, so is not constant.
7321 if (ElementSize.isZero()) {
7322 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7323 << ElementType;
7324 return false;
7325 }
7326
Richard Smith1b470412012-02-01 08:10:20 +00007327 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7328 // and produce incorrect results when it overflows. Such behavior
7329 // appears to be non-conforming, but is common, so perhaps we should
7330 // assume the standard intended for such cases to be undefined behavior
7331 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007332
Richard Smith1b470412012-02-01 08:10:20 +00007333 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7334 // overflow in the final conversion to ptrdiff_t.
7335 APSInt LHS(
7336 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7337 APSInt RHS(
7338 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7339 APSInt ElemSize(
7340 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7341 APSInt TrueResult = (LHS - RHS) / ElemSize;
7342 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7343
7344 if (Result.extend(65) != TrueResult)
7345 HandleOverflow(Info, E, TrueResult, E->getType());
7346 return Success(Result, E);
7347 }
Richard Smithde21b242012-01-31 06:41:30 +00007348
7349 // C++11 [expr.rel]p3:
7350 // Pointers to void (after pointer conversions) can be compared, with a
7351 // result defined as follows: If both pointers represent the same
7352 // address or are both the null pointer value, the result is true if the
7353 // operator is <= or >= and false otherwise; otherwise the result is
7354 // unspecified.
7355 // We interpret this as applying to pointers to *cv* void.
7356 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007357 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007358 CCEDiag(E, diag::note_constexpr_void_comparison);
7359
Richard Smith84f6dcf2012-02-02 01:16:57 +00007360 // C++11 [expr.rel]p2:
7361 // - If two pointers point to non-static data members of the same object,
7362 // or to subobjects or array elements fo such members, recursively, the
7363 // pointer to the later declared member compares greater provided the
7364 // two members have the same access control and provided their class is
7365 // not a union.
7366 // [...]
7367 // - Otherwise pointer comparisons are unspecified.
7368 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7369 E->isRelationalOp()) {
7370 bool WasArrayIndex;
7371 unsigned Mismatch =
7372 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7373 RHSDesignator, WasArrayIndex);
7374 // At the point where the designators diverge, the comparison has a
7375 // specified value if:
7376 // - we are comparing array indices
7377 // - we are comparing fields of a union, or fields with the same access
7378 // Otherwise, the result is unspecified and thus the comparison is not a
7379 // constant expression.
7380 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7381 Mismatch < RHSDesignator.Entries.size()) {
7382 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7383 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7384 if (!LF && !RF)
7385 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7386 else if (!LF)
7387 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7388 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7389 << RF->getParent() << RF;
7390 else if (!RF)
7391 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7392 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7393 << LF->getParent() << LF;
7394 else if (!LF->getParent()->isUnion() &&
7395 LF->getAccess() != RF->getAccess())
7396 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7397 << LF << LF->getAccess() << RF << RF->getAccess()
7398 << LF->getParent();
7399 }
7400 }
7401
Eli Friedman6c31cb42012-04-16 04:30:08 +00007402 // The comparison here must be unsigned, and performed with the same
7403 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007404 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7405 uint64_t CompareLHS = LHSOffset.getQuantity();
7406 uint64_t CompareRHS = RHSOffset.getQuantity();
7407 assert(PtrSize <= 64 && "Unexpected pointer width");
7408 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7409 CompareLHS &= Mask;
7410 CompareRHS &= Mask;
7411
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007412 // If there is a base and this is a relational operator, we can only
7413 // compare pointers within the object in question; otherwise, the result
7414 // depends on where the object is located in memory.
7415 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7416 QualType BaseTy = getType(LHSValue.Base);
7417 if (BaseTy->isIncompleteType())
7418 return Error(E);
7419 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7420 uint64_t OffsetLimit = Size.getQuantity();
7421 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7422 return Error(E);
7423 }
7424
Richard Smith8b3497e2011-10-31 01:37:14 +00007425 switch (E->getOpcode()) {
7426 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007427 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7428 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7429 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7430 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7431 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7432 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007433 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007434 }
7435 }
Richard Smith7bb00672012-02-01 01:42:44 +00007436
7437 if (LHSTy->isMemberPointerType()) {
7438 assert(E->isEqualityOp() && "unexpected member pointer operation");
7439 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7440
7441 MemberPtr LHSValue, RHSValue;
7442
7443 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7444 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7445 return false;
7446
7447 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7448 return false;
7449
7450 // C++11 [expr.eq]p2:
7451 // If both operands are null, they compare equal. Otherwise if only one is
7452 // null, they compare unequal.
7453 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7454 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7455 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7456 }
7457
7458 // Otherwise if either is a pointer to a virtual member function, the
7459 // result is unspecified.
7460 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7461 if (MD->isVirtual())
7462 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7463 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7464 if (MD->isVirtual())
7465 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7466
7467 // Otherwise they compare equal if and only if they would refer to the
7468 // same member of the same most derived object or the same subobject if
7469 // they were dereferenced with a hypothetical object of the associated
7470 // class type.
7471 bool Equal = LHSValue == RHSValue;
7472 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7473 }
7474
Richard Smithab44d9b2012-02-14 22:35:28 +00007475 if (LHSTy->isNullPtrType()) {
7476 assert(E->isComparisonOp() && "unexpected nullptr operation");
7477 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7478 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7479 // are compared, the result is true of the operator is <=, >= or ==, and
7480 // false otherwise.
7481 BinaryOperator::Opcode Opcode = E->getOpcode();
7482 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7483 }
7484
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007485 assert((!LHSTy->isIntegralOrEnumerationType() ||
7486 !RHSTy->isIntegralOrEnumerationType()) &&
7487 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7488 // We can't continue from here for non-integral types.
7489 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007490}
7491
Peter Collingbournee190dee2011-03-11 19:24:49 +00007492/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7493/// a result as the expression's type.
7494bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7495 const UnaryExprOrTypeTraitExpr *E) {
7496 switch(E->getKind()) {
7497 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007498 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007499 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007500 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007501 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007502 }
Eli Friedman64004332009-03-23 04:38:34 +00007503
Peter Collingbournee190dee2011-03-11 19:24:49 +00007504 case UETT_VecStep: {
7505 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007506
Peter Collingbournee190dee2011-03-11 19:24:49 +00007507 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007508 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007509
Peter Collingbournee190dee2011-03-11 19:24:49 +00007510 // The vec_step built-in functions that take a 3-component
7511 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7512 if (n == 3)
7513 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007514
Peter Collingbournee190dee2011-03-11 19:24:49 +00007515 return Success(n, E);
7516 } else
7517 return Success(1, E);
7518 }
7519
7520 case UETT_SizeOf: {
7521 QualType SrcTy = E->getTypeOfArgument();
7522 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7523 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007524 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7525 SrcTy = Ref->getPointeeType();
7526
Richard Smithd62306a2011-11-10 06:34:14 +00007527 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007528 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007529 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007530 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007531 }
Alexey Bataev00396512015-07-02 03:40:19 +00007532 case UETT_OpenMPRequiredSimdAlign:
7533 assert(E->isArgumentType());
7534 return Success(
7535 Info.Ctx.toCharUnitsFromBits(
7536 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7537 .getQuantity(),
7538 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007539 }
7540
7541 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007542}
7543
Peter Collingbournee9200682011-05-13 03:29:01 +00007544bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007545 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007546 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007547 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007548 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007549 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007550 for (unsigned i = 0; i != n; ++i) {
7551 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7552 switch (ON.getKind()) {
7553 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007554 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007555 APSInt IdxResult;
7556 if (!EvaluateInteger(Idx, IdxResult, Info))
7557 return false;
7558 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7559 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007560 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007561 CurrentType = AT->getElementType();
7562 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7563 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007564 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007565 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007566
Douglas Gregor882211c2010-04-28 22:16:22 +00007567 case OffsetOfExpr::OffsetOfNode::Field: {
7568 FieldDecl *MemberDecl = ON.getField();
7569 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007570 if (!RT)
7571 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007572 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007573 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007574 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007575 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007576 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007577 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007578 CurrentType = MemberDecl->getType().getNonReferenceType();
7579 break;
7580 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007581
Douglas Gregor882211c2010-04-28 22:16:22 +00007582 case OffsetOfExpr::OffsetOfNode::Identifier:
7583 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007584
Douglas Gregord1702062010-04-29 00:18:15 +00007585 case OffsetOfExpr::OffsetOfNode::Base: {
7586 CXXBaseSpecifier *BaseSpec = ON.getBase();
7587 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007588 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007589
7590 // Find the layout of the class whose base we are looking into.
7591 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007592 if (!RT)
7593 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007594 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007595 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007596 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7597
7598 // Find the base class itself.
7599 CurrentType = BaseSpec->getType();
7600 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7601 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007602 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007603
7604 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007605 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007606 break;
7607 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007608 }
7609 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007610 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007611}
7612
Chris Lattnere13042c2008-07-11 19:10:17 +00007613bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007614 switch (E->getOpcode()) {
7615 default:
7616 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7617 // See C99 6.6p3.
7618 return Error(E);
7619 case UO_Extension:
7620 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7621 // If so, we could clear the diagnostic ID.
7622 return Visit(E->getSubExpr());
7623 case UO_Plus:
7624 // The result is just the value.
7625 return Visit(E->getSubExpr());
7626 case UO_Minus: {
7627 if (!Visit(E->getSubExpr()))
7628 return false;
7629 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007630 const APSInt &Value = Result.getInt();
7631 if (Value.isSigned() && Value.isMinSignedValue())
7632 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7633 E->getType());
7634 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007635 }
7636 case UO_Not: {
7637 if (!Visit(E->getSubExpr()))
7638 return false;
7639 if (!Result.isInt()) return Error(E);
7640 return Success(~Result.getInt(), E);
7641 }
7642 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007643 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007644 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007645 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007646 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007647 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007648 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007649}
Mike Stump11289f42009-09-09 15:08:12 +00007650
Chris Lattner477c4be2008-07-12 01:15:53 +00007651/// HandleCast - This is used to evaluate implicit or explicit casts where the
7652/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007653bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7654 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007655 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007656 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007657
Eli Friedmanc757de22011-03-25 00:43:55 +00007658 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007659 case CK_BaseToDerived:
7660 case CK_DerivedToBase:
7661 case CK_UncheckedDerivedToBase:
7662 case CK_Dynamic:
7663 case CK_ToUnion:
7664 case CK_ArrayToPointerDecay:
7665 case CK_FunctionToPointerDecay:
7666 case CK_NullToPointer:
7667 case CK_NullToMemberPointer:
7668 case CK_BaseToDerivedMemberPointer:
7669 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007670 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007671 case CK_ConstructorConversion:
7672 case CK_IntegralToPointer:
7673 case CK_ToVoid:
7674 case CK_VectorSplat:
7675 case CK_IntegralToFloating:
7676 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007677 case CK_CPointerToObjCPointerCast:
7678 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007679 case CK_AnyPointerToBlockPointerCast:
7680 case CK_ObjCObjectLValueCast:
7681 case CK_FloatingRealToComplex:
7682 case CK_FloatingComplexToReal:
7683 case CK_FloatingComplexCast:
7684 case CK_FloatingComplexToIntegralComplex:
7685 case CK_IntegralRealToComplex:
7686 case CK_IntegralComplexCast:
7687 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007688 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007689 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007690 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007691 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007692 llvm_unreachable("invalid cast kind for integral value");
7693
Eli Friedman9faf2f92011-03-25 19:07:11 +00007694 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007695 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007696 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007697 case CK_ARCProduceObject:
7698 case CK_ARCConsumeObject:
7699 case CK_ARCReclaimReturnedObject:
7700 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007701 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007702 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007703
Richard Smith4ef685b2012-01-17 21:17:26 +00007704 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007705 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007706 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007707 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007708 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007709
7710 case CK_MemberPointerToBoolean:
7711 case CK_PointerToBoolean:
7712 case CK_IntegralToBoolean:
7713 case CK_FloatingToBoolean:
7714 case CK_FloatingComplexToBoolean:
7715 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007716 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007717 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007718 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007719 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007720 }
7721
Eli Friedmanc757de22011-03-25 00:43:55 +00007722 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007723 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007724 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007725
Eli Friedman742421e2009-02-20 01:15:07 +00007726 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007727 // Allow casts of address-of-label differences if they are no-ops
7728 // or narrowing. (The narrowing case isn't actually guaranteed to
7729 // be constant-evaluatable except in some narrow cases which are hard
7730 // to detect here. We let it through on the assumption the user knows
7731 // what they are doing.)
7732 if (Result.isAddrLabelDiff())
7733 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007734 // Only allow casts of lvalues if they are lossless.
7735 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7736 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007737
Richard Smith911e1422012-01-30 22:27:01 +00007738 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7739 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007740 }
Mike Stump11289f42009-09-09 15:08:12 +00007741
Eli Friedmanc757de22011-03-25 00:43:55 +00007742 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007743 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7744
John McCall45d55e42010-05-07 21:00:08 +00007745 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007746 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007747 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007748
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007749 if (LV.getLValueBase()) {
7750 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007751 // FIXME: Allow a larger integer size than the pointer size, and allow
7752 // narrowing back down to pointer width in subsequent integral casts.
7753 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007754 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007755 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007756
Richard Smithcf74da72011-11-16 07:18:12 +00007757 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007758 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007759 return true;
7760 }
7761
Ken Dyck02990832010-01-15 12:37:54 +00007762 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7763 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007764 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007765 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007766
Eli Friedmanc757de22011-03-25 00:43:55 +00007767 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007768 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007769 if (!EvaluateComplex(SubExpr, C, Info))
7770 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007771 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007772 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007773
Eli Friedmanc757de22011-03-25 00:43:55 +00007774 case CK_FloatingToIntegral: {
7775 APFloat F(0.0);
7776 if (!EvaluateFloat(SubExpr, F, Info))
7777 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007778
Richard Smith357362d2011-12-13 06:39:58 +00007779 APSInt Value;
7780 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7781 return false;
7782 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007783 }
7784 }
Mike Stump11289f42009-09-09 15:08:12 +00007785
Eli Friedmanc757de22011-03-25 00:43:55 +00007786 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007787}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007788
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007789bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7790 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007791 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007792 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7793 return false;
7794 if (!LV.isComplexInt())
7795 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007796 return Success(LV.getComplexIntReal(), E);
7797 }
7798
7799 return Visit(E->getSubExpr());
7800}
7801
Eli Friedman4e7a2412009-02-27 04:45:43 +00007802bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007803 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007804 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007805 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7806 return false;
7807 if (!LV.isComplexInt())
7808 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007809 return Success(LV.getComplexIntImag(), E);
7810 }
7811
Richard Smith4a678122011-10-24 18:44:57 +00007812 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007813 return Success(0, E);
7814}
7815
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007816bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7817 return Success(E->getPackLength(), E);
7818}
7819
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007820bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7821 return Success(E->getValue(), E);
7822}
7823
Chris Lattner05706e882008-07-11 18:11:29 +00007824//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007825// Float Evaluation
7826//===----------------------------------------------------------------------===//
7827
7828namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007829class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007830 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007831 APFloat &Result;
7832public:
7833 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007834 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007835
Richard Smith2e312c82012-03-03 22:46:17 +00007836 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007837 Result = V.getFloat();
7838 return true;
7839 }
Eli Friedman24c01542008-08-22 00:06:13 +00007840
Richard Smithfddd3842011-12-30 21:15:51 +00007841 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007842 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7843 return true;
7844 }
7845
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007846 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007847
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007848 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007849 bool VisitBinaryOperator(const BinaryOperator *E);
7850 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007851 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007852
John McCallb1fb0d32010-05-07 22:08:54 +00007853 bool VisitUnaryReal(const UnaryOperator *E);
7854 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007855
Richard Smithfddd3842011-12-30 21:15:51 +00007856 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007857};
7858} // end anonymous namespace
7859
7860static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007861 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007862 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007863}
7864
Jay Foad39c79802011-01-12 09:06:06 +00007865static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007866 QualType ResultTy,
7867 const Expr *Arg,
7868 bool SNaN,
7869 llvm::APFloat &Result) {
7870 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7871 if (!S) return false;
7872
7873 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7874
7875 llvm::APInt fill;
7876
7877 // Treat empty strings as if they were zero.
7878 if (S->getString().empty())
7879 fill = llvm::APInt(32, 0);
7880 else if (S->getString().getAsInteger(0, fill))
7881 return false;
7882
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00007883 if (Context.getTargetInfo().isNan2008()) {
7884 if (SNaN)
7885 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7886 else
7887 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7888 } else {
7889 // Prior to IEEE 754-2008, architectures were allowed to choose whether
7890 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
7891 // a different encoding to what became a standard in 2008, and for pre-
7892 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
7893 // sNaN. This is now known as "legacy NaN" encoding.
7894 if (SNaN)
7895 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7896 else
7897 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7898 }
7899
John McCall16291492010-02-28 13:00:19 +00007900 return true;
7901}
7902
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007903bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007904 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007905 default:
7906 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7907
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007908 case Builtin::BI__builtin_huge_val:
7909 case Builtin::BI__builtin_huge_valf:
7910 case Builtin::BI__builtin_huge_vall:
7911 case Builtin::BI__builtin_inf:
7912 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007913 case Builtin::BI__builtin_infl: {
7914 const llvm::fltSemantics &Sem =
7915 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007916 Result = llvm::APFloat::getInf(Sem);
7917 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007918 }
Mike Stump11289f42009-09-09 15:08:12 +00007919
John McCall16291492010-02-28 13:00:19 +00007920 case Builtin::BI__builtin_nans:
7921 case Builtin::BI__builtin_nansf:
7922 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007923 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7924 true, Result))
7925 return Error(E);
7926 return true;
John McCall16291492010-02-28 13:00:19 +00007927
Chris Lattner0b7282e2008-10-06 06:31:58 +00007928 case Builtin::BI__builtin_nan:
7929 case Builtin::BI__builtin_nanf:
7930 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007931 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007932 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007933 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7934 false, Result))
7935 return Error(E);
7936 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007937
7938 case Builtin::BI__builtin_fabs:
7939 case Builtin::BI__builtin_fabsf:
7940 case Builtin::BI__builtin_fabsl:
7941 if (!EvaluateFloat(E->getArg(0), Result, Info))
7942 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007943
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007944 if (Result.isNegative())
7945 Result.changeSign();
7946 return true;
7947
Richard Smith8889a3d2013-06-13 06:26:32 +00007948 // FIXME: Builtin::BI__builtin_powi
7949 // FIXME: Builtin::BI__builtin_powif
7950 // FIXME: Builtin::BI__builtin_powil
7951
Mike Stump11289f42009-09-09 15:08:12 +00007952 case Builtin::BI__builtin_copysign:
7953 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007954 case Builtin::BI__builtin_copysignl: {
7955 APFloat RHS(0.);
7956 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7957 !EvaluateFloat(E->getArg(1), RHS, Info))
7958 return false;
7959 Result.copySign(RHS);
7960 return true;
7961 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007962 }
7963}
7964
John McCallb1fb0d32010-05-07 22:08:54 +00007965bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007966 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7967 ComplexValue CV;
7968 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7969 return false;
7970 Result = CV.FloatReal;
7971 return true;
7972 }
7973
7974 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007975}
7976
7977bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007978 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7979 ComplexValue CV;
7980 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7981 return false;
7982 Result = CV.FloatImag;
7983 return true;
7984 }
7985
Richard Smith4a678122011-10-24 18:44:57 +00007986 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007987 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7988 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007989 return true;
7990}
7991
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007992bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007993 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007994 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007995 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007996 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007997 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007998 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7999 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008000 Result.changeSign();
8001 return true;
8002 }
8003}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008004
Eli Friedman24c01542008-08-22 00:06:13 +00008005bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008006 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8007 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008008
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008009 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008010 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
8011 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008012 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008013 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8014 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008015}
8016
8017bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8018 Result = E->getValue();
8019 return true;
8020}
8021
Peter Collingbournee9200682011-05-13 03:29:01 +00008022bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8023 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008024
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008025 switch (E->getCastKind()) {
8026 default:
Richard Smith11562c52011-10-28 17:51:58 +00008027 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008028
8029 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008030 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008031 return EvaluateInteger(SubExpr, IntResult, Info) &&
8032 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8033 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008034 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008035
8036 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008037 if (!Visit(SubExpr))
8038 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008039 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8040 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008041 }
John McCalld7646252010-11-14 08:17:51 +00008042
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008043 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008044 ComplexValue V;
8045 if (!EvaluateComplex(SubExpr, V, Info))
8046 return false;
8047 Result = V.getComplexFloatReal();
8048 return true;
8049 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008050 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008051}
8052
Eli Friedman24c01542008-08-22 00:06:13 +00008053//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008054// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008055//===----------------------------------------------------------------------===//
8056
8057namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008058class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008059 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008060 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008061
Anders Carlsson537969c2008-11-16 20:27:53 +00008062public:
John McCall93d91dc2010-05-07 17:22:02 +00008063 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008064 : ExprEvaluatorBaseTy(info), Result(Result) {}
8065
Richard Smith2e312c82012-03-03 22:46:17 +00008066 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008067 Result.setFrom(V);
8068 return true;
8069 }
Mike Stump11289f42009-09-09 15:08:12 +00008070
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008071 bool ZeroInitialization(const Expr *E);
8072
Anders Carlsson537969c2008-11-16 20:27:53 +00008073 //===--------------------------------------------------------------------===//
8074 // Visitor Methods
8075 //===--------------------------------------------------------------------===//
8076
Peter Collingbournee9200682011-05-13 03:29:01 +00008077 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008078 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008079 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008080 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008081 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008082};
8083} // end anonymous namespace
8084
John McCall93d91dc2010-05-07 17:22:02 +00008085static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8086 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008087 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008088 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008089}
8090
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008091bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008092 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008093 if (ElemTy->isRealFloatingType()) {
8094 Result.makeComplexFloat();
8095 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8096 Result.FloatReal = Zero;
8097 Result.FloatImag = Zero;
8098 } else {
8099 Result.makeComplexInt();
8100 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8101 Result.IntReal = Zero;
8102 Result.IntImag = Zero;
8103 }
8104 return true;
8105}
8106
Peter Collingbournee9200682011-05-13 03:29:01 +00008107bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8108 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008109
8110 if (SubExpr->getType()->isRealFloatingType()) {
8111 Result.makeComplexFloat();
8112 APFloat &Imag = Result.FloatImag;
8113 if (!EvaluateFloat(SubExpr, Imag, Info))
8114 return false;
8115
8116 Result.FloatReal = APFloat(Imag.getSemantics());
8117 return true;
8118 } else {
8119 assert(SubExpr->getType()->isIntegerType() &&
8120 "Unexpected imaginary literal.");
8121
8122 Result.makeComplexInt();
8123 APSInt &Imag = Result.IntImag;
8124 if (!EvaluateInteger(SubExpr, Imag, Info))
8125 return false;
8126
8127 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8128 return true;
8129 }
8130}
8131
Peter Collingbournee9200682011-05-13 03:29:01 +00008132bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008133
John McCallfcef3cf2010-12-14 17:51:41 +00008134 switch (E->getCastKind()) {
8135 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008136 case CK_BaseToDerived:
8137 case CK_DerivedToBase:
8138 case CK_UncheckedDerivedToBase:
8139 case CK_Dynamic:
8140 case CK_ToUnion:
8141 case CK_ArrayToPointerDecay:
8142 case CK_FunctionToPointerDecay:
8143 case CK_NullToPointer:
8144 case CK_NullToMemberPointer:
8145 case CK_BaseToDerivedMemberPointer:
8146 case CK_DerivedToBaseMemberPointer:
8147 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008148 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008149 case CK_ConstructorConversion:
8150 case CK_IntegralToPointer:
8151 case CK_PointerToIntegral:
8152 case CK_PointerToBoolean:
8153 case CK_ToVoid:
8154 case CK_VectorSplat:
8155 case CK_IntegralCast:
8156 case CK_IntegralToBoolean:
8157 case CK_IntegralToFloating:
8158 case CK_FloatingToIntegral:
8159 case CK_FloatingToBoolean:
8160 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008161 case CK_CPointerToObjCPointerCast:
8162 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008163 case CK_AnyPointerToBlockPointerCast:
8164 case CK_ObjCObjectLValueCast:
8165 case CK_FloatingComplexToReal:
8166 case CK_FloatingComplexToBoolean:
8167 case CK_IntegralComplexToReal:
8168 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008169 case CK_ARCProduceObject:
8170 case CK_ARCConsumeObject:
8171 case CK_ARCReclaimReturnedObject:
8172 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008173 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008174 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008175 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008176 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008177 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008178 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008179
John McCallfcef3cf2010-12-14 17:51:41 +00008180 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008181 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008182 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008183 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008184
8185 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008186 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008187 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008188 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008189
8190 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008191 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008192 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008193 return false;
8194
John McCallfcef3cf2010-12-14 17:51:41 +00008195 Result.makeComplexFloat();
8196 Result.FloatImag = APFloat(Real.getSemantics());
8197 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008198 }
8199
John McCallfcef3cf2010-12-14 17:51:41 +00008200 case CK_FloatingComplexCast: {
8201 if (!Visit(E->getSubExpr()))
8202 return false;
8203
8204 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8205 QualType From
8206 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8207
Richard Smith357362d2011-12-13 06:39:58 +00008208 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8209 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008210 }
8211
8212 case CK_FloatingComplexToIntegralComplex: {
8213 if (!Visit(E->getSubExpr()))
8214 return false;
8215
8216 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8217 QualType From
8218 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8219 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008220 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8221 To, Result.IntReal) &&
8222 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8223 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008224 }
8225
8226 case CK_IntegralRealToComplex: {
8227 APSInt &Real = Result.IntReal;
8228 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8229 return false;
8230
8231 Result.makeComplexInt();
8232 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8233 return true;
8234 }
8235
8236 case CK_IntegralComplexCast: {
8237 if (!Visit(E->getSubExpr()))
8238 return false;
8239
8240 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8241 QualType From
8242 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8243
Richard Smith911e1422012-01-30 22:27:01 +00008244 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8245 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008246 return true;
8247 }
8248
8249 case CK_IntegralComplexToFloatingComplex: {
8250 if (!Visit(E->getSubExpr()))
8251 return false;
8252
Ted Kremenek28831752012-08-23 20:46:57 +00008253 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008254 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008255 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008256 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008257 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8258 To, Result.FloatReal) &&
8259 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8260 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008261 }
8262 }
8263
8264 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008265}
8266
John McCall93d91dc2010-05-07 17:22:02 +00008267bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008268 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008269 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8270
Chandler Carrutha216cad2014-10-11 00:57:18 +00008271 // Track whether the LHS or RHS is real at the type system level. When this is
8272 // the case we can simplify our evaluation strategy.
8273 bool LHSReal = false, RHSReal = false;
8274
8275 bool LHSOK;
8276 if (E->getLHS()->getType()->isRealFloatingType()) {
8277 LHSReal = true;
8278 APFloat &Real = Result.FloatReal;
8279 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8280 if (LHSOK) {
8281 Result.makeComplexFloat();
8282 Result.FloatImag = APFloat(Real.getSemantics());
8283 }
8284 } else {
8285 LHSOK = Visit(E->getLHS());
8286 }
Richard Smith253c2a32012-01-27 01:14:48 +00008287 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008288 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008289
John McCall93d91dc2010-05-07 17:22:02 +00008290 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008291 if (E->getRHS()->getType()->isRealFloatingType()) {
8292 RHSReal = true;
8293 APFloat &Real = RHS.FloatReal;
8294 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8295 return false;
8296 RHS.makeComplexFloat();
8297 RHS.FloatImag = APFloat(Real.getSemantics());
8298 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008299 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008300
Chandler Carrutha216cad2014-10-11 00:57:18 +00008301 assert(!(LHSReal && RHSReal) &&
8302 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008303 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008304 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008305 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008306 if (Result.isComplexFloat()) {
8307 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8308 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008309 if (LHSReal)
8310 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8311 else if (!RHSReal)
8312 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8313 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008314 } else {
8315 Result.getComplexIntReal() += RHS.getComplexIntReal();
8316 Result.getComplexIntImag() += RHS.getComplexIntImag();
8317 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008318 break;
John McCalle3027922010-08-25 11:45:40 +00008319 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008320 if (Result.isComplexFloat()) {
8321 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8322 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008323 if (LHSReal) {
8324 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8325 Result.getComplexFloatImag().changeSign();
8326 } else if (!RHSReal) {
8327 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8328 APFloat::rmNearestTiesToEven);
8329 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008330 } else {
8331 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8332 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8333 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008334 break;
John McCalle3027922010-08-25 11:45:40 +00008335 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008336 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008337 // This is an implementation of complex multiplication according to the
8338 // constraints laid out in C11 Annex G. The implemantion uses the
8339 // following naming scheme:
8340 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008341 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008342 APFloat &A = LHS.getComplexFloatReal();
8343 APFloat &B = LHS.getComplexFloatImag();
8344 APFloat &C = RHS.getComplexFloatReal();
8345 APFloat &D = RHS.getComplexFloatImag();
8346 APFloat &ResR = Result.getComplexFloatReal();
8347 APFloat &ResI = Result.getComplexFloatImag();
8348 if (LHSReal) {
8349 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8350 ResR = A * C;
8351 ResI = A * D;
8352 } else if (RHSReal) {
8353 ResR = C * A;
8354 ResI = C * B;
8355 } else {
8356 // In the fully general case, we need to handle NaNs and infinities
8357 // robustly.
8358 APFloat AC = A * C;
8359 APFloat BD = B * D;
8360 APFloat AD = A * D;
8361 APFloat BC = B * C;
8362 ResR = AC - BD;
8363 ResI = AD + BC;
8364 if (ResR.isNaN() && ResI.isNaN()) {
8365 bool Recalc = false;
8366 if (A.isInfinity() || B.isInfinity()) {
8367 A = APFloat::copySign(
8368 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8369 B = APFloat::copySign(
8370 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8371 if (C.isNaN())
8372 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8373 if (D.isNaN())
8374 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8375 Recalc = true;
8376 }
8377 if (C.isInfinity() || D.isInfinity()) {
8378 C = APFloat::copySign(
8379 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8380 D = APFloat::copySign(
8381 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8382 if (A.isNaN())
8383 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8384 if (B.isNaN())
8385 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8386 Recalc = true;
8387 }
8388 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8389 AD.isInfinity() || BC.isInfinity())) {
8390 if (A.isNaN())
8391 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8392 if (B.isNaN())
8393 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8394 if (C.isNaN())
8395 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8396 if (D.isNaN())
8397 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8398 Recalc = true;
8399 }
8400 if (Recalc) {
8401 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8402 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8403 }
8404 }
8405 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008406 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008407 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008408 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008409 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8410 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008411 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008412 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8413 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8414 }
8415 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008416 case BO_Div:
8417 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008418 // This is an implementation of complex division according to the
8419 // constraints laid out in C11 Annex G. The implemantion uses the
8420 // following naming scheme:
8421 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008422 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008423 APFloat &A = LHS.getComplexFloatReal();
8424 APFloat &B = LHS.getComplexFloatImag();
8425 APFloat &C = RHS.getComplexFloatReal();
8426 APFloat &D = RHS.getComplexFloatImag();
8427 APFloat &ResR = Result.getComplexFloatReal();
8428 APFloat &ResI = Result.getComplexFloatImag();
8429 if (RHSReal) {
8430 ResR = A / C;
8431 ResI = B / C;
8432 } else {
8433 if (LHSReal) {
8434 // No real optimizations we can do here, stub out with zero.
8435 B = APFloat::getZero(A.getSemantics());
8436 }
8437 int DenomLogB = 0;
8438 APFloat MaxCD = maxnum(abs(C), abs(D));
8439 if (MaxCD.isFinite()) {
8440 DenomLogB = ilogb(MaxCD);
8441 C = scalbn(C, -DenomLogB);
8442 D = scalbn(D, -DenomLogB);
8443 }
8444 APFloat Denom = C * C + D * D;
8445 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8446 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8447 if (ResR.isNaN() && ResI.isNaN()) {
8448 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8449 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8450 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8451 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8452 D.isFinite()) {
8453 A = APFloat::copySign(
8454 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8455 B = APFloat::copySign(
8456 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8457 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8458 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8459 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8460 C = APFloat::copySign(
8461 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8462 D = APFloat::copySign(
8463 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8464 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8465 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8466 }
8467 }
8468 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008469 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008470 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8471 return Error(E, diag::note_expr_divide_by_zero);
8472
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008473 ComplexValue LHS = Result;
8474 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8475 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8476 Result.getComplexIntReal() =
8477 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8478 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8479 Result.getComplexIntImag() =
8480 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8481 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8482 }
8483 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008484 }
8485
John McCall93d91dc2010-05-07 17:22:02 +00008486 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008487}
8488
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008489bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8490 // Get the operand value into 'Result'.
8491 if (!Visit(E->getSubExpr()))
8492 return false;
8493
8494 switch (E->getOpcode()) {
8495 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008496 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008497 case UO_Extension:
8498 return true;
8499 case UO_Plus:
8500 // The result is always just the subexpr.
8501 return true;
8502 case UO_Minus:
8503 if (Result.isComplexFloat()) {
8504 Result.getComplexFloatReal().changeSign();
8505 Result.getComplexFloatImag().changeSign();
8506 }
8507 else {
8508 Result.getComplexIntReal() = -Result.getComplexIntReal();
8509 Result.getComplexIntImag() = -Result.getComplexIntImag();
8510 }
8511 return true;
8512 case UO_Not:
8513 if (Result.isComplexFloat())
8514 Result.getComplexFloatImag().changeSign();
8515 else
8516 Result.getComplexIntImag() = -Result.getComplexIntImag();
8517 return true;
8518 }
8519}
8520
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008521bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8522 if (E->getNumInits() == 2) {
8523 if (E->getType()->isComplexType()) {
8524 Result.makeComplexFloat();
8525 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8526 return false;
8527 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8528 return false;
8529 } else {
8530 Result.makeComplexInt();
8531 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8532 return false;
8533 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8534 return false;
8535 }
8536 return true;
8537 }
8538 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8539}
8540
Anders Carlsson537969c2008-11-16 20:27:53 +00008541//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008542// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8543// implicit conversion.
8544//===----------------------------------------------------------------------===//
8545
8546namespace {
8547class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008548 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008549 APValue &Result;
8550public:
8551 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8552 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8553
8554 bool Success(const APValue &V, const Expr *E) {
8555 Result = V;
8556 return true;
8557 }
8558
8559 bool ZeroInitialization(const Expr *E) {
8560 ImplicitValueInitExpr VIE(
8561 E->getType()->castAs<AtomicType>()->getValueType());
8562 return Evaluate(Result, Info, &VIE);
8563 }
8564
8565 bool VisitCastExpr(const CastExpr *E) {
8566 switch (E->getCastKind()) {
8567 default:
8568 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8569 case CK_NonAtomicToAtomic:
8570 return Evaluate(Result, Info, E->getSubExpr());
8571 }
8572 }
8573};
8574} // end anonymous namespace
8575
8576static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8577 assert(E->isRValue() && E->getType()->isAtomicType());
8578 return AtomicExprEvaluator(Info, Result).Visit(E);
8579}
8580
8581//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008582// Void expression evaluation, primarily for a cast to void on the LHS of a
8583// comma operator
8584//===----------------------------------------------------------------------===//
8585
8586namespace {
8587class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008588 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008589public:
8590 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8591
Richard Smith2e312c82012-03-03 22:46:17 +00008592 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008593
8594 bool VisitCastExpr(const CastExpr *E) {
8595 switch (E->getCastKind()) {
8596 default:
8597 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8598 case CK_ToVoid:
8599 VisitIgnoredValue(E->getSubExpr());
8600 return true;
8601 }
8602 }
Hal Finkela8443c32014-07-17 14:49:58 +00008603
8604 bool VisitCallExpr(const CallExpr *E) {
8605 switch (E->getBuiltinCallee()) {
8606 default:
8607 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8608 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008609 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008610 // The argument is not evaluated!
8611 return true;
8612 }
8613 }
Richard Smith42d3af92011-12-07 00:43:50 +00008614};
8615} // end anonymous namespace
8616
8617static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8618 assert(E->isRValue() && E->getType()->isVoidType());
8619 return VoidExprEvaluator(Info).Visit(E);
8620}
8621
8622//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008623// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008624//===----------------------------------------------------------------------===//
8625
Richard Smith2e312c82012-03-03 22:46:17 +00008626static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008627 // In C, function designators are not lvalues, but we evaluate them as if they
8628 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008629 QualType T = E->getType();
8630 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008631 LValue LV;
8632 if (!EvaluateLValue(E, LV, Info))
8633 return false;
8634 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008635 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008636 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008637 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008638 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008639 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008640 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008641 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008642 LValue LV;
8643 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008644 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008645 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008646 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008647 llvm::APFloat F(0.0);
8648 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008649 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008650 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008651 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008652 ComplexValue C;
8653 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008654 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008655 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008656 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008657 MemberPtr P;
8658 if (!EvaluateMemberPointer(E, P, Info))
8659 return false;
8660 P.moveInto(Result);
8661 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008662 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008663 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008664 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008665 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8666 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008667 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008668 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008669 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008670 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008671 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008672 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8673 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008674 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008675 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008676 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008677 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008678 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008679 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008680 if (!EvaluateVoid(E, Info))
8681 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008682 } else if (T->isAtomicType()) {
8683 if (!EvaluateAtomic(E, Result, Info))
8684 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008685 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008686 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008687 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008688 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008689 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008690 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008691 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008692
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008693 return true;
8694}
8695
Richard Smithb228a862012-02-15 02:18:13 +00008696/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8697/// cases, the in-place evaluation is essential, since later initializers for
8698/// an object can indirectly refer to subobjects which were initialized earlier.
8699static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008700 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008701 assert(!E->isValueDependent());
8702
Richard Smith7525ff62013-05-09 07:14:00 +00008703 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008704 return false;
8705
8706 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008707 // Evaluate arrays and record types in-place, so that later initializers can
8708 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008709 if (E->getType()->isArrayType())
8710 return EvaluateArray(E, This, Result, Info);
8711 else if (E->getType()->isRecordType())
8712 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008713 }
8714
8715 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008716 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008717}
8718
Richard Smithf57d8cb2011-12-09 22:58:01 +00008719/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8720/// lvalue-to-rvalue cast if it is an lvalue.
8721static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008722 if (E->getType().isNull())
8723 return false;
8724
Richard Smithfddd3842011-12-30 21:15:51 +00008725 if (!CheckLiteralType(Info, E))
8726 return false;
8727
Richard Smith2e312c82012-03-03 22:46:17 +00008728 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008729 return false;
8730
8731 if (E->isGLValue()) {
8732 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008733 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008734 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008735 return false;
8736 }
8737
Richard Smith2e312c82012-03-03 22:46:17 +00008738 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008739 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008740}
Richard Smith11562c52011-10-28 17:51:58 +00008741
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008742static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8743 const ASTContext &Ctx, bool &IsConst) {
8744 // Fast-path evaluations of integer literals, since we sometimes see files
8745 // containing vast quantities of these.
8746 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8747 Result.Val = APValue(APSInt(L->getValue(),
8748 L->getType()->isUnsignedIntegerType()));
8749 IsConst = true;
8750 return true;
8751 }
James Dennett0492ef02014-03-14 17:44:10 +00008752
8753 // This case should be rare, but we need to check it before we check on
8754 // the type below.
8755 if (Exp->getType().isNull()) {
8756 IsConst = false;
8757 return true;
8758 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008759
8760 // FIXME: Evaluating values of large array and record types can cause
8761 // performance problems. Only do so in C++11 for now.
8762 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8763 Exp->getType()->isRecordType()) &&
8764 !Ctx.getLangOpts().CPlusPlus11) {
8765 IsConst = false;
8766 return true;
8767 }
8768 return false;
8769}
8770
8771
Richard Smith7b553f12011-10-29 00:50:52 +00008772/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008773/// any crazy technique (that has nothing to do with language standards) that
8774/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008775/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8776/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008777bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008778 bool IsConst;
8779 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8780 return IsConst;
8781
Richard Smith6d4c6582013-11-05 22:18:15 +00008782 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008783 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008784}
8785
Jay Foad39c79802011-01-12 09:06:06 +00008786bool Expr::EvaluateAsBooleanCondition(bool &Result,
8787 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008788 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008789 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008790 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008791}
8792
Richard Smith5fab0c92011-12-28 19:48:30 +00008793bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8794 SideEffectsKind AllowSideEffects) const {
8795 if (!getType()->isIntegralOrEnumerationType())
8796 return false;
8797
Richard Smith11562c52011-10-28 17:51:58 +00008798 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008799 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8800 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008801 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008802
Richard Smith11562c52011-10-28 17:51:58 +00008803 Result = ExprResult.Val.getInt();
8804 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008805}
8806
Jay Foad39c79802011-01-12 09:06:06 +00008807bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008808 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008809
John McCall45d55e42010-05-07 21:00:08 +00008810 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008811 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8812 !CheckLValueConstantExpression(Info, getExprLoc(),
8813 Ctx.getLValueReferenceType(getType()), LV))
8814 return false;
8815
Richard Smith2e312c82012-03-03 22:46:17 +00008816 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008817 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008818}
8819
Richard Smithd0b4dd62011-12-19 06:19:21 +00008820bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8821 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008822 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008823 // FIXME: Evaluating initializers for large array and record types can cause
8824 // performance problems. Only do so in C++11 for now.
8825 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008826 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008827 return false;
8828
Richard Smithd0b4dd62011-12-19 06:19:21 +00008829 Expr::EvalStatus EStatus;
8830 EStatus.Diag = &Notes;
8831
Richard Smith6d4c6582013-11-05 22:18:15 +00008832 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008833 InitInfo.setEvaluatingDecl(VD, Value);
8834
8835 LValue LVal;
8836 LVal.set(VD);
8837
Richard Smithfddd3842011-12-30 21:15:51 +00008838 // C++11 [basic.start.init]p2:
8839 // Variables with static storage duration or thread storage duration shall be
8840 // zero-initialized before any other initialization takes place.
8841 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008842 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008843 !VD->getType()->isReferenceType()) {
8844 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008845 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008846 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008847 return false;
8848 }
8849
Richard Smith7525ff62013-05-09 07:14:00 +00008850 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8851 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008852 EStatus.HasSideEffects)
8853 return false;
8854
8855 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8856 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008857}
8858
Richard Smith7b553f12011-10-29 00:50:52 +00008859/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8860/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008861bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008862 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008863 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008864}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008865
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008866APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008867 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008868 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008869 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008870 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008871 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008872 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008873 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008874
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008875 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008876}
John McCall864e3962010-05-07 05:32:02 +00008877
Richard Smithe9ff7702013-11-05 22:23:30 +00008878void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008879 bool IsConst;
8880 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008881 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008882 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008883 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8884 }
8885}
8886
Richard Smithe6c01442013-06-05 00:46:14 +00008887bool Expr::EvalResult::isGlobalLValue() const {
8888 assert(Val.isLValue());
8889 return IsGlobalLValue(Val.getLValueBase());
8890}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008891
8892
John McCall864e3962010-05-07 05:32:02 +00008893/// isIntegerConstantExpr - this recursive routine will test if an expression is
8894/// an integer constant expression.
8895
8896/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8897/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008898
8899// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008900// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8901// and a (possibly null) SourceLocation indicating the location of the problem.
8902//
John McCall864e3962010-05-07 05:32:02 +00008903// Note that to reduce code duplication, this helper does no evaluation
8904// itself; the caller checks whether the expression is evaluatable, and
8905// in the rare cases where CheckICE actually cares about the evaluated
8906// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008907
Dan Gohman28ade552010-07-26 21:25:24 +00008908namespace {
8909
Richard Smith9e575da2012-12-28 13:25:52 +00008910enum ICEKind {
8911 /// This expression is an ICE.
8912 IK_ICE,
8913 /// This expression is not an ICE, but if it isn't evaluated, it's
8914 /// a legal subexpression for an ICE. This return value is used to handle
8915 /// the comma operator in C99 mode, and non-constant subexpressions.
8916 IK_ICEIfUnevaluated,
8917 /// This expression is not an ICE, and is not a legal subexpression for one.
8918 IK_NotICE
8919};
8920
John McCall864e3962010-05-07 05:32:02 +00008921struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008922 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008923 SourceLocation Loc;
8924
Richard Smith9e575da2012-12-28 13:25:52 +00008925 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008926};
8927
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008928}
Dan Gohman28ade552010-07-26 21:25:24 +00008929
Richard Smith9e575da2012-12-28 13:25:52 +00008930static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8931
8932static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008933
Craig Toppera31a8822013-08-22 07:09:37 +00008934static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008935 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008936 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008937 !EVResult.Val.isInt())
8938 return ICEDiag(IK_NotICE, E->getLocStart());
8939
John McCall864e3962010-05-07 05:32:02 +00008940 return NoDiag();
8941}
8942
Craig Toppera31a8822013-08-22 07:09:37 +00008943static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008944 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008945 if (!E->getType()->isIntegralOrEnumerationType())
8946 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008947
8948 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008949#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008950#define STMT(Node, Base) case Expr::Node##Class:
8951#define EXPR(Node, Base)
8952#include "clang/AST/StmtNodes.inc"
8953 case Expr::PredefinedExprClass:
8954 case Expr::FloatingLiteralClass:
8955 case Expr::ImaginaryLiteralClass:
8956 case Expr::StringLiteralClass:
8957 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008958 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00008959 case Expr::MemberExprClass:
8960 case Expr::CompoundAssignOperatorClass:
8961 case Expr::CompoundLiteralExprClass:
8962 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008963 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00008964 case Expr::NoInitExprClass:
8965 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00008966 case Expr::ImplicitValueInitExprClass:
8967 case Expr::ParenListExprClass:
8968 case Expr::VAArgExprClass:
8969 case Expr::AddrLabelExprClass:
8970 case Expr::StmtExprClass:
8971 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008972 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008973 case Expr::CXXDynamicCastExprClass:
8974 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008975 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008976 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00008977 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008978 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008979 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008980 case Expr::CXXThisExprClass:
8981 case Expr::CXXThrowExprClass:
8982 case Expr::CXXNewExprClass:
8983 case Expr::CXXDeleteExprClass:
8984 case Expr::CXXPseudoDestructorExprClass:
8985 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00008986 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00008987 case Expr::DependentScopeDeclRefExprClass:
8988 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008989 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008990 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008991 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008992 case Expr::CXXTemporaryObjectExprClass:
8993 case Expr::CXXUnresolvedConstructExprClass:
8994 case Expr::CXXDependentScopeMemberExprClass:
8995 case Expr::UnresolvedMemberExprClass:
8996 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008997 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008998 case Expr::ObjCArrayLiteralClass:
8999 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009000 case Expr::ObjCEncodeExprClass:
9001 case Expr::ObjCMessageExprClass:
9002 case Expr::ObjCSelectorExprClass:
9003 case Expr::ObjCProtocolExprClass:
9004 case Expr::ObjCIvarRefExprClass:
9005 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009006 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009007 case Expr::ObjCIsaExprClass:
9008 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009009 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009010 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009011 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009012 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009013 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009014 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009015 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009016 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009017 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009018 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009019 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009020 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009021 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009022 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009023 case Expr::CoawaitExprClass:
9024 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009025 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009026
Richard Smithf137f932014-01-25 20:50:08 +00009027 case Expr::InitListExprClass: {
9028 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9029 // form "T x = { a };" is equivalent to "T x = a;".
9030 // Unless we're initializing a reference, T is a scalar as it is known to be
9031 // of integral or enumeration type.
9032 if (E->isRValue())
9033 if (cast<InitListExpr>(E)->getNumInits() == 1)
9034 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9035 return ICEDiag(IK_NotICE, E->getLocStart());
9036 }
9037
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009038 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009039 case Expr::GNUNullExprClass:
9040 // GCC considers the GNU __null value to be an integral constant expression.
9041 return NoDiag();
9042
John McCall7c454bb2011-07-15 05:09:51 +00009043 case Expr::SubstNonTypeTemplateParmExprClass:
9044 return
9045 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9046
John McCall864e3962010-05-07 05:32:02 +00009047 case Expr::ParenExprClass:
9048 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009049 case Expr::GenericSelectionExprClass:
9050 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009051 case Expr::IntegerLiteralClass:
9052 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009053 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009054 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009055 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009056 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009057 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009058 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009059 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009060 return NoDiag();
9061 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009062 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009063 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9064 // constant expressions, but they can never be ICEs because an ICE cannot
9065 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009066 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009067 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009068 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009069 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009070 }
Richard Smith6365c912012-02-24 22:12:32 +00009071 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009072 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9073 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009074 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009075 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009076 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009077 // Parameter variables are never constants. Without this check,
9078 // getAnyInitializer() can find a default argument, which leads
9079 // to chaos.
9080 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009081 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009082
9083 // C++ 7.1.5.1p2
9084 // A variable of non-volatile const-qualified integral or enumeration
9085 // type initialized by an ICE can be used in ICEs.
9086 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009087 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009088 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009089
Richard Smithd0b4dd62011-12-19 06:19:21 +00009090 const VarDecl *VD;
9091 // Look for a declaration of this variable that has an initializer, and
9092 // check whether it is an ICE.
9093 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9094 return NoDiag();
9095 else
Richard Smith9e575da2012-12-28 13:25:52 +00009096 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009097 }
9098 }
Richard Smith9e575da2012-12-28 13:25:52 +00009099 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009100 }
John McCall864e3962010-05-07 05:32:02 +00009101 case Expr::UnaryOperatorClass: {
9102 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9103 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009104 case UO_PostInc:
9105 case UO_PostDec:
9106 case UO_PreInc:
9107 case UO_PreDec:
9108 case UO_AddrOf:
9109 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009110 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009111 // C99 6.6/3 allows increment and decrement within unevaluated
9112 // subexpressions of constant expressions, but they can never be ICEs
9113 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009114 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009115 case UO_Extension:
9116 case UO_LNot:
9117 case UO_Plus:
9118 case UO_Minus:
9119 case UO_Not:
9120 case UO_Real:
9121 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009122 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009123 }
Richard Smith9e575da2012-12-28 13:25:52 +00009124
John McCall864e3962010-05-07 05:32:02 +00009125 // OffsetOf falls through here.
9126 }
9127 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009128 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9129 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9130 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9131 // compliance: we should warn earlier for offsetof expressions with
9132 // array subscripts that aren't ICEs, and if the array subscripts
9133 // are ICEs, the value of the offsetof must be an integer constant.
9134 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009135 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009136 case Expr::UnaryExprOrTypeTraitExprClass: {
9137 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9138 if ((Exp->getKind() == UETT_SizeOf) &&
9139 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009140 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009141 return NoDiag();
9142 }
9143 case Expr::BinaryOperatorClass: {
9144 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9145 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009146 case BO_PtrMemD:
9147 case BO_PtrMemI:
9148 case BO_Assign:
9149 case BO_MulAssign:
9150 case BO_DivAssign:
9151 case BO_RemAssign:
9152 case BO_AddAssign:
9153 case BO_SubAssign:
9154 case BO_ShlAssign:
9155 case BO_ShrAssign:
9156 case BO_AndAssign:
9157 case BO_XorAssign:
9158 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009159 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9160 // constant expressions, but they can never be ICEs because an ICE cannot
9161 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009162 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009163
John McCalle3027922010-08-25 11:45:40 +00009164 case BO_Mul:
9165 case BO_Div:
9166 case BO_Rem:
9167 case BO_Add:
9168 case BO_Sub:
9169 case BO_Shl:
9170 case BO_Shr:
9171 case BO_LT:
9172 case BO_GT:
9173 case BO_LE:
9174 case BO_GE:
9175 case BO_EQ:
9176 case BO_NE:
9177 case BO_And:
9178 case BO_Xor:
9179 case BO_Or:
9180 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009181 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9182 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009183 if (Exp->getOpcode() == BO_Div ||
9184 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009185 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009186 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009187 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009188 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009189 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009190 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009191 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009192 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009193 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009194 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009195 }
9196 }
9197 }
John McCalle3027922010-08-25 11:45:40 +00009198 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009199 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009200 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9201 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009202 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9203 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009204 } else {
9205 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009206 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009207 }
9208 }
Richard Smith9e575da2012-12-28 13:25:52 +00009209 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009210 }
John McCalle3027922010-08-25 11:45:40 +00009211 case BO_LAnd:
9212 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009213 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9214 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009215 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009216 // Rare case where the RHS has a comma "side-effect"; we need
9217 // to actually check the condition to see whether the side
9218 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009219 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009220 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009221 return RHSResult;
9222 return NoDiag();
9223 }
9224
Richard Smith9e575da2012-12-28 13:25:52 +00009225 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009226 }
9227 }
9228 }
9229 case Expr::ImplicitCastExprClass:
9230 case Expr::CStyleCastExprClass:
9231 case Expr::CXXFunctionalCastExprClass:
9232 case Expr::CXXStaticCastExprClass:
9233 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009234 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009235 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009236 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009237 if (isa<ExplicitCastExpr>(E)) {
9238 if (const FloatingLiteral *FL
9239 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9240 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9241 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9242 APSInt IgnoredVal(DestWidth, !DestSigned);
9243 bool Ignored;
9244 // If the value does not fit in the destination type, the behavior is
9245 // undefined, so we are not required to treat it as a constant
9246 // expression.
9247 if (FL->getValue().convertToInteger(IgnoredVal,
9248 llvm::APFloat::rmTowardZero,
9249 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009250 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009251 return NoDiag();
9252 }
9253 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009254 switch (cast<CastExpr>(E)->getCastKind()) {
9255 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009256 case CK_AtomicToNonAtomic:
9257 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009258 case CK_NoOp:
9259 case CK_IntegralToBoolean:
9260 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009261 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009262 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009263 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009264 }
John McCall864e3962010-05-07 05:32:02 +00009265 }
John McCallc07a0c72011-02-17 10:25:35 +00009266 case Expr::BinaryConditionalOperatorClass: {
9267 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9268 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009269 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009270 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009271 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9272 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9273 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009274 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009275 return FalseResult;
9276 }
John McCall864e3962010-05-07 05:32:02 +00009277 case Expr::ConditionalOperatorClass: {
9278 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9279 // If the condition (ignoring parens) is a __builtin_constant_p call,
9280 // then only the true side is actually considered in an integer constant
9281 // expression, and it is fully evaluated. This is an important GNU
9282 // extension. See GCC PR38377 for discussion.
9283 if (const CallExpr *CallCE
9284 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009285 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009286 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009287 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009288 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009289 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009290
Richard Smithf57d8cb2011-12-09 22:58:01 +00009291 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9292 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009293
Richard Smith9e575da2012-12-28 13:25:52 +00009294 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009295 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009296 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009297 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009298 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009299 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009300 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009301 return NoDiag();
9302 // Rare case where the diagnostics depend on which side is evaluated
9303 // Note that if we get here, CondResult is 0, and at least one of
9304 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009305 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009306 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009307 return TrueResult;
9308 }
9309 case Expr::CXXDefaultArgExprClass:
9310 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009311 case Expr::CXXDefaultInitExprClass:
9312 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009313 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009314 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009315 }
9316 }
9317
David Blaikiee4d798f2012-01-20 21:50:17 +00009318 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009319}
9320
Richard Smithf57d8cb2011-12-09 22:58:01 +00009321/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009322static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009323 const Expr *E,
9324 llvm::APSInt *Value,
9325 SourceLocation *Loc) {
9326 if (!E->getType()->isIntegralOrEnumerationType()) {
9327 if (Loc) *Loc = E->getExprLoc();
9328 return false;
9329 }
9330
Richard Smith66e05fe2012-01-18 05:21:49 +00009331 APValue Result;
9332 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009333 return false;
9334
Richard Smith98710fc2014-11-13 23:03:19 +00009335 if (!Result.isInt()) {
9336 if (Loc) *Loc = E->getExprLoc();
9337 return false;
9338 }
9339
Richard Smith66e05fe2012-01-18 05:21:49 +00009340 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009341 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009342}
9343
Craig Toppera31a8822013-08-22 07:09:37 +00009344bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9345 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009346 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009347 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009348
Richard Smith9e575da2012-12-28 13:25:52 +00009349 ICEDiag D = CheckICE(this, Ctx);
9350 if (D.Kind != IK_ICE) {
9351 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009352 return false;
9353 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009354 return true;
9355}
9356
Craig Toppera31a8822013-08-22 07:09:37 +00009357bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009358 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009359 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009360 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9361
9362 if (!isIntegerConstantExpr(Ctx, Loc))
9363 return false;
9364 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00009365 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009366 return true;
9367}
Richard Smith66e05fe2012-01-18 05:21:49 +00009368
Craig Toppera31a8822013-08-22 07:09:37 +00009369bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009370 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009371}
9372
Craig Toppera31a8822013-08-22 07:09:37 +00009373bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009374 SourceLocation *Loc) const {
9375 // We support this checking in C++98 mode in order to diagnose compatibility
9376 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009377 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009378
Richard Smith98a0a492012-02-14 21:38:30 +00009379 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009380 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009381 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009382 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009383 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009384
9385 APValue Scratch;
9386 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9387
9388 if (!Diags.empty()) {
9389 IsConstExpr = false;
9390 if (Loc) *Loc = Diags[0].first;
9391 } else if (!IsConstExpr) {
9392 // FIXME: This shouldn't happen.
9393 if (Loc) *Loc = getExprLoc();
9394 }
9395
9396 return IsConstExpr;
9397}
Richard Smith253c2a32012-01-27 01:14:48 +00009398
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009399bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9400 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009401 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009402 Expr::EvalStatus Status;
9403 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9404
9405 ArgVector ArgValues(Args.size());
9406 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9407 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009408 if ((*I)->isValueDependent() ||
9409 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009410 // If evaluation fails, throw away the argument entirely.
9411 ArgValues[I - Args.begin()] = APValue();
9412 if (Info.EvalStatus.HasSideEffects)
9413 return false;
9414 }
9415
9416 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009417 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009418 ArgValues.data());
9419 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9420}
9421
Richard Smith253c2a32012-01-27 01:14:48 +00009422bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009423 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009424 PartialDiagnosticAt> &Diags) {
9425 // FIXME: It would be useful to check constexpr function templates, but at the
9426 // moment the constant expression evaluator cannot cope with the non-rigorous
9427 // ASTs which we build for dependent expressions.
9428 if (FD->isDependentContext())
9429 return true;
9430
9431 Expr::EvalStatus Status;
9432 Status.Diag = &Diags;
9433
Richard Smith6d4c6582013-11-05 22:18:15 +00009434 EvalInfo Info(FD->getASTContext(), Status,
9435 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009436
9437 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009438 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009439
Richard Smith7525ff62013-05-09 07:14:00 +00009440 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009441 // is a temporary being used as the 'this' pointer.
9442 LValue This;
9443 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009444 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009445
Richard Smith253c2a32012-01-27 01:14:48 +00009446 ArrayRef<const Expr*> Args;
9447
9448 SourceLocation Loc = FD->getLocation();
9449
Richard Smith2e312c82012-03-03 22:46:17 +00009450 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009451 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9452 // Evaluate the call as a constant initializer, to allow the construction
9453 // of objects of non-literal types.
9454 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009455 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009456 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009457 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009458 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith253c2a32012-01-27 01:14:48 +00009459
9460 return Diags.empty();
9461}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009462
9463bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9464 const FunctionDecl *FD,
9465 SmallVectorImpl<
9466 PartialDiagnosticAt> &Diags) {
9467 Expr::EvalStatus Status;
9468 Status.Diag = &Diags;
9469
9470 EvalInfo Info(FD->getASTContext(), Status,
9471 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9472
9473 // Fabricate a call stack frame to give the arguments a plausible cover story.
9474 ArrayRef<const Expr*> Args;
9475 ArgVector ArgValues(0);
9476 bool Success = EvaluateArgs(Args, ArgValues, Info);
9477 (void)Success;
9478 assert(Success &&
9479 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009480 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009481
9482 APValue ResultScratch;
9483 Evaluate(ResultScratch, Info, E);
9484 return Diags.empty();
9485}