blob: 1c0d9eae69f5f3c1ed13792eec8cd690839263f6 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-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//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Richard Smith180f4792011-11-10 06:34:14 +000046 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000049
Richard Smith1bf9a9e2011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smith180f4792011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smithb4e85ed2012-01-06 16:39:00 +000079 /// Find the path length and type of the most-derived subobject in the given
80 /// path, and find the size of the containing array, if any.
81 static
82 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
83 ArrayRef<APValue::LValuePathEntry> Path,
84 uint64_t &ArraySize, QualType &Type) {
85 unsigned MostDerivedLength = 0;
86 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +000087 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +000088 if (Type->isArrayType()) {
89 const ConstantArrayType *CAT =
90 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
91 Type = CAT->getElementType();
92 ArraySize = CAT->getSize().getZExtValue();
93 MostDerivedLength = I + 1;
94 } else if (const FieldDecl *FD = getAsField(Path[I])) {
95 Type = FD->getType();
96 ArraySize = 0;
97 MostDerivedLength = I + 1;
98 } else {
Richard Smith9a17a682011-11-07 05:07:52 +000099 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000100 ArraySize = 0;
101 }
Richard Smith9a17a682011-11-07 05:07:52 +0000102 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000103 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000104 }
105
Richard Smithb4e85ed2012-01-06 16:39:00 +0000106 // The order of this enum is important for diagnostics.
107 enum CheckSubobjectKind {
108 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex
109 };
110
Richard Smith0a3bdb62011-11-04 02:25:55 +0000111 /// A path from a glvalue to a subobject of that glvalue.
112 struct SubobjectDesignator {
113 /// True if the subobject was named in a manner not supported by C++11. Such
114 /// lvalues can still be folded, but they are not core constant expressions
115 /// and we cannot perform lvalue-to-rvalue conversions on them.
116 bool Invalid : 1;
117
Richard Smithb4e85ed2012-01-06 16:39:00 +0000118 /// Is this a pointer one past the end of an object?
119 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000120
Richard Smithb4e85ed2012-01-06 16:39:00 +0000121 /// The length of the path to the most-derived object of which this is a
122 /// subobject.
123 unsigned MostDerivedPathLength : 30;
124
125 /// The size of the array of which the most-derived object is an element, or
126 /// 0 if the most-derived object is not an array element.
127 uint64_t MostDerivedArraySize;
128
129 /// The type of the most derived object referred to by this address.
130 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000131
Richard Smith9a17a682011-11-07 05:07:52 +0000132 typedef APValue::LValuePathEntry PathEntry;
133
Richard Smith0a3bdb62011-11-04 02:25:55 +0000134 /// The entries on the path from the glvalue to the designated subobject.
135 SmallVector<PathEntry, 8> Entries;
136
Richard Smithb4e85ed2012-01-06 16:39:00 +0000137 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000138
Richard Smithb4e85ed2012-01-06 16:39:00 +0000139 explicit SubobjectDesignator(QualType T)
140 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
141 MostDerivedArraySize(0), MostDerivedType(T) {}
142
143 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
144 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
145 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000146 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000147 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000148 ArrayRef<PathEntry> VEntries = V.getLValuePath();
149 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
150 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000151 MostDerivedPathLength =
152 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
153 V.getLValuePath(), MostDerivedArraySize,
154 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000155 }
156 }
157
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158 void setInvalid() {
159 Invalid = true;
160 Entries.clear();
161 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000162
163 /// Determine whether this is a one-past-the-end pointer.
164 bool isOnePastTheEnd() const {
165 if (IsOnePastTheEnd)
166 return true;
167 if (MostDerivedArraySize &&
168 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
169 return true;
170 return false;
171 }
172
173 /// Check that this refers to a valid subobject.
174 bool isValidSubobject() const {
175 if (Invalid)
176 return false;
177 return !isOnePastTheEnd();
178 }
179 /// Check that this refers to a valid subobject, and if not, produce a
180 /// relevant diagnostic and set the designator as invalid.
181 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
182
183 /// Update this designator to refer to the first element within this array.
184 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000185 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000186 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000187 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000188
189 // This is a most-derived object.
190 MostDerivedType = CAT->getElementType();
191 MostDerivedArraySize = CAT->getSize().getZExtValue();
192 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000193 }
194 /// Update this designator to refer to the given base or member of this
195 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000196 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000197 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000198 APValue::BaseOrMemberType Value(D, Virtual);
199 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000200 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000201
202 // If this isn't a base class, it's a new most-derived object.
203 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
204 MostDerivedType = FD->getType();
205 MostDerivedArraySize = 0;
206 MostDerivedPathLength = Entries.size();
207 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000210 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000211 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000212 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000213 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000214 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000215 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
216 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
217 setInvalid();
218 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000219 return;
220 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000221 // [expr.add]p4: For the purposes of these operators, a pointer to a
222 // nonarray object behaves the same as a pointer to the first element of
223 // an array of length one with the type of the object as its element type.
224 if (IsOnePastTheEnd && N == (uint64_t)-1)
225 IsOnePastTheEnd = false;
226 else if (!IsOnePastTheEnd && N == 1)
227 IsOnePastTheEnd = true;
228 else if (N != 0) {
229 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000230 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000231 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000232 }
233 };
234
Richard Smith47a1eed2011-10-29 20:57:55 +0000235 /// A core constant value. This can be the value of any constant expression,
236 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000237 ///
238 /// For an LValue, the base and offset are stored in the APValue subobject,
239 /// but the other information is stored in the SubobjectDesignator. For all
240 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000241 class CCValue : public APValue {
242 typedef llvm::APSInt APSInt;
243 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000244 /// If the value is a reference or pointer into a parameter or temporary,
245 /// this is the corresponding call stack frame.
246 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000247 /// If the value is a reference or pointer, this is a description of how the
248 /// subobject was specified.
249 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000250 public:
Richard Smith177dce72011-11-01 16:57:24 +0000251 struct GlobalValue {};
252
Richard Smith47a1eed2011-10-29 20:57:55 +0000253 CCValue() {}
254 explicit CCValue(const APSInt &I) : APValue(I) {}
255 explicit CCValue(const APFloat &F) : APValue(F) {}
256 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
257 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
258 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000259 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000260 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000261 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000262 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000263 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
264 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000265 CCValue(const ValueDecl *D, bool IsDerivedMember,
266 ArrayRef<const CXXRecordDecl*> Path) :
267 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000268 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
269 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000270
Richard Smith177dce72011-11-01 16:57:24 +0000271 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000272 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000273 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000274 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000275 SubobjectDesignator &getLValueDesignator() {
276 assert(getKind() == LValue);
277 return Designator;
278 }
279 const SubobjectDesignator &getLValueDesignator() const {
280 return const_cast<CCValue*>(this)->getLValueDesignator();
281 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000282 };
283
Richard Smithd0dccea2011-10-28 22:34:42 +0000284 /// A stack frame in the constexpr call stack.
285 struct CallStackFrame {
286 EvalInfo &Info;
287
288 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000289 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000290
Richard Smith08d6e032011-12-16 19:06:07 +0000291 /// CallLoc - The location of the call expression for this call.
292 SourceLocation CallLoc;
293
294 /// Callee - The function which was called.
295 const FunctionDecl *Callee;
296
Richard Smith180f4792011-11-10 06:34:14 +0000297 /// This - The binding for the this pointer in this call, if any.
298 const LValue *This;
299
Richard Smithd0dccea2011-10-28 22:34:42 +0000300 /// ParmBindings - Parameter bindings for this function call, indexed by
301 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000302 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000303
Richard Smithbd552ef2011-10-31 05:52:43 +0000304 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
305 typedef MapTy::const_iterator temp_iterator;
306 /// Temporaries - Temporary lvalues materialized within this stack frame.
307 MapTy Temporaries;
308
Richard Smith08d6e032011-12-16 19:06:07 +0000309 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
310 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000311 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000312 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000313 };
314
Richard Smithdd1f29b2011-12-12 09:28:41 +0000315 /// A partial diagnostic which we might know in advance that we are not going
316 /// to emit.
317 class OptionalDiagnostic {
318 PartialDiagnostic *Diag;
319
320 public:
321 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
322
323 template<typename T>
324 OptionalDiagnostic &operator<<(const T &v) {
325 if (Diag)
326 *Diag << v;
327 return *this;
328 }
329 };
330
Richard Smithbd552ef2011-10-31 05:52:43 +0000331 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000332 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000333
334 /// EvalStatus - Contains information about the evaluation.
335 Expr::EvalStatus &EvalStatus;
336
337 /// CurrentCall - The top of the constexpr call stack.
338 CallStackFrame *CurrentCall;
339
Richard Smithbd552ef2011-10-31 05:52:43 +0000340 /// CallStackDepth - The number of calls in the call stack right now.
341 unsigned CallStackDepth;
342
343 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
344 /// OpaqueValues - Values used as the common expression in a
345 /// BinaryConditionalOperator.
346 MapTy OpaqueValues;
347
348 /// BottomFrame - The frame in which evaluation started. This must be
349 /// initialized last.
350 CallStackFrame BottomFrame;
351
Richard Smith180f4792011-11-10 06:34:14 +0000352 /// EvaluatingDecl - This is the declaration whose initializer is being
353 /// evaluated, if any.
354 const VarDecl *EvaluatingDecl;
355
356 /// EvaluatingDeclValue - This is the value being constructed for the
357 /// declaration whose initializer is being evaluated, if any.
358 APValue *EvaluatingDeclValue;
359
Richard Smithc1c5f272011-12-13 06:39:58 +0000360 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
361 /// notes attached to it will also be stored, otherwise they will not be.
362 bool HasActiveDiagnostic;
363
Richard Smithbd552ef2011-10-31 05:52:43 +0000364
365 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000366 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000367 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
368 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000369
Richard Smithbd552ef2011-10-31 05:52:43 +0000370 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
371 MapTy::const_iterator i = OpaqueValues.find(e);
372 if (i == OpaqueValues.end()) return 0;
373 return &i->second;
374 }
375
Richard Smith180f4792011-11-10 06:34:14 +0000376 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
377 EvaluatingDecl = VD;
378 EvaluatingDeclValue = &Value;
379 }
380
Richard Smithc18c4232011-11-21 19:36:32 +0000381 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
382
Richard Smithc1c5f272011-12-13 06:39:58 +0000383 bool CheckCallLimit(SourceLocation Loc) {
384 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
385 return true;
386 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
387 << getLangOpts().ConstexprCallDepth;
388 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000389 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000390
Richard Smithc1c5f272011-12-13 06:39:58 +0000391 private:
392 /// Add a diagnostic to the diagnostics list.
393 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
394 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
395 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
396 return EvalStatus.Diag->back().second;
397 }
398
Richard Smith08d6e032011-12-16 19:06:07 +0000399 /// Add notes containing a call stack to the current point of evaluation.
400 void addCallStack(unsigned Limit);
401
Richard Smithc1c5f272011-12-13 06:39:58 +0000402 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000403 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000404 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
405 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000406 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000407 // If we have a prior diagnostic, it will be noting that the expression
408 // isn't a constant expression. This diagnostic is more important.
409 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000410 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000411 unsigned CallStackNotes = CallStackDepth - 1;
412 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
413 if (Limit)
414 CallStackNotes = std::min(CallStackNotes, Limit + 1);
415
Richard Smithc1c5f272011-12-13 06:39:58 +0000416 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000417 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000418 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
419 addDiag(Loc, DiagId);
420 addCallStack(Limit);
421 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000422 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000423 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000424 return OptionalDiagnostic();
425 }
426
427 /// Diagnose that the evaluation does not produce a C++11 core constant
428 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000429 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
430 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000431 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000432 // Don't override a previous diagnostic.
433 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
434 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000435 return Diag(Loc, DiagId, ExtraNotes);
436 }
437
438 /// Add a note to a prior diagnostic.
439 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
440 if (!HasActiveDiagnostic)
441 return OptionalDiagnostic();
442 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000443 }
Richard Smith099e7f62011-12-19 06:19:21 +0000444
445 /// Add a stack of notes to a prior diagnostic.
446 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
447 if (HasActiveDiagnostic) {
448 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
449 Diags.begin(), Diags.end());
450 }
451 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000452 };
Richard Smith08d6e032011-12-16 19:06:07 +0000453}
Richard Smithbd552ef2011-10-31 05:52:43 +0000454
Richard Smithb4e85ed2012-01-06 16:39:00 +0000455bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
456 CheckSubobjectKind CSK) {
457 if (Invalid)
458 return false;
459 if (isOnePastTheEnd()) {
460 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
461 << CSK;
462 setInvalid();
463 return false;
464 }
465 return true;
466}
467
468void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
469 const Expr *E, uint64_t N) {
470 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
471 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
472 << static_cast<int>(N) << /*array*/ 0
473 << static_cast<unsigned>(MostDerivedArraySize);
474 else
475 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
476 << static_cast<int>(N) << /*non-array*/ 1;
477 setInvalid();
478}
479
Richard Smith08d6e032011-12-16 19:06:07 +0000480CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
481 const FunctionDecl *Callee, const LValue *This,
482 const CCValue *Arguments)
483 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
484 This(This), Arguments(Arguments) {
485 Info.CurrentCall = this;
486 ++Info.CallStackDepth;
487}
488
489CallStackFrame::~CallStackFrame() {
490 assert(Info.CurrentCall == this && "calls retired out of order");
491 --Info.CallStackDepth;
492 Info.CurrentCall = Caller;
493}
494
495/// Produce a string describing the given constexpr call.
496static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
497 unsigned ArgIndex = 0;
498 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
499 !isa<CXXConstructorDecl>(Frame->Callee);
500
501 if (!IsMemberCall)
502 Out << *Frame->Callee << '(';
503
504 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
505 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
506 if (ArgIndex > IsMemberCall)
507 Out << ", ";
508
509 const ParmVarDecl *Param = *I;
510 const CCValue &Arg = Frame->Arguments[ArgIndex];
511 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
512 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
513 else {
514 // Deliberately slice off the frame to form an APValue we can print.
515 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
516 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000517 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000518 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
519 }
520
521 if (ArgIndex == 0 && IsMemberCall)
522 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000523 }
524
Richard Smith08d6e032011-12-16 19:06:07 +0000525 Out << ')';
526}
527
528void EvalInfo::addCallStack(unsigned Limit) {
529 // Determine which calls to skip, if any.
530 unsigned ActiveCalls = CallStackDepth - 1;
531 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
532 if (Limit && Limit < ActiveCalls) {
533 SkipStart = Limit / 2 + Limit % 2;
534 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000535 }
536
Richard Smith08d6e032011-12-16 19:06:07 +0000537 // Walk the call stack and add the diagnostics.
538 unsigned CallIdx = 0;
539 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
540 Frame = Frame->Caller, ++CallIdx) {
541 // Skip this call?
542 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
543 if (CallIdx == SkipStart) {
544 // Note that we're skipping calls.
545 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
546 << unsigned(ActiveCalls - Limit);
547 }
548 continue;
549 }
550
551 llvm::SmallVector<char, 128> Buffer;
552 llvm::raw_svector_ostream Out(Buffer);
553 describeCall(Frame, Out);
554 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
555 }
556}
557
558namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000559 struct ComplexValue {
560 private:
561 bool IsInt;
562
563 public:
564 APSInt IntReal, IntImag;
565 APFloat FloatReal, FloatImag;
566
567 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
568
569 void makeComplexFloat() { IsInt = false; }
570 bool isComplexFloat() const { return !IsInt; }
571 APFloat &getComplexFloatReal() { return FloatReal; }
572 APFloat &getComplexFloatImag() { return FloatImag; }
573
574 void makeComplexInt() { IsInt = true; }
575 bool isComplexInt() const { return IsInt; }
576 APSInt &getComplexIntReal() { return IntReal; }
577 APSInt &getComplexIntImag() { return IntImag; }
578
Richard Smith47a1eed2011-10-29 20:57:55 +0000579 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000580 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000581 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000582 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000583 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000584 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000585 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000586 assert(v.isComplexFloat() || v.isComplexInt());
587 if (v.isComplexFloat()) {
588 makeComplexFloat();
589 FloatReal = v.getComplexFloatReal();
590 FloatImag = v.getComplexFloatImag();
591 } else {
592 makeComplexInt();
593 IntReal = v.getComplexIntReal();
594 IntImag = v.getComplexIntImag();
595 }
596 }
John McCallf4cf1a12010-05-07 17:22:02 +0000597 };
John McCallefdb83e2010-05-07 21:00:08 +0000598
599 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000600 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000601 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000602 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000603 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000604
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000605 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000606 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000607 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000608 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000609 SubobjectDesignator &getLValueDesignator() { return Designator; }
610 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000611
Richard Smith47a1eed2011-10-29 20:57:55 +0000612 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000613 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000614 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000615 void setFrom(const CCValue &V) {
616 assert(V.isLValue());
617 Base = V.getLValueBase();
618 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000619 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000620 Designator = V.getLValueDesignator();
621 }
622
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000623 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
624 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000625 Offset = CharUnits::Zero();
626 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000627 Designator = SubobjectDesignator(getType(B));
628 }
629
630 // Check that this LValue is not based on a null pointer. If it is, produce
631 // a diagnostic and mark the designator as invalid.
632 bool checkNullPointer(EvalInfo &Info, const Expr *E,
633 CheckSubobjectKind CSK) {
634 if (Designator.Invalid)
635 return false;
636 if (!Base) {
637 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
638 << CSK;
639 Designator.setInvalid();
640 return false;
641 }
642 return true;
643 }
644
645 // Check this LValue refers to an object. If not, set the designator to be
646 // invalid and emit a diagnostic.
647 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
648 return checkNullPointer(Info, E, CSK) &&
649 Designator.checkSubobject(Info, E, CSK);
650 }
651
652 void addDecl(EvalInfo &Info, const Expr *E,
653 const Decl *D, bool Virtual = false) {
654 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
655 Designator.addDeclUnchecked(D, Virtual);
656 }
657 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
658 checkSubobject(Info, E, CSK_ArrayToPointer);
659 Designator.addArrayUnchecked(CAT);
660 }
661 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
662 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
663 return;
664 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000665 }
John McCallefdb83e2010-05-07 21:00:08 +0000666 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000667
668 struct MemberPtr {
669 MemberPtr() {}
670 explicit MemberPtr(const ValueDecl *Decl) :
671 DeclAndIsDerivedMember(Decl, false), Path() {}
672
673 /// The member or (direct or indirect) field referred to by this member
674 /// pointer, or 0 if this is a null member pointer.
675 const ValueDecl *getDecl() const {
676 return DeclAndIsDerivedMember.getPointer();
677 }
678 /// Is this actually a member of some type derived from the relevant class?
679 bool isDerivedMember() const {
680 return DeclAndIsDerivedMember.getInt();
681 }
682 /// Get the class which the declaration actually lives in.
683 const CXXRecordDecl *getContainingRecord() const {
684 return cast<CXXRecordDecl>(
685 DeclAndIsDerivedMember.getPointer()->getDeclContext());
686 }
687
688 void moveInto(CCValue &V) const {
689 V = CCValue(getDecl(), isDerivedMember(), Path);
690 }
691 void setFrom(const CCValue &V) {
692 assert(V.isMemberPointer());
693 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
694 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
695 Path.clear();
696 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
697 Path.insert(Path.end(), P.begin(), P.end());
698 }
699
700 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
701 /// whether the member is a member of some class derived from the class type
702 /// of the member pointer.
703 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
704 /// Path - The path of base/derived classes from the member declaration's
705 /// class (exclusive) to the class type of the member pointer (inclusive).
706 SmallVector<const CXXRecordDecl*, 4> Path;
707
708 /// Perform a cast towards the class of the Decl (either up or down the
709 /// hierarchy).
710 bool castBack(const CXXRecordDecl *Class) {
711 assert(!Path.empty());
712 const CXXRecordDecl *Expected;
713 if (Path.size() >= 2)
714 Expected = Path[Path.size() - 2];
715 else
716 Expected = getContainingRecord();
717 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
718 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
719 // if B does not contain the original member and is not a base or
720 // derived class of the class containing the original member, the result
721 // of the cast is undefined.
722 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
723 // (D::*). We consider that to be a language defect.
724 return false;
725 }
726 Path.pop_back();
727 return true;
728 }
729 /// Perform a base-to-derived member pointer cast.
730 bool castToDerived(const CXXRecordDecl *Derived) {
731 if (!getDecl())
732 return true;
733 if (!isDerivedMember()) {
734 Path.push_back(Derived);
735 return true;
736 }
737 if (!castBack(Derived))
738 return false;
739 if (Path.empty())
740 DeclAndIsDerivedMember.setInt(false);
741 return true;
742 }
743 /// Perform a derived-to-base member pointer cast.
744 bool castToBase(const CXXRecordDecl *Base) {
745 if (!getDecl())
746 return true;
747 if (Path.empty())
748 DeclAndIsDerivedMember.setInt(true);
749 if (isDerivedMember()) {
750 Path.push_back(Base);
751 return true;
752 }
753 return castBack(Base);
754 }
755 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000756
757 /// Kinds of constant expression checking, for diagnostics.
758 enum CheckConstantExpressionKind {
759 CCEK_Constant, ///< A normal constant.
760 CCEK_ReturnValue, ///< A constexpr function return value.
761 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
762 };
John McCallf4cf1a12010-05-07 17:22:02 +0000763}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000764
Richard Smith47a1eed2011-10-29 20:57:55 +0000765static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000766static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000767 const LValue &This, const Expr *E,
768 CheckConstantExpressionKind CCEK
769 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000770static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
771static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000772static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
773 EvalInfo &Info);
774static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000775static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000776static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000777 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000778static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000779static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000780
781//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000782// Misc utilities
783//===----------------------------------------------------------------------===//
784
Richard Smith180f4792011-11-10 06:34:14 +0000785/// Should this call expression be treated as a string literal?
786static bool IsStringLiteralCall(const CallExpr *E) {
787 unsigned Builtin = E->isBuiltinCall();
788 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
789 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
790}
791
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000792static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000793 // C++11 [expr.const]p3 An address constant expression is a prvalue core
794 // constant expression of pointer type that evaluates to...
795
796 // ... a null pointer value, or a prvalue core constant expression of type
797 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000798 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000799
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000800 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
801 // ... the address of an object with static storage duration,
802 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
803 return VD->hasGlobalStorage();
804 // ... the address of a function,
805 return isa<FunctionDecl>(D);
806 }
807
808 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000809 switch (E->getStmtClass()) {
810 default:
811 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000812 case Expr::CompoundLiteralExprClass:
813 return cast<CompoundLiteralExpr>(E)->isFileScope();
814 // A string literal has static storage duration.
815 case Expr::StringLiteralClass:
816 case Expr::PredefinedExprClass:
817 case Expr::ObjCStringLiteralClass:
818 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000819 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000820 return true;
821 case Expr::CallExprClass:
822 return IsStringLiteralCall(cast<CallExpr>(E));
823 // For GCC compatibility, &&label has static storage duration.
824 case Expr::AddrLabelExprClass:
825 return true;
826 // A Block literal expression may be used as the initialization value for
827 // Block variables at global or local static scope.
828 case Expr::BlockExprClass:
829 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
830 }
John McCall42c8f872010-05-10 23:27:23 +0000831}
832
Richard Smith9a17a682011-11-07 05:07:52 +0000833/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000834/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000835/// either LValue or CCValue. Return true if we can fold this expression,
836/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000837template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000838static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000839 const T &LVal, APValue &Value,
840 CheckConstantExpressionKind CCEK) {
841 APValue::LValueBase Base = LVal.getLValueBase();
842 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
843
844 if (!IsGlobalLValue(Base)) {
845 if (Info.getLangOpts().CPlusPlus0x) {
846 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
847 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
848 << E->isGLValue() << !Designator.Entries.empty()
849 << !!VD << CCEK << VD;
850 if (VD)
851 Info.Note(VD->getLocation(), diag::note_declared_at);
852 else
853 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
854 diag::note_constexpr_temporary_here);
855 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000856 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000857 }
Richard Smith61e61622012-01-12 06:08:57 +0000858 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000859 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000860 }
Richard Smith9a17a682011-11-07 05:07:52 +0000861
Richard Smithb4e85ed2012-01-06 16:39:00 +0000862 bool IsReferenceType = E->isGLValue();
863
864 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000865 // This is not a core constant expression. An appropriate diagnostic will
866 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000867 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
868 APValue::NoLValuePath());
869 return true;
870 }
871
Richard Smithb4e85ed2012-01-06 16:39:00 +0000872 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
873 Designator.Entries, Designator.IsOnePastTheEnd);
874
875 // Allow address constant expressions to be past-the-end pointers. This is
876 // an extension: the standard requires them to point to an object.
877 if (!IsReferenceType)
878 return true;
879
880 // A reference constant expression must refer to an object.
881 if (!Base) {
882 // FIXME: diagnostic
883 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000884 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000885 }
886
Richard Smithc1c5f272011-12-13 06:39:58 +0000887 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000888 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000889 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
890 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
891 << !Designator.Entries.empty() << !!VD << VD;
892 if (VD)
893 Info.Note(VD->getLocation(), diag::note_declared_at);
894 else
895 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
896 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000897 }
898
Richard Smith9a17a682011-11-07 05:07:52 +0000899 return true;
900}
901
Richard Smith51201882011-12-30 21:15:51 +0000902/// Check that this core constant expression is of literal type, and if not,
903/// produce an appropriate diagnostic.
904static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
905 if (!E->isRValue() || E->getType()->isLiteralType())
906 return true;
907
908 // Prvalue constant expressions must be of literal types.
909 if (Info.getLangOpts().CPlusPlus0x)
910 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
911 << E->getType();
912 else
913 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
914 return false;
915}
916
Richard Smith47a1eed2011-10-29 20:57:55 +0000917/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000918/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +0000919/// If not, report an appropriate diagnostic. Does not check that the expression
920/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000921static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000922 const CCValue &CCValue, APValue &Value,
923 CheckConstantExpressionKind CCEK
924 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000925 if (!CCValue.isLValue()) {
926 Value = CCValue;
927 return true;
928 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000929 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000930}
931
Richard Smith9e36b532011-10-31 05:11:32 +0000932const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000933 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000934}
935
936static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000937 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000938}
939
Richard Smith65ac5982011-11-01 21:06:14 +0000940static bool IsWeakLValue(const LValue &Value) {
941 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000942 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000943}
944
Richard Smithe24f5fc2011-11-17 22:56:20 +0000945static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000946 // A null base expression indicates a null pointer. These are always
947 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000948 if (!Value.getLValueBase()) {
949 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000950 return true;
951 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000952
John McCall42c8f872010-05-10 23:27:23 +0000953 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000954 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000955 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall42c8f872010-05-10 23:27:23 +0000956
Richard Smithe24f5fc2011-11-17 22:56:20 +0000957 // We have a non-null base. These are generally known to be true, but if it's
958 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000959 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000960 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +0000961 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +0000962}
963
Richard Smith47a1eed2011-10-29 20:57:55 +0000964static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000965 switch (Val.getKind()) {
966 case APValue::Uninitialized:
967 return false;
968 case APValue::Int:
969 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000970 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000971 case APValue::Float:
972 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000973 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000974 case APValue::ComplexInt:
975 Result = Val.getComplexIntReal().getBoolValue() ||
976 Val.getComplexIntImag().getBoolValue();
977 return true;
978 case APValue::ComplexFloat:
979 Result = !Val.getComplexFloatReal().isZero() ||
980 !Val.getComplexFloatImag().isZero();
981 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000982 case APValue::LValue:
983 return EvalPointerValueAsBool(Val, Result);
984 case APValue::MemberPointer:
985 Result = Val.getMemberPointerDecl();
986 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000987 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000988 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000989 case APValue::Struct:
990 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +0000991 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +0000992 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000993 }
994
Richard Smithc49bd112011-10-28 17:51:58 +0000995 llvm_unreachable("unknown APValue kind");
996}
997
998static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
999 EvalInfo &Info) {
1000 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001001 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001002 if (!Evaluate(Val, Info, E))
1003 return false;
1004 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001005}
1006
Richard Smithc1c5f272011-12-13 06:39:58 +00001007template<typename T>
1008static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1009 const T &SrcValue, QualType DestType) {
1010 llvm::SmallVector<char, 32> Buffer;
1011 SrcValue.toString(Buffer);
1012 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
1013 << StringRef(Buffer.data(), Buffer.size()) << DestType;
1014 return false;
1015}
1016
1017static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1018 QualType SrcType, const APFloat &Value,
1019 QualType DestType, APSInt &Result) {
1020 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001021 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001022 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Richard Smithc1c5f272011-12-13 06:39:58 +00001024 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001025 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001026 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1027 & APFloat::opInvalidOp)
1028 return HandleOverflow(Info, E, Value, DestType);
1029 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001030}
1031
Richard Smithc1c5f272011-12-13 06:39:58 +00001032static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1033 QualType SrcType, QualType DestType,
1034 APFloat &Result) {
1035 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001036 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001037 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1038 APFloat::rmNearestTiesToEven, &ignored)
1039 & APFloat::opOverflow)
1040 return HandleOverflow(Info, E, Value, DestType);
1041 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001042}
1043
Mike Stump1eb44332009-09-09 15:08:12 +00001044static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +00001045 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001046 unsigned DestWidth = Ctx.getIntWidth(DestType);
1047 APSInt Result = Value;
1048 // Figure out if this is a truncate, extend or noop cast.
1049 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001050 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001051 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001052 return Result;
1053}
1054
Richard Smithc1c5f272011-12-13 06:39:58 +00001055static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1056 QualType SrcType, const APSInt &Value,
1057 QualType DestType, APFloat &Result) {
1058 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1059 if (Result.convertFromAPInt(Value, Value.isSigned(),
1060 APFloat::rmNearestTiesToEven)
1061 & APFloat::opOverflow)
1062 return HandleOverflow(Info, E, Value, DestType);
1063 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001064}
1065
Eli Friedmane6a24e82011-12-22 03:51:45 +00001066static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1067 llvm::APInt &Res) {
1068 CCValue SVal;
1069 if (!Evaluate(SVal, Info, E))
1070 return false;
1071 if (SVal.isInt()) {
1072 Res = SVal.getInt();
1073 return true;
1074 }
1075 if (SVal.isFloat()) {
1076 Res = SVal.getFloat().bitcastToAPInt();
1077 return true;
1078 }
1079 if (SVal.isVector()) {
1080 QualType VecTy = E->getType();
1081 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1082 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1083 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1084 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1085 Res = llvm::APInt::getNullValue(VecSize);
1086 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1087 APValue &Elt = SVal.getVectorElt(i);
1088 llvm::APInt EltAsInt;
1089 if (Elt.isInt()) {
1090 EltAsInt = Elt.getInt();
1091 } else if (Elt.isFloat()) {
1092 EltAsInt = Elt.getFloat().bitcastToAPInt();
1093 } else {
1094 // Don't try to handle vectors of anything other than int or float
1095 // (not sure if it's possible to hit this case).
1096 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1097 return false;
1098 }
1099 unsigned BaseEltSize = EltAsInt.getBitWidth();
1100 if (BigEndian)
1101 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1102 else
1103 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1104 }
1105 return true;
1106 }
1107 // Give up if the input isn't an int, float, or vector. For example, we
1108 // reject "(v4i16)(intptr_t)&a".
1109 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1110 return false;
1111}
1112
Richard Smithb4e85ed2012-01-06 16:39:00 +00001113/// Cast an lvalue referring to a base subobject to a derived class, by
1114/// truncating the lvalue's path to the given length.
1115static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1116 const RecordDecl *TruncatedType,
1117 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001118 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001119
1120 // Check we actually point to a derived class object.
1121 if (TruncatedElements == D.Entries.size())
1122 return true;
1123 assert(TruncatedElements >= D.MostDerivedPathLength &&
1124 "not casting to a derived class");
1125 if (!Result.checkSubobject(Info, E, CSK_Derived))
1126 return false;
1127
1128 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001129 const RecordDecl *RD = TruncatedType;
1130 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001131 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1132 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001133 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001134 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001135 else
Richard Smith180f4792011-11-10 06:34:14 +00001136 Result.Offset -= Layout.getBaseClassOffset(Base);
1137 RD = Base;
1138 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001139 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001140 return true;
1141}
1142
Richard Smithb4e85ed2012-01-06 16:39:00 +00001143static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001144 const CXXRecordDecl *Derived,
1145 const CXXRecordDecl *Base,
1146 const ASTRecordLayout *RL = 0) {
1147 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1148 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001149 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001150}
1151
Richard Smithb4e85ed2012-01-06 16:39:00 +00001152static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001153 const CXXRecordDecl *DerivedDecl,
1154 const CXXBaseSpecifier *Base) {
1155 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1156
1157 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001158 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001159 return true;
1160 }
1161
Richard Smithb4e85ed2012-01-06 16:39:00 +00001162 SubobjectDesignator &D = Obj.Designator;
1163 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001164 return false;
1165
Richard Smithb4e85ed2012-01-06 16:39:00 +00001166 // Extract most-derived object and corresponding type.
1167 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1168 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1169 return false;
1170
1171 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001172 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1173 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001174 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001175 return true;
1176}
1177
1178/// Update LVal to refer to the given field, which must be a member of the type
1179/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001180static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001181 const FieldDecl *FD,
1182 const ASTRecordLayout *RL = 0) {
1183 if (!RL)
1184 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1185
1186 unsigned I = FD->getFieldIndex();
1187 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001188 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001189}
1190
Richard Smithd9b02e72012-01-25 22:15:11 +00001191/// Update LVal to refer to the given indirect field.
1192static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1193 LValue &LVal,
1194 const IndirectFieldDecl *IFD) {
1195 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1196 CE = IFD->chain_end(); C != CE; ++C)
1197 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1198}
1199
Richard Smith180f4792011-11-10 06:34:14 +00001200/// Get the size of the given type in char units.
1201static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1202 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1203 // extension.
1204 if (Type->isVoidType() || Type->isFunctionType()) {
1205 Size = CharUnits::One();
1206 return true;
1207 }
1208
1209 if (!Type->isConstantSizeType()) {
1210 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001211 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001212 return false;
1213 }
1214
1215 Size = Info.Ctx.getTypeSizeInChars(Type);
1216 return true;
1217}
1218
1219/// Update a pointer value to model pointer arithmetic.
1220/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001221/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001222/// \param LVal - The pointer value to be updated.
1223/// \param EltTy - The pointee type represented by LVal.
1224/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001225static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1226 LValue &LVal, QualType EltTy,
1227 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001228 CharUnits SizeOfPointee;
1229 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1230 return false;
1231
1232 // Compute the new offset in the appropriate width.
1233 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001234 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001235 return true;
1236}
1237
Richard Smith03f96112011-10-24 17:54:18 +00001238/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001239static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1240 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001241 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001242 // If this is a parameter to an active constexpr function call, perform
1243 // argument substitution.
1244 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001245 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001246 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001247 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001248 }
Richard Smith177dce72011-11-01 16:57:24 +00001249 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1250 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001251 }
Richard Smith03f96112011-10-24 17:54:18 +00001252
Richard Smith099e7f62011-12-19 06:19:21 +00001253 // Dig out the initializer, and use the declaration which it's attached to.
1254 const Expr *Init = VD->getAnyInitializer(VD);
1255 if (!Init || Init->isValueDependent()) {
1256 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1257 return false;
1258 }
1259
Richard Smith180f4792011-11-10 06:34:14 +00001260 // If we're currently evaluating the initializer of this declaration, use that
1261 // in-flight value.
1262 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001263 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1264 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001265 return !Result.isUninit();
1266 }
1267
Richard Smith65ac5982011-11-01 21:06:14 +00001268 // Never evaluate the initializer of a weak variable. We can't be sure that
1269 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001270 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001271 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001272 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001273 }
Richard Smith65ac5982011-11-01 21:06:14 +00001274
Richard Smith099e7f62011-12-19 06:19:21 +00001275 // Check that we can fold the initializer. In C++, we will have already done
1276 // this in the cases where it matters for conformance.
1277 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1278 if (!VD->evaluateValue(Notes)) {
1279 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1280 Notes.size() + 1) << VD;
1281 Info.Note(VD->getLocation(), diag::note_declared_at);
1282 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001283 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001284 } else if (!VD->checkInitIsICE()) {
1285 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1286 Notes.size() + 1) << VD;
1287 Info.Note(VD->getLocation(), diag::note_declared_at);
1288 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001289 }
Richard Smith03f96112011-10-24 17:54:18 +00001290
Richard Smithb4e85ed2012-01-06 16:39:00 +00001291 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001292 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001293}
1294
Richard Smithc49bd112011-10-28 17:51:58 +00001295static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001296 Qualifiers Quals = T.getQualifiers();
1297 return Quals.hasConst() && !Quals.hasVolatile();
1298}
1299
Richard Smith59efe262011-11-11 04:05:33 +00001300/// Get the base index of the given base class within an APValue representing
1301/// the given derived class.
1302static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1303 const CXXRecordDecl *Base) {
1304 Base = Base->getCanonicalDecl();
1305 unsigned Index = 0;
1306 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1307 E = Derived->bases_end(); I != E; ++I, ++Index) {
1308 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1309 return Index;
1310 }
1311
1312 llvm_unreachable("base class missing from derived class's bases list");
1313}
1314
Richard Smithcc5d4f62011-11-07 09:22:26 +00001315/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001316static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1317 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001318 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001319 if (Sub.Invalid)
1320 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001321 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001322 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001323 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001324 (unsigned)diag::note_constexpr_read_past_end :
1325 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001326 return false;
1327 }
Richard Smithf64699e2011-11-11 08:28:03 +00001328 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001329 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001330
1331 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1332 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001333 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001334 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001335 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001336 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001337 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001338 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001339 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001340 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001341 // Note, it should not be possible to form a pointer with a valid
1342 // designator which points more than one past the end of the array.
1343 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001344 (unsigned)diag::note_constexpr_read_past_end :
1345 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001346 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001347 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001348 if (O->getArrayInitializedElts() > Index)
1349 O = &O->getArrayInitializedElt(Index);
1350 else
1351 O = &O->getArrayFiller();
1352 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001353 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1354 // Next subobject is a class, struct or union field.
1355 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1356 if (RD->isUnion()) {
1357 const FieldDecl *UnionField = O->getUnionField();
1358 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001359 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001360 Info.Diag(E->getExprLoc(),
1361 diag::note_constexpr_read_inactive_union_member)
1362 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001363 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001364 }
Richard Smith180f4792011-11-10 06:34:14 +00001365 O = &O->getUnionValue();
1366 } else
1367 O = &O->getStructField(Field->getFieldIndex());
1368 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001369
1370 if (ObjType.isVolatileQualified()) {
1371 if (Info.getLangOpts().CPlusPlus) {
1372 // FIXME: Include a description of the path to the volatile subobject.
1373 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1374 << 2 << Field;
1375 Info.Note(Field->getLocation(), diag::note_declared_at);
1376 } else {
1377 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1378 }
1379 return false;
1380 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001381 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001382 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001383 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1384 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1385 O = &O->getStructBase(getBaseIndex(Derived, Base));
1386 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001387 }
Richard Smith180f4792011-11-10 06:34:14 +00001388
Richard Smithf48fdb02011-12-09 22:58:01 +00001389 if (O->isUninit()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001390 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001391 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001392 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001393 }
1394
Richard Smithb4e85ed2012-01-06 16:39:00 +00001395 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001396 return true;
1397}
1398
Richard Smith180f4792011-11-10 06:34:14 +00001399/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1400/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1401/// for looking up the glvalue referred to by an entity of reference type.
1402///
1403/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001404/// \param Conv - The expression for which we are performing the conversion.
1405/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001406/// \param Type - The type we expect this conversion to produce.
1407/// \param LVal - The glvalue on which we are attempting to perform this action.
1408/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001409static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1410 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001411 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001412 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1413 if (!Info.getLangOpts().CPlusPlus)
1414 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1415
Richard Smithb4e85ed2012-01-06 16:39:00 +00001416 if (LVal.Designator.Invalid)
1417 // A diagnostic will have already been produced.
1418 return false;
1419
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001420 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001421 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001422 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001423
Richard Smithf48fdb02011-12-09 22:58:01 +00001424 if (!LVal.Base) {
1425 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001426 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1427 return false;
1428 }
1429
1430 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1431 // is not a constant expression (even if the object is non-volatile). We also
1432 // apply this rule to C++98, in order to conform to the expected 'volatile'
1433 // semantics.
1434 if (Type.isVolatileQualified()) {
1435 if (Info.getLangOpts().CPlusPlus)
1436 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1437 else
1438 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001439 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001440 }
Richard Smithc49bd112011-10-28 17:51:58 +00001441
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001442 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001443 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1444 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001445 // expressions are constant expressions too. Inside constexpr functions,
1446 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001447 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001448 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001449 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001450 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001451 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001452 }
1453
Richard Smith7098cbd2011-12-21 05:04:46 +00001454 // DR1313: If the object is volatile-qualified but the glvalue was not,
1455 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001456 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001457 if (VT.isVolatileQualified()) {
1458 if (Info.getLangOpts().CPlusPlus) {
1459 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1460 Info.Note(VD->getLocation(), diag::note_declared_at);
1461 } else {
1462 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001463 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001464 return false;
1465 }
1466
1467 if (!isa<ParmVarDecl>(VD)) {
1468 if (VD->isConstexpr()) {
1469 // OK, we can read this variable.
1470 } else if (VT->isIntegralOrEnumerationType()) {
1471 if (!VT.isConstQualified()) {
1472 if (Info.getLangOpts().CPlusPlus) {
1473 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1474 Info.Note(VD->getLocation(), diag::note_declared_at);
1475 } else {
1476 Info.Diag(Loc);
1477 }
1478 return false;
1479 }
1480 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1481 // We support folding of const floating-point types, in order to make
1482 // static const data members of such types (supported as an extension)
1483 // more useful.
1484 if (Info.getLangOpts().CPlusPlus0x) {
1485 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1486 Info.Note(VD->getLocation(), diag::note_declared_at);
1487 } else {
1488 Info.CCEDiag(Loc);
1489 }
1490 } else {
1491 // FIXME: Allow folding of values of any literal type in all languages.
1492 if (Info.getLangOpts().CPlusPlus0x) {
1493 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1494 Info.Note(VD->getLocation(), diag::note_declared_at);
1495 } else {
1496 Info.Diag(Loc);
1497 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001498 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001499 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001500 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001501
Richard Smithf48fdb02011-12-09 22:58:01 +00001502 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001503 return false;
1504
Richard Smith47a1eed2011-10-29 20:57:55 +00001505 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001506 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001507
1508 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1509 // conversion. This happens when the declaration and the lvalue should be
1510 // considered synonymous, for instance when initializing an array of char
1511 // from a string literal. Continue as if the initializer lvalue was the
1512 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001513 assert(RVal.getLValueOffset().isZero() &&
1514 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001515 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001516 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001517 }
1518
Richard Smith7098cbd2011-12-21 05:04:46 +00001519 // Volatile temporary objects cannot be read in constant expressions.
1520 if (Base->getType().isVolatileQualified()) {
1521 if (Info.getLangOpts().CPlusPlus) {
1522 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1523 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1524 } else {
1525 Info.Diag(Loc);
1526 }
1527 return false;
1528 }
1529
Richard Smith0a3bdb62011-11-04 02:25:55 +00001530 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1531 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1532 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001533 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001534 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001535 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001536 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001537
1538 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001539 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001540 const ConstantArrayType *CAT =
1541 Info.Ctx.getAsConstantArrayType(S->getType());
1542 if (Index >= CAT->getSize().getZExtValue()) {
1543 // Note, it should not be possible to form a pointer which points more
1544 // than one past the end of the array without producing a prior const expr
1545 // diagnostic.
1546 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001547 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001548 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001549 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1550 Type->isUnsignedIntegerType());
1551 if (Index < S->getLength())
1552 Value = S->getCodeUnit(Index);
1553 RVal = CCValue(Value);
1554 return true;
1555 }
1556
Richard Smithcc5d4f62011-11-07 09:22:26 +00001557 if (Frame) {
1558 // If this is a temporary expression with a nontrivial initializer, grab the
1559 // value from the relevant stack frame.
1560 RVal = Frame->Temporaries[Base];
1561 } else if (const CompoundLiteralExpr *CLE
1562 = dyn_cast<CompoundLiteralExpr>(Base)) {
1563 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1564 // initializer until now for such expressions. Such an expression can't be
1565 // an ICE in C, so this only matters for fold.
1566 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1567 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1568 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001569 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001570 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001571 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001572 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001573
Richard Smithf48fdb02011-12-09 22:58:01 +00001574 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1575 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001576}
1577
Richard Smith59efe262011-11-11 04:05:33 +00001578/// Build an lvalue for the object argument of a member function call.
1579static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1580 LValue &This) {
1581 if (Object->getType()->isPointerType())
1582 return EvaluatePointer(Object, This, Info);
1583
1584 if (Object->isGLValue())
1585 return EvaluateLValue(Object, This, Info);
1586
Richard Smithe24f5fc2011-11-17 22:56:20 +00001587 if (Object->getType()->isLiteralType())
1588 return EvaluateTemporary(Object, This, Info);
1589
1590 return false;
1591}
1592
1593/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1594/// lvalue referring to the result.
1595///
1596/// \param Info - Information about the ongoing evaluation.
1597/// \param BO - The member pointer access operation.
1598/// \param LV - Filled in with a reference to the resulting object.
1599/// \param IncludeMember - Specifies whether the member itself is included in
1600/// the resulting LValue subobject designator. This is not possible when
1601/// creating a bound member function.
1602/// \return The field or method declaration to which the member pointer refers,
1603/// or 0 if evaluation fails.
1604static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1605 const BinaryOperator *BO,
1606 LValue &LV,
1607 bool IncludeMember = true) {
1608 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1609
1610 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1611 return 0;
1612
1613 MemberPtr MemPtr;
1614 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1615 return 0;
1616
1617 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1618 // member value, the behavior is undefined.
1619 if (!MemPtr.getDecl())
1620 return 0;
1621
1622 if (MemPtr.isDerivedMember()) {
1623 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001624 // The end of the derived-to-base path for the base object must match the
1625 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001626 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001627 LV.Designator.Entries.size())
1628 return 0;
1629 unsigned PathLengthToMember =
1630 LV.Designator.Entries.size() - MemPtr.Path.size();
1631 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1632 const CXXRecordDecl *LVDecl = getAsBaseClass(
1633 LV.Designator.Entries[PathLengthToMember + I]);
1634 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1635 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1636 return 0;
1637 }
1638
1639 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001640 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1641 PathLengthToMember))
1642 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001643 } else if (!MemPtr.Path.empty()) {
1644 // Extend the LValue path with the member pointer's path.
1645 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1646 MemPtr.Path.size() + IncludeMember);
1647
1648 // Walk down to the appropriate base class.
1649 QualType LVType = BO->getLHS()->getType();
1650 if (const PointerType *PT = LVType->getAs<PointerType>())
1651 LVType = PT->getPointeeType();
1652 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1653 assert(RD && "member pointer access on non-class-type expression");
1654 // The first class in the path is that of the lvalue.
1655 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1656 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001657 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001658 RD = Base;
1659 }
1660 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001661 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001662 }
1663
1664 // Add the member. Note that we cannot build bound member functions here.
1665 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001666 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1667 HandleLValueMember(Info, BO, LV, FD);
1668 else if (const IndirectFieldDecl *IFD =
1669 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1670 HandleLValueIndirectMember(Info, BO, LV, IFD);
1671 else
1672 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001673 }
1674
1675 return MemPtr.getDecl();
1676}
1677
1678/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1679/// the provided lvalue, which currently refers to the base object.
1680static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1681 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001682 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001683 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001684 return false;
1685
Richard Smithb4e85ed2012-01-06 16:39:00 +00001686 QualType TargetQT = E->getType();
1687 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1688 TargetQT = PT->getPointeeType();
1689
1690 // Check this cast lands within the final derived-to-base subobject path.
1691 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1692 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1693 << D.MostDerivedType << TargetQT;
1694 return false;
1695 }
1696
Richard Smithe24f5fc2011-11-17 22:56:20 +00001697 // Check the type of the final cast. We don't need to check the path,
1698 // since a cast can only be formed if the path is unique.
1699 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001700 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1701 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001702 if (NewEntriesSize == D.MostDerivedPathLength)
1703 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1704 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001705 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001706 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1707 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1708 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001709 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001710 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001711
1712 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001713 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001714}
1715
Mike Stumpc4c90452009-10-27 22:09:17 +00001716namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001717enum EvalStmtResult {
1718 /// Evaluation failed.
1719 ESR_Failed,
1720 /// Hit a 'return' statement.
1721 ESR_Returned,
1722 /// Evaluation succeeded.
1723 ESR_Succeeded
1724};
1725}
1726
1727// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001728static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001729 const Stmt *S) {
1730 switch (S->getStmtClass()) {
1731 default:
1732 return ESR_Failed;
1733
1734 case Stmt::NullStmtClass:
1735 case Stmt::DeclStmtClass:
1736 return ESR_Succeeded;
1737
Richard Smithc1c5f272011-12-13 06:39:58 +00001738 case Stmt::ReturnStmtClass: {
1739 CCValue CCResult;
1740 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1741 if (!Evaluate(CCResult, Info, RetExpr) ||
1742 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1743 CCEK_ReturnValue))
1744 return ESR_Failed;
1745 return ESR_Returned;
1746 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001747
1748 case Stmt::CompoundStmtClass: {
1749 const CompoundStmt *CS = cast<CompoundStmt>(S);
1750 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1751 BE = CS->body_end(); BI != BE; ++BI) {
1752 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1753 if (ESR != ESR_Succeeded)
1754 return ESR;
1755 }
1756 return ESR_Succeeded;
1757 }
1758 }
1759}
1760
Richard Smith61802452011-12-22 02:22:31 +00001761/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1762/// default constructor. If so, we'll fold it whether or not it's marked as
1763/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1764/// so we need special handling.
1765static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001766 const CXXConstructorDecl *CD,
1767 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001768 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1769 return false;
1770
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001771 // Value-initialization does not call a trivial default constructor, so such a
1772 // call is a core constant expression whether or not the constructor is
1773 // constexpr.
1774 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001775 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001776 // FIXME: If DiagDecl is an implicitly-declared special member function,
1777 // we should be much more explicit about why it's not constexpr.
1778 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1779 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1780 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001781 } else {
1782 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1783 }
1784 }
1785 return true;
1786}
1787
Richard Smithc1c5f272011-12-13 06:39:58 +00001788/// CheckConstexprFunction - Check that a function can be called in a constant
1789/// expression.
1790static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1791 const FunctionDecl *Declaration,
1792 const FunctionDecl *Definition) {
1793 // Can we evaluate this function call?
1794 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1795 return true;
1796
1797 if (Info.getLangOpts().CPlusPlus0x) {
1798 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001799 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1800 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001801 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1802 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1803 << DiagDecl;
1804 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1805 } else {
1806 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1807 }
1808 return false;
1809}
1810
Richard Smith180f4792011-11-10 06:34:14 +00001811namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001812typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001813}
1814
1815/// EvaluateArgs - Evaluate the arguments to a function call.
1816static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1817 EvalInfo &Info) {
1818 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1819 I != E; ++I)
1820 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1821 return false;
1822 return true;
1823}
1824
Richard Smithd0dccea2011-10-28 22:34:42 +00001825/// Evaluate a function call.
Richard Smith08d6e032011-12-16 19:06:07 +00001826static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1827 const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001828 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001829 EvalInfo &Info, APValue &Result) {
1830 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd0dccea2011-10-28 22:34:42 +00001831 return false;
1832
Richard Smith180f4792011-11-10 06:34:14 +00001833 ArgVector ArgValues(Args.size());
1834 if (!EvaluateArgs(Args, ArgValues, Info))
1835 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001836
Richard Smith08d6e032011-12-16 19:06:07 +00001837 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1838 ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001839 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1840}
1841
Richard Smith180f4792011-11-10 06:34:14 +00001842/// Evaluate a constructor call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001843static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001844 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001845 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00001846 EvalInfo &Info, APValue &Result) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001847 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith180f4792011-11-10 06:34:14 +00001848 return false;
1849
1850 ArgVector ArgValues(Args.size());
1851 if (!EvaluateArgs(Args, ArgValues, Info))
1852 return false;
1853
Richard Smith08d6e032011-12-16 19:06:07 +00001854 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1855 &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001856
1857 // If it's a delegating constructor, just delegate.
1858 if (Definition->isDelegatingConstructor()) {
1859 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1860 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1861 }
1862
Richard Smith610a60c2012-01-10 04:32:03 +00001863 // For a trivial copy or move constructor, perform an APValue copy. This is
1864 // essential for unions, where the operations performed by the constructor
1865 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00001866 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00001867 if (Definition->isDefaulted() &&
1868 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1869 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1870 LValue RHS;
1871 RHS.setFrom(ArgValues[0]);
1872 CCValue Value;
1873 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1874 RHS, Value) &&
1875 CheckConstantExpression(Info, CallExpr, Value, Result);
1876 }
1877
1878 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00001879 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001880 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1881 std::distance(RD->field_begin(), RD->field_end()));
1882
1883 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1884
1885 unsigned BasesSeen = 0;
1886#ifndef NDEBUG
1887 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1888#endif
1889 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1890 E = Definition->init_end(); I != E; ++I) {
1891 if ((*I)->isBaseInitializer()) {
1892 QualType BaseType((*I)->getBaseClass(), 0);
1893#ifndef NDEBUG
1894 // Non-virtual base classes are initialized in the order in the class
1895 // definition. We cannot have a virtual base class for a literal type.
1896 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1897 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1898 "base class initializers not in expected order");
1899 ++BaseIt;
1900#endif
1901 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001902 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00001903 BaseType->getAsCXXRecordDecl(), &Layout);
1904 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1905 Subobject, (*I)->getInit()))
1906 return false;
1907 } else if (FieldDecl *FD = (*I)->getMember()) {
1908 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001909 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00001910 if (RD->isUnion()) {
1911 Result = APValue(FD);
Richard Smithc1c5f272011-12-13 06:39:58 +00001912 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1913 (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001914 return false;
1915 } else if (!EvaluateConstantExpression(
1916 Result.getStructField(FD->getFieldIndex()),
Richard Smithc1c5f272011-12-13 06:39:58 +00001917 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001918 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00001919 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
1920 LValue Subobject = This;
1921 APValue *Value = &Result;
1922 // Walk the indirect field decl's chain to find the object to initialize,
1923 // and make sure we've initialized every step along it.
1924 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1925 CE = IFD->chain_end();
1926 C != CE; ++C) {
1927 FieldDecl *FD = cast<FieldDecl>(*C);
1928 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
1929 // Switch the union field if it differs. This happens if we had
1930 // preceding zero-initialization, and we're now initializing a union
1931 // subobject other than the first.
1932 // FIXME: In this case, the values of the other subobjects are
1933 // specified, since zero-initialization sets all padding bits to zero.
1934 if (Value->isUninit() ||
1935 (Value->isUnion() && Value->getUnionField() != FD)) {
1936 if (CD->isUnion())
1937 *Value = APValue(FD);
1938 else
1939 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
1940 std::distance(CD->field_begin(), CD->field_end()));
1941 }
1942 if (CD->isUnion())
1943 Value = &Value->getUnionValue();
1944 else
1945 Value = &Value->getStructField(FD->getFieldIndex());
1946 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
1947 }
1948 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
1949 CCEK_MemberInit))
1950 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001951 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001952 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00001953 }
1954 }
1955
1956 return true;
1957}
1958
Richard Smithd0dccea2011-10-28 22:34:42 +00001959namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001960class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001961 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001962 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001963public:
1964
Richard Smith1e12c592011-10-16 21:26:27 +00001965 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001966
1967 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001968 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001969 return true;
1970 }
1971
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001972 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1973 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001974 return Visit(E->getResultExpr());
1975 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001976 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001977 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001978 return true;
1979 return false;
1980 }
John McCallf85e1932011-06-15 23:02:42 +00001981 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001982 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001983 return true;
1984 return false;
1985 }
1986 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001987 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001988 return true;
1989 return false;
1990 }
1991
Mike Stumpc4c90452009-10-27 22:09:17 +00001992 // We don't want to evaluate BlockExprs multiple times, as they generate
1993 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001994 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1995 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1996 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001997 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001998 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1999 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2000 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2001 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2002 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2003 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002004 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002005 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002006 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002007 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002008 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002009 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2010 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2011 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2012 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002013 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002014 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2015 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2016 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2017 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2018 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002019 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002020 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002021 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002022 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002023 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002024
2025 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002026 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002027 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2028 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002029 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002030 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002031 return false;
2032 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002033
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002034 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002035};
2036
John McCall56ca35d2011-02-17 10:25:35 +00002037class OpaqueValueEvaluation {
2038 EvalInfo &info;
2039 OpaqueValueExpr *opaqueValue;
2040
2041public:
2042 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2043 Expr *value)
2044 : info(info), opaqueValue(opaqueValue) {
2045
2046 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002047 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002048 this->opaqueValue = 0;
2049 return;
2050 }
John McCall56ca35d2011-02-17 10:25:35 +00002051 }
2052
2053 bool hasError() const { return opaqueValue == 0; }
2054
2055 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002056 // FIXME: This will not work for recursive constexpr functions using opaque
2057 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002058 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2059 }
2060};
2061
Mike Stumpc4c90452009-10-27 22:09:17 +00002062} // end anonymous namespace
2063
Eli Friedman4efaa272008-11-12 09:44:48 +00002064//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002065// Generic Evaluation
2066//===----------------------------------------------------------------------===//
2067namespace {
2068
Richard Smithf48fdb02011-12-09 22:58:01 +00002069// FIXME: RetTy is always bool. Remove it.
2070template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002071class ExprEvaluatorBase
2072 : public ConstStmtVisitor<Derived, RetTy> {
2073private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002074 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002075 return static_cast<Derived*>(this)->Success(V, E);
2076 }
Richard Smith51201882011-12-30 21:15:51 +00002077 RetTy DerivedZeroInitialization(const Expr *E) {
2078 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002079 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002080
2081protected:
2082 EvalInfo &Info;
2083 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2084 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2085
Richard Smithdd1f29b2011-12-12 09:28:41 +00002086 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002087 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002088 }
2089
2090 /// Report an evaluation error. This should only be called when an error is
2091 /// first discovered. When propagating an error, just return false.
2092 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002093 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002094 return false;
2095 }
2096 bool Error(const Expr *E) {
2097 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2098 }
2099
Richard Smith51201882011-12-30 21:15:51 +00002100 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002101
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002102public:
2103 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2104
2105 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002106 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002107 }
2108 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002109 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002110 }
2111
2112 RetTy VisitParenExpr(const ParenExpr *E)
2113 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2114 RetTy VisitUnaryExtension(const UnaryOperator *E)
2115 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2116 RetTy VisitUnaryPlus(const UnaryOperator *E)
2117 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2118 RetTy VisitChooseExpr(const ChooseExpr *E)
2119 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2120 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2121 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002122 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2123 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002124 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2125 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002126 // We cannot create any objects for which cleanups are required, so there is
2127 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2128 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2129 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002130
Richard Smithc216a012011-12-12 12:46:16 +00002131 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2132 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2133 return static_cast<Derived*>(this)->VisitCastExpr(E);
2134 }
2135 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2136 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2137 return static_cast<Derived*>(this)->VisitCastExpr(E);
2138 }
2139
Richard Smithe24f5fc2011-11-17 22:56:20 +00002140 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2141 switch (E->getOpcode()) {
2142 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002143 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002144
2145 case BO_Comma:
2146 VisitIgnoredValue(E->getLHS());
2147 return StmtVisitorTy::Visit(E->getRHS());
2148
2149 case BO_PtrMemD:
2150 case BO_PtrMemI: {
2151 LValue Obj;
2152 if (!HandleMemberPointerAccess(Info, E, Obj))
2153 return false;
2154 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002155 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002156 return false;
2157 return DerivedSuccess(Result, E);
2158 }
2159 }
2160 }
2161
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002162 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2163 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2164 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002165 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002166
2167 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002168 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002169 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002170
2171 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2172 }
2173
2174 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2175 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002176 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002177 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002178
Richard Smithc49bd112011-10-28 17:51:58 +00002179 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002180 return StmtVisitorTy::Visit(EvalExpr);
2181 }
2182
2183 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002184 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002185 if (!Value) {
2186 const Expr *Source = E->getSourceExpr();
2187 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002188 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002189 if (Source == E) { // sanity checking.
2190 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002191 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002192 }
2193 return StmtVisitorTy::Visit(Source);
2194 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002195 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002196 }
Richard Smithf10d9172011-10-11 21:43:33 +00002197
Richard Smithd0dccea2011-10-28 22:34:42 +00002198 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002199 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002200 QualType CalleeType = Callee->getType();
2201
Richard Smithd0dccea2011-10-28 22:34:42 +00002202 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002203 LValue *This = 0, ThisVal;
2204 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002205
Richard Smith59efe262011-11-11 04:05:33 +00002206 // Extract function decl and 'this' pointer from the callee.
2207 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002208 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002209 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2210 // Explicit bound member calls, such as x.f() or p->g();
2211 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002212 return false;
2213 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002214 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002215 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2216 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002217 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2218 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002219 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002220 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002221 return Error(Callee);
2222
2223 FD = dyn_cast<FunctionDecl>(Member);
2224 if (!FD)
2225 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002226 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002227 LValue Call;
2228 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002229 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002230
Richard Smithb4e85ed2012-01-06 16:39:00 +00002231 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002232 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002233 FD = dyn_cast_or_null<FunctionDecl>(
2234 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002235 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002236 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002237
2238 // Overloaded operator calls to member functions are represented as normal
2239 // calls with '*this' as the first argument.
2240 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2241 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002242 // FIXME: When selecting an implicit conversion for an overloaded
2243 // operator delete, we sometimes try to evaluate calls to conversion
2244 // operators without a 'this' parameter!
2245 if (Args.empty())
2246 return Error(E);
2247
Richard Smith59efe262011-11-11 04:05:33 +00002248 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2249 return false;
2250 This = &ThisVal;
2251 Args = Args.slice(1);
2252 }
2253
2254 // Don't call function pointers which have been cast to some other type.
2255 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002256 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002257 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002258 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002259
Richard Smithc1c5f272011-12-13 06:39:58 +00002260 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002261 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002262 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002263
Richard Smithc1c5f272011-12-13 06:39:58 +00002264 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith08d6e032011-12-16 19:06:07 +00002265 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002266 return false;
2267
Richard Smithb4e85ed2012-01-06 16:39:00 +00002268 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002269 }
2270
Richard Smithc49bd112011-10-28 17:51:58 +00002271 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2272 return StmtVisitorTy::Visit(E->getInitializer());
2273 }
Richard Smithf10d9172011-10-11 21:43:33 +00002274 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002275 if (E->getNumInits() == 0)
2276 return DerivedZeroInitialization(E);
2277 if (E->getNumInits() == 1)
2278 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002279 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002280 }
2281 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002282 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002283 }
2284 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002285 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002286 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002287 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002288 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002289 }
Richard Smithf10d9172011-10-11 21:43:33 +00002290
Richard Smith180f4792011-11-10 06:34:14 +00002291 /// A member expression where the object is a prvalue is itself a prvalue.
2292 RetTy VisitMemberExpr(const MemberExpr *E) {
2293 assert(!E->isArrow() && "missing call to bound member function?");
2294
2295 CCValue Val;
2296 if (!Evaluate(Val, Info, E->getBase()))
2297 return false;
2298
2299 QualType BaseTy = E->getBase()->getType();
2300
2301 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002302 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002303 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2304 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2305 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2306
Richard Smithb4e85ed2012-01-06 16:39:00 +00002307 SubobjectDesignator Designator(BaseTy);
2308 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002309
Richard Smithf48fdb02011-12-09 22:58:01 +00002310 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002311 DerivedSuccess(Val, E);
2312 }
2313
Richard Smithc49bd112011-10-28 17:51:58 +00002314 RetTy VisitCastExpr(const CastExpr *E) {
2315 switch (E->getCastKind()) {
2316 default:
2317 break;
2318
David Chisnall7a7ee302012-01-16 17:27:18 +00002319 case CK_AtomicToNonAtomic:
2320 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002321 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002322 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002323 return StmtVisitorTy::Visit(E->getSubExpr());
2324
2325 case CK_LValueToRValue: {
2326 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002327 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2328 return false;
2329 CCValue RVal;
2330 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2331 return false;
2332 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002333 }
2334 }
2335
Richard Smithf48fdb02011-12-09 22:58:01 +00002336 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002337 }
2338
Richard Smith8327fad2011-10-24 18:44:57 +00002339 /// Visit a value which is evaluated, but whose value is ignored.
2340 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002341 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002342 if (!Evaluate(Scratch, Info, E))
2343 Info.EvalStatus.HasSideEffects = true;
2344 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002345};
2346
2347}
2348
2349//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002350// Common base class for lvalue and temporary evaluation.
2351//===----------------------------------------------------------------------===//
2352namespace {
2353template<class Derived>
2354class LValueExprEvaluatorBase
2355 : public ExprEvaluatorBase<Derived, bool> {
2356protected:
2357 LValue &Result;
2358 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2359 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2360
2361 bool Success(APValue::LValueBase B) {
2362 Result.set(B);
2363 return true;
2364 }
2365
2366public:
2367 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2368 ExprEvaluatorBaseTy(Info), Result(Result) {}
2369
2370 bool Success(const CCValue &V, const Expr *E) {
2371 Result.setFrom(V);
2372 return true;
2373 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002374
Richard Smithe24f5fc2011-11-17 22:56:20 +00002375 bool VisitMemberExpr(const MemberExpr *E) {
2376 // Handle non-static data members.
2377 QualType BaseTy;
2378 if (E->isArrow()) {
2379 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2380 return false;
2381 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002382 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002383 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002384 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2385 return false;
2386 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002387 } else {
2388 if (!this->Visit(E->getBase()))
2389 return false;
2390 BaseTy = E->getBase()->getType();
2391 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002392
Richard Smithd9b02e72012-01-25 22:15:11 +00002393 const ValueDecl *MD = E->getMemberDecl();
2394 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2395 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2396 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2397 (void)BaseTy;
2398 HandleLValueMember(this->Info, E, Result, FD);
2399 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2400 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2401 } else
2402 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002403
Richard Smithd9b02e72012-01-25 22:15:11 +00002404 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002405 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002406 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002407 RefValue))
2408 return false;
2409 return Success(RefValue, E);
2410 }
2411 return true;
2412 }
2413
2414 bool VisitBinaryOperator(const BinaryOperator *E) {
2415 switch (E->getOpcode()) {
2416 default:
2417 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2418
2419 case BO_PtrMemD:
2420 case BO_PtrMemI:
2421 return HandleMemberPointerAccess(this->Info, E, Result);
2422 }
2423 }
2424
2425 bool VisitCastExpr(const CastExpr *E) {
2426 switch (E->getCastKind()) {
2427 default:
2428 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2429
2430 case CK_DerivedToBase:
2431 case CK_UncheckedDerivedToBase: {
2432 if (!this->Visit(E->getSubExpr()))
2433 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002434
2435 // Now figure out the necessary offset to add to the base LV to get from
2436 // the derived class to the base class.
2437 QualType Type = E->getSubExpr()->getType();
2438
2439 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2440 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002441 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002442 *PathI))
2443 return false;
2444 Type = (*PathI)->getType();
2445 }
2446
2447 return true;
2448 }
2449 }
2450 }
2451};
2452}
2453
2454//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002455// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002456//
2457// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2458// function designators (in C), decl references to void objects (in C), and
2459// temporaries (if building with -Wno-address-of-temporary).
2460//
2461// LValue evaluation produces values comprising a base expression of one of the
2462// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002463// - Declarations
2464// * VarDecl
2465// * FunctionDecl
2466// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002467// * CompoundLiteralExpr in C
2468// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002469// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002470// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002471// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002472// * ObjCEncodeExpr
2473// * AddrLabelExpr
2474// * BlockExpr
2475// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002476// - Locals and temporaries
2477// * Any Expr, with a Frame indicating the function in which the temporary was
2478// evaluated.
2479// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002480//===----------------------------------------------------------------------===//
2481namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002482class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002483 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002484public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002485 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2486 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002487
Richard Smithc49bd112011-10-28 17:51:58 +00002488 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2489
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002490 bool VisitDeclRefExpr(const DeclRefExpr *E);
2491 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002492 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002493 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2494 bool VisitMemberExpr(const MemberExpr *E);
2495 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2496 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002497 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002498 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2499 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002500
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002501 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002502 switch (E->getCastKind()) {
2503 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002504 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002505
Eli Friedmandb924222011-10-11 00:13:24 +00002506 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002507 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002508 if (!Visit(E->getSubExpr()))
2509 return false;
2510 Result.Designator.setInvalid();
2511 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002512
Richard Smithe24f5fc2011-11-17 22:56:20 +00002513 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002514 if (!Visit(E->getSubExpr()))
2515 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002516 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002517 }
2518 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002519
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002520 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002521
Eli Friedman4efaa272008-11-12 09:44:48 +00002522};
2523} // end anonymous namespace
2524
Richard Smithc49bd112011-10-28 17:51:58 +00002525/// Evaluate an expression as an lvalue. This can be legitimately called on
2526/// expressions which are not glvalues, in a few cases:
2527/// * function designators in C,
2528/// * "extern void" objects,
2529/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002530static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002531 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2532 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2533 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002534 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002535}
2536
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002537bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002538 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2539 return Success(FD);
2540 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002541 return VisitVarDecl(E, VD);
2542 return Error(E);
2543}
Richard Smith436c8892011-10-24 23:14:33 +00002544
Richard Smithc49bd112011-10-28 17:51:58 +00002545bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002546 if (!VD->getType()->isReferenceType()) {
2547 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002548 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002549 return true;
2550 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002551 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002552 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002553
Richard Smith47a1eed2011-10-29 20:57:55 +00002554 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002555 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2556 return false;
2557 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002558}
2559
Richard Smithbd552ef2011-10-31 05:52:43 +00002560bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2561 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002562 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002563 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002564 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2565
2566 Result.set(E, Info.CurrentCall);
2567 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2568 Result, E->GetTemporaryExpr());
2569 }
2570
2571 // Materialization of an lvalue temporary occurs when we need to force a copy
2572 // (for instance, if it's a bitfield).
2573 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2574 if (!Visit(E->GetTemporaryExpr()))
2575 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002576 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002577 Info.CurrentCall->Temporaries[E]))
2578 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002579 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002580 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002581}
2582
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002583bool
2584LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002585 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2586 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2587 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002588 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002589}
2590
Richard Smith47d21452011-12-27 12:18:28 +00002591bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2592 if (E->isTypeOperand())
2593 return Success(E);
2594 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2595 if (RD && RD->isPolymorphic()) {
2596 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2597 << E->getExprOperand()->getType()
2598 << E->getExprOperand()->getSourceRange();
2599 return false;
2600 }
2601 return Success(E);
2602}
2603
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002604bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002605 // Handle static data members.
2606 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2607 VisitIgnoredValue(E->getBase());
2608 return VisitVarDecl(E, VD);
2609 }
2610
Richard Smithd0dccea2011-10-28 22:34:42 +00002611 // Handle static member functions.
2612 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2613 if (MD->isStatic()) {
2614 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002615 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002616 }
2617 }
2618
Richard Smith180f4792011-11-10 06:34:14 +00002619 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002620 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002621}
2622
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002623bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002624 // FIXME: Deal with vectors as array subscript bases.
2625 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002626 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002627
Anders Carlsson3068d112008-11-16 19:01:22 +00002628 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002629 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002630
Anders Carlsson3068d112008-11-16 19:01:22 +00002631 APSInt Index;
2632 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002633 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002634 int64_t IndexValue
2635 = Index.isSigned() ? Index.getSExtValue()
2636 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002637
Richard Smithb4e85ed2012-01-06 16:39:00 +00002638 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002639}
Eli Friedman4efaa272008-11-12 09:44:48 +00002640
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002641bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002642 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002643}
2644
Eli Friedman4efaa272008-11-12 09:44:48 +00002645//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002646// Pointer Evaluation
2647//===----------------------------------------------------------------------===//
2648
Anders Carlssonc754aa62008-07-08 05:13:58 +00002649namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002650class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002651 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002652 LValue &Result;
2653
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002654 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002655 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002656 return true;
2657 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002658public:
Mike Stump1eb44332009-09-09 15:08:12 +00002659
John McCallefdb83e2010-05-07 21:00:08 +00002660 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002661 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002662
Richard Smith47a1eed2011-10-29 20:57:55 +00002663 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002664 Result.setFrom(V);
2665 return true;
2666 }
Richard Smith51201882011-12-30 21:15:51 +00002667 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002668 return Success((Expr*)0);
2669 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002670
John McCallefdb83e2010-05-07 21:00:08 +00002671 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002672 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002673 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002674 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002675 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002676 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002677 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002678 bool VisitCallExpr(const CallExpr *E);
2679 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002680 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002681 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002682 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002683 }
Richard Smith180f4792011-11-10 06:34:14 +00002684 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2685 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002686 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002687 Result = *Info.CurrentCall->This;
2688 return true;
2689 }
John McCall56ca35d2011-02-17 10:25:35 +00002690
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002691 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002692};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002693} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002694
John McCallefdb83e2010-05-07 21:00:08 +00002695static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002696 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002697 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002698}
2699
John McCallefdb83e2010-05-07 21:00:08 +00002700bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002701 if (E->getOpcode() != BO_Add &&
2702 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002703 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002704
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002705 const Expr *PExp = E->getLHS();
2706 const Expr *IExp = E->getRHS();
2707 if (IExp->getType()->isPointerType())
2708 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002709
John McCallefdb83e2010-05-07 21:00:08 +00002710 if (!EvaluatePointer(PExp, Result, Info))
2711 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002712
John McCallefdb83e2010-05-07 21:00:08 +00002713 llvm::APSInt Offset;
2714 if (!EvaluateInteger(IExp, Offset, Info))
2715 return false;
2716 int64_t AdditionalOffset
2717 = Offset.isSigned() ? Offset.getSExtValue()
2718 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002719 if (E->getOpcode() == BO_Sub)
2720 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002721
Richard Smith180f4792011-11-10 06:34:14 +00002722 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002723 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2724 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002725}
Eli Friedman4efaa272008-11-12 09:44:48 +00002726
John McCallefdb83e2010-05-07 21:00:08 +00002727bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2728 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002729}
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002731bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2732 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002733
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002734 switch (E->getCastKind()) {
2735 default:
2736 break;
2737
John McCall2de56d12010-08-25 11:45:40 +00002738 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002739 case CK_CPointerToObjCPointerCast:
2740 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002741 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002742 if (!Visit(SubExpr))
2743 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002744 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2745 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2746 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002747 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002748 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002749 if (SubExpr->getType()->isVoidPointerType())
2750 CCEDiag(E, diag::note_constexpr_invalid_cast)
2751 << 3 << SubExpr->getType();
2752 else
2753 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2754 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002755 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002756
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002757 case CK_DerivedToBase:
2758 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002759 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002760 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002761 if (!Result.Base && Result.Offset.isZero())
2762 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002763
Richard Smith180f4792011-11-10 06:34:14 +00002764 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002765 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002766 QualType Type =
2767 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002768
Richard Smith180f4792011-11-10 06:34:14 +00002769 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002770 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002771 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2772 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002773 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002774 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002775 }
2776
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002777 return true;
2778 }
2779
Richard Smithe24f5fc2011-11-17 22:56:20 +00002780 case CK_BaseToDerived:
2781 if (!Visit(E->getSubExpr()))
2782 return false;
2783 if (!Result.Base && Result.Offset.isZero())
2784 return true;
2785 return HandleBaseToDerivedCast(Info, E, Result);
2786
Richard Smith47a1eed2011-10-29 20:57:55 +00002787 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002788 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002789
John McCall2de56d12010-08-25 11:45:40 +00002790 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002791 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2792
Richard Smith47a1eed2011-10-29 20:57:55 +00002793 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002794 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002795 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002796
John McCallefdb83e2010-05-07 21:00:08 +00002797 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002798 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2799 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002800 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002801 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002802 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002803 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002804 return true;
2805 } else {
2806 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002807 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002808 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002809 }
2810 }
John McCall2de56d12010-08-25 11:45:40 +00002811 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002812 if (SubExpr->isGLValue()) {
2813 if (!EvaluateLValue(SubExpr, Result, Info))
2814 return false;
2815 } else {
2816 Result.set(SubExpr, Info.CurrentCall);
2817 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2818 Info, Result, SubExpr))
2819 return false;
2820 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002821 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002822 if (const ConstantArrayType *CAT
2823 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2824 Result.addArray(Info, E, CAT);
2825 else
2826 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00002827 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002828
John McCall2de56d12010-08-25 11:45:40 +00002829 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002830 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002831 }
2832
Richard Smithc49bd112011-10-28 17:51:58 +00002833 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002834}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002835
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002836bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002837 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002838 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002839
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002840 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002841}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002842
2843//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002844// Member Pointer Evaluation
2845//===----------------------------------------------------------------------===//
2846
2847namespace {
2848class MemberPointerExprEvaluator
2849 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2850 MemberPtr &Result;
2851
2852 bool Success(const ValueDecl *D) {
2853 Result = MemberPtr(D);
2854 return true;
2855 }
2856public:
2857
2858 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2859 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2860
2861 bool Success(const CCValue &V, const Expr *E) {
2862 Result.setFrom(V);
2863 return true;
2864 }
Richard Smith51201882011-12-30 21:15:51 +00002865 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002866 return Success((const ValueDecl*)0);
2867 }
2868
2869 bool VisitCastExpr(const CastExpr *E);
2870 bool VisitUnaryAddrOf(const UnaryOperator *E);
2871};
2872} // end anonymous namespace
2873
2874static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2875 EvalInfo &Info) {
2876 assert(E->isRValue() && E->getType()->isMemberPointerType());
2877 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2878}
2879
2880bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2881 switch (E->getCastKind()) {
2882 default:
2883 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2884
2885 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00002886 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002887
2888 case CK_BaseToDerivedMemberPointer: {
2889 if (!Visit(E->getSubExpr()))
2890 return false;
2891 if (E->path_empty())
2892 return true;
2893 // Base-to-derived member pointer casts store the path in derived-to-base
2894 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2895 // the wrong end of the derived->base arc, so stagger the path by one class.
2896 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2897 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2898 PathI != PathE; ++PathI) {
2899 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2900 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2901 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002902 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002903 }
2904 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2905 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002906 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002907 return true;
2908 }
2909
2910 case CK_DerivedToBaseMemberPointer:
2911 if (!Visit(E->getSubExpr()))
2912 return false;
2913 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2914 PathE = E->path_end(); PathI != PathE; ++PathI) {
2915 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2916 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2917 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002918 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002919 }
2920 return true;
2921 }
2922}
2923
2924bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2925 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2926 // member can be formed.
2927 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2928}
2929
2930//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002931// Record Evaluation
2932//===----------------------------------------------------------------------===//
2933
2934namespace {
2935 class RecordExprEvaluator
2936 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2937 const LValue &This;
2938 APValue &Result;
2939 public:
2940
2941 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2942 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2943
2944 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002945 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002946 }
Richard Smith51201882011-12-30 21:15:51 +00002947 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002948
Richard Smith59efe262011-11-11 04:05:33 +00002949 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002950 bool VisitInitListExpr(const InitListExpr *E);
2951 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2952 };
2953}
2954
Richard Smith51201882011-12-30 21:15:51 +00002955/// Perform zero-initialization on an object of non-union class type.
2956/// C++11 [dcl.init]p5:
2957/// To zero-initialize an object or reference of type T means:
2958/// [...]
2959/// -- if T is a (possibly cv-qualified) non-union class type,
2960/// each non-static data member and each base-class subobject is
2961/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00002962static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
2963 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00002964 const LValue &This, APValue &Result) {
2965 assert(!RD->isUnion() && "Expected non-union class type");
2966 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2967 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2968 std::distance(RD->field_begin(), RD->field_end()));
2969
2970 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2971
2972 if (CD) {
2973 unsigned Index = 0;
2974 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00002975 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00002976 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2977 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002978 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
2979 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00002980 Result.getStructBase(Index)))
2981 return false;
2982 }
2983 }
2984
Richard Smithb4e85ed2012-01-06 16:39:00 +00002985 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
2986 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00002987 // -- if T is a reference type, no initialization is performed.
2988 if ((*I)->getType()->isReferenceType())
2989 continue;
2990
2991 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002992 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00002993
2994 ImplicitValueInitExpr VIE((*I)->getType());
2995 if (!EvaluateConstantExpression(
2996 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2997 return false;
2998 }
2999
3000 return true;
3001}
3002
3003bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3004 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3005 if (RD->isUnion()) {
3006 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3007 // object's first non-static named data member is zero-initialized
3008 RecordDecl::field_iterator I = RD->field_begin();
3009 if (I == RD->field_end()) {
3010 Result = APValue((const FieldDecl*)0);
3011 return true;
3012 }
3013
3014 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003015 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003016 Result = APValue(*I);
3017 ImplicitValueInitExpr VIE((*I)->getType());
3018 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3019 Subobject, &VIE);
3020 }
3021
Richard Smithb4e85ed2012-01-06 16:39:00 +00003022 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003023}
3024
Richard Smith59efe262011-11-11 04:05:33 +00003025bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3026 switch (E->getCastKind()) {
3027 default:
3028 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3029
3030 case CK_ConstructorConversion:
3031 return Visit(E->getSubExpr());
3032
3033 case CK_DerivedToBase:
3034 case CK_UncheckedDerivedToBase: {
3035 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003036 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003037 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003038 if (!DerivedObject.isStruct())
3039 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003040
3041 // Derived-to-base rvalue conversion: just slice off the derived part.
3042 APValue *Value = &DerivedObject;
3043 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3044 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3045 PathE = E->path_end(); PathI != PathE; ++PathI) {
3046 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3047 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3048 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3049 RD = Base;
3050 }
3051 Result = *Value;
3052 return true;
3053 }
3054 }
3055}
3056
Richard Smith180f4792011-11-10 06:34:14 +00003057bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3058 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3059 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3060
3061 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003062 const FieldDecl *Field = E->getInitializedFieldInUnion();
3063 Result = APValue(Field);
3064 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003065 return true;
Richard Smithec789162012-01-12 18:54:33 +00003066
3067 // If the initializer list for a union does not contain any elements, the
3068 // first element of the union is value-initialized.
3069 ImplicitValueInitExpr VIE(Field->getType());
3070 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3071
Richard Smith180f4792011-11-10 06:34:14 +00003072 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003073 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003074 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003075 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003076 }
3077
3078 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3079 "initializer list for class with base classes");
3080 Result = APValue(APValue::UninitStruct(), 0,
3081 std::distance(RD->field_begin(), RD->field_end()));
3082 unsigned ElementNo = 0;
3083 for (RecordDecl::field_iterator Field = RD->field_begin(),
3084 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3085 // Anonymous bit-fields are not considered members of the class for
3086 // purposes of aggregate initialization.
3087 if (Field->isUnnamedBitfield())
3088 continue;
3089
3090 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003091
3092 if (ElementNo < E->getNumInits()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003093 HandleLValueMember(Info, E->getInit(ElementNo), Subobject, *Field,
3094 &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003095 if (!EvaluateConstantExpression(
3096 Result.getStructField((*Field)->getFieldIndex()),
3097 Info, Subobject, E->getInit(ElementNo++)))
3098 return false;
3099 } else {
3100 // Perform an implicit value-initialization for members beyond the end of
3101 // the initializer list.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003102 HandleLValueMember(Info, E, Subobject, *Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003103 ImplicitValueInitExpr VIE(Field->getType());
3104 if (!EvaluateConstantExpression(
3105 Result.getStructField((*Field)->getFieldIndex()),
3106 Info, Subobject, &VIE))
3107 return false;
3108 }
3109 }
3110
3111 return true;
3112}
3113
3114bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3115 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003116 bool ZeroInit = E->requiresZeroInitialization();
3117 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003118 // If we've already performed zero-initialization, we're already done.
3119 if (!Result.isUninit())
3120 return true;
3121
Richard Smith51201882011-12-30 21:15:51 +00003122 if (ZeroInit)
3123 return ZeroInitialization(E);
3124
Richard Smith61802452011-12-22 02:22:31 +00003125 const CXXRecordDecl *RD = FD->getParent();
3126 if (RD->isUnion())
3127 Result = APValue((FieldDecl*)0);
3128 else
3129 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3130 std::distance(RD->field_begin(), RD->field_end()));
3131 return true;
3132 }
3133
Richard Smith180f4792011-11-10 06:34:14 +00003134 const FunctionDecl *Definition = 0;
3135 FD->getBody(Definition);
3136
Richard Smithc1c5f272011-12-13 06:39:58 +00003137 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3138 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003139
Richard Smith610a60c2012-01-10 04:32:03 +00003140 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003141 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003142 if (const MaterializeTemporaryExpr *ME
3143 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3144 return Visit(ME->GetTemporaryExpr());
3145
Richard Smith51201882011-12-30 21:15:51 +00003146 if (ZeroInit && !ZeroInitialization(E))
3147 return false;
3148
Richard Smith180f4792011-11-10 06:34:14 +00003149 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003150 return HandleConstructorCall(E, This, Args,
3151 cast<CXXConstructorDecl>(Definition), Info,
3152 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003153}
3154
3155static bool EvaluateRecord(const Expr *E, const LValue &This,
3156 APValue &Result, EvalInfo &Info) {
3157 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003158 "can't evaluate expression as a record rvalue");
3159 return RecordExprEvaluator(Info, This, Result).Visit(E);
3160}
3161
3162//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003163// Temporary Evaluation
3164//
3165// Temporaries are represented in the AST as rvalues, but generally behave like
3166// lvalues. The full-object of which the temporary is a subobject is implicitly
3167// materialized so that a reference can bind to it.
3168//===----------------------------------------------------------------------===//
3169namespace {
3170class TemporaryExprEvaluator
3171 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3172public:
3173 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3174 LValueExprEvaluatorBaseTy(Info, Result) {}
3175
3176 /// Visit an expression which constructs the value of this temporary.
3177 bool VisitConstructExpr(const Expr *E) {
3178 Result.set(E, Info.CurrentCall);
3179 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3180 Result, E);
3181 }
3182
3183 bool VisitCastExpr(const CastExpr *E) {
3184 switch (E->getCastKind()) {
3185 default:
3186 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3187
3188 case CK_ConstructorConversion:
3189 return VisitConstructExpr(E->getSubExpr());
3190 }
3191 }
3192 bool VisitInitListExpr(const InitListExpr *E) {
3193 return VisitConstructExpr(E);
3194 }
3195 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3196 return VisitConstructExpr(E);
3197 }
3198 bool VisitCallExpr(const CallExpr *E) {
3199 return VisitConstructExpr(E);
3200 }
3201};
3202} // end anonymous namespace
3203
3204/// Evaluate an expression of record type as a temporary.
3205static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003206 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003207 return TemporaryExprEvaluator(Info, Result).Visit(E);
3208}
3209
3210//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003211// Vector Evaluation
3212//===----------------------------------------------------------------------===//
3213
3214namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003215 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003216 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3217 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003218 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Richard Smith07fc6572011-10-22 21:10:00 +00003220 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3221 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Richard Smith07fc6572011-10-22 21:10:00 +00003223 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3224 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3225 // FIXME: remove this APValue copy.
3226 Result = APValue(V.data(), V.size());
3227 return true;
3228 }
Richard Smith69c2c502011-11-04 05:33:44 +00003229 bool Success(const CCValue &V, const Expr *E) {
3230 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003231 Result = V;
3232 return true;
3233 }
Richard Smith51201882011-12-30 21:15:51 +00003234 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Richard Smith07fc6572011-10-22 21:10:00 +00003236 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003237 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003238 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003239 bool VisitInitListExpr(const InitListExpr *E);
3240 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003241 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003242 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003243 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003244 };
3245} // end anonymous namespace
3246
3247static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003248 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003249 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003250}
3251
Richard Smith07fc6572011-10-22 21:10:00 +00003252bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3253 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003254 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Richard Smithd62ca372011-12-06 22:44:34 +00003256 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003257 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003258
Eli Friedman46a52322011-03-25 00:43:55 +00003259 switch (E->getCastKind()) {
3260 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003261 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003262 if (SETy->isIntegerType()) {
3263 APSInt IntResult;
3264 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003265 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003266 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003267 } else if (SETy->isRealFloatingType()) {
3268 APFloat F(0.0);
3269 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003270 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003271 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003272 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003273 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003274 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003275
3276 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003277 SmallVector<APValue, 4> Elts(NElts, Val);
3278 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003279 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003280 case CK_BitCast: {
3281 // Evaluate the operand into an APInt we can extract from.
3282 llvm::APInt SValInt;
3283 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3284 return false;
3285 // Extract the elements
3286 QualType EltTy = VTy->getElementType();
3287 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3288 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3289 SmallVector<APValue, 4> Elts;
3290 if (EltTy->isRealFloatingType()) {
3291 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3292 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3293 unsigned FloatEltSize = EltSize;
3294 if (&Sem == &APFloat::x87DoubleExtended)
3295 FloatEltSize = 80;
3296 for (unsigned i = 0; i < NElts; i++) {
3297 llvm::APInt Elt;
3298 if (BigEndian)
3299 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3300 else
3301 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3302 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3303 }
3304 } else if (EltTy->isIntegerType()) {
3305 for (unsigned i = 0; i < NElts; i++) {
3306 llvm::APInt Elt;
3307 if (BigEndian)
3308 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3309 else
3310 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3311 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3312 }
3313 } else {
3314 return Error(E);
3315 }
3316 return Success(Elts, E);
3317 }
Eli Friedman46a52322011-03-25 00:43:55 +00003318 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003319 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003320 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003321}
3322
Richard Smith07fc6572011-10-22 21:10:00 +00003323bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003324VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003325 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003326 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003327 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003328
Nate Begeman59b5da62009-01-18 03:20:47 +00003329 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003330 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003331
Eli Friedman3edd5a92012-01-03 23:24:20 +00003332 // The number of initializers can be less than the number of
3333 // vector elements. For OpenCL, this can be due to nested vector
3334 // initialization. For GCC compatibility, missing trailing elements
3335 // should be initialized with zeroes.
3336 unsigned CountInits = 0, CountElts = 0;
3337 while (CountElts < NumElements) {
3338 // Handle nested vector initialization.
3339 if (CountInits < NumInits
3340 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3341 APValue v;
3342 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3343 return Error(E);
3344 unsigned vlen = v.getVectorLength();
3345 for (unsigned j = 0; j < vlen; j++)
3346 Elements.push_back(v.getVectorElt(j));
3347 CountElts += vlen;
3348 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003349 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003350 if (CountInits < NumInits) {
3351 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3352 return Error(E);
3353 } else // trailing integer zero.
3354 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3355 Elements.push_back(APValue(sInt));
3356 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003357 } else {
3358 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003359 if (CountInits < NumInits) {
3360 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3361 return Error(E);
3362 } else // trailing float zero.
3363 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3364 Elements.push_back(APValue(f));
3365 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003366 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003367 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003368 }
Richard Smith07fc6572011-10-22 21:10:00 +00003369 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003370}
3371
Richard Smith07fc6572011-10-22 21:10:00 +00003372bool
Richard Smith51201882011-12-30 21:15:51 +00003373VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003374 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003375 QualType EltTy = VT->getElementType();
3376 APValue ZeroElement;
3377 if (EltTy->isIntegerType())
3378 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3379 else
3380 ZeroElement =
3381 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3382
Chris Lattner5f9e2722011-07-23 10:55:15 +00003383 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003384 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003385}
3386
Richard Smith07fc6572011-10-22 21:10:00 +00003387bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003388 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003389 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003390}
3391
Nate Begeman59b5da62009-01-18 03:20:47 +00003392//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003393// Array Evaluation
3394//===----------------------------------------------------------------------===//
3395
3396namespace {
3397 class ArrayExprEvaluator
3398 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003399 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003400 APValue &Result;
3401 public:
3402
Richard Smith180f4792011-11-10 06:34:14 +00003403 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3404 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003405
3406 bool Success(const APValue &V, const Expr *E) {
3407 assert(V.isArray() && "Expected array type");
3408 Result = V;
3409 return true;
3410 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003411
Richard Smith51201882011-12-30 21:15:51 +00003412 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003413 const ConstantArrayType *CAT =
3414 Info.Ctx.getAsConstantArrayType(E->getType());
3415 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003416 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003417
3418 Result = APValue(APValue::UninitArray(), 0,
3419 CAT->getSize().getZExtValue());
3420 if (!Result.hasArrayFiller()) return true;
3421
Richard Smith51201882011-12-30 21:15:51 +00003422 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003423 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003424 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003425 ImplicitValueInitExpr VIE(CAT->getElementType());
3426 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3427 Subobject, &VIE);
3428 }
3429
Richard Smithcc5d4f62011-11-07 09:22:26 +00003430 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003431 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003432 };
3433} // end anonymous namespace
3434
Richard Smith180f4792011-11-10 06:34:14 +00003435static bool EvaluateArray(const Expr *E, const LValue &This,
3436 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003437 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003438 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003439}
3440
3441bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3442 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3443 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003444 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003445
Richard Smith974c5f92011-12-22 01:07:19 +00003446 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3447 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003448 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003449 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3450 LValue LV;
3451 if (!EvaluateLValue(E->getInit(0), LV, Info))
3452 return false;
3453 uint64_t NumElements = CAT->getSize().getZExtValue();
3454 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3455
3456 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003457 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003458 for (uint64_t I = 0; I < NumElements; ++I) {
3459 CCValue Char;
3460 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3461 CAT->getElementType(), LV, Char))
3462 return false;
3463 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3464 Result.getArrayInitializedElt(I)))
3465 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003466 if (!HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
3467 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003468 return false;
3469 }
3470 return true;
3471 }
3472
Richard Smithcc5d4f62011-11-07 09:22:26 +00003473 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3474 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003475 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003476 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003477 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003478 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003479 I != End; ++I, ++Index) {
3480 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3481 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003482 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003483 if (!HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3484 CAT->getElementType(), 1))
Richard Smith180f4792011-11-10 06:34:14 +00003485 return false;
3486 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003487
3488 if (!Result.hasArrayFiller()) return true;
3489 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003490 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3491 // but sometimes does:
3492 // struct S { constexpr S() : p(&p) {} void *p; };
3493 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003494 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00003495 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00003496}
3497
Richard Smithe24f5fc2011-11-17 22:56:20 +00003498bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3499 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3500 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003501 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003502
Richard Smithec789162012-01-12 18:54:33 +00003503 bool HadZeroInit = !Result.isUninit();
3504 if (!HadZeroInit)
3505 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003506 if (!Result.hasArrayFiller())
3507 return true;
3508
3509 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003510
Richard Smith51201882011-12-30 21:15:51 +00003511 bool ZeroInit = E->requiresZeroInitialization();
3512 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003513 if (HadZeroInit)
3514 return true;
3515
Richard Smith51201882011-12-30 21:15:51 +00003516 if (ZeroInit) {
3517 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003518 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003519 ImplicitValueInitExpr VIE(CAT->getElementType());
3520 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3521 Subobject, &VIE);
3522 }
3523
Richard Smith61802452011-12-22 02:22:31 +00003524 const CXXRecordDecl *RD = FD->getParent();
3525 if (RD->isUnion())
3526 Result.getArrayFiller() = APValue((FieldDecl*)0);
3527 else
3528 Result.getArrayFiller() =
3529 APValue(APValue::UninitStruct(), RD->getNumBases(),
3530 std::distance(RD->field_begin(), RD->field_end()));
3531 return true;
3532 }
3533
Richard Smithe24f5fc2011-11-17 22:56:20 +00003534 const FunctionDecl *Definition = 0;
3535 FD->getBody(Definition);
3536
Richard Smithc1c5f272011-12-13 06:39:58 +00003537 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3538 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003539
3540 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3541 // but sometimes does:
3542 // struct S { constexpr S() : p(&p) {} void *p; };
3543 // S s[10];
3544 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003545 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003546
Richard Smithec789162012-01-12 18:54:33 +00003547 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003548 ImplicitValueInitExpr VIE(CAT->getElementType());
3549 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3550 &VIE))
3551 return false;
3552 }
3553
Richard Smithe24f5fc2011-11-17 22:56:20 +00003554 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003555 return HandleConstructorCall(E, Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003556 cast<CXXConstructorDecl>(Definition),
3557 Info, Result.getArrayFiller());
3558}
3559
Richard Smithcc5d4f62011-11-07 09:22:26 +00003560//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003561// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003562//
3563// As a GNU extension, we support casting pointers to sufficiently-wide integer
3564// types and back in constant folding. Integer values are thus represented
3565// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003566//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003567
3568namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003569class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003570 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003571 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003572public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003573 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003574 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003575
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003576 bool Success(const llvm::APSInt &SI, const Expr *E) {
3577 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003578 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003579 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003580 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003581 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003582 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003583 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003584 return true;
3585 }
3586
Daniel Dunbar131eb432009-02-19 09:06:44 +00003587 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003588 assert(E->getType()->isIntegralOrEnumerationType() &&
3589 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003590 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003591 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003592 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003593 Result.getInt().setIsUnsigned(
3594 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003595 return true;
3596 }
3597
3598 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003599 assert(E->getType()->isIntegralOrEnumerationType() &&
3600 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003601 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003602 return true;
3603 }
3604
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003605 bool Success(CharUnits Size, const Expr *E) {
3606 return Success(Size.getQuantity(), E);
3607 }
3608
Richard Smith47a1eed2011-10-29 20:57:55 +00003609 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003610 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003611 Result = V;
3612 return true;
3613 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003614 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003615 }
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Richard Smith51201882011-12-30 21:15:51 +00003617 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003618
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003619 //===--------------------------------------------------------------------===//
3620 // Visitor Methods
3621 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003622
Chris Lattner4c4867e2008-07-12 00:38:25 +00003623 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003624 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003625 }
3626 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003627 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003628 }
Eli Friedman04309752009-11-24 05:28:59 +00003629
3630 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3631 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003632 if (CheckReferencedDecl(E, E->getDecl()))
3633 return true;
3634
3635 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003636 }
3637 bool VisitMemberExpr(const MemberExpr *E) {
3638 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003639 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003640 return true;
3641 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003642
3643 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003644 }
3645
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003646 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003647 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003648 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003649 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003650
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003651 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003652 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003653
Anders Carlsson3068d112008-11-16 19:01:22 +00003654 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003655 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003656 }
Mike Stump1eb44332009-09-09 15:08:12 +00003657
Richard Smithf10d9172011-10-11 21:43:33 +00003658 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003659 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003660 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003661 }
3662
Sebastian Redl64b45f72009-01-05 20:52:13 +00003663 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003664 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003665 }
3666
Francois Pichet6ad6f282010-12-07 00:08:36 +00003667 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3668 return Success(E->getValue(), E);
3669 }
3670
John Wiegley21ff2e52011-04-28 00:16:57 +00003671 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3672 return Success(E->getValue(), E);
3673 }
3674
John Wiegley55262202011-04-25 06:54:41 +00003675 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3676 return Success(E->getValue(), E);
3677 }
3678
Eli Friedman722c7172009-02-28 03:59:05 +00003679 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003680 bool VisitUnaryImag(const UnaryOperator *E);
3681
Sebastian Redl295995c2010-09-10 20:55:47 +00003682 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003683 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003684
Chris Lattnerfcee0012008-07-11 21:24:13 +00003685private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003686 CharUnits GetAlignOfExpr(const Expr *E);
3687 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003688 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003689 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003690 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003691};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003692} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003693
Richard Smithc49bd112011-10-28 17:51:58 +00003694/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3695/// produce either the integer value or a pointer.
3696///
3697/// GCC has a heinous extension which folds casts between pointer types and
3698/// pointer-sized integral types. We support this by allowing the evaluation of
3699/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3700/// Some simple arithmetic on such values is supported (they are treated much
3701/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003702static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003703 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003704 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003705 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003706}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003707
Richard Smithf48fdb02011-12-09 22:58:01 +00003708static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003709 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003710 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003711 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003712 if (!Val.isInt()) {
3713 // FIXME: It would be better to produce the diagnostic for casting
3714 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003715 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003716 return false;
3717 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003718 Result = Val.getInt();
3719 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003720}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003721
Richard Smithf48fdb02011-12-09 22:58:01 +00003722/// Check whether the given declaration can be directly converted to an integral
3723/// rvalue. If not, no diagnostic is produced; there are other things we can
3724/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003725bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003726 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003727 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003728 // Check for signedness/width mismatches between E type and ECD value.
3729 bool SameSign = (ECD->getInitVal().isSigned()
3730 == E->getType()->isSignedIntegerOrEnumerationType());
3731 bool SameWidth = (ECD->getInitVal().getBitWidth()
3732 == Info.Ctx.getIntWidth(E->getType()));
3733 if (SameSign && SameWidth)
3734 return Success(ECD->getInitVal(), E);
3735 else {
3736 // Get rid of mismatch (otherwise Success assertions will fail)
3737 // by computing a new value matching the type of E.
3738 llvm::APSInt Val = ECD->getInitVal();
3739 if (!SameSign)
3740 Val.setIsSigned(!ECD->getInitVal().isSigned());
3741 if (!SameWidth)
3742 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3743 return Success(Val, E);
3744 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003745 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003746 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003747}
3748
Chris Lattnera4d55d82008-10-06 06:40:35 +00003749/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3750/// as GCC.
3751static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3752 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003753 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003754 enum gcc_type_class {
3755 no_type_class = -1,
3756 void_type_class, integer_type_class, char_type_class,
3757 enumeral_type_class, boolean_type_class,
3758 pointer_type_class, reference_type_class, offset_type_class,
3759 real_type_class, complex_type_class,
3760 function_type_class, method_type_class,
3761 record_type_class, union_type_class,
3762 array_type_class, string_type_class,
3763 lang_type_class
3764 };
Mike Stump1eb44332009-09-09 15:08:12 +00003765
3766 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003767 // ideal, however it is what gcc does.
3768 if (E->getNumArgs() == 0)
3769 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Chris Lattnera4d55d82008-10-06 06:40:35 +00003771 QualType ArgTy = E->getArg(0)->getType();
3772 if (ArgTy->isVoidType())
3773 return void_type_class;
3774 else if (ArgTy->isEnumeralType())
3775 return enumeral_type_class;
3776 else if (ArgTy->isBooleanType())
3777 return boolean_type_class;
3778 else if (ArgTy->isCharType())
3779 return string_type_class; // gcc doesn't appear to use char_type_class
3780 else if (ArgTy->isIntegerType())
3781 return integer_type_class;
3782 else if (ArgTy->isPointerType())
3783 return pointer_type_class;
3784 else if (ArgTy->isReferenceType())
3785 return reference_type_class;
3786 else if (ArgTy->isRealType())
3787 return real_type_class;
3788 else if (ArgTy->isComplexType())
3789 return complex_type_class;
3790 else if (ArgTy->isFunctionType())
3791 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003792 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003793 return record_type_class;
3794 else if (ArgTy->isUnionType())
3795 return union_type_class;
3796 else if (ArgTy->isArrayType())
3797 return array_type_class;
3798 else if (ArgTy->isUnionType())
3799 return union_type_class;
3800 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003801 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003802}
3803
Richard Smith80d4b552011-12-28 19:48:30 +00003804/// EvaluateBuiltinConstantPForLValue - Determine the result of
3805/// __builtin_constant_p when applied to the given lvalue.
3806///
3807/// An lvalue is only "constant" if it is a pointer or reference to the first
3808/// character of a string literal.
3809template<typename LValue>
3810static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3811 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3812 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3813}
3814
3815/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3816/// GCC as we can manage.
3817static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3818 QualType ArgType = Arg->getType();
3819
3820 // __builtin_constant_p always has one operand. The rules which gcc follows
3821 // are not precisely documented, but are as follows:
3822 //
3823 // - If the operand is of integral, floating, complex or enumeration type,
3824 // and can be folded to a known value of that type, it returns 1.
3825 // - If the operand and can be folded to a pointer to the first character
3826 // of a string literal (or such a pointer cast to an integral type), it
3827 // returns 1.
3828 //
3829 // Otherwise, it returns 0.
3830 //
3831 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3832 // its support for this does not currently work.
3833 if (ArgType->isIntegralOrEnumerationType()) {
3834 Expr::EvalResult Result;
3835 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3836 return false;
3837
3838 APValue &V = Result.Val;
3839 if (V.getKind() == APValue::Int)
3840 return true;
3841
3842 return EvaluateBuiltinConstantPForLValue(V);
3843 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3844 return Arg->isEvaluatable(Ctx);
3845 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3846 LValue LV;
3847 Expr::EvalStatus Status;
3848 EvalInfo Info(Ctx, Status);
3849 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3850 : EvaluatePointer(Arg, LV, Info)) &&
3851 !Status.HasSideEffects)
3852 return EvaluateBuiltinConstantPForLValue(LV);
3853 }
3854
3855 // Anything else isn't considered to be sufficiently constant.
3856 return false;
3857}
3858
John McCall42c8f872010-05-10 23:27:23 +00003859/// Retrieves the "underlying object type" of the given expression,
3860/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003861QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3862 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3863 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003864 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003865 } else if (const Expr *E = B.get<const Expr*>()) {
3866 if (isa<CompoundLiteralExpr>(E))
3867 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003868 }
3869
3870 return QualType();
3871}
3872
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003873bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003874 // TODO: Perhaps we should let LLVM lower this?
3875 LValue Base;
3876 if (!EvaluatePointer(E->getArg(0), Base, Info))
3877 return false;
3878
3879 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003880 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003881
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003882 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003883 if (T.isNull() ||
3884 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003885 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003886 T->isVariablyModifiedType() ||
3887 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003888 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003889
3890 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3891 CharUnits Offset = Base.getLValueOffset();
3892
3893 if (!Offset.isNegative() && Offset <= Size)
3894 Size -= Offset;
3895 else
3896 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003897 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003898}
3899
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003900bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003901 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003902 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003903 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003904
3905 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003906 if (TryEvaluateBuiltinObjectSize(E))
3907 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003908
Eric Christopherb2aaf512010-01-19 22:58:35 +00003909 // If evaluating the argument has side-effects we can't determine
3910 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003911 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003912 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003913 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003914 return Success(0, E);
3915 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003916
Richard Smithf48fdb02011-12-09 22:58:01 +00003917 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003918 }
3919
Chris Lattner019f4e82008-10-06 05:28:25 +00003920 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003921 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003922
Richard Smith80d4b552011-12-28 19:48:30 +00003923 case Builtin::BI__builtin_constant_p:
3924 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00003925
Chris Lattner21fb98e2009-09-23 06:06:36 +00003926 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003927 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003928 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003929 return Success(Operand, E);
3930 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003931
3932 case Builtin::BI__builtin_expect:
3933 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00003934
Douglas Gregor5726d402010-09-10 06:27:15 +00003935 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00003936 // A call to strlen is not a constant expression.
3937 if (Info.getLangOpts().CPlusPlus0x)
3938 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
3939 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
3940 else
3941 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
3942 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00003943 case Builtin::BI__builtin_strlen:
3944 // As an extension, we support strlen() and __builtin_strlen() as constant
3945 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003946 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003947 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3948 // The string literal may have embedded null characters. Find the first
3949 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003950 StringRef Str = S->getString();
3951 StringRef::size_type Pos = Str.find(0);
3952 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003953 Str = Str.substr(0, Pos);
3954
3955 return Success(Str.size(), E);
3956 }
3957
Richard Smithf48fdb02011-12-09 22:58:01 +00003958 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003959
3960 case Builtin::BI__atomic_is_lock_free: {
3961 APSInt SizeVal;
3962 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3963 return false;
3964
3965 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3966 // of two less than the maximum inline atomic width, we know it is
3967 // lock-free. If the size isn't a power of two, or greater than the
3968 // maximum alignment where we promote atomics, we know it is not lock-free
3969 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3970 // the answer can only be determined at runtime; for example, 16-byte
3971 // atomics have lock-free implementations on some, but not all,
3972 // x86-64 processors.
3973
3974 // Check power-of-two.
3975 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3976 if (!Size.isPowerOfTwo())
3977#if 0
3978 // FIXME: Suppress this folding until the ABI for the promotion width
3979 // settles.
3980 return Success(0, E);
3981#else
Richard Smithf48fdb02011-12-09 22:58:01 +00003982 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003983#endif
3984
3985#if 0
3986 // Check against promotion width.
3987 // FIXME: Suppress this folding until the ABI for the promotion width
3988 // settles.
3989 unsigned PromoteWidthBits =
3990 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3991 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3992 return Success(0, E);
3993#endif
3994
3995 // Check against inlining width.
3996 unsigned InlineWidthBits =
3997 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3998 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3999 return Success(1, E);
4000
Richard Smithf48fdb02011-12-09 22:58:01 +00004001 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004002 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004003 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004004}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004005
Richard Smith625b8072011-10-31 01:37:14 +00004006static bool HasSameBase(const LValue &A, const LValue &B) {
4007 if (!A.getLValueBase())
4008 return !B.getLValueBase();
4009 if (!B.getLValueBase())
4010 return false;
4011
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004012 if (A.getLValueBase().getOpaqueValue() !=
4013 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004014 const Decl *ADecl = GetLValueBaseDecl(A);
4015 if (!ADecl)
4016 return false;
4017 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004018 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004019 return false;
4020 }
4021
4022 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004023 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004024}
4025
Chris Lattnerb542afe2008-07-11 19:10:17 +00004026bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004027 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004028 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004029
John McCall2de56d12010-08-25 11:45:40 +00004030 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004031 VisitIgnoredValue(E->getLHS());
4032 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004033 }
4034
4035 if (E->isLogicalOp()) {
4036 // These need to be handled specially because the operands aren't
4037 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004038 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Richard Smithc49bd112011-10-28 17:51:58 +00004040 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004041 // We were able to evaluate the LHS, see if we can get away with not
4042 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004043 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004044 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004045
Richard Smithc49bd112011-10-28 17:51:58 +00004046 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004047 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004048 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004049 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004050 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004051 }
4052 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004053 // FIXME: If both evaluations fail, we should produce the diagnostic from
4054 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4055 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004056 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004057 // We can't evaluate the LHS; however, sometimes the result
4058 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004059 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004060 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004061 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004062 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004063
4064 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004065 }
4066 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004067 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004068
Eli Friedmana6afa762008-11-13 06:09:17 +00004069 return false;
4070 }
4071
Anders Carlsson286f85e2008-11-16 07:17:21 +00004072 QualType LHSTy = E->getLHS()->getType();
4073 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004074
4075 if (LHSTy->isAnyComplexType()) {
4076 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004077 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004078
4079 if (!EvaluateComplex(E->getLHS(), LHS, Info))
4080 return false;
4081
4082 if (!EvaluateComplex(E->getRHS(), RHS, Info))
4083 return false;
4084
4085 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004086 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004087 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004088 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004089 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4090
John McCall2de56d12010-08-25 11:45:40 +00004091 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004092 return Success((CR_r == APFloat::cmpEqual &&
4093 CR_i == APFloat::cmpEqual), E);
4094 else {
John McCall2de56d12010-08-25 11:45:40 +00004095 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004096 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004097 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004098 CR_r == APFloat::cmpLessThan ||
4099 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004100 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004101 CR_i == APFloat::cmpLessThan ||
4102 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004103 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004104 } else {
John McCall2de56d12010-08-25 11:45:40 +00004105 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004106 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4107 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4108 else {
John McCall2de56d12010-08-25 11:45:40 +00004109 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004110 "Invalid compex comparison.");
4111 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4112 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4113 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004114 }
4115 }
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Anders Carlsson286f85e2008-11-16 07:17:21 +00004117 if (LHSTy->isRealFloatingType() &&
4118 RHSTy->isRealFloatingType()) {
4119 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Anders Carlsson286f85e2008-11-16 07:17:21 +00004121 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4122 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Anders Carlsson286f85e2008-11-16 07:17:21 +00004124 if (!EvaluateFloat(E->getLHS(), LHS, Info))
4125 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004126
Anders Carlsson286f85e2008-11-16 07:17:21 +00004127 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004128
Anders Carlsson286f85e2008-11-16 07:17:21 +00004129 switch (E->getOpcode()) {
4130 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004131 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004132 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004133 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004134 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004135 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004136 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004137 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004138 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004139 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004140 E);
John McCall2de56d12010-08-25 11:45:40 +00004141 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004142 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004143 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004144 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004145 || CR == APFloat::cmpLessThan
4146 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004147 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004148 }
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004150 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004151 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00004152 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00004153 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
4154 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004155
John McCallefdb83e2010-05-07 21:00:08 +00004156 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00004157 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
4158 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004159
Richard Smith625b8072011-10-31 01:37:14 +00004160 // Reject differing bases from the normal codepath; we special-case
4161 // comparisons to null.
4162 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004163 if (E->getOpcode() == BO_Sub) {
4164 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004165 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4166 return false;
4167 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4168 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4169 if (!LHSExpr || !RHSExpr)
4170 return false;
4171 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4172 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4173 if (!LHSAddrExpr || !RHSAddrExpr)
4174 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004175 // Make sure both labels come from the same function.
4176 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4177 RHSAddrExpr->getLabel()->getDeclContext())
4178 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004179 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4180 return true;
4181 }
Richard Smith9e36b532011-10-31 05:11:32 +00004182 // Inequalities and subtractions between unrelated pointers have
4183 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004184 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004185 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004186 // A constant address may compare equal to the address of a symbol.
4187 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004188 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004189 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4190 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004191 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004192 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00004193 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00004194 // distinct. However, we do know that the address of a literal will be
4195 // non-null.
4196 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4197 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004198 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004199 // We can't tell whether weak symbols will end up pointing to the same
4200 // object.
4201 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004202 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004203 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004204 // (Note that clang defaults to -fmerge-all-constants, which can
4205 // lead to inconsistent results for comparisons involving the address
4206 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004207 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004208 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004209
Richard Smithcc5d4f62011-11-07 09:22:26 +00004210 // FIXME: Implement the C++11 restrictions:
4211 // - Pointer subtractions must be on elements of the same array.
4212 // - Pointer comparisons must be between members with the same access.
4213
John McCall2de56d12010-08-25 11:45:40 +00004214 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004215 QualType Type = E->getLHS()->getType();
4216 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004217
Richard Smith180f4792011-11-10 06:34:14 +00004218 CharUnits ElementSize;
4219 if (!HandleSizeof(Info, ElementType, ElementSize))
4220 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004221
Richard Smith180f4792011-11-10 06:34:14 +00004222 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004223 RHSValue.getLValueOffset();
4224 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004225 }
Richard Smith625b8072011-10-31 01:37:14 +00004226
4227 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4228 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4229 switch (E->getOpcode()) {
4230 default: llvm_unreachable("missing comparison operator");
4231 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4232 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4233 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4234 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4235 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4236 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004237 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004238 }
4239 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004240 if (!LHSTy->isIntegralOrEnumerationType() ||
4241 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004242 // We can't continue from here for non-integral types.
4243 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004244 }
4245
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004246 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004247 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00004248 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00004249 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004250
Richard Smithc49bd112011-10-28 17:51:58 +00004251 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004252 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004253 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004254
4255 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004256 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004257 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4258 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004259 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004260 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004261 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004262 LHSVal.getLValueOffset() -= AdditionalOffset;
4263 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004264 return true;
4265 }
4266
4267 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004268 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004269 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004270 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4271 LHSVal.getInt().getZExtValue());
4272 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004273 return true;
4274 }
4275
Eli Friedman65639282012-01-04 23:13:47 +00004276 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4277 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004278 if (!LHSVal.getLValueOffset().isZero() ||
4279 !RHSVal.getLValueOffset().isZero())
4280 return false;
4281 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4282 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4283 if (!LHSExpr || !RHSExpr)
4284 return false;
4285 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4286 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4287 if (!LHSAddrExpr || !RHSAddrExpr)
4288 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004289 // Make sure both labels come from the same function.
4290 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4291 RHSAddrExpr->getLabel()->getDeclContext())
4292 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004293 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4294 return true;
4295 }
4296
Eli Friedman42edd0d2009-03-24 01:14:50 +00004297 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004298 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004299 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004300
Richard Smithc49bd112011-10-28 17:51:58 +00004301 APSInt &LHS = LHSVal.getInt();
4302 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004303
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004304 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004305 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004306 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004307 case BO_Mul: return Success(LHS * RHS, E);
4308 case BO_Add: return Success(LHS + RHS, E);
4309 case BO_Sub: return Success(LHS - RHS, E);
4310 case BO_And: return Success(LHS & RHS, E);
4311 case BO_Xor: return Success(LHS ^ RHS, E);
4312 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004313 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00004314 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004315 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004316 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004317 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004318 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004319 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004320 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004321 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00004322 // During constant-folding, a negative shift is an opposite shift.
4323 if (RHS.isSigned() && RHS.isNegative()) {
4324 RHS = -RHS;
4325 goto shift_right;
4326 }
4327
4328 shift_left:
4329 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00004330 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4331 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004332 }
John McCall2de56d12010-08-25 11:45:40 +00004333 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00004334 // During constant-folding, a negative shift is an opposite shift.
4335 if (RHS.isSigned() && RHS.isNegative()) {
4336 RHS = -RHS;
4337 goto shift_left;
4338 }
4339
4340 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00004341 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00004342 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4343 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004344 }
Mike Stump1eb44332009-09-09 15:08:12 +00004345
Richard Smithc49bd112011-10-28 17:51:58 +00004346 case BO_LT: return Success(LHS < RHS, E);
4347 case BO_GT: return Success(LHS > RHS, E);
4348 case BO_LE: return Success(LHS <= RHS, E);
4349 case BO_GE: return Success(LHS >= RHS, E);
4350 case BO_EQ: return Success(LHS == RHS, E);
4351 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004352 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004353}
4354
Ken Dyck8b752f12010-01-27 17:10:57 +00004355CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004356 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4357 // the result is the size of the referenced type."
4358 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4359 // result shall be the alignment of the referenced type."
4360 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4361 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004362
4363 // __alignof is defined to return the preferred alignment.
4364 return Info.Ctx.toCharUnitsFromBits(
4365 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004366}
4367
Ken Dyck8b752f12010-01-27 17:10:57 +00004368CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004369 E = E->IgnoreParens();
4370
4371 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004372 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004373 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004374 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4375 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004376
Chris Lattneraf707ab2009-01-24 21:53:27 +00004377 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004378 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4379 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004380
Chris Lattnere9feb472009-01-24 21:09:06 +00004381 return GetAlignOfType(E->getType());
4382}
4383
4384
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004385/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4386/// a result as the expression's type.
4387bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4388 const UnaryExprOrTypeTraitExpr *E) {
4389 switch(E->getKind()) {
4390 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004391 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004392 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004393 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004394 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004395 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004396
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004397 case UETT_VecStep: {
4398 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004399
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004400 if (Ty->isVectorType()) {
4401 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004402
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004403 // The vec_step built-in functions that take a 3-component
4404 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4405 if (n == 3)
4406 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004407
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004408 return Success(n, E);
4409 } else
4410 return Success(1, E);
4411 }
4412
4413 case UETT_SizeOf: {
4414 QualType SrcTy = E->getTypeOfArgument();
4415 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4416 // the result is the size of the referenced type."
4417 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4418 // result shall be the alignment of the referenced type."
4419 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4420 SrcTy = Ref->getPointeeType();
4421
Richard Smith180f4792011-11-10 06:34:14 +00004422 CharUnits Sizeof;
4423 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004424 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004425 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004426 }
4427 }
4428
4429 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004430}
4431
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004432bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004433 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004434 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004435 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004436 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004437 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004438 for (unsigned i = 0; i != n; ++i) {
4439 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4440 switch (ON.getKind()) {
4441 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004442 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004443 APSInt IdxResult;
4444 if (!EvaluateInteger(Idx, IdxResult, Info))
4445 return false;
4446 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4447 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004448 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004449 CurrentType = AT->getElementType();
4450 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4451 Result += IdxResult.getSExtValue() * ElementSize;
4452 break;
4453 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004454
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004455 case OffsetOfExpr::OffsetOfNode::Field: {
4456 FieldDecl *MemberDecl = ON.getField();
4457 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004458 if (!RT)
4459 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004460 RecordDecl *RD = RT->getDecl();
4461 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004462 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004463 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004464 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004465 CurrentType = MemberDecl->getType().getNonReferenceType();
4466 break;
4467 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004468
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004469 case OffsetOfExpr::OffsetOfNode::Identifier:
4470 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004471
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004472 case OffsetOfExpr::OffsetOfNode::Base: {
4473 CXXBaseSpecifier *BaseSpec = ON.getBase();
4474 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004475 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004476
4477 // Find the layout of the class whose base we are looking into.
4478 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004479 if (!RT)
4480 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004481 RecordDecl *RD = RT->getDecl();
4482 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4483
4484 // Find the base class itself.
4485 CurrentType = BaseSpec->getType();
4486 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4487 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004488 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004489
4490 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004491 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004492 break;
4493 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004494 }
4495 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004496 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004497}
4498
Chris Lattnerb542afe2008-07-11 19:10:17 +00004499bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004500 switch (E->getOpcode()) {
4501 default:
4502 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4503 // See C99 6.6p3.
4504 return Error(E);
4505 case UO_Extension:
4506 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4507 // If so, we could clear the diagnostic ID.
4508 return Visit(E->getSubExpr());
4509 case UO_Plus:
4510 // The result is just the value.
4511 return Visit(E->getSubExpr());
4512 case UO_Minus: {
4513 if (!Visit(E->getSubExpr()))
4514 return false;
4515 if (!Result.isInt()) return Error(E);
4516 return Success(-Result.getInt(), E);
4517 }
4518 case UO_Not: {
4519 if (!Visit(E->getSubExpr()))
4520 return false;
4521 if (!Result.isInt()) return Error(E);
4522 return Success(~Result.getInt(), E);
4523 }
4524 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004525 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004526 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004527 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004528 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004529 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004530 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004531}
Mike Stump1eb44332009-09-09 15:08:12 +00004532
Chris Lattner732b2232008-07-12 01:15:53 +00004533/// HandleCast - This is used to evaluate implicit or explicit casts where the
4534/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004535bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4536 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004537 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004538 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004539
Eli Friedman46a52322011-03-25 00:43:55 +00004540 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004541 case CK_BaseToDerived:
4542 case CK_DerivedToBase:
4543 case CK_UncheckedDerivedToBase:
4544 case CK_Dynamic:
4545 case CK_ToUnion:
4546 case CK_ArrayToPointerDecay:
4547 case CK_FunctionToPointerDecay:
4548 case CK_NullToPointer:
4549 case CK_NullToMemberPointer:
4550 case CK_BaseToDerivedMemberPointer:
4551 case CK_DerivedToBaseMemberPointer:
4552 case CK_ConstructorConversion:
4553 case CK_IntegralToPointer:
4554 case CK_ToVoid:
4555 case CK_VectorSplat:
4556 case CK_IntegralToFloating:
4557 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004558 case CK_CPointerToObjCPointerCast:
4559 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004560 case CK_AnyPointerToBlockPointerCast:
4561 case CK_ObjCObjectLValueCast:
4562 case CK_FloatingRealToComplex:
4563 case CK_FloatingComplexToReal:
4564 case CK_FloatingComplexCast:
4565 case CK_FloatingComplexToIntegralComplex:
4566 case CK_IntegralRealToComplex:
4567 case CK_IntegralComplexCast:
4568 case CK_IntegralComplexToFloatingComplex:
4569 llvm_unreachable("invalid cast kind for integral value");
4570
Eli Friedmane50c2972011-03-25 19:07:11 +00004571 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004572 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004573 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004574 case CK_ARCProduceObject:
4575 case CK_ARCConsumeObject:
4576 case CK_ARCReclaimReturnedObject:
4577 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004578 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004579
Richard Smith7d580a42012-01-17 21:17:26 +00004580 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004581 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004582 case CK_AtomicToNonAtomic:
4583 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004584 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004585 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004586
4587 case CK_MemberPointerToBoolean:
4588 case CK_PointerToBoolean:
4589 case CK_IntegralToBoolean:
4590 case CK_FloatingToBoolean:
4591 case CK_FloatingComplexToBoolean:
4592 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004593 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004594 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004595 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004596 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004597 }
4598
Eli Friedman46a52322011-03-25 00:43:55 +00004599 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004600 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004601 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004602
Eli Friedmanbe265702009-02-20 01:15:07 +00004603 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004604 // Allow casts of address-of-label differences if they are no-ops
4605 // or narrowing. (The narrowing case isn't actually guaranteed to
4606 // be constant-evaluatable except in some narrow cases which are hard
4607 // to detect here. We let it through on the assumption the user knows
4608 // what they are doing.)
4609 if (Result.isAddrLabelDiff())
4610 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00004611 // Only allow casts of lvalues if they are lossless.
4612 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4613 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004614
Daniel Dunbardd211642009-02-19 22:24:01 +00004615 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004616 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004617 }
Mike Stump1eb44332009-09-09 15:08:12 +00004618
Eli Friedman46a52322011-03-25 00:43:55 +00004619 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004620 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4621
John McCallefdb83e2010-05-07 21:00:08 +00004622 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004623 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004624 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004625
Daniel Dunbardd211642009-02-19 22:24:01 +00004626 if (LV.getLValueBase()) {
4627 // Only allow based lvalue casts if they are lossless.
4628 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004629 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004630
Richard Smithb755a9d2011-11-16 07:18:12 +00004631 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004632 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004633 return true;
4634 }
4635
Ken Dycka7305832010-01-15 12:37:54 +00004636 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4637 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00004638 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004639 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004640
Eli Friedman46a52322011-03-25 00:43:55 +00004641 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004642 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004643 if (!EvaluateComplex(SubExpr, C, Info))
4644 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004645 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004646 }
Eli Friedman2217c872009-02-22 11:46:18 +00004647
Eli Friedman46a52322011-03-25 00:43:55 +00004648 case CK_FloatingToIntegral: {
4649 APFloat F(0.0);
4650 if (!EvaluateFloat(SubExpr, F, Info))
4651 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004652
Richard Smithc1c5f272011-12-13 06:39:58 +00004653 APSInt Value;
4654 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4655 return false;
4656 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004657 }
4658 }
Mike Stump1eb44332009-09-09 15:08:12 +00004659
Eli Friedman46a52322011-03-25 00:43:55 +00004660 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004661}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004662
Eli Friedman722c7172009-02-28 03:59:05 +00004663bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4664 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004665 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004666 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4667 return false;
4668 if (!LV.isComplexInt())
4669 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004670 return Success(LV.getComplexIntReal(), E);
4671 }
4672
4673 return Visit(E->getSubExpr());
4674}
4675
Eli Friedman664a1042009-02-27 04:45:43 +00004676bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004677 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004678 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004679 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4680 return false;
4681 if (!LV.isComplexInt())
4682 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004683 return Success(LV.getComplexIntImag(), E);
4684 }
4685
Richard Smith8327fad2011-10-24 18:44:57 +00004686 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004687 return Success(0, E);
4688}
4689
Douglas Gregoree8aff02011-01-04 17:33:58 +00004690bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4691 return Success(E->getPackLength(), E);
4692}
4693
Sebastian Redl295995c2010-09-10 20:55:47 +00004694bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4695 return Success(E->getValue(), E);
4696}
4697
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004698//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004699// Float Evaluation
4700//===----------------------------------------------------------------------===//
4701
4702namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004703class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004704 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004705 APFloat &Result;
4706public:
4707 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004708 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004709
Richard Smith47a1eed2011-10-29 20:57:55 +00004710 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004711 Result = V.getFloat();
4712 return true;
4713 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004714
Richard Smith51201882011-12-30 21:15:51 +00004715 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004716 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4717 return true;
4718 }
4719
Chris Lattner019f4e82008-10-06 05:28:25 +00004720 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004721
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004722 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004723 bool VisitBinaryOperator(const BinaryOperator *E);
4724 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004725 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004726
John McCallabd3a852010-05-07 22:08:54 +00004727 bool VisitUnaryReal(const UnaryOperator *E);
4728 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004729
Richard Smith51201882011-12-30 21:15:51 +00004730 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004731};
4732} // end anonymous namespace
4733
4734static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004735 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004736 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004737}
4738
Jay Foad4ba2a172011-01-12 09:06:06 +00004739static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004740 QualType ResultTy,
4741 const Expr *Arg,
4742 bool SNaN,
4743 llvm::APFloat &Result) {
4744 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4745 if (!S) return false;
4746
4747 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4748
4749 llvm::APInt fill;
4750
4751 // Treat empty strings as if they were zero.
4752 if (S->getString().empty())
4753 fill = llvm::APInt(32, 0);
4754 else if (S->getString().getAsInteger(0, fill))
4755 return false;
4756
4757 if (SNaN)
4758 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4759 else
4760 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4761 return true;
4762}
4763
Chris Lattner019f4e82008-10-06 05:28:25 +00004764bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004765 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004766 default:
4767 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4768
Chris Lattner019f4e82008-10-06 05:28:25 +00004769 case Builtin::BI__builtin_huge_val:
4770 case Builtin::BI__builtin_huge_valf:
4771 case Builtin::BI__builtin_huge_vall:
4772 case Builtin::BI__builtin_inf:
4773 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004774 case Builtin::BI__builtin_infl: {
4775 const llvm::fltSemantics &Sem =
4776 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004777 Result = llvm::APFloat::getInf(Sem);
4778 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004779 }
Mike Stump1eb44332009-09-09 15:08:12 +00004780
John McCalldb7b72a2010-02-28 13:00:19 +00004781 case Builtin::BI__builtin_nans:
4782 case Builtin::BI__builtin_nansf:
4783 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004784 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4785 true, Result))
4786 return Error(E);
4787 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004788
Chris Lattner9e621712008-10-06 06:31:58 +00004789 case Builtin::BI__builtin_nan:
4790 case Builtin::BI__builtin_nanf:
4791 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004792 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004793 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004794 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4795 false, Result))
4796 return Error(E);
4797 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004798
4799 case Builtin::BI__builtin_fabs:
4800 case Builtin::BI__builtin_fabsf:
4801 case Builtin::BI__builtin_fabsl:
4802 if (!EvaluateFloat(E->getArg(0), Result, Info))
4803 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004804
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004805 if (Result.isNegative())
4806 Result.changeSign();
4807 return true;
4808
Mike Stump1eb44332009-09-09 15:08:12 +00004809 case Builtin::BI__builtin_copysign:
4810 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004811 case Builtin::BI__builtin_copysignl: {
4812 APFloat RHS(0.);
4813 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4814 !EvaluateFloat(E->getArg(1), RHS, Info))
4815 return false;
4816 Result.copySign(RHS);
4817 return true;
4818 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004819 }
4820}
4821
John McCallabd3a852010-05-07 22:08:54 +00004822bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004823 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4824 ComplexValue CV;
4825 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4826 return false;
4827 Result = CV.FloatReal;
4828 return true;
4829 }
4830
4831 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004832}
4833
4834bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004835 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4836 ComplexValue CV;
4837 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4838 return false;
4839 Result = CV.FloatImag;
4840 return true;
4841 }
4842
Richard Smith8327fad2011-10-24 18:44:57 +00004843 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004844 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4845 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004846 return true;
4847}
4848
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004849bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004850 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004851 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004852 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004853 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004854 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004855 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4856 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004857 Result.changeSign();
4858 return true;
4859 }
4860}
Chris Lattner019f4e82008-10-06 05:28:25 +00004861
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004862bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004863 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4864 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004865
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004866 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004867 if (!EvaluateFloat(E->getLHS(), Result, Info))
4868 return false;
4869 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4870 return false;
4871
4872 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004873 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004874 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004875 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4876 return true;
John McCall2de56d12010-08-25 11:45:40 +00004877 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004878 Result.add(RHS, APFloat::rmNearestTiesToEven);
4879 return true;
John McCall2de56d12010-08-25 11:45:40 +00004880 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004881 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4882 return true;
John McCall2de56d12010-08-25 11:45:40 +00004883 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004884 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4885 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004886 }
4887}
4888
4889bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4890 Result = E->getValue();
4891 return true;
4892}
4893
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004894bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4895 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004896
Eli Friedman2a523ee2011-03-25 00:54:52 +00004897 switch (E->getCastKind()) {
4898 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004899 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004900
4901 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004902 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004903 return EvaluateInteger(SubExpr, IntResult, Info) &&
4904 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4905 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004906 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004907
4908 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004909 if (!Visit(SubExpr))
4910 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004911 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4912 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004913 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004914
Eli Friedman2a523ee2011-03-25 00:54:52 +00004915 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004916 ComplexValue V;
4917 if (!EvaluateComplex(SubExpr, V, Info))
4918 return false;
4919 Result = V.getComplexFloatReal();
4920 return true;
4921 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004922 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004923}
4924
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004925//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004926// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004927//===----------------------------------------------------------------------===//
4928
4929namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004930class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004931 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004932 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004933
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004934public:
John McCallf4cf1a12010-05-07 17:22:02 +00004935 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004936 : ExprEvaluatorBaseTy(info), Result(Result) {}
4937
Richard Smith47a1eed2011-10-29 20:57:55 +00004938 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004939 Result.setFrom(V);
4940 return true;
4941 }
Mike Stump1eb44332009-09-09 15:08:12 +00004942
Eli Friedman7ead5c72012-01-10 04:58:17 +00004943 bool ZeroInitialization(const Expr *E);
4944
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004945 //===--------------------------------------------------------------------===//
4946 // Visitor Methods
4947 //===--------------------------------------------------------------------===//
4948
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004949 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004950 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00004951 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004952 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00004953 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004954};
4955} // end anonymous namespace
4956
John McCallf4cf1a12010-05-07 17:22:02 +00004957static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4958 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004959 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004960 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004961}
4962
Eli Friedman7ead5c72012-01-10 04:58:17 +00004963bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00004964 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00004965 if (ElemTy->isRealFloatingType()) {
4966 Result.makeComplexFloat();
4967 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
4968 Result.FloatReal = Zero;
4969 Result.FloatImag = Zero;
4970 } else {
4971 Result.makeComplexInt();
4972 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
4973 Result.IntReal = Zero;
4974 Result.IntImag = Zero;
4975 }
4976 return true;
4977}
4978
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004979bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4980 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004981
4982 if (SubExpr->getType()->isRealFloatingType()) {
4983 Result.makeComplexFloat();
4984 APFloat &Imag = Result.FloatImag;
4985 if (!EvaluateFloat(SubExpr, Imag, Info))
4986 return false;
4987
4988 Result.FloatReal = APFloat(Imag.getSemantics());
4989 return true;
4990 } else {
4991 assert(SubExpr->getType()->isIntegerType() &&
4992 "Unexpected imaginary literal.");
4993
4994 Result.makeComplexInt();
4995 APSInt &Imag = Result.IntImag;
4996 if (!EvaluateInteger(SubExpr, Imag, Info))
4997 return false;
4998
4999 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5000 return true;
5001 }
5002}
5003
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005004bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005005
John McCall8786da72010-12-14 17:51:41 +00005006 switch (E->getCastKind()) {
5007 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005008 case CK_BaseToDerived:
5009 case CK_DerivedToBase:
5010 case CK_UncheckedDerivedToBase:
5011 case CK_Dynamic:
5012 case CK_ToUnion:
5013 case CK_ArrayToPointerDecay:
5014 case CK_FunctionToPointerDecay:
5015 case CK_NullToPointer:
5016 case CK_NullToMemberPointer:
5017 case CK_BaseToDerivedMemberPointer:
5018 case CK_DerivedToBaseMemberPointer:
5019 case CK_MemberPointerToBoolean:
5020 case CK_ConstructorConversion:
5021 case CK_IntegralToPointer:
5022 case CK_PointerToIntegral:
5023 case CK_PointerToBoolean:
5024 case CK_ToVoid:
5025 case CK_VectorSplat:
5026 case CK_IntegralCast:
5027 case CK_IntegralToBoolean:
5028 case CK_IntegralToFloating:
5029 case CK_FloatingToIntegral:
5030 case CK_FloatingToBoolean:
5031 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005032 case CK_CPointerToObjCPointerCast:
5033 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005034 case CK_AnyPointerToBlockPointerCast:
5035 case CK_ObjCObjectLValueCast:
5036 case CK_FloatingComplexToReal:
5037 case CK_FloatingComplexToBoolean:
5038 case CK_IntegralComplexToReal:
5039 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005040 case CK_ARCProduceObject:
5041 case CK_ARCConsumeObject:
5042 case CK_ARCReclaimReturnedObject:
5043 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005044 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005045
John McCall8786da72010-12-14 17:51:41 +00005046 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005047 case CK_AtomicToNonAtomic:
5048 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005049 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005050 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005051
5052 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005053 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005054 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005055 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005056
5057 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005058 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005059 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005060 return false;
5061
John McCall8786da72010-12-14 17:51:41 +00005062 Result.makeComplexFloat();
5063 Result.FloatImag = APFloat(Real.getSemantics());
5064 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005065 }
5066
John McCall8786da72010-12-14 17:51:41 +00005067 case CK_FloatingComplexCast: {
5068 if (!Visit(E->getSubExpr()))
5069 return false;
5070
5071 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5072 QualType From
5073 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5074
Richard Smithc1c5f272011-12-13 06:39:58 +00005075 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5076 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005077 }
5078
5079 case CK_FloatingComplexToIntegralComplex: {
5080 if (!Visit(E->getSubExpr()))
5081 return false;
5082
5083 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5084 QualType From
5085 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5086 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005087 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5088 To, Result.IntReal) &&
5089 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5090 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005091 }
5092
5093 case CK_IntegralRealToComplex: {
5094 APSInt &Real = Result.IntReal;
5095 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5096 return false;
5097
5098 Result.makeComplexInt();
5099 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5100 return true;
5101 }
5102
5103 case CK_IntegralComplexCast: {
5104 if (!Visit(E->getSubExpr()))
5105 return false;
5106
5107 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5108 QualType From
5109 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5110
5111 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
5112 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
5113 return true;
5114 }
5115
5116 case CK_IntegralComplexToFloatingComplex: {
5117 if (!Visit(E->getSubExpr()))
5118 return false;
5119
5120 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5121 QualType From
5122 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5123 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005124 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5125 To, Result.FloatReal) &&
5126 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5127 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005128 }
5129 }
5130
5131 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005132}
5133
John McCallf4cf1a12010-05-07 17:22:02 +00005134bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005135 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005136 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5137
John McCallf4cf1a12010-05-07 17:22:02 +00005138 if (!Visit(E->getLHS()))
5139 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005140
John McCallf4cf1a12010-05-07 17:22:02 +00005141 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005142 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00005143 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005144
Daniel Dunbar3f279872009-01-29 01:32:56 +00005145 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5146 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005147 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005148 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005149 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005150 if (Result.isComplexFloat()) {
5151 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5152 APFloat::rmNearestTiesToEven);
5153 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5154 APFloat::rmNearestTiesToEven);
5155 } else {
5156 Result.getComplexIntReal() += RHS.getComplexIntReal();
5157 Result.getComplexIntImag() += RHS.getComplexIntImag();
5158 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005159 break;
John McCall2de56d12010-08-25 11:45:40 +00005160 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005161 if (Result.isComplexFloat()) {
5162 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5163 APFloat::rmNearestTiesToEven);
5164 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5165 APFloat::rmNearestTiesToEven);
5166 } else {
5167 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5168 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5169 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005170 break;
John McCall2de56d12010-08-25 11:45:40 +00005171 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005172 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005173 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005174 APFloat &LHS_r = LHS.getComplexFloatReal();
5175 APFloat &LHS_i = LHS.getComplexFloatImag();
5176 APFloat &RHS_r = RHS.getComplexFloatReal();
5177 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005178
Daniel Dunbar3f279872009-01-29 01:32:56 +00005179 APFloat Tmp = LHS_r;
5180 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5181 Result.getComplexFloatReal() = Tmp;
5182 Tmp = LHS_i;
5183 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5184 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5185
5186 Tmp = LHS_r;
5187 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5188 Result.getComplexFloatImag() = Tmp;
5189 Tmp = LHS_i;
5190 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5191 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5192 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005193 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005194 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005195 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5196 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005197 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005198 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5199 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5200 }
5201 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005202 case BO_Div:
5203 if (Result.isComplexFloat()) {
5204 ComplexValue LHS = Result;
5205 APFloat &LHS_r = LHS.getComplexFloatReal();
5206 APFloat &LHS_i = LHS.getComplexFloatImag();
5207 APFloat &RHS_r = RHS.getComplexFloatReal();
5208 APFloat &RHS_i = RHS.getComplexFloatImag();
5209 APFloat &Res_r = Result.getComplexFloatReal();
5210 APFloat &Res_i = Result.getComplexFloatImag();
5211
5212 APFloat Den = RHS_r;
5213 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5214 APFloat Tmp = RHS_i;
5215 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5216 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5217
5218 Res_r = LHS_r;
5219 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5220 Tmp = LHS_i;
5221 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5222 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5223 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5224
5225 Res_i = LHS_i;
5226 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5227 Tmp = LHS_r;
5228 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5229 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5230 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5231 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005232 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5233 return Error(E, diag::note_expr_divide_by_zero);
5234
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005235 ComplexValue LHS = Result;
5236 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5237 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5238 Result.getComplexIntReal() =
5239 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5240 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5241 Result.getComplexIntImag() =
5242 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5243 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5244 }
5245 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005246 }
5247
John McCallf4cf1a12010-05-07 17:22:02 +00005248 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005249}
5250
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005251bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5252 // Get the operand value into 'Result'.
5253 if (!Visit(E->getSubExpr()))
5254 return false;
5255
5256 switch (E->getOpcode()) {
5257 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005258 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005259 case UO_Extension:
5260 return true;
5261 case UO_Plus:
5262 // The result is always just the subexpr.
5263 return true;
5264 case UO_Minus:
5265 if (Result.isComplexFloat()) {
5266 Result.getComplexFloatReal().changeSign();
5267 Result.getComplexFloatImag().changeSign();
5268 }
5269 else {
5270 Result.getComplexIntReal() = -Result.getComplexIntReal();
5271 Result.getComplexIntImag() = -Result.getComplexIntImag();
5272 }
5273 return true;
5274 case UO_Not:
5275 if (Result.isComplexFloat())
5276 Result.getComplexFloatImag().changeSign();
5277 else
5278 Result.getComplexIntImag() = -Result.getComplexIntImag();
5279 return true;
5280 }
5281}
5282
Eli Friedman7ead5c72012-01-10 04:58:17 +00005283bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5284 if (E->getNumInits() == 2) {
5285 if (E->getType()->isComplexType()) {
5286 Result.makeComplexFloat();
5287 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5288 return false;
5289 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5290 return false;
5291 } else {
5292 Result.makeComplexInt();
5293 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5294 return false;
5295 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5296 return false;
5297 }
5298 return true;
5299 }
5300 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5301}
5302
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005303//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005304// Void expression evaluation, primarily for a cast to void on the LHS of a
5305// comma operator
5306//===----------------------------------------------------------------------===//
5307
5308namespace {
5309class VoidExprEvaluator
5310 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5311public:
5312 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5313
5314 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005315
5316 bool VisitCastExpr(const CastExpr *E) {
5317 switch (E->getCastKind()) {
5318 default:
5319 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5320 case CK_ToVoid:
5321 VisitIgnoredValue(E->getSubExpr());
5322 return true;
5323 }
5324 }
5325};
5326} // end anonymous namespace
5327
5328static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5329 assert(E->isRValue() && E->getType()->isVoidType());
5330 return VoidExprEvaluator(Info).Visit(E);
5331}
5332
5333//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005334// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005335//===----------------------------------------------------------------------===//
5336
Richard Smith47a1eed2011-10-29 20:57:55 +00005337static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005338 // In C, function designators are not lvalues, but we evaluate them as if they
5339 // are.
5340 if (E->isGLValue() || E->getType()->isFunctionType()) {
5341 LValue LV;
5342 if (!EvaluateLValue(E, LV, Info))
5343 return false;
5344 LV.moveInto(Result);
5345 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005346 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005347 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005348 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005349 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005350 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005351 } else if (E->getType()->hasPointerRepresentation()) {
5352 LValue LV;
5353 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005354 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005355 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005356 } else if (E->getType()->isRealFloatingType()) {
5357 llvm::APFloat F(0.0);
5358 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005359 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005360 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005361 } else if (E->getType()->isAnyComplexType()) {
5362 ComplexValue C;
5363 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005364 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005365 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005366 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005367 MemberPtr P;
5368 if (!EvaluateMemberPointer(E, P, Info))
5369 return false;
5370 P.moveInto(Result);
5371 return true;
Richard Smith51201882011-12-30 21:15:51 +00005372 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005373 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005374 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005375 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005376 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005377 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005378 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005379 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005380 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005381 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5382 return false;
5383 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005384 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005385 if (Info.getLangOpts().CPlusPlus0x)
5386 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5387 << E->getType();
5388 else
5389 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005390 if (!EvaluateVoid(E, Info))
5391 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005392 } else if (Info.getLangOpts().CPlusPlus0x) {
5393 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5394 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005395 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005396 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005397 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005398 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005399
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005400 return true;
5401}
5402
Richard Smith69c2c502011-11-04 05:33:44 +00005403/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5404/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5405/// since later initializers for an object can indirectly refer to subobjects
5406/// which were initialized earlier.
5407static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005408 const LValue &This, const Expr *E,
5409 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005410 if (!CheckLiteralType(Info, E))
5411 return false;
5412
5413 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005414 // Evaluate arrays and record types in-place, so that later initializers can
5415 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005416 if (E->getType()->isArrayType())
5417 return EvaluateArray(E, This, Result, Info);
5418 else if (E->getType()->isRecordType())
5419 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005420 }
5421
5422 // For any other type, in-place evaluation is unimportant.
5423 CCValue CoreConstResult;
5424 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005425 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005426}
5427
Richard Smithf48fdb02011-12-09 22:58:01 +00005428/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5429/// lvalue-to-rvalue cast if it is an lvalue.
5430static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005431 if (!CheckLiteralType(Info, E))
5432 return false;
5433
Richard Smithf48fdb02011-12-09 22:58:01 +00005434 CCValue Value;
5435 if (!::Evaluate(Value, Info, E))
5436 return false;
5437
5438 if (E->isGLValue()) {
5439 LValue LV;
5440 LV.setFrom(Value);
5441 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5442 return false;
5443 }
5444
5445 // Check this core constant expression is a constant expression, and if so,
5446 // convert it to one.
5447 return CheckConstantExpression(Info, E, Value, Result);
5448}
Richard Smithc49bd112011-10-28 17:51:58 +00005449
Richard Smith51f47082011-10-29 00:50:52 +00005450/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005451/// any crazy technique (that has nothing to do with language standards) that
5452/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005453/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5454/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005455bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005456 // Fast-path evaluations of integer literals, since we sometimes see files
5457 // containing vast quantities of these.
5458 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5459 Result.Val = APValue(APSInt(L->getValue(),
5460 L->getType()->isUnsignedIntegerType()));
5461 return true;
5462 }
5463
Richard Smith2d6a5672012-01-14 04:30:29 +00005464 // FIXME: Evaluating values of large array and record types can cause
5465 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005466 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5467 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005468 return false;
5469
Richard Smithf48fdb02011-12-09 22:58:01 +00005470 EvalInfo Info(Ctx, Result);
5471 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005472}
5473
Jay Foad4ba2a172011-01-12 09:06:06 +00005474bool Expr::EvaluateAsBooleanCondition(bool &Result,
5475 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005476 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005477 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005478 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5479 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005480 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005481}
5482
Richard Smith80d4b552011-12-28 19:48:30 +00005483bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5484 SideEffectsKind AllowSideEffects) const {
5485 if (!getType()->isIntegralOrEnumerationType())
5486 return false;
5487
Richard Smithc49bd112011-10-28 17:51:58 +00005488 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005489 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5490 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005491 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005492
Richard Smithc49bd112011-10-28 17:51:58 +00005493 Result = ExprResult.Val.getInt();
5494 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005495}
5496
Jay Foad4ba2a172011-01-12 09:06:06 +00005497bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005498 EvalInfo Info(Ctx, Result);
5499
John McCallefdb83e2010-05-07 21:00:08 +00005500 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005501 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005502 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5503 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005504}
5505
Richard Smith099e7f62011-12-19 06:19:21 +00005506bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5507 const VarDecl *VD,
5508 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005509 // FIXME: Evaluating initializers for large array and record types can cause
5510 // performance problems. Only do so in C++11 for now.
5511 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5512 !Ctx.getLangOptions().CPlusPlus0x)
5513 return false;
5514
Richard Smith099e7f62011-12-19 06:19:21 +00005515 Expr::EvalStatus EStatus;
5516 EStatus.Diag = &Notes;
5517
5518 EvalInfo InitInfo(Ctx, EStatus);
5519 InitInfo.setEvaluatingDecl(VD, Value);
5520
Richard Smith51201882011-12-30 21:15:51 +00005521 if (!CheckLiteralType(InitInfo, this))
5522 return false;
5523
Richard Smith099e7f62011-12-19 06:19:21 +00005524 LValue LVal;
5525 LVal.set(VD);
5526
Richard Smith51201882011-12-30 21:15:51 +00005527 // C++11 [basic.start.init]p2:
5528 // Variables with static storage duration or thread storage duration shall be
5529 // zero-initialized before any other initialization takes place.
5530 // This behavior is not present in C.
5531 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5532 !VD->getType()->isReferenceType()) {
5533 ImplicitValueInitExpr VIE(VD->getType());
5534 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5535 return false;
5536 }
5537
Richard Smith099e7f62011-12-19 06:19:21 +00005538 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5539 !EStatus.HasSideEffects;
5540}
5541
Richard Smith51f47082011-10-29 00:50:52 +00005542/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5543/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005544bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005545 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005546 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005547}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005548
Jay Foad4ba2a172011-01-12 09:06:06 +00005549bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005550 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005551}
5552
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005553APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005554 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005555 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005556 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005557 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005558 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005559
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005560 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005561}
John McCalld905f5a2010-05-07 05:32:02 +00005562
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005563 bool Expr::EvalResult::isGlobalLValue() const {
5564 assert(Val.isLValue());
5565 return IsGlobalLValue(Val.getLValueBase());
5566 }
5567
5568
John McCalld905f5a2010-05-07 05:32:02 +00005569/// isIntegerConstantExpr - this recursive routine will test if an expression is
5570/// an integer constant expression.
5571
5572/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5573/// comma, etc
5574///
5575/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5576/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5577/// cast+dereference.
5578
5579// CheckICE - This function does the fundamental ICE checking: the returned
5580// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5581// Note that to reduce code duplication, this helper does no evaluation
5582// itself; the caller checks whether the expression is evaluatable, and
5583// in the rare cases where CheckICE actually cares about the evaluated
5584// value, it calls into Evalute.
5585//
5586// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005587// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005588// 1: This expression is not an ICE, but if it isn't evaluated, it's
5589// a legal subexpression for an ICE. This return value is used to handle
5590// the comma operator in C99 mode.
5591// 2: This expression is not an ICE, and is not a legal subexpression for one.
5592
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005593namespace {
5594
John McCalld905f5a2010-05-07 05:32:02 +00005595struct ICEDiag {
5596 unsigned Val;
5597 SourceLocation Loc;
5598
5599 public:
5600 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5601 ICEDiag() : Val(0) {}
5602};
5603
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005604}
5605
5606static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005607
5608static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5609 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005610 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005611 !EVResult.Val.isInt()) {
5612 return ICEDiag(2, E->getLocStart());
5613 }
5614 return NoDiag();
5615}
5616
5617static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5618 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005619 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005620 return ICEDiag(2, E->getLocStart());
5621 }
5622
5623 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005624#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005625#define STMT(Node, Base) case Expr::Node##Class:
5626#define EXPR(Node, Base)
5627#include "clang/AST/StmtNodes.inc"
5628 case Expr::PredefinedExprClass:
5629 case Expr::FloatingLiteralClass:
5630 case Expr::ImaginaryLiteralClass:
5631 case Expr::StringLiteralClass:
5632 case Expr::ArraySubscriptExprClass:
5633 case Expr::MemberExprClass:
5634 case Expr::CompoundAssignOperatorClass:
5635 case Expr::CompoundLiteralExprClass:
5636 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005637 case Expr::DesignatedInitExprClass:
5638 case Expr::ImplicitValueInitExprClass:
5639 case Expr::ParenListExprClass:
5640 case Expr::VAArgExprClass:
5641 case Expr::AddrLabelExprClass:
5642 case Expr::StmtExprClass:
5643 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005644 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005645 case Expr::CXXDynamicCastExprClass:
5646 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005647 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005648 case Expr::CXXNullPtrLiteralExprClass:
5649 case Expr::CXXThisExprClass:
5650 case Expr::CXXThrowExprClass:
5651 case Expr::CXXNewExprClass:
5652 case Expr::CXXDeleteExprClass:
5653 case Expr::CXXPseudoDestructorExprClass:
5654 case Expr::UnresolvedLookupExprClass:
5655 case Expr::DependentScopeDeclRefExprClass:
5656 case Expr::CXXConstructExprClass:
5657 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005658 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005659 case Expr::CXXTemporaryObjectExprClass:
5660 case Expr::CXXUnresolvedConstructExprClass:
5661 case Expr::CXXDependentScopeMemberExprClass:
5662 case Expr::UnresolvedMemberExprClass:
5663 case Expr::ObjCStringLiteralClass:
5664 case Expr::ObjCEncodeExprClass:
5665 case Expr::ObjCMessageExprClass:
5666 case Expr::ObjCSelectorExprClass:
5667 case Expr::ObjCProtocolExprClass:
5668 case Expr::ObjCIvarRefExprClass:
5669 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005670 case Expr::ObjCIsaExprClass:
5671 case Expr::ShuffleVectorExprClass:
5672 case Expr::BlockExprClass:
5673 case Expr::BlockDeclRefExprClass:
5674 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005675 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005676 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005677 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005678 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005679 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005680 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005681 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005682 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005683 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005684 return ICEDiag(2, E->getLocStart());
5685
Douglas Gregoree8aff02011-01-04 17:33:58 +00005686 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005687 case Expr::GNUNullExprClass:
5688 // GCC considers the GNU __null value to be an integral constant expression.
5689 return NoDiag();
5690
John McCall91a57552011-07-15 05:09:51 +00005691 case Expr::SubstNonTypeTemplateParmExprClass:
5692 return
5693 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5694
John McCalld905f5a2010-05-07 05:32:02 +00005695 case Expr::ParenExprClass:
5696 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005697 case Expr::GenericSelectionExprClass:
5698 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005699 case Expr::IntegerLiteralClass:
5700 case Expr::CharacterLiteralClass:
5701 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005702 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005703 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005704 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005705 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005706 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005707 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005708 return NoDiag();
5709 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005710 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005711 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5712 // constant expressions, but they can never be ICEs because an ICE cannot
5713 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005714 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005715 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005716 return CheckEvalInICE(E, Ctx);
5717 return ICEDiag(2, E->getLocStart());
5718 }
5719 case Expr::DeclRefExprClass:
5720 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5721 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005722 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005723 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5724
5725 // Parameter variables are never constants. Without this check,
5726 // getAnyInitializer() can find a default argument, which leads
5727 // to chaos.
5728 if (isa<ParmVarDecl>(D))
5729 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5730
5731 // C++ 7.1.5.1p2
5732 // A variable of non-volatile const-qualified integral or enumeration
5733 // type initialized by an ICE can be used in ICEs.
5734 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005735 if (!Dcl->getType()->isIntegralOrEnumerationType())
5736 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5737
Richard Smith099e7f62011-12-19 06:19:21 +00005738 const VarDecl *VD;
5739 // Look for a declaration of this variable that has an initializer, and
5740 // check whether it is an ICE.
5741 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5742 return NoDiag();
5743 else
5744 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005745 }
5746 }
5747 return ICEDiag(2, E->getLocStart());
5748 case Expr::UnaryOperatorClass: {
5749 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5750 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005751 case UO_PostInc:
5752 case UO_PostDec:
5753 case UO_PreInc:
5754 case UO_PreDec:
5755 case UO_AddrOf:
5756 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005757 // C99 6.6/3 allows increment and decrement within unevaluated
5758 // subexpressions of constant expressions, but they can never be ICEs
5759 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005760 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005761 case UO_Extension:
5762 case UO_LNot:
5763 case UO_Plus:
5764 case UO_Minus:
5765 case UO_Not:
5766 case UO_Real:
5767 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005768 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005769 }
5770
5771 // OffsetOf falls through here.
5772 }
5773 case Expr::OffsetOfExprClass: {
5774 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005775 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005776 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005777 // compliance: we should warn earlier for offsetof expressions with
5778 // array subscripts that aren't ICEs, and if the array subscripts
5779 // are ICEs, the value of the offsetof must be an integer constant.
5780 return CheckEvalInICE(E, Ctx);
5781 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005782 case Expr::UnaryExprOrTypeTraitExprClass: {
5783 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5784 if ((Exp->getKind() == UETT_SizeOf) &&
5785 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005786 return ICEDiag(2, E->getLocStart());
5787 return NoDiag();
5788 }
5789 case Expr::BinaryOperatorClass: {
5790 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5791 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005792 case BO_PtrMemD:
5793 case BO_PtrMemI:
5794 case BO_Assign:
5795 case BO_MulAssign:
5796 case BO_DivAssign:
5797 case BO_RemAssign:
5798 case BO_AddAssign:
5799 case BO_SubAssign:
5800 case BO_ShlAssign:
5801 case BO_ShrAssign:
5802 case BO_AndAssign:
5803 case BO_XorAssign:
5804 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005805 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5806 // constant expressions, but they can never be ICEs because an ICE cannot
5807 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005808 return ICEDiag(2, E->getLocStart());
5809
John McCall2de56d12010-08-25 11:45:40 +00005810 case BO_Mul:
5811 case BO_Div:
5812 case BO_Rem:
5813 case BO_Add:
5814 case BO_Sub:
5815 case BO_Shl:
5816 case BO_Shr:
5817 case BO_LT:
5818 case BO_GT:
5819 case BO_LE:
5820 case BO_GE:
5821 case BO_EQ:
5822 case BO_NE:
5823 case BO_And:
5824 case BO_Xor:
5825 case BO_Or:
5826 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005827 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5828 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005829 if (Exp->getOpcode() == BO_Div ||
5830 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005831 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005832 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005833 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005834 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005835 if (REval == 0)
5836 return ICEDiag(1, E->getLocStart());
5837 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005838 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005839 if (LEval.isMinSignedValue())
5840 return ICEDiag(1, E->getLocStart());
5841 }
5842 }
5843 }
John McCall2de56d12010-08-25 11:45:40 +00005844 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005845 if (Ctx.getLangOptions().C99) {
5846 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5847 // if it isn't evaluated.
5848 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5849 return ICEDiag(1, E->getLocStart());
5850 } else {
5851 // In both C89 and C++, commas in ICEs are illegal.
5852 return ICEDiag(2, E->getLocStart());
5853 }
5854 }
5855 if (LHSResult.Val >= RHSResult.Val)
5856 return LHSResult;
5857 return RHSResult;
5858 }
John McCall2de56d12010-08-25 11:45:40 +00005859 case BO_LAnd:
5860 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005861 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5862 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5863 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5864 // Rare case where the RHS has a comma "side-effect"; we need
5865 // to actually check the condition to see whether the side
5866 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005867 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005868 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005869 return RHSResult;
5870 return NoDiag();
5871 }
5872
5873 if (LHSResult.Val >= RHSResult.Val)
5874 return LHSResult;
5875 return RHSResult;
5876 }
5877 }
5878 }
5879 case Expr::ImplicitCastExprClass:
5880 case Expr::CStyleCastExprClass:
5881 case Expr::CXXFunctionalCastExprClass:
5882 case Expr::CXXStaticCastExprClass:
5883 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005884 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005885 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005886 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00005887 if (isa<ExplicitCastExpr>(E)) {
5888 if (const FloatingLiteral *FL
5889 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5890 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5891 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5892 APSInt IgnoredVal(DestWidth, !DestSigned);
5893 bool Ignored;
5894 // If the value does not fit in the destination type, the behavior is
5895 // undefined, so we are not required to treat it as a constant
5896 // expression.
5897 if (FL->getValue().convertToInteger(IgnoredVal,
5898 llvm::APFloat::rmTowardZero,
5899 &Ignored) & APFloat::opInvalidOp)
5900 return ICEDiag(2, E->getLocStart());
5901 return NoDiag();
5902 }
5903 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00005904 switch (cast<CastExpr>(E)->getCastKind()) {
5905 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005906 case CK_AtomicToNonAtomic:
5907 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005908 case CK_NoOp:
5909 case CK_IntegralToBoolean:
5910 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00005911 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00005912 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005913 return ICEDiag(2, E->getLocStart());
5914 }
John McCalld905f5a2010-05-07 05:32:02 +00005915 }
John McCall56ca35d2011-02-17 10:25:35 +00005916 case Expr::BinaryConditionalOperatorClass: {
5917 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5918 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5919 if (CommonResult.Val == 2) return CommonResult;
5920 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5921 if (FalseResult.Val == 2) return FalseResult;
5922 if (CommonResult.Val == 1) return CommonResult;
5923 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005924 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00005925 return FalseResult;
5926 }
John McCalld905f5a2010-05-07 05:32:02 +00005927 case Expr::ConditionalOperatorClass: {
5928 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5929 // If the condition (ignoring parens) is a __builtin_constant_p call,
5930 // then only the true side is actually considered in an integer constant
5931 // expression, and it is fully evaluated. This is an important GNU
5932 // extension. See GCC PR38377 for discussion.
5933 if (const CallExpr *CallCE
5934 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00005935 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5936 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005937 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005938 if (CondResult.Val == 2)
5939 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00005940
Richard Smithf48fdb02011-12-09 22:58:01 +00005941 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5942 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00005943
John McCalld905f5a2010-05-07 05:32:02 +00005944 if (TrueResult.Val == 2)
5945 return TrueResult;
5946 if (FalseResult.Val == 2)
5947 return FalseResult;
5948 if (CondResult.Val == 1)
5949 return CondResult;
5950 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5951 return NoDiag();
5952 // Rare case where the diagnostics depend on which side is evaluated
5953 // Note that if we get here, CondResult is 0, and at least one of
5954 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005955 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00005956 return FalseResult;
5957 }
5958 return TrueResult;
5959 }
5960 case Expr::CXXDefaultArgExprClass:
5961 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5962 case Expr::ChooseExprClass: {
5963 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5964 }
5965 }
5966
David Blaikie30263482012-01-20 21:50:17 +00005967 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00005968}
5969
Richard Smithf48fdb02011-12-09 22:58:01 +00005970/// Evaluate an expression as a C++11 integral constant expression.
5971static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5972 const Expr *E,
5973 llvm::APSInt *Value,
5974 SourceLocation *Loc) {
5975 if (!E->getType()->isIntegralOrEnumerationType()) {
5976 if (Loc) *Loc = E->getExprLoc();
5977 return false;
5978 }
5979
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005980 APValue Result;
5981 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00005982 return false;
5983
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005984 assert(Result.isInt() && "pointer cast to int is not an ICE");
5985 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00005986 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00005987}
5988
Richard Smithdd1f29b2011-12-12 09:28:41 +00005989bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00005990 if (Ctx.getLangOptions().CPlusPlus0x)
5991 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5992
John McCalld905f5a2010-05-07 05:32:02 +00005993 ICEDiag d = CheckICE(this, Ctx);
5994 if (d.Val != 0) {
5995 if (Loc) *Loc = d.Loc;
5996 return false;
5997 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005998 return true;
5999}
6000
6001bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6002 SourceLocation *Loc, bool isEvaluated) const {
6003 if (Ctx.getLangOptions().CPlusPlus0x)
6004 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6005
6006 if (!isIntegerConstantExpr(Ctx, Loc))
6007 return false;
6008 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006009 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006010 return true;
6011}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006012
6013bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6014 SourceLocation *Loc) const {
6015 // We support this checking in C++98 mode in order to diagnose compatibility
6016 // issues.
6017 assert(Ctx.getLangOptions().CPlusPlus);
6018
6019 Expr::EvalStatus Status;
6020 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6021 Status.Diag = &Diags;
6022 EvalInfo Info(Ctx, Status);
6023
6024 APValue Scratch;
6025 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6026
6027 if (!Diags.empty()) {
6028 IsConstExpr = false;
6029 if (Loc) *Loc = Diags[0].first;
6030 } else if (!IsConstExpr) {
6031 // FIXME: This shouldn't happen.
6032 if (Loc) *Loc = getExprLoc();
6033 }
6034
6035 return IsConstExpr;
6036}