blob: 949988db1a5958b94a3dc4e64f42db726773edad [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-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 McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000046 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000049
Richard Smithce40ad62011-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 Smithd62306a2011-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 Smith80815602011-11-07 05:07:52 +000079 /// Determine whether the described subobject is an array element.
80 static bool SubobjectIsArrayElement(QualType Base,
81 ArrayRef<APValue::LValuePathEntry> Path) {
82 bool IsArrayElement = false;
83 const Type *T = Base.getTypePtr();
84 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
85 IsArrayElement = T && T->isArrayType();
86 if (IsArrayElement)
87 T = T->getBaseElementTypeUnsafe();
Richard Smithd62306a2011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith80815602011-11-07 05:07:52 +000089 T = FD->getType().getTypePtr();
90 else
91 // Path[I] describes a base class.
92 T = 0;
93 }
94 return IsArrayElement;
95 }
96
Richard Smith96e0c102011-11-04 02:25:55 +000097 /// A path from a glvalue to a subobject of that glvalue.
98 struct SubobjectDesignator {
99 /// True if the subobject was named in a manner not supported by C++11. Such
100 /// lvalues can still be folded, but they are not core constant expressions
101 /// and we cannot perform lvalue-to-rvalue conversions on them.
102 bool Invalid : 1;
103
104 /// Whether this designates an array element.
105 bool ArrayElement : 1;
106
107 /// Whether this designates 'one past the end' of the current subobject.
108 bool OnePastTheEnd : 1;
109
Richard Smith80815602011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith96e0c102011-11-04 02:25:55 +0000112 /// The entries on the path from the glvalue to the designated subobject.
113 SmallVector<PathEntry, 8> Entries;
114
115 SubobjectDesignator() :
116 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
117
Richard Smith80815602011-11-07 05:07:52 +0000118 SubobjectDesignator(const APValue &V) :
119 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
120 OnePastTheEnd(false) {
121 if (!Invalid) {
122 ArrayRef<PathEntry> VEntries = V.getLValuePath();
123 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
124 if (V.getLValueBase())
Richard Smithce40ad62011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith80815602011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smith027bf112011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith96e0c102011-11-04 02:25:55 +0000133 void setInvalid() {
134 Invalid = true;
135 Entries.clear();
136 }
137 /// Update this designator to refer to the given element within this array.
138 void addIndex(uint64_t N) {
139 if (Invalid) return;
140 if (OnePastTheEnd) {
141 setInvalid();
142 return;
143 }
144 PathEntry Entry;
Richard Smith80815602011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith96e0c102011-11-04 02:25:55 +0000146 Entries.push_back(Entry);
147 ArrayElement = true;
148 }
149 /// Update this designator to refer to the given base or member of this
150 /// object.
Richard Smithd62306a2011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000160 Entries.push_back(Entry);
161 ArrayElement = false;
162 }
163 /// Add N to the address of this subobject.
164 void adjustIndex(uint64_t N) {
165 if (Invalid) return;
166 if (ArrayElement) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith80815602011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith96e0c102011-11-04 02:25:55 +0000169 return;
170 }
171 if (OnePastTheEnd && N == (uint64_t)-1)
172 OnePastTheEnd = false;
173 else if (!OnePastTheEnd && N == 1)
174 OnePastTheEnd = true;
175 else if (N != 0)
176 setInvalid();
177 }
178 };
179
Richard Smith0b0a0b62011-10-29 20:57:55 +0000180 /// A core constant value. This can be the value of any constant expression,
181 /// or a pointer or reference to a non-static object or function parameter.
Richard Smith027bf112011-11-17 22:56:20 +0000182 ///
183 /// For an LValue, the base and offset are stored in the APValue subobject,
184 /// but the other information is stored in the SubobjectDesignator. For all
185 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000189 /// If the value is a reference or pointer into a parameter or temporary,
190 /// this is the corresponding call stack frame.
191 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000192 /// If the value is a reference or pointer, this is a description of how the
193 /// subobject was specified.
194 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000195 public:
Richard Smithfec09922011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith0b0a0b62011-10-29 20:57:55 +0000198 CCValue() {}
199 explicit CCValue(const APSInt &I) : APValue(I) {}
200 explicit CCValue(const APFloat &F) : APValue(F) {}
201 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
202 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
203 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smithce40ad62011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith96e0c102011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith80815602011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith027bf112011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000213 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
214 APValue(LHSExpr, RHSExpr) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215
Richard Smithfec09922011-11-01 16:57:24 +0000216 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000217 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000218 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000219 }
Richard Smith96e0c102011-11-04 02:25:55 +0000220 SubobjectDesignator &getLValueDesignator() {
221 assert(getKind() == LValue);
222 return Designator;
223 }
224 const SubobjectDesignator &getLValueDesignator() const {
225 return const_cast<CCValue*>(this)->getLValueDesignator();
226 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000227 };
228
Richard Smith254a73d2011-10-28 22:34:42 +0000229 /// A stack frame in the constexpr call stack.
230 struct CallStackFrame {
231 EvalInfo &Info;
232
233 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000234 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000235
Richard Smithf6f003a2011-12-16 19:06:07 +0000236 /// CallLoc - The location of the call expression for this call.
237 SourceLocation CallLoc;
238
239 /// Callee - The function which was called.
240 const FunctionDecl *Callee;
241
Richard Smithd62306a2011-11-10 06:34:14 +0000242 /// This - The binding for the this pointer in this call, if any.
243 const LValue *This;
244
Richard Smith254a73d2011-10-28 22:34:42 +0000245 /// ParmBindings - Parameter bindings for this function call, indexed by
246 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000247 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000248
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000249 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
250 typedef MapTy::const_iterator temp_iterator;
251 /// Temporaries - Temporary lvalues materialized within this stack frame.
252 MapTy Temporaries;
253
Richard Smithf6f003a2011-12-16 19:06:07 +0000254 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
255 const FunctionDecl *Callee, const LValue *This,
Richard Smithd62306a2011-11-10 06:34:14 +0000256 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000257 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000258 };
259
Richard Smith92b1ce02011-12-12 09:28:41 +0000260 /// A partial diagnostic which we might know in advance that we are not going
261 /// to emit.
262 class OptionalDiagnostic {
263 PartialDiagnostic *Diag;
264
265 public:
266 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
267
268 template<typename T>
269 OptionalDiagnostic &operator<<(const T &v) {
270 if (Diag)
271 *Diag << v;
272 return *this;
273 }
274 };
275
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000276 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000277 ASTContext &Ctx;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000278
279 /// EvalStatus - Contains information about the evaluation.
280 Expr::EvalStatus &EvalStatus;
281
282 /// CurrentCall - The top of the constexpr call stack.
283 CallStackFrame *CurrentCall;
284
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000285 /// CallStackDepth - The number of calls in the call stack right now.
286 unsigned CallStackDepth;
287
288 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
289 /// OpaqueValues - Values used as the common expression in a
290 /// BinaryConditionalOperator.
291 MapTy OpaqueValues;
292
293 /// BottomFrame - The frame in which evaluation started. This must be
294 /// initialized last.
295 CallStackFrame BottomFrame;
296
Richard Smithd62306a2011-11-10 06:34:14 +0000297 /// EvaluatingDecl - This is the declaration whose initializer is being
298 /// evaluated, if any.
299 const VarDecl *EvaluatingDecl;
300
301 /// EvaluatingDeclValue - This is the value being constructed for the
302 /// declaration whose initializer is being evaluated, if any.
303 APValue *EvaluatingDeclValue;
304
Richard Smith357362d2011-12-13 06:39:58 +0000305 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
306 /// notes attached to it will also be stored, otherwise they will not be.
307 bool HasActiveDiagnostic;
308
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000309
310 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000311 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithf6f003a2011-12-16 19:06:07 +0000312 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
313 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000314
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000315 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
316 MapTy::const_iterator i = OpaqueValues.find(e);
317 if (i == OpaqueValues.end()) return 0;
318 return &i->second;
319 }
320
Richard Smithd62306a2011-11-10 06:34:14 +0000321 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
322 EvaluatingDecl = VD;
323 EvaluatingDeclValue = &Value;
324 }
325
Richard Smith9a568822011-11-21 19:36:32 +0000326 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
327
Richard Smith357362d2011-12-13 06:39:58 +0000328 bool CheckCallLimit(SourceLocation Loc) {
329 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
330 return true;
331 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
332 << getLangOpts().ConstexprCallDepth;
333 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000334 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000335
Richard Smith357362d2011-12-13 06:39:58 +0000336 private:
337 /// Add a diagnostic to the diagnostics list.
338 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
339 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
340 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
341 return EvalStatus.Diag->back().second;
342 }
343
Richard Smithf6f003a2011-12-16 19:06:07 +0000344 /// Add notes containing a call stack to the current point of evaluation.
345 void addCallStack(unsigned Limit);
346
Richard Smith357362d2011-12-13 06:39:58 +0000347 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000348 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000349 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
350 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000351 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000352 // If we have a prior diagnostic, it will be noting that the expression
353 // isn't a constant expression. This diagnostic is more important.
354 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000355 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000356 unsigned CallStackNotes = CallStackDepth - 1;
357 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
358 if (Limit)
359 CallStackNotes = std::min(CallStackNotes, Limit + 1);
360
Richard Smith357362d2011-12-13 06:39:58 +0000361 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000362 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000363 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
364 addDiag(Loc, DiagId);
365 addCallStack(Limit);
366 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000367 }
Richard Smith357362d2011-12-13 06:39:58 +0000368 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000369 return OptionalDiagnostic();
370 }
371
372 /// Diagnose that the evaluation does not produce a C++11 core constant
373 /// expression.
Richard Smithf2b681b2011-12-21 05:04:46 +0000374 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
375 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000376 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000377 // Don't override a previous diagnostic.
378 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
379 return OptionalDiagnostic();
Richard Smith357362d2011-12-13 06:39:58 +0000380 return Diag(Loc, DiagId, ExtraNotes);
381 }
382
383 /// Add a note to a prior diagnostic.
384 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
385 if (!HasActiveDiagnostic)
386 return OptionalDiagnostic();
387 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000388 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000389
390 /// Add a stack of notes to a prior diagnostic.
391 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
392 if (HasActiveDiagnostic) {
393 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
394 Diags.begin(), Diags.end());
395 }
396 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000397 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000398}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000399
Richard Smithf6f003a2011-12-16 19:06:07 +0000400CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
401 const FunctionDecl *Callee, const LValue *This,
402 const CCValue *Arguments)
403 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
404 This(This), Arguments(Arguments) {
405 Info.CurrentCall = this;
406 ++Info.CallStackDepth;
407}
408
409CallStackFrame::~CallStackFrame() {
410 assert(Info.CurrentCall == this && "calls retired out of order");
411 --Info.CallStackDepth;
412 Info.CurrentCall = Caller;
413}
414
415/// Produce a string describing the given constexpr call.
416static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
417 unsigned ArgIndex = 0;
418 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
419 !isa<CXXConstructorDecl>(Frame->Callee);
420
421 if (!IsMemberCall)
422 Out << *Frame->Callee << '(';
423
424 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
425 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
426 if (ArgIndex > IsMemberCall)
427 Out << ", ";
428
429 const ParmVarDecl *Param = *I;
430 const CCValue &Arg = Frame->Arguments[ArgIndex];
431 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
432 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
433 else {
434 // Deliberately slice off the frame to form an APValue we can print.
435 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
436 Arg.getLValueDesignator().Entries,
437 Arg.getLValueDesignator().OnePastTheEnd);
438 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
439 }
440
441 if (ArgIndex == 0 && IsMemberCall)
442 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000443 }
444
Richard Smithf6f003a2011-12-16 19:06:07 +0000445 Out << ')';
446}
447
448void EvalInfo::addCallStack(unsigned Limit) {
449 // Determine which calls to skip, if any.
450 unsigned ActiveCalls = CallStackDepth - 1;
451 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
452 if (Limit && Limit < ActiveCalls) {
453 SkipStart = Limit / 2 + Limit % 2;
454 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000455 }
456
Richard Smithf6f003a2011-12-16 19:06:07 +0000457 // Walk the call stack and add the diagnostics.
458 unsigned CallIdx = 0;
459 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
460 Frame = Frame->Caller, ++CallIdx) {
461 // Skip this call?
462 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
463 if (CallIdx == SkipStart) {
464 // Note that we're skipping calls.
465 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
466 << unsigned(ActiveCalls - Limit);
467 }
468 continue;
469 }
470
471 llvm::SmallVector<char, 128> Buffer;
472 llvm::raw_svector_ostream Out(Buffer);
473 describeCall(Frame, Out);
474 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
475 }
476}
477
478namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000479 struct ComplexValue {
480 private:
481 bool IsInt;
482
483 public:
484 APSInt IntReal, IntImag;
485 APFloat FloatReal, FloatImag;
486
487 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
488
489 void makeComplexFloat() { IsInt = false; }
490 bool isComplexFloat() const { return !IsInt; }
491 APFloat &getComplexFloatReal() { return FloatReal; }
492 APFloat &getComplexFloatImag() { return FloatImag; }
493
494 void makeComplexInt() { IsInt = true; }
495 bool isComplexInt() const { return IsInt; }
496 APSInt &getComplexIntReal() { return IntReal; }
497 APSInt &getComplexIntImag() { return IntImag; }
498
Richard Smith0b0a0b62011-10-29 20:57:55 +0000499 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000500 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000501 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000502 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000503 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000504 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000505 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000506 assert(v.isComplexFloat() || v.isComplexInt());
507 if (v.isComplexFloat()) {
508 makeComplexFloat();
509 FloatReal = v.getComplexFloatReal();
510 FloatImag = v.getComplexFloatImag();
511 } else {
512 makeComplexInt();
513 IntReal = v.getComplexIntReal();
514 IntImag = v.getComplexIntImag();
515 }
516 }
John McCall93d91dc2010-05-07 17:22:02 +0000517 };
John McCall45d55e42010-05-07 21:00:08 +0000518
519 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000520 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000521 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000522 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000523 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000524
Richard Smithce40ad62011-11-12 22:28:03 +0000525 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000526 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000527 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000528 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000529 SubobjectDesignator &getLValueDesignator() { return Designator; }
530 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000531
Richard Smith0b0a0b62011-10-29 20:57:55 +0000532 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000533 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000534 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000535 void setFrom(const CCValue &V) {
536 assert(V.isLValue());
537 Base = V.getLValueBase();
538 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000539 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000540 Designator = V.getLValueDesignator();
541 }
542
Richard Smithce40ad62011-11-12 22:28:03 +0000543 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
544 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000545 Offset = CharUnits::Zero();
546 Frame = F;
547 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000548 }
John McCall45d55e42010-05-07 21:00:08 +0000549 };
Richard Smith027bf112011-11-17 22:56:20 +0000550
551 struct MemberPtr {
552 MemberPtr() {}
553 explicit MemberPtr(const ValueDecl *Decl) :
554 DeclAndIsDerivedMember(Decl, false), Path() {}
555
556 /// The member or (direct or indirect) field referred to by this member
557 /// pointer, or 0 if this is a null member pointer.
558 const ValueDecl *getDecl() const {
559 return DeclAndIsDerivedMember.getPointer();
560 }
561 /// Is this actually a member of some type derived from the relevant class?
562 bool isDerivedMember() const {
563 return DeclAndIsDerivedMember.getInt();
564 }
565 /// Get the class which the declaration actually lives in.
566 const CXXRecordDecl *getContainingRecord() const {
567 return cast<CXXRecordDecl>(
568 DeclAndIsDerivedMember.getPointer()->getDeclContext());
569 }
570
571 void moveInto(CCValue &V) const {
572 V = CCValue(getDecl(), isDerivedMember(), Path);
573 }
574 void setFrom(const CCValue &V) {
575 assert(V.isMemberPointer());
576 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
577 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
578 Path.clear();
579 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
580 Path.insert(Path.end(), P.begin(), P.end());
581 }
582
583 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
584 /// whether the member is a member of some class derived from the class type
585 /// of the member pointer.
586 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
587 /// Path - The path of base/derived classes from the member declaration's
588 /// class (exclusive) to the class type of the member pointer (inclusive).
589 SmallVector<const CXXRecordDecl*, 4> Path;
590
591 /// Perform a cast towards the class of the Decl (either up or down the
592 /// hierarchy).
593 bool castBack(const CXXRecordDecl *Class) {
594 assert(!Path.empty());
595 const CXXRecordDecl *Expected;
596 if (Path.size() >= 2)
597 Expected = Path[Path.size() - 2];
598 else
599 Expected = getContainingRecord();
600 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
601 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
602 // if B does not contain the original member and is not a base or
603 // derived class of the class containing the original member, the result
604 // of the cast is undefined.
605 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
606 // (D::*). We consider that to be a language defect.
607 return false;
608 }
609 Path.pop_back();
610 return true;
611 }
612 /// Perform a base-to-derived member pointer cast.
613 bool castToDerived(const CXXRecordDecl *Derived) {
614 if (!getDecl())
615 return true;
616 if (!isDerivedMember()) {
617 Path.push_back(Derived);
618 return true;
619 }
620 if (!castBack(Derived))
621 return false;
622 if (Path.empty())
623 DeclAndIsDerivedMember.setInt(false);
624 return true;
625 }
626 /// Perform a derived-to-base member pointer cast.
627 bool castToBase(const CXXRecordDecl *Base) {
628 if (!getDecl())
629 return true;
630 if (Path.empty())
631 DeclAndIsDerivedMember.setInt(true);
632 if (isDerivedMember()) {
633 Path.push_back(Base);
634 return true;
635 }
636 return castBack(Base);
637 }
638 };
Richard Smith357362d2011-12-13 06:39:58 +0000639
640 /// Kinds of constant expression checking, for diagnostics.
641 enum CheckConstantExpressionKind {
642 CCEK_Constant, ///< A normal constant.
643 CCEK_ReturnValue, ///< A constexpr function return value.
644 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
645 };
John McCall93d91dc2010-05-07 17:22:02 +0000646}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000647
Richard Smith0b0a0b62011-10-29 20:57:55 +0000648static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000649static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +0000650 const LValue &This, const Expr *E,
651 CheckConstantExpressionKind CCEK
652 = CCEK_Constant);
John McCall45d55e42010-05-07 21:00:08 +0000653static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
654static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000655static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
656 EvalInfo &Info);
657static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000658static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000659static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000660 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000661static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000662static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000663
664//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000665// Misc utilities
666//===----------------------------------------------------------------------===//
667
Richard Smithd62306a2011-11-10 06:34:14 +0000668/// Should this call expression be treated as a string literal?
669static bool IsStringLiteralCall(const CallExpr *E) {
670 unsigned Builtin = E->isBuiltinCall();
671 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
672 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
673}
674
Richard Smithce40ad62011-11-12 22:28:03 +0000675static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000676 // C++11 [expr.const]p3 An address constant expression is a prvalue core
677 // constant expression of pointer type that evaluates to...
678
679 // ... a null pointer value, or a prvalue core constant expression of type
680 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000681 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000682
Richard Smithce40ad62011-11-12 22:28:03 +0000683 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
684 // ... the address of an object with static storage duration,
685 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
686 return VD->hasGlobalStorage();
687 // ... the address of a function,
688 return isa<FunctionDecl>(D);
689 }
690
691 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000692 switch (E->getStmtClass()) {
693 default:
694 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000695 case Expr::CompoundLiteralExprClass:
696 return cast<CompoundLiteralExpr>(E)->isFileScope();
697 // A string literal has static storage duration.
698 case Expr::StringLiteralClass:
699 case Expr::PredefinedExprClass:
700 case Expr::ObjCStringLiteralClass:
701 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000702 case Expr::CXXTypeidExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000703 return true;
704 case Expr::CallExprClass:
705 return IsStringLiteralCall(cast<CallExpr>(E));
706 // For GCC compatibility, &&label has static storage duration.
707 case Expr::AddrLabelExprClass:
708 return true;
709 // A Block literal expression may be used as the initialization value for
710 // Block variables at global or local static scope.
711 case Expr::BlockExprClass:
712 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
713 }
John McCall95007602010-05-10 23:27:23 +0000714}
715
Richard Smith80815602011-11-07 05:07:52 +0000716/// Check that this reference or pointer core constant expression is a valid
717/// value for a constant expression. Type T should be either LValue or CCValue.
718template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000719static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000720 const T &LVal, APValue &Value,
721 CheckConstantExpressionKind CCEK) {
722 APValue::LValueBase Base = LVal.getLValueBase();
723 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
724
725 if (!IsGlobalLValue(Base)) {
726 if (Info.getLangOpts().CPlusPlus0x) {
727 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
728 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
729 << E->isGLValue() << !Designator.Entries.empty()
730 << !!VD << CCEK << VD;
731 if (VD)
732 Info.Note(VD->getLocation(), diag::note_declared_at);
733 else
734 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
735 diag::note_constexpr_temporary_here);
736 } else {
Richard Smithf2b681b2011-12-21 05:04:46 +0000737 Info.Diag(E->getExprLoc());
Richard Smith357362d2011-12-13 06:39:58 +0000738 }
Richard Smith80815602011-11-07 05:07:52 +0000739 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000740 }
Richard Smith80815602011-11-07 05:07:52 +0000741
Richard Smith80815602011-11-07 05:07:52 +0000742 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000743 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000744 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith357362d2011-12-13 06:39:58 +0000745 // FIXME: This is not a core constant expression. We should have already
746 // produced a CCE diagnostic.
Richard Smith80815602011-11-07 05:07:52 +0000747 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
748 APValue::NoLValuePath());
749 return true;
750 }
751
Richard Smith357362d2011-12-13 06:39:58 +0000752 // Does this refer one past the end of some object?
753 // This is technically not an address constant expression nor a reference
754 // constant expression, but we allow it for address constant expressions.
755 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
756 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
757 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
758 << !Designator.Entries.empty() << !!VD << VD;
759 if (VD)
760 Info.Note(VD->getLocation(), diag::note_declared_at);
761 else
762 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
763 diag::note_constexpr_temporary_here);
764 return false;
765 }
766
Richard Smith80815602011-11-07 05:07:52 +0000767 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000768 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000769 return true;
770}
771
Richard Smithfddd3842011-12-30 21:15:51 +0000772/// Check that this core constant expression is of literal type, and if not,
773/// produce an appropriate diagnostic.
774static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
775 if (!E->isRValue() || E->getType()->isLiteralType())
776 return true;
777
778 // Prvalue constant expressions must be of literal types.
779 if (Info.getLangOpts().CPlusPlus0x)
780 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
781 << E->getType();
782 else
783 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
784 return false;
785}
786
Richard Smith0b0a0b62011-10-29 20:57:55 +0000787/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000788/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithfddd3842011-12-30 21:15:51 +0000789/// If not, report an appropriate diagnostic. Does not check that the expression
790/// is of literal type.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000791static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000792 const CCValue &CCValue, APValue &Value,
793 CheckConstantExpressionKind CCEK
794 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000795 if (!CCValue.isLValue()) {
796 Value = CCValue;
797 return true;
798 }
Richard Smith357362d2011-12-13 06:39:58 +0000799 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000800}
801
Richard Smith83c68212011-10-31 05:11:32 +0000802const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000803 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000804}
805
806static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000807 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000808}
809
Richard Smithcecf1842011-11-01 21:06:14 +0000810static bool IsWeakLValue(const LValue &Value) {
811 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000812 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000813}
814
Richard Smith027bf112011-11-17 22:56:20 +0000815static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000816 // A null base expression indicates a null pointer. These are always
817 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000818 if (!Value.getLValueBase()) {
819 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000820 return true;
821 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000822
John McCall95007602010-05-10 23:27:23 +0000823 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000824 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000825 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000826
Richard Smith027bf112011-11-17 22:56:20 +0000827 // We have a non-null base. These are generally known to be true, but if it's
828 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000829 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000830 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000831 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000832}
833
Richard Smith0b0a0b62011-10-29 20:57:55 +0000834static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000835 switch (Val.getKind()) {
836 case APValue::Uninitialized:
837 return false;
838 case APValue::Int:
839 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000840 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000841 case APValue::Float:
842 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000843 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000844 case APValue::ComplexInt:
845 Result = Val.getComplexIntReal().getBoolValue() ||
846 Val.getComplexIntImag().getBoolValue();
847 return true;
848 case APValue::ComplexFloat:
849 Result = !Val.getComplexFloatReal().isZero() ||
850 !Val.getComplexFloatImag().isZero();
851 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000852 case APValue::LValue:
853 return EvalPointerValueAsBool(Val, Result);
854 case APValue::MemberPointer:
855 Result = Val.getMemberPointerDecl();
856 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000857 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000858 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000859 case APValue::Struct:
860 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000861 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +0000862 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000863 }
864
Richard Smith11562c52011-10-28 17:51:58 +0000865 llvm_unreachable("unknown APValue kind");
866}
867
868static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
869 EvalInfo &Info) {
870 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000871 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000872 if (!Evaluate(Val, Info, E))
873 return false;
874 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000875}
876
Richard Smith357362d2011-12-13 06:39:58 +0000877template<typename T>
878static bool HandleOverflow(EvalInfo &Info, const Expr *E,
879 const T &SrcValue, QualType DestType) {
880 llvm::SmallVector<char, 32> Buffer;
881 SrcValue.toString(Buffer);
882 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
883 << StringRef(Buffer.data(), Buffer.size()) << DestType;
884 return false;
885}
886
887static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
888 QualType SrcType, const APFloat &Value,
889 QualType DestType, APSInt &Result) {
890 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000891 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000892 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000893
Richard Smith357362d2011-12-13 06:39:58 +0000894 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000895 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000896 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
897 & APFloat::opInvalidOp)
898 return HandleOverflow(Info, E, Value, DestType);
899 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000900}
901
Richard Smith357362d2011-12-13 06:39:58 +0000902static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
903 QualType SrcType, QualType DestType,
904 APFloat &Result) {
905 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000906 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000907 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
908 APFloat::rmNearestTiesToEven, &ignored)
909 & APFloat::opOverflow)
910 return HandleOverflow(Info, E, Value, DestType);
911 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000912}
913
Mike Stump11289f42009-09-09 15:08:12 +0000914static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000915 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000916 unsigned DestWidth = Ctx.getIntWidth(DestType);
917 APSInt Result = Value;
918 // Figure out if this is a truncate, extend or noop cast.
919 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000920 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000921 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000922 return Result;
923}
924
Richard Smith357362d2011-12-13 06:39:58 +0000925static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
926 QualType SrcType, const APSInt &Value,
927 QualType DestType, APFloat &Result) {
928 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
929 if (Result.convertFromAPInt(Value, Value.isSigned(),
930 APFloat::rmNearestTiesToEven)
931 & APFloat::opOverflow)
932 return HandleOverflow(Info, E, Value, DestType);
933 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000934}
935
Eli Friedman803acb32011-12-22 03:51:45 +0000936static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
937 llvm::APInt &Res) {
938 CCValue SVal;
939 if (!Evaluate(SVal, Info, E))
940 return false;
941 if (SVal.isInt()) {
942 Res = SVal.getInt();
943 return true;
944 }
945 if (SVal.isFloat()) {
946 Res = SVal.getFloat().bitcastToAPInt();
947 return true;
948 }
949 if (SVal.isVector()) {
950 QualType VecTy = E->getType();
951 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
952 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
953 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
954 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
955 Res = llvm::APInt::getNullValue(VecSize);
956 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
957 APValue &Elt = SVal.getVectorElt(i);
958 llvm::APInt EltAsInt;
959 if (Elt.isInt()) {
960 EltAsInt = Elt.getInt();
961 } else if (Elt.isFloat()) {
962 EltAsInt = Elt.getFloat().bitcastToAPInt();
963 } else {
964 // Don't try to handle vectors of anything other than int or float
965 // (not sure if it's possible to hit this case).
966 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
967 return false;
968 }
969 unsigned BaseEltSize = EltAsInt.getBitWidth();
970 if (BigEndian)
971 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
972 else
973 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
974 }
975 return true;
976 }
977 // Give up if the input isn't an int, float, or vector. For example, we
978 // reject "(v4i16)(intptr_t)&a".
979 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
980 return false;
981}
982
Richard Smith027bf112011-11-17 22:56:20 +0000983static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
984 const CXXRecordDecl *&MostDerivedType,
985 unsigned &MostDerivedPathLength,
986 bool &MostDerivedIsArrayElement) {
987 const SubobjectDesignator &D = LVal.Designator;
988 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000989 return false;
990
Richard Smith027bf112011-11-17 22:56:20 +0000991 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000992
993 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000994 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000995 MostDerivedPathLength = 0;
996 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000997
998 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
999 bool IsArray = T && T->isArrayType();
1000 if (IsArray)
1001 T = T->getBaseElementTypeUnsafe();
1002 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
1003 T = FD->getType().getTypePtr();
1004 else
1005 T = 0;
1006
1007 if (T) {
1008 MostDerivedType = T->getAsCXXRecordDecl();
1009 MostDerivedPathLength = I + 1;
1010 MostDerivedIsArrayElement = IsArray;
1011 }
1012 }
1013
Richard Smithd62306a2011-11-10 06:34:14 +00001014 // (B*)&d + 1 has no most-derived object.
1015 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
1016 return false;
1017
Richard Smith027bf112011-11-17 22:56:20 +00001018 return MostDerivedType != 0;
1019}
1020
1021static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
1022 const RecordDecl *TruncatedType,
1023 unsigned TruncatedElements,
1024 bool IsArrayElement) {
1025 SubobjectDesignator &D = Result.Designator;
1026 const RecordDecl *RD = TruncatedType;
1027 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +00001028 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1029 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001030 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001031 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001032 else
Richard Smithd62306a2011-11-10 06:34:14 +00001033 Result.Offset -= Layout.getBaseClassOffset(Base);
1034 RD = Base;
1035 }
Richard Smith027bf112011-11-17 22:56:20 +00001036 D.Entries.resize(TruncatedElements);
1037 D.ArrayElement = IsArrayElement;
1038}
1039
1040/// If the given LValue refers to a base subobject of some object, find the most
1041/// derived object and the corresponding complete record type. This is necessary
1042/// in order to find the offset of a virtual base class.
1043static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
1044 const CXXRecordDecl *&MostDerivedType) {
1045 unsigned MostDerivedPathLength;
1046 bool MostDerivedIsArrayElement;
1047 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1048 MostDerivedPathLength, MostDerivedIsArrayElement))
1049 return false;
1050
1051 // Remove the trailing base class path entries and their offsets.
1052 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
1053 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +00001054 return true;
1055}
1056
1057static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
1058 const CXXRecordDecl *Derived,
1059 const CXXRecordDecl *Base,
1060 const ASTRecordLayout *RL = 0) {
1061 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1062 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1063 Obj.Designator.addDecl(Base, /*Virtual*/ false);
1064}
1065
1066static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1067 const CXXRecordDecl *DerivedDecl,
1068 const CXXBaseSpecifier *Base) {
1069 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1070
1071 if (!Base->isVirtual()) {
1072 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1073 return true;
1074 }
1075
1076 // Extract most-derived object and corresponding type.
1077 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1078 return false;
1079
1080 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1081 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1082 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1083 return true;
1084}
1085
1086/// Update LVal to refer to the given field, which must be a member of the type
1087/// currently described by LVal.
1088static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1089 const FieldDecl *FD,
1090 const ASTRecordLayout *RL = 0) {
1091 if (!RL)
1092 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1093
1094 unsigned I = FD->getFieldIndex();
1095 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1096 LVal.Designator.addDecl(FD);
1097}
1098
1099/// Get the size of the given type in char units.
1100static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1101 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1102 // extension.
1103 if (Type->isVoidType() || Type->isFunctionType()) {
1104 Size = CharUnits::One();
1105 return true;
1106 }
1107
1108 if (!Type->isConstantSizeType()) {
1109 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1110 return false;
1111 }
1112
1113 Size = Info.Ctx.getTypeSizeInChars(Type);
1114 return true;
1115}
1116
1117/// Update a pointer value to model pointer arithmetic.
1118/// \param Info - Information about the ongoing evaluation.
1119/// \param LVal - The pointer value to be updated.
1120/// \param EltTy - The pointee type represented by LVal.
1121/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1122static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1123 QualType EltTy, int64_t Adjustment) {
1124 CharUnits SizeOfPointee;
1125 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1126 return false;
1127
1128 // Compute the new offset in the appropriate width.
1129 LVal.Offset += Adjustment * SizeOfPointee;
1130 LVal.Designator.adjustIndex(Adjustment);
1131 return true;
1132}
1133
Richard Smith27908702011-10-24 17:54:18 +00001134/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001135static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1136 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001137 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001138 // If this is a parameter to an active constexpr function call, perform
1139 // argument substitution.
1140 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001141 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001142 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001143 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001144 }
Richard Smithfec09922011-11-01 16:57:24 +00001145 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1146 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001147 }
Richard Smith27908702011-10-24 17:54:18 +00001148
Richard Smithd0b4dd62011-12-19 06:19:21 +00001149 // Dig out the initializer, and use the declaration which it's attached to.
1150 const Expr *Init = VD->getAnyInitializer(VD);
1151 if (!Init || Init->isValueDependent()) {
1152 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1153 return false;
1154 }
1155
Richard Smithd62306a2011-11-10 06:34:14 +00001156 // If we're currently evaluating the initializer of this declaration, use that
1157 // in-flight value.
1158 if (Info.EvaluatingDecl == VD) {
1159 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1160 return !Result.isUninit();
1161 }
1162
Richard Smithcecf1842011-11-01 21:06:14 +00001163 // Never evaluate the initializer of a weak variable. We can't be sure that
1164 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001165 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001166 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001167 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001168 }
Richard Smithcecf1842011-11-01 21:06:14 +00001169
Richard Smithd0b4dd62011-12-19 06:19:21 +00001170 // Check that we can fold the initializer. In C++, we will have already done
1171 // this in the cases where it matters for conformance.
1172 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1173 if (!VD->evaluateValue(Notes)) {
1174 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1175 Notes.size() + 1) << VD;
1176 Info.Note(VD->getLocation(), diag::note_declared_at);
1177 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001178 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001179 } else if (!VD->checkInitIsICE()) {
1180 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1181 Notes.size() + 1) << VD;
1182 Info.Note(VD->getLocation(), diag::note_declared_at);
1183 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001184 }
Richard Smith27908702011-10-24 17:54:18 +00001185
Richard Smithd0b4dd62011-12-19 06:19:21 +00001186 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001187 return true;
Richard Smith27908702011-10-24 17:54:18 +00001188}
1189
Richard Smith11562c52011-10-28 17:51:58 +00001190static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001191 Qualifiers Quals = T.getQualifiers();
1192 return Quals.hasConst() && !Quals.hasVolatile();
1193}
1194
Richard Smithe97cbd72011-11-11 04:05:33 +00001195/// Get the base index of the given base class within an APValue representing
1196/// the given derived class.
1197static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1198 const CXXRecordDecl *Base) {
1199 Base = Base->getCanonicalDecl();
1200 unsigned Index = 0;
1201 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1202 E = Derived->bases_end(); I != E; ++I, ++Index) {
1203 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1204 return Index;
1205 }
1206
1207 llvm_unreachable("base class missing from derived class's bases list");
1208}
1209
Richard Smithf3e9e432011-11-07 09:22:26 +00001210/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001211static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1212 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001213 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001214 if (Sub.Invalid) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001215 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001216 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001217 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001218 if (Sub.OnePastTheEnd) {
1219 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001220 (unsigned)diag::note_constexpr_read_past_end :
1221 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001222 return false;
1223 }
Richard Smith6804be52011-11-11 08:28:03 +00001224 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001225 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001226
1227 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1228 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001229 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001230 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001231 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001232 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001233 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001234 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001235 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001236 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001237 // Note, it should not be possible to form a pointer with a valid
1238 // designator which points more than one past the end of the array.
1239 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001240 (unsigned)diag::note_constexpr_read_past_end :
1241 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001242 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001243 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001244 if (O->getArrayInitializedElts() > Index)
1245 O = &O->getArrayInitializedElt(Index);
1246 else
1247 O = &O->getArrayFiller();
1248 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001249 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1250 // Next subobject is a class, struct or union field.
1251 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1252 if (RD->isUnion()) {
1253 const FieldDecl *UnionField = O->getUnionField();
1254 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001255 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001256 Info.Diag(E->getExprLoc(),
1257 diag::note_constexpr_read_inactive_union_member)
1258 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001259 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001260 }
Richard Smithd62306a2011-11-10 06:34:14 +00001261 O = &O->getUnionValue();
1262 } else
1263 O = &O->getStructField(Field->getFieldIndex());
1264 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001265
1266 if (ObjType.isVolatileQualified()) {
1267 if (Info.getLangOpts().CPlusPlus) {
1268 // FIXME: Include a description of the path to the volatile subobject.
1269 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1270 << 2 << Field;
1271 Info.Note(Field->getLocation(), diag::note_declared_at);
1272 } else {
1273 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1274 }
1275 return false;
1276 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001277 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001278 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001279 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1280 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1281 O = &O->getStructBase(getBaseIndex(Derived, Base));
1282 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001283 }
Richard Smithd62306a2011-11-10 06:34:14 +00001284
Richard Smithf57d8cb2011-12-09 22:58:01 +00001285 if (O->isUninit()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001286 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001287 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001288 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001289 }
1290
Richard Smithf3e9e432011-11-07 09:22:26 +00001291 Obj = CCValue(*O, CCValue::GlobalValue());
1292 return true;
1293}
1294
Richard Smithd62306a2011-11-10 06:34:14 +00001295/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1296/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1297/// for looking up the glvalue referred to by an entity of reference type.
1298///
1299/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001300/// \param Conv - The expression for which we are performing the conversion.
1301/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001302/// \param Type - The type we expect this conversion to produce.
1303/// \param LVal - The glvalue on which we are attempting to perform this action.
1304/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001305static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1306 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001307 const LValue &LVal, CCValue &RVal) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001308 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1309 if (!Info.getLangOpts().CPlusPlus)
1310 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1311
Richard Smithce40ad62011-11-12 22:28:03 +00001312 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001313 CallStackFrame *Frame = LVal.Frame;
Richard Smithf2b681b2011-12-21 05:04:46 +00001314 SourceLocation Loc = Conv->getExprLoc();
Richard Smith11562c52011-10-28 17:51:58 +00001315
Richard Smithf57d8cb2011-12-09 22:58:01 +00001316 if (!LVal.Base) {
1317 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithf2b681b2011-12-21 05:04:46 +00001318 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1319 return false;
1320 }
1321
1322 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1323 // is not a constant expression (even if the object is non-volatile). We also
1324 // apply this rule to C++98, in order to conform to the expected 'volatile'
1325 // semantics.
1326 if (Type.isVolatileQualified()) {
1327 if (Info.getLangOpts().CPlusPlus)
1328 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1329 else
1330 Info.Diag(Loc);
Richard Smith11562c52011-10-28 17:51:58 +00001331 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001332 }
Richard Smith11562c52011-10-28 17:51:58 +00001333
Richard Smithce40ad62011-11-12 22:28:03 +00001334 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001335 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1336 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001337 // expressions are constant expressions too. Inside constexpr functions,
1338 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001339 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001340 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001341 if (!VD || VD->isInvalidDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001342 Info.Diag(Loc);
Richard Smith96e0c102011-11-04 02:25:55 +00001343 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001344 }
1345
Richard Smithf2b681b2011-12-21 05:04:46 +00001346 // DR1313: If the object is volatile-qualified but the glvalue was not,
1347 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001348 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001349 if (VT.isVolatileQualified()) {
1350 if (Info.getLangOpts().CPlusPlus) {
1351 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1352 Info.Note(VD->getLocation(), diag::note_declared_at);
1353 } else {
1354 Info.Diag(Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001355 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001356 return false;
1357 }
1358
1359 if (!isa<ParmVarDecl>(VD)) {
1360 if (VD->isConstexpr()) {
1361 // OK, we can read this variable.
1362 } else if (VT->isIntegralOrEnumerationType()) {
1363 if (!VT.isConstQualified()) {
1364 if (Info.getLangOpts().CPlusPlus) {
1365 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1366 Info.Note(VD->getLocation(), diag::note_declared_at);
1367 } else {
1368 Info.Diag(Loc);
1369 }
1370 return false;
1371 }
1372 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1373 // We support folding of const floating-point types, in order to make
1374 // static const data members of such types (supported as an extension)
1375 // more useful.
1376 if (Info.getLangOpts().CPlusPlus0x) {
1377 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1378 Info.Note(VD->getLocation(), diag::note_declared_at);
1379 } else {
1380 Info.CCEDiag(Loc);
1381 }
1382 } else {
1383 // FIXME: Allow folding of values of any literal type in all languages.
1384 if (Info.getLangOpts().CPlusPlus0x) {
1385 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1386 Info.Note(VD->getLocation(), diag::note_declared_at);
1387 } else {
1388 Info.Diag(Loc);
1389 }
Richard Smith96e0c102011-11-04 02:25:55 +00001390 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001391 }
Richard Smith96e0c102011-11-04 02:25:55 +00001392 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001393
Richard Smithf57d8cb2011-12-09 22:58:01 +00001394 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001395 return false;
1396
Richard Smith0b0a0b62011-10-29 20:57:55 +00001397 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001398 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001399
1400 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1401 // conversion. This happens when the declaration and the lvalue should be
1402 // considered synonymous, for instance when initializing an array of char
1403 // from a string literal. Continue as if the initializer lvalue was the
1404 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001405 assert(RVal.getLValueOffset().isZero() &&
1406 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001407 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001408 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001409 }
1410
Richard Smithf2b681b2011-12-21 05:04:46 +00001411 // Volatile temporary objects cannot be read in constant expressions.
1412 if (Base->getType().isVolatileQualified()) {
1413 if (Info.getLangOpts().CPlusPlus) {
1414 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1415 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1416 } else {
1417 Info.Diag(Loc);
1418 }
1419 return false;
1420 }
1421
Richard Smith96e0c102011-11-04 02:25:55 +00001422 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1423 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1424 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001425 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001426 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001427 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001428 }
Richard Smith96e0c102011-11-04 02:25:55 +00001429
1430 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001431 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf2b681b2011-12-21 05:04:46 +00001432 const ConstantArrayType *CAT =
1433 Info.Ctx.getAsConstantArrayType(S->getType());
1434 if (Index >= CAT->getSize().getZExtValue()) {
1435 // Note, it should not be possible to form a pointer which points more
1436 // than one past the end of the array without producing a prior const expr
1437 // diagnostic.
1438 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith96e0c102011-11-04 02:25:55 +00001439 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001440 }
Richard Smith96e0c102011-11-04 02:25:55 +00001441 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1442 Type->isUnsignedIntegerType());
1443 if (Index < S->getLength())
1444 Value = S->getCodeUnit(Index);
1445 RVal = CCValue(Value);
1446 return true;
1447 }
1448
Richard Smithf3e9e432011-11-07 09:22:26 +00001449 if (Frame) {
1450 // If this is a temporary expression with a nontrivial initializer, grab the
1451 // value from the relevant stack frame.
1452 RVal = Frame->Temporaries[Base];
1453 } else if (const CompoundLiteralExpr *CLE
1454 = dyn_cast<CompoundLiteralExpr>(Base)) {
1455 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1456 // initializer until now for such expressions. Such an expression can't be
1457 // an ICE in C, so this only matters for fold.
1458 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1459 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1460 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001461 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001462 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001463 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001464 }
Richard Smith96e0c102011-11-04 02:25:55 +00001465
Richard Smithf57d8cb2011-12-09 22:58:01 +00001466 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1467 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001468}
1469
Richard Smithe97cbd72011-11-11 04:05:33 +00001470/// Build an lvalue for the object argument of a member function call.
1471static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1472 LValue &This) {
1473 if (Object->getType()->isPointerType())
1474 return EvaluatePointer(Object, This, Info);
1475
1476 if (Object->isGLValue())
1477 return EvaluateLValue(Object, This, Info);
1478
Richard Smith027bf112011-11-17 22:56:20 +00001479 if (Object->getType()->isLiteralType())
1480 return EvaluateTemporary(Object, This, Info);
1481
1482 return false;
1483}
1484
1485/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1486/// lvalue referring to the result.
1487///
1488/// \param Info - Information about the ongoing evaluation.
1489/// \param BO - The member pointer access operation.
1490/// \param LV - Filled in with a reference to the resulting object.
1491/// \param IncludeMember - Specifies whether the member itself is included in
1492/// the resulting LValue subobject designator. This is not possible when
1493/// creating a bound member function.
1494/// \return The field or method declaration to which the member pointer refers,
1495/// or 0 if evaluation fails.
1496static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1497 const BinaryOperator *BO,
1498 LValue &LV,
1499 bool IncludeMember = true) {
1500 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1501
1502 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1503 return 0;
1504
1505 MemberPtr MemPtr;
1506 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1507 return 0;
1508
1509 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1510 // member value, the behavior is undefined.
1511 if (!MemPtr.getDecl())
1512 return 0;
1513
1514 if (MemPtr.isDerivedMember()) {
1515 // This is a member of some derived class. Truncate LV appropriately.
1516 const CXXRecordDecl *MostDerivedType;
1517 unsigned MostDerivedPathLength;
1518 bool MostDerivedIsArrayElement;
1519 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1520 MostDerivedIsArrayElement))
1521 return 0;
1522
1523 // The end of the derived-to-base path for the base object must match the
1524 // derived-to-base path for the member pointer.
1525 if (MostDerivedPathLength + MemPtr.Path.size() >
1526 LV.Designator.Entries.size())
1527 return 0;
1528 unsigned PathLengthToMember =
1529 LV.Designator.Entries.size() - MemPtr.Path.size();
1530 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1531 const CXXRecordDecl *LVDecl = getAsBaseClass(
1532 LV.Designator.Entries[PathLengthToMember + I]);
1533 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1534 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1535 return 0;
1536 }
1537
1538 // Truncate the lvalue to the appropriate derived class.
1539 bool ResultIsArray = false;
1540 if (PathLengthToMember == MostDerivedPathLength)
1541 ResultIsArray = MostDerivedIsArrayElement;
1542 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1543 PathLengthToMember, ResultIsArray);
1544 } else if (!MemPtr.Path.empty()) {
1545 // Extend the LValue path with the member pointer's path.
1546 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1547 MemPtr.Path.size() + IncludeMember);
1548
1549 // Walk down to the appropriate base class.
1550 QualType LVType = BO->getLHS()->getType();
1551 if (const PointerType *PT = LVType->getAs<PointerType>())
1552 LVType = PT->getPointeeType();
1553 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1554 assert(RD && "member pointer access on non-class-type expression");
1555 // The first class in the path is that of the lvalue.
1556 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1557 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1558 HandleLValueDirectBase(Info, LV, RD, Base);
1559 RD = Base;
1560 }
1561 // Finally cast to the class containing the member.
1562 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1563 }
1564
1565 // Add the member. Note that we cannot build bound member functions here.
1566 if (IncludeMember) {
1567 // FIXME: Deal with IndirectFieldDecls.
1568 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1569 if (!FD) return 0;
1570 HandleLValueMember(Info, LV, FD);
1571 }
1572
1573 return MemPtr.getDecl();
1574}
1575
1576/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1577/// the provided lvalue, which currently refers to the base object.
1578static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1579 LValue &Result) {
1580 const CXXRecordDecl *MostDerivedType;
1581 unsigned MostDerivedPathLength;
1582 bool MostDerivedIsArrayElement;
1583
1584 // Check this cast doesn't take us outside the object.
1585 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1586 MostDerivedPathLength,
1587 MostDerivedIsArrayElement))
1588 return false;
1589 SubobjectDesignator &D = Result.Designator;
1590 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1591 return false;
1592
1593 // Check the type of the final cast. We don't need to check the path,
1594 // since a cast can only be formed if the path is unique.
1595 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1596 bool ResultIsArray = false;
1597 QualType TargetQT = E->getType();
1598 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1599 TargetQT = PT->getPointeeType();
1600 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1601 const CXXRecordDecl *FinalType;
1602 if (NewEntriesSize == MostDerivedPathLength) {
1603 ResultIsArray = MostDerivedIsArrayElement;
1604 FinalType = MostDerivedType;
1605 } else
1606 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1607 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1608 return false;
1609
1610 // Truncate the lvalue to the appropriate derived class.
1611 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1612 ResultIsArray);
1613 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001614}
1615
Mike Stump876387b2009-10-27 22:09:17 +00001616namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001617enum EvalStmtResult {
1618 /// Evaluation failed.
1619 ESR_Failed,
1620 /// Hit a 'return' statement.
1621 ESR_Returned,
1622 /// Evaluation succeeded.
1623 ESR_Succeeded
1624};
1625}
1626
1627// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001628static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001629 const Stmt *S) {
1630 switch (S->getStmtClass()) {
1631 default:
1632 return ESR_Failed;
1633
1634 case Stmt::NullStmtClass:
1635 case Stmt::DeclStmtClass:
1636 return ESR_Succeeded;
1637
Richard Smith357362d2011-12-13 06:39:58 +00001638 case Stmt::ReturnStmtClass: {
1639 CCValue CCResult;
1640 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1641 if (!Evaluate(CCResult, Info, RetExpr) ||
1642 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1643 CCEK_ReturnValue))
1644 return ESR_Failed;
1645 return ESR_Returned;
1646 }
Richard Smith254a73d2011-10-28 22:34:42 +00001647
1648 case Stmt::CompoundStmtClass: {
1649 const CompoundStmt *CS = cast<CompoundStmt>(S);
1650 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1651 BE = CS->body_end(); BI != BE; ++BI) {
1652 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1653 if (ESR != ESR_Succeeded)
1654 return ESR;
1655 }
1656 return ESR_Succeeded;
1657 }
1658 }
1659}
1660
Richard Smithcc36f692011-12-22 02:22:31 +00001661/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1662/// default constructor. If so, we'll fold it whether or not it's marked as
1663/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1664/// so we need special handling.
1665static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00001666 const CXXConstructorDecl *CD,
1667 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00001668 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1669 return false;
1670
1671 if (!CD->isConstexpr()) {
1672 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smithfddd3842011-12-30 21:15:51 +00001673 // Value-initialization does not call a trivial default constructor, so
1674 // such a call is a core constant expression whether or not the
1675 // constructor is constexpr.
1676 if (!IsValueInitialization) {
1677 // FIXME: If DiagDecl is an implicitly-declared special member function,
1678 // we should be much more explicit about why it's not constexpr.
1679 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1680 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1681 Info.Note(CD->getLocation(), diag::note_declared_at);
1682 }
Richard Smithcc36f692011-12-22 02:22:31 +00001683 } else {
1684 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1685 }
1686 }
1687 return true;
1688}
1689
Richard Smith357362d2011-12-13 06:39:58 +00001690/// CheckConstexprFunction - Check that a function can be called in a constant
1691/// expression.
1692static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1693 const FunctionDecl *Declaration,
1694 const FunctionDecl *Definition) {
1695 // Can we evaluate this function call?
1696 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1697 return true;
1698
1699 if (Info.getLangOpts().CPlusPlus0x) {
1700 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001701 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1702 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001703 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1704 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1705 << DiagDecl;
1706 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1707 } else {
1708 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1709 }
1710 return false;
1711}
1712
Richard Smithd62306a2011-11-10 06:34:14 +00001713namespace {
Richard Smith60494462011-11-11 05:48:57 +00001714typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001715}
1716
1717/// EvaluateArgs - Evaluate the arguments to a function call.
1718static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1719 EvalInfo &Info) {
1720 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1721 I != E; ++I)
1722 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1723 return false;
1724 return true;
1725}
1726
Richard Smith254a73d2011-10-28 22:34:42 +00001727/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001728static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1729 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001730 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001731 EvalInfo &Info, APValue &Result) {
1732 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001733 return false;
1734
Richard Smithd62306a2011-11-10 06:34:14 +00001735 ArgVector ArgValues(Args.size());
1736 if (!EvaluateArgs(Args, ArgValues, Info))
1737 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001738
Richard Smithf6f003a2011-12-16 19:06:07 +00001739 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1740 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001741 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1742}
1743
Richard Smithd62306a2011-11-10 06:34:14 +00001744/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001746 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001747 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00001748 EvalInfo &Info, APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001749 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001750 return false;
1751
1752 ArgVector ArgValues(Args.size());
1753 if (!EvaluateArgs(Args, ArgValues, Info))
1754 return false;
1755
Richard Smithf6f003a2011-12-16 19:06:07 +00001756 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1757 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001758
1759 // If it's a delegating constructor, just delegate.
1760 if (Definition->isDelegatingConstructor()) {
1761 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1762 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1763 }
1764
1765 // Reserve space for the struct members.
1766 const CXXRecordDecl *RD = Definition->getParent();
Richard Smithfddd3842011-12-30 21:15:51 +00001767 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00001768 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1769 std::distance(RD->field_begin(), RD->field_end()));
1770
1771 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1772
1773 unsigned BasesSeen = 0;
1774#ifndef NDEBUG
1775 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1776#endif
1777 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1778 E = Definition->init_end(); I != E; ++I) {
1779 if ((*I)->isBaseInitializer()) {
1780 QualType BaseType((*I)->getBaseClass(), 0);
1781#ifndef NDEBUG
1782 // Non-virtual base classes are initialized in the order in the class
1783 // definition. We cannot have a virtual base class for a literal type.
1784 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1785 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1786 "base class initializers not in expected order");
1787 ++BaseIt;
1788#endif
1789 LValue Subobject = This;
1790 HandleLValueDirectBase(Info, Subobject, RD,
1791 BaseType->getAsCXXRecordDecl(), &Layout);
1792 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1793 Subobject, (*I)->getInit()))
1794 return false;
1795 } else if (FieldDecl *FD = (*I)->getMember()) {
1796 LValue Subobject = This;
1797 HandleLValueMember(Info, Subobject, FD, &Layout);
1798 if (RD->isUnion()) {
1799 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001800 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1801 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001802 return false;
1803 } else if (!EvaluateConstantExpression(
1804 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001805 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001806 return false;
1807 } else {
1808 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001809 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001810 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001811 return false;
1812 }
1813 }
1814
1815 return true;
1816}
1817
Richard Smith254a73d2011-10-28 22:34:42 +00001818namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001819class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001820 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001821 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001822public:
1823
Richard Smith725810a2011-10-16 21:26:27 +00001824 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001825
1826 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001827 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001828 return true;
1829 }
1830
Peter Collingbournee9200682011-05-13 03:29:01 +00001831 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1832 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001833 return Visit(E->getResultExpr());
1834 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001835 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001836 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001837 return true;
1838 return false;
1839 }
John McCall31168b02011-06-15 23:02:42 +00001840 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001841 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001842 return true;
1843 return false;
1844 }
1845 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001846 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001847 return true;
1848 return false;
1849 }
1850
Mike Stump876387b2009-10-27 22:09:17 +00001851 // We don't want to evaluate BlockExprs multiple times, as they generate
1852 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001853 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1854 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1855 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001856 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001857 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1858 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1859 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1860 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1861 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1862 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001863 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001864 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001865 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001866 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001867 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001868 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1869 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1870 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1871 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001872 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001873 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1874 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1875 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1876 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1877 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001878 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001879 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001880 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001881 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001882 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001883
1884 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001885 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001886 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1887 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001888 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001889 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001890 return false;
1891 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001892
Peter Collingbournee9200682011-05-13 03:29:01 +00001893 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001894};
1895
John McCallc07a0c72011-02-17 10:25:35 +00001896class OpaqueValueEvaluation {
1897 EvalInfo &info;
1898 OpaqueValueExpr *opaqueValue;
1899
1900public:
1901 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1902 Expr *value)
1903 : info(info), opaqueValue(opaqueValue) {
1904
1905 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001906 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001907 this->opaqueValue = 0;
1908 return;
1909 }
John McCallc07a0c72011-02-17 10:25:35 +00001910 }
1911
1912 bool hasError() const { return opaqueValue == 0; }
1913
1914 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001915 // FIXME: This will not work for recursive constexpr functions using opaque
1916 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001917 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1918 }
1919};
1920
Mike Stump876387b2009-10-27 22:09:17 +00001921} // end anonymous namespace
1922
Eli Friedman9a156e52008-11-12 09:44:48 +00001923//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001924// Generic Evaluation
1925//===----------------------------------------------------------------------===//
1926namespace {
1927
Richard Smithf57d8cb2011-12-09 22:58:01 +00001928// FIXME: RetTy is always bool. Remove it.
1929template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001930class ExprEvaluatorBase
1931 : public ConstStmtVisitor<Derived, RetTy> {
1932private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001933 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001934 return static_cast<Derived*>(this)->Success(V, E);
1935 }
Richard Smithfddd3842011-12-30 21:15:51 +00001936 RetTy DerivedZeroInitialization(const Expr *E) {
1937 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001938 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001939
1940protected:
1941 EvalInfo &Info;
1942 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1943 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1944
Richard Smith92b1ce02011-12-12 09:28:41 +00001945 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001946 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001947 }
1948
1949 /// Report an evaluation error. This should only be called when an error is
1950 /// first discovered. When propagating an error, just return false.
1951 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001952 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001953 return false;
1954 }
1955 bool Error(const Expr *E) {
1956 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1957 }
1958
Richard Smithfddd3842011-12-30 21:15:51 +00001959 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001960
Peter Collingbournee9200682011-05-13 03:29:01 +00001961public:
1962 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1963
1964 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001965 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001966 }
1967 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001968 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001969 }
1970
1971 RetTy VisitParenExpr(const ParenExpr *E)
1972 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1973 RetTy VisitUnaryExtension(const UnaryOperator *E)
1974 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1975 RetTy VisitUnaryPlus(const UnaryOperator *E)
1976 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1977 RetTy VisitChooseExpr(const ChooseExpr *E)
1978 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1979 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1980 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001981 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1982 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001983 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1984 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00001985 // We cannot create any objects for which cleanups are required, so there is
1986 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1987 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1988 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001989
Richard Smith6d6ecc32011-12-12 12:46:16 +00001990 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1991 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1992 return static_cast<Derived*>(this)->VisitCastExpr(E);
1993 }
1994 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1995 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1996 return static_cast<Derived*>(this)->VisitCastExpr(E);
1997 }
1998
Richard Smith027bf112011-11-17 22:56:20 +00001999 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2000 switch (E->getOpcode()) {
2001 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002002 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002003
2004 case BO_Comma:
2005 VisitIgnoredValue(E->getLHS());
2006 return StmtVisitorTy::Visit(E->getRHS());
2007
2008 case BO_PtrMemD:
2009 case BO_PtrMemI: {
2010 LValue Obj;
2011 if (!HandleMemberPointerAccess(Info, E, Obj))
2012 return false;
2013 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002014 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002015 return false;
2016 return DerivedSuccess(Result, E);
2017 }
2018 }
2019 }
2020
Peter Collingbournee9200682011-05-13 03:29:01 +00002021 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2022 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2023 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002024 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002025
2026 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00002027 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002028 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002029
2030 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2031 }
2032
2033 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2034 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002035 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002036 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002037
Richard Smith11562c52011-10-28 17:51:58 +00002038 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00002039 return StmtVisitorTy::Visit(EvalExpr);
2040 }
2041
2042 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002043 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002044 if (!Value) {
2045 const Expr *Source = E->getSourceExpr();
2046 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002047 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002048 if (Source == E) { // sanity checking.
2049 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002050 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002051 }
2052 return StmtVisitorTy::Visit(Source);
2053 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00002054 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002055 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002056
Richard Smith254a73d2011-10-28 22:34:42 +00002057 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002058 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002059 QualType CalleeType = Callee->getType();
2060
Richard Smith254a73d2011-10-28 22:34:42 +00002061 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002062 LValue *This = 0, ThisVal;
2063 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00002064
Richard Smithe97cbd72011-11-11 04:05:33 +00002065 // Extract function decl and 'this' pointer from the callee.
2066 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002067 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002068 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2069 // Explicit bound member calls, such as x.f() or p->g();
2070 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002071 return false;
2072 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002073 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002074 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2075 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002076 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2077 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002078 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002079 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002080 return Error(Callee);
2081
2082 FD = dyn_cast<FunctionDecl>(Member);
2083 if (!FD)
2084 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002085 } else if (CalleeType->isFunctionPointerType()) {
2086 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002087 if (!Evaluate(Call, Info, Callee))
2088 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002089
Richard Smithf57d8cb2011-12-09 22:58:01 +00002090 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
2091 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002092 FD = dyn_cast_or_null<FunctionDecl>(
2093 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002094 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002095 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002096
2097 // Overloaded operator calls to member functions are represented as normal
2098 // calls with '*this' as the first argument.
2099 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2100 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002101 // FIXME: When selecting an implicit conversion for an overloaded
2102 // operator delete, we sometimes try to evaluate calls to conversion
2103 // operators without a 'this' parameter!
2104 if (Args.empty())
2105 return Error(E);
2106
Richard Smithe97cbd72011-11-11 04:05:33 +00002107 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2108 return false;
2109 This = &ThisVal;
2110 Args = Args.slice(1);
2111 }
2112
2113 // Don't call function pointers which have been cast to some other type.
2114 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002115 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002116 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002117 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002118
Richard Smith357362d2011-12-13 06:39:58 +00002119 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002120 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002121 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002122
Richard Smith357362d2011-12-13 06:39:58 +00002123 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002124 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002125 return false;
2126
2127 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002128 }
2129
Richard Smith11562c52011-10-28 17:51:58 +00002130 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2131 return StmtVisitorTy::Visit(E->getInitializer());
2132 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002133 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002134 if (E->getNumInits() == 0)
2135 return DerivedZeroInitialization(E);
2136 if (E->getNumInits() == 1)
2137 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002138 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002139 }
2140 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002141 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002142 }
2143 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002144 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002145 }
Richard Smith027bf112011-11-17 22:56:20 +00002146 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002147 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002148 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002149
Richard Smithd62306a2011-11-10 06:34:14 +00002150 /// A member expression where the object is a prvalue is itself a prvalue.
2151 RetTy VisitMemberExpr(const MemberExpr *E) {
2152 assert(!E->isArrow() && "missing call to bound member function?");
2153
2154 CCValue Val;
2155 if (!Evaluate(Val, Info, E->getBase()))
2156 return false;
2157
2158 QualType BaseTy = E->getBase()->getType();
2159
2160 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002161 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002162 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2163 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2164 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2165
2166 SubobjectDesignator Designator;
2167 Designator.addDecl(FD);
2168
Richard Smithf57d8cb2011-12-09 22:58:01 +00002169 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002170 DerivedSuccess(Val, E);
2171 }
2172
Richard Smith11562c52011-10-28 17:51:58 +00002173 RetTy VisitCastExpr(const CastExpr *E) {
2174 switch (E->getCastKind()) {
2175 default:
2176 break;
2177
2178 case CK_NoOp:
2179 return StmtVisitorTy::Visit(E->getSubExpr());
2180
2181 case CK_LValueToRValue: {
2182 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002183 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2184 return false;
2185 CCValue RVal;
2186 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2187 return false;
2188 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002189 }
2190 }
2191
Richard Smithf57d8cb2011-12-09 22:58:01 +00002192 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002193 }
2194
Richard Smith4a678122011-10-24 18:44:57 +00002195 /// Visit a value which is evaluated, but whose value is ignored.
2196 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002197 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002198 if (!Evaluate(Scratch, Info, E))
2199 Info.EvalStatus.HasSideEffects = true;
2200 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002201};
2202
2203}
2204
2205//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002206// Common base class for lvalue and temporary evaluation.
2207//===----------------------------------------------------------------------===//
2208namespace {
2209template<class Derived>
2210class LValueExprEvaluatorBase
2211 : public ExprEvaluatorBase<Derived, bool> {
2212protected:
2213 LValue &Result;
2214 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2215 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2216
2217 bool Success(APValue::LValueBase B) {
2218 Result.set(B);
2219 return true;
2220 }
2221
2222public:
2223 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2224 ExprEvaluatorBaseTy(Info), Result(Result) {}
2225
2226 bool Success(const CCValue &V, const Expr *E) {
2227 Result.setFrom(V);
2228 return true;
2229 }
Richard Smith027bf112011-11-17 22:56:20 +00002230
2231 bool CheckValidLValue() {
2232 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2233 // there are no null references, nor once-past-the-end references.
2234 // FIXME: Check for one-past-the-end array indices
2235 return Result.Base && !Result.Designator.Invalid &&
2236 !Result.Designator.OnePastTheEnd;
2237 }
2238
2239 bool VisitMemberExpr(const MemberExpr *E) {
2240 // Handle non-static data members.
2241 QualType BaseTy;
2242 if (E->isArrow()) {
2243 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2244 return false;
2245 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002246 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002247 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002248 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2249 return false;
2250 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002251 } else {
2252 if (!this->Visit(E->getBase()))
2253 return false;
2254 BaseTy = E->getBase()->getType();
2255 }
2256 // FIXME: In C++11, require the result to be a valid lvalue.
2257
2258 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2259 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002260 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002261 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2262 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2263 (void)BaseTy;
2264
2265 HandleLValueMember(this->Info, Result, FD);
2266
2267 if (FD->getType()->isReferenceType()) {
2268 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002269 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002270 RefValue))
2271 return false;
2272 return Success(RefValue, E);
2273 }
2274 return true;
2275 }
2276
2277 bool VisitBinaryOperator(const BinaryOperator *E) {
2278 switch (E->getOpcode()) {
2279 default:
2280 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2281
2282 case BO_PtrMemD:
2283 case BO_PtrMemI:
2284 return HandleMemberPointerAccess(this->Info, E, Result);
2285 }
2286 }
2287
2288 bool VisitCastExpr(const CastExpr *E) {
2289 switch (E->getCastKind()) {
2290 default:
2291 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2292
2293 case CK_DerivedToBase:
2294 case CK_UncheckedDerivedToBase: {
2295 if (!this->Visit(E->getSubExpr()))
2296 return false;
2297 if (!CheckValidLValue())
2298 return false;
2299
2300 // Now figure out the necessary offset to add to the base LV to get from
2301 // the derived class to the base class.
2302 QualType Type = E->getSubExpr()->getType();
2303
2304 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2305 PathE = E->path_end(); PathI != PathE; ++PathI) {
2306 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2307 *PathI))
2308 return false;
2309 Type = (*PathI)->getType();
2310 }
2311
2312 return true;
2313 }
2314 }
2315 }
2316};
2317}
2318
2319//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002320// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002321//
2322// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2323// function designators (in C), decl references to void objects (in C), and
2324// temporaries (if building with -Wno-address-of-temporary).
2325//
2326// LValue evaluation produces values comprising a base expression of one of the
2327// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002328// - Declarations
2329// * VarDecl
2330// * FunctionDecl
2331// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002332// * CompoundLiteralExpr in C
2333// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002334// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002335// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002336// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002337// * ObjCEncodeExpr
2338// * AddrLabelExpr
2339// * BlockExpr
2340// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002341// - Locals and temporaries
2342// * Any Expr, with a Frame indicating the function in which the temporary was
2343// evaluated.
2344// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002345//===----------------------------------------------------------------------===//
2346namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002347class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002348 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002349public:
Richard Smith027bf112011-11-17 22:56:20 +00002350 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2351 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002352
Richard Smith11562c52011-10-28 17:51:58 +00002353 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2354
Peter Collingbournee9200682011-05-13 03:29:01 +00002355 bool VisitDeclRefExpr(const DeclRefExpr *E);
2356 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002357 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002358 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2359 bool VisitMemberExpr(const MemberExpr *E);
2360 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2361 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002362 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002363 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2364 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002365
Peter Collingbournee9200682011-05-13 03:29:01 +00002366 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002367 switch (E->getCastKind()) {
2368 default:
Richard Smith027bf112011-11-17 22:56:20 +00002369 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002370
Eli Friedmance3e02a2011-10-11 00:13:24 +00002371 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002372 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002373 if (!Visit(E->getSubExpr()))
2374 return false;
2375 Result.Designator.setInvalid();
2376 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002377
Richard Smith027bf112011-11-17 22:56:20 +00002378 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002379 if (!Visit(E->getSubExpr()))
2380 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002381 if (!CheckValidLValue())
2382 return false;
2383 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002384 }
2385 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002386
Eli Friedman449fe542009-03-23 04:56:01 +00002387 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002388
Eli Friedman9a156e52008-11-12 09:44:48 +00002389};
2390} // end anonymous namespace
2391
Richard Smith11562c52011-10-28 17:51:58 +00002392/// Evaluate an expression as an lvalue. This can be legitimately called on
2393/// expressions which are not glvalues, in a few cases:
2394/// * function designators in C,
2395/// * "extern void" objects,
2396/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002397static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002398 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2399 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2400 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002401 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002402}
2403
Peter Collingbournee9200682011-05-13 03:29:01 +00002404bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002405 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2406 return Success(FD);
2407 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002408 return VisitVarDecl(E, VD);
2409 return Error(E);
2410}
Richard Smith733237d2011-10-24 23:14:33 +00002411
Richard Smith11562c52011-10-28 17:51:58 +00002412bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002413 if (!VD->getType()->isReferenceType()) {
2414 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002415 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002416 return true;
2417 }
Richard Smithce40ad62011-11-12 22:28:03 +00002418 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002419 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002420
Richard Smith0b0a0b62011-10-29 20:57:55 +00002421 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002422 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2423 return false;
2424 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002425}
2426
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002427bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2428 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002429 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002430 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002431 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2432
2433 Result.set(E, Info.CurrentCall);
2434 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2435 Result, E->GetTemporaryExpr());
2436 }
2437
2438 // Materialization of an lvalue temporary occurs when we need to force a copy
2439 // (for instance, if it's a bitfield).
2440 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2441 if (!Visit(E->GetTemporaryExpr()))
2442 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002443 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002444 Info.CurrentCall->Temporaries[E]))
2445 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002446 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002447 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002448}
2449
Peter Collingbournee9200682011-05-13 03:29:01 +00002450bool
2451LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002452 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2453 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2454 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002455 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002456}
2457
Richard Smith6e525142011-12-27 12:18:28 +00002458bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2459 if (E->isTypeOperand())
2460 return Success(E);
2461 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2462 if (RD && RD->isPolymorphic()) {
2463 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2464 << E->getExprOperand()->getType()
2465 << E->getExprOperand()->getSourceRange();
2466 return false;
2467 }
2468 return Success(E);
2469}
2470
Peter Collingbournee9200682011-05-13 03:29:01 +00002471bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002472 // Handle static data members.
2473 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2474 VisitIgnoredValue(E->getBase());
2475 return VisitVarDecl(E, VD);
2476 }
2477
Richard Smith254a73d2011-10-28 22:34:42 +00002478 // Handle static member functions.
2479 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2480 if (MD->isStatic()) {
2481 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002482 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002483 }
2484 }
2485
Richard Smithd62306a2011-11-10 06:34:14 +00002486 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002487 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002488}
2489
Peter Collingbournee9200682011-05-13 03:29:01 +00002490bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002491 // FIXME: Deal with vectors as array subscript bases.
2492 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002493 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002494
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002495 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002496 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002497
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002498 APSInt Index;
2499 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002500 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002501 int64_t IndexValue
2502 = Index.isSigned() ? Index.getSExtValue()
2503 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002504
Richard Smith027bf112011-11-17 22:56:20 +00002505 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002506 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002507}
Eli Friedman9a156e52008-11-12 09:44:48 +00002508
Peter Collingbournee9200682011-05-13 03:29:01 +00002509bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002510 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002511 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002512}
2513
Eli Friedman9a156e52008-11-12 09:44:48 +00002514//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002515// Pointer Evaluation
2516//===----------------------------------------------------------------------===//
2517
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002518namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002519class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002520 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002521 LValue &Result;
2522
Peter Collingbournee9200682011-05-13 03:29:01 +00002523 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002524 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002525 return true;
2526 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002527public:
Mike Stump11289f42009-09-09 15:08:12 +00002528
John McCall45d55e42010-05-07 21:00:08 +00002529 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002530 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002531
Richard Smith0b0a0b62011-10-29 20:57:55 +00002532 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002533 Result.setFrom(V);
2534 return true;
2535 }
Richard Smithfddd3842011-12-30 21:15:51 +00002536 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002537 return Success((Expr*)0);
2538 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002539
John McCall45d55e42010-05-07 21:00:08 +00002540 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002541 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002542 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002543 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002544 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002545 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002546 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002547 bool VisitCallExpr(const CallExpr *E);
2548 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002549 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002550 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002551 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002552 }
Richard Smithd62306a2011-11-10 06:34:14 +00002553 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2554 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002555 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002556 Result = *Info.CurrentCall->This;
2557 return true;
2558 }
John McCallc07a0c72011-02-17 10:25:35 +00002559
Eli Friedman449fe542009-03-23 04:56:01 +00002560 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002561};
Chris Lattner05706e882008-07-11 18:11:29 +00002562} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002563
John McCall45d55e42010-05-07 21:00:08 +00002564static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002565 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002566 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002567}
2568
John McCall45d55e42010-05-07 21:00:08 +00002569bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002570 if (E->getOpcode() != BO_Add &&
2571 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002572 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002573
Chris Lattner05706e882008-07-11 18:11:29 +00002574 const Expr *PExp = E->getLHS();
2575 const Expr *IExp = E->getRHS();
2576 if (IExp->getType()->isPointerType())
2577 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002578
John McCall45d55e42010-05-07 21:00:08 +00002579 if (!EvaluatePointer(PExp, Result, Info))
2580 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002581
John McCall45d55e42010-05-07 21:00:08 +00002582 llvm::APSInt Offset;
2583 if (!EvaluateInteger(IExp, Offset, Info))
2584 return false;
2585 int64_t AdditionalOffset
2586 = Offset.isSigned() ? Offset.getSExtValue()
2587 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002588 if (E->getOpcode() == BO_Sub)
2589 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002590
Richard Smithd62306a2011-11-10 06:34:14 +00002591 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002592 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002593 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002594}
Eli Friedman9a156e52008-11-12 09:44:48 +00002595
John McCall45d55e42010-05-07 21:00:08 +00002596bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2597 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002598}
Mike Stump11289f42009-09-09 15:08:12 +00002599
Peter Collingbournee9200682011-05-13 03:29:01 +00002600bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2601 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002602
Eli Friedman847a2bc2009-12-27 05:43:15 +00002603 switch (E->getCastKind()) {
2604 default:
2605 break;
2606
John McCalle3027922010-08-25 11:45:40 +00002607 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002608 case CK_CPointerToObjCPointerCast:
2609 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002610 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002611 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2612 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2613 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002614 if (!E->getType()->isVoidPointerType()) {
2615 if (SubExpr->getType()->isVoidPointerType())
2616 CCEDiag(E, diag::note_constexpr_invalid_cast)
2617 << 3 << SubExpr->getType();
2618 else
2619 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2620 }
Richard Smith96e0c102011-11-04 02:25:55 +00002621 if (!Visit(SubExpr))
2622 return false;
2623 Result.Designator.setInvalid();
2624 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002625
Anders Carlsson18275092010-10-31 20:41:46 +00002626 case CK_DerivedToBase:
2627 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002628 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002629 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002630 if (!Result.Base && Result.Offset.isZero())
2631 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002632
Richard Smithd62306a2011-11-10 06:34:14 +00002633 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002634 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002635 QualType Type =
2636 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002637
Richard Smithd62306a2011-11-10 06:34:14 +00002638 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002639 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002640 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002641 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002642 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002643 }
2644
Anders Carlsson18275092010-10-31 20:41:46 +00002645 return true;
2646 }
2647
Richard Smith027bf112011-11-17 22:56:20 +00002648 case CK_BaseToDerived:
2649 if (!Visit(E->getSubExpr()))
2650 return false;
2651 if (!Result.Base && Result.Offset.isZero())
2652 return true;
2653 return HandleBaseToDerivedCast(Info, E, Result);
2654
Richard Smith0b0a0b62011-10-29 20:57:55 +00002655 case CK_NullToPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002656 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002657
John McCalle3027922010-08-25 11:45:40 +00002658 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002659 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2660
Richard Smith0b0a0b62011-10-29 20:57:55 +00002661 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002662 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002663 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002664
John McCall45d55e42010-05-07 21:00:08 +00002665 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002666 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2667 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002668 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002669 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002670 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002671 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002672 return true;
2673 } else {
2674 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002675 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002676 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002677 }
2678 }
John McCalle3027922010-08-25 11:45:40 +00002679 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002680 if (SubExpr->isGLValue()) {
2681 if (!EvaluateLValue(SubExpr, Result, Info))
2682 return false;
2683 } else {
2684 Result.set(SubExpr, Info.CurrentCall);
2685 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2686 Info, Result, SubExpr))
2687 return false;
2688 }
Richard Smith96e0c102011-11-04 02:25:55 +00002689 // The result is a pointer to the first element of the array.
2690 Result.Designator.addIndex(0);
2691 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002692
John McCalle3027922010-08-25 11:45:40 +00002693 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002694 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002695 }
2696
Richard Smith11562c52011-10-28 17:51:58 +00002697 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002698}
Chris Lattner05706e882008-07-11 18:11:29 +00002699
Peter Collingbournee9200682011-05-13 03:29:01 +00002700bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002701 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002702 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002703
Peter Collingbournee9200682011-05-13 03:29:01 +00002704 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002705}
Chris Lattner05706e882008-07-11 18:11:29 +00002706
2707//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002708// Member Pointer Evaluation
2709//===----------------------------------------------------------------------===//
2710
2711namespace {
2712class MemberPointerExprEvaluator
2713 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2714 MemberPtr &Result;
2715
2716 bool Success(const ValueDecl *D) {
2717 Result = MemberPtr(D);
2718 return true;
2719 }
2720public:
2721
2722 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2723 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2724
2725 bool Success(const CCValue &V, const Expr *E) {
2726 Result.setFrom(V);
2727 return true;
2728 }
Richard Smithfddd3842011-12-30 21:15:51 +00002729 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002730 return Success((const ValueDecl*)0);
2731 }
2732
2733 bool VisitCastExpr(const CastExpr *E);
2734 bool VisitUnaryAddrOf(const UnaryOperator *E);
2735};
2736} // end anonymous namespace
2737
2738static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2739 EvalInfo &Info) {
2740 assert(E->isRValue() && E->getType()->isMemberPointerType());
2741 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2742}
2743
2744bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2745 switch (E->getCastKind()) {
2746 default:
2747 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2748
2749 case CK_NullToMemberPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002750 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002751
2752 case CK_BaseToDerivedMemberPointer: {
2753 if (!Visit(E->getSubExpr()))
2754 return false;
2755 if (E->path_empty())
2756 return true;
2757 // Base-to-derived member pointer casts store the path in derived-to-base
2758 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2759 // the wrong end of the derived->base arc, so stagger the path by one class.
2760 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2761 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2762 PathI != PathE; ++PathI) {
2763 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2764 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2765 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002766 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002767 }
2768 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2769 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002770 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002771 return true;
2772 }
2773
2774 case CK_DerivedToBaseMemberPointer:
2775 if (!Visit(E->getSubExpr()))
2776 return false;
2777 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2778 PathE = E->path_end(); PathI != PathE; ++PathI) {
2779 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2780 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2781 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002782 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002783 }
2784 return true;
2785 }
2786}
2787
2788bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2789 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2790 // member can be formed.
2791 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2792}
2793
2794//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002795// Record Evaluation
2796//===----------------------------------------------------------------------===//
2797
2798namespace {
2799 class RecordExprEvaluator
2800 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2801 const LValue &This;
2802 APValue &Result;
2803 public:
2804
2805 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2806 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2807
2808 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002809 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002810 }
Richard Smithfddd3842011-12-30 21:15:51 +00002811 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002812
Richard Smithe97cbd72011-11-11 04:05:33 +00002813 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002814 bool VisitInitListExpr(const InitListExpr *E);
2815 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2816 };
2817}
2818
Richard Smithfddd3842011-12-30 21:15:51 +00002819/// Perform zero-initialization on an object of non-union class type.
2820/// C++11 [dcl.init]p5:
2821/// To zero-initialize an object or reference of type T means:
2822/// [...]
2823/// -- if T is a (possibly cv-qualified) non-union class type,
2824/// each non-static data member and each base-class subobject is
2825/// zero-initialized
2826static bool HandleClassZeroInitialization(EvalInfo &Info, const RecordDecl *RD,
2827 const LValue &This, APValue &Result) {
2828 assert(!RD->isUnion() && "Expected non-union class type");
2829 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2830 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2831 std::distance(RD->field_begin(), RD->field_end()));
2832
2833 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2834
2835 if (CD) {
2836 unsigned Index = 0;
2837 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
2838 E = CD->bases_end(); I != E; ++I, ++Index) {
2839 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2840 LValue Subobject = This;
2841 HandleLValueDirectBase(Info, Subobject, CD, Base, &Layout);
2842 if (!HandleClassZeroInitialization(Info, Base, Subobject,
2843 Result.getStructBase(Index)))
2844 return false;
2845 }
2846 }
2847
2848 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2849 I != E; ++I) {
2850 // -- if T is a reference type, no initialization is performed.
2851 if ((*I)->getType()->isReferenceType())
2852 continue;
2853
2854 LValue Subobject = This;
2855 HandleLValueMember(Info, Subobject, *I, &Layout);
2856
2857 ImplicitValueInitExpr VIE((*I)->getType());
2858 if (!EvaluateConstantExpression(
2859 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2860 return false;
2861 }
2862
2863 return true;
2864}
2865
2866bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2867 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2868 if (RD->isUnion()) {
2869 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2870 // object's first non-static named data member is zero-initialized
2871 RecordDecl::field_iterator I = RD->field_begin();
2872 if (I == RD->field_end()) {
2873 Result = APValue((const FieldDecl*)0);
2874 return true;
2875 }
2876
2877 LValue Subobject = This;
2878 HandleLValueMember(Info, Subobject, *I);
2879 Result = APValue(*I);
2880 ImplicitValueInitExpr VIE((*I)->getType());
2881 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2882 Subobject, &VIE);
2883 }
2884
2885 return HandleClassZeroInitialization(Info, RD, This, Result);
2886}
2887
Richard Smithe97cbd72011-11-11 04:05:33 +00002888bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2889 switch (E->getCastKind()) {
2890 default:
2891 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2892
2893 case CK_ConstructorConversion:
2894 return Visit(E->getSubExpr());
2895
2896 case CK_DerivedToBase:
2897 case CK_UncheckedDerivedToBase: {
2898 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002899 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002900 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002901 if (!DerivedObject.isStruct())
2902 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002903
2904 // Derived-to-base rvalue conversion: just slice off the derived part.
2905 APValue *Value = &DerivedObject;
2906 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2907 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2908 PathE = E->path_end(); PathI != PathE; ++PathI) {
2909 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2910 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2911 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2912 RD = Base;
2913 }
2914 Result = *Value;
2915 return true;
2916 }
2917 }
2918}
2919
Richard Smithd62306a2011-11-10 06:34:14 +00002920bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2921 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2922 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2923
2924 if (RD->isUnion()) {
2925 Result = APValue(E->getInitializedFieldInUnion());
2926 if (!E->getNumInits())
2927 return true;
2928 LValue Subobject = This;
2929 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2930 &Layout);
2931 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2932 Subobject, E->getInit(0));
2933 }
2934
2935 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2936 "initializer list for class with base classes");
2937 Result = APValue(APValue::UninitStruct(), 0,
2938 std::distance(RD->field_begin(), RD->field_end()));
2939 unsigned ElementNo = 0;
2940 for (RecordDecl::field_iterator Field = RD->field_begin(),
2941 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2942 // Anonymous bit-fields are not considered members of the class for
2943 // purposes of aggregate initialization.
2944 if (Field->isUnnamedBitfield())
2945 continue;
2946
2947 LValue Subobject = This;
2948 HandleLValueMember(Info, Subobject, *Field, &Layout);
2949
2950 if (ElementNo < E->getNumInits()) {
2951 if (!EvaluateConstantExpression(
2952 Result.getStructField((*Field)->getFieldIndex()),
2953 Info, Subobject, E->getInit(ElementNo++)))
2954 return false;
2955 } else {
2956 // Perform an implicit value-initialization for members beyond the end of
2957 // the initializer list.
2958 ImplicitValueInitExpr VIE(Field->getType());
2959 if (!EvaluateConstantExpression(
2960 Result.getStructField((*Field)->getFieldIndex()),
2961 Info, Subobject, &VIE))
2962 return false;
2963 }
2964 }
2965
2966 return true;
2967}
2968
2969bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2970 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithfddd3842011-12-30 21:15:51 +00002971 bool ZeroInit = E->requiresZeroInitialization();
2972 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
2973 if (ZeroInit)
2974 return ZeroInitialization(E);
2975
Richard Smithcc36f692011-12-22 02:22:31 +00002976 const CXXRecordDecl *RD = FD->getParent();
2977 if (RD->isUnion())
2978 Result = APValue((FieldDecl*)0);
2979 else
2980 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2981 std::distance(RD->field_begin(), RD->field_end()));
2982 return true;
2983 }
2984
Richard Smithd62306a2011-11-10 06:34:14 +00002985 const FunctionDecl *Definition = 0;
2986 FD->getBody(Definition);
2987
Richard Smith357362d2011-12-13 06:39:58 +00002988 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2989 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002990
2991 // FIXME: Elide the copy/move construction wherever we can.
Richard Smithfddd3842011-12-30 21:15:51 +00002992 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00002993 if (const MaterializeTemporaryExpr *ME
2994 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2995 return Visit(ME->GetTemporaryExpr());
2996
Richard Smithfddd3842011-12-30 21:15:51 +00002997 if (ZeroInit && !ZeroInitialization(E))
2998 return false;
2999
Richard Smithd62306a2011-11-10 06:34:14 +00003000 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003001 return HandleConstructorCall(E, This, Args,
3002 cast<CXXConstructorDecl>(Definition), Info,
3003 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003004}
3005
3006static bool EvaluateRecord(const Expr *E, const LValue &This,
3007 APValue &Result, EvalInfo &Info) {
3008 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003009 "can't evaluate expression as a record rvalue");
3010 return RecordExprEvaluator(Info, This, Result).Visit(E);
3011}
3012
3013//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003014// Temporary Evaluation
3015//
3016// Temporaries are represented in the AST as rvalues, but generally behave like
3017// lvalues. The full-object of which the temporary is a subobject is implicitly
3018// materialized so that a reference can bind to it.
3019//===----------------------------------------------------------------------===//
3020namespace {
3021class TemporaryExprEvaluator
3022 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3023public:
3024 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3025 LValueExprEvaluatorBaseTy(Info, Result) {}
3026
3027 /// Visit an expression which constructs the value of this temporary.
3028 bool VisitConstructExpr(const Expr *E) {
3029 Result.set(E, Info.CurrentCall);
3030 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3031 Result, E);
3032 }
3033
3034 bool VisitCastExpr(const CastExpr *E) {
3035 switch (E->getCastKind()) {
3036 default:
3037 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3038
3039 case CK_ConstructorConversion:
3040 return VisitConstructExpr(E->getSubExpr());
3041 }
3042 }
3043 bool VisitInitListExpr(const InitListExpr *E) {
3044 return VisitConstructExpr(E);
3045 }
3046 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3047 return VisitConstructExpr(E);
3048 }
3049 bool VisitCallExpr(const CallExpr *E) {
3050 return VisitConstructExpr(E);
3051 }
3052};
3053} // end anonymous namespace
3054
3055/// Evaluate an expression of record type as a temporary.
3056static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003057 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003058 return TemporaryExprEvaluator(Info, Result).Visit(E);
3059}
3060
3061//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003062// Vector Evaluation
3063//===----------------------------------------------------------------------===//
3064
3065namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003066 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003067 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3068 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003069 public:
Mike Stump11289f42009-09-09 15:08:12 +00003070
Richard Smith2d406342011-10-22 21:10:00 +00003071 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3072 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003073
Richard Smith2d406342011-10-22 21:10:00 +00003074 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3075 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3076 // FIXME: remove this APValue copy.
3077 Result = APValue(V.data(), V.size());
3078 return true;
3079 }
Richard Smithed5165f2011-11-04 05:33:44 +00003080 bool Success(const CCValue &V, const Expr *E) {
3081 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003082 Result = V;
3083 return true;
3084 }
Richard Smithfddd3842011-12-30 21:15:51 +00003085 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003086
Richard Smith2d406342011-10-22 21:10:00 +00003087 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003088 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003089 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003090 bool VisitInitListExpr(const InitListExpr *E);
3091 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003092 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003093 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003094 // shufflevector, ExtVectorElementExpr
3095 // (Note that these require implementing conversions
3096 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003097 };
3098} // end anonymous namespace
3099
3100static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003101 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003102 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003103}
3104
Richard Smith2d406342011-10-22 21:10:00 +00003105bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3106 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003107 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003108
Richard Smith161f09a2011-12-06 22:44:34 +00003109 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003110 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003111
Eli Friedmanc757de22011-03-25 00:43:55 +00003112 switch (E->getCastKind()) {
3113 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003114 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003115 if (SETy->isIntegerType()) {
3116 APSInt IntResult;
3117 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003118 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003119 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003120 } else if (SETy->isRealFloatingType()) {
3121 APFloat F(0.0);
3122 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003123 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003124 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003125 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003126 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003127 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003128
3129 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003130 SmallVector<APValue, 4> Elts(NElts, Val);
3131 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003132 }
Eli Friedman803acb32011-12-22 03:51:45 +00003133 case CK_BitCast: {
3134 // Evaluate the operand into an APInt we can extract from.
3135 llvm::APInt SValInt;
3136 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3137 return false;
3138 // Extract the elements
3139 QualType EltTy = VTy->getElementType();
3140 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3141 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3142 SmallVector<APValue, 4> Elts;
3143 if (EltTy->isRealFloatingType()) {
3144 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3145 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3146 unsigned FloatEltSize = EltSize;
3147 if (&Sem == &APFloat::x87DoubleExtended)
3148 FloatEltSize = 80;
3149 for (unsigned i = 0; i < NElts; i++) {
3150 llvm::APInt Elt;
3151 if (BigEndian)
3152 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3153 else
3154 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3155 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3156 }
3157 } else if (EltTy->isIntegerType()) {
3158 for (unsigned i = 0; i < NElts; i++) {
3159 llvm::APInt Elt;
3160 if (BigEndian)
3161 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3162 else
3163 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3164 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3165 }
3166 } else {
3167 return Error(E);
3168 }
3169 return Success(Elts, E);
3170 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003171 default:
Richard Smith11562c52011-10-28 17:51:58 +00003172 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003173 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003174}
3175
Richard Smith2d406342011-10-22 21:10:00 +00003176bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003177VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003178 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003179 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003180 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003181
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003182 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003183 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003184
Eli Friedmanb9c71292012-01-03 23:24:20 +00003185 // The number of initializers can be less than the number of
3186 // vector elements. For OpenCL, this can be due to nested vector
3187 // initialization. For GCC compatibility, missing trailing elements
3188 // should be initialized with zeroes.
3189 unsigned CountInits = 0, CountElts = 0;
3190 while (CountElts < NumElements) {
3191 // Handle nested vector initialization.
3192 if (CountInits < NumInits
3193 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3194 APValue v;
3195 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3196 return Error(E);
3197 unsigned vlen = v.getVectorLength();
3198 for (unsigned j = 0; j < vlen; j++)
3199 Elements.push_back(v.getVectorElt(j));
3200 CountElts += vlen;
3201 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003202 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003203 if (CountInits < NumInits) {
3204 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3205 return Error(E);
3206 } else // trailing integer zero.
3207 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3208 Elements.push_back(APValue(sInt));
3209 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003210 } else {
3211 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003212 if (CountInits < NumInits) {
3213 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3214 return Error(E);
3215 } else // trailing float zero.
3216 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3217 Elements.push_back(APValue(f));
3218 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003219 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003220 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003221 }
Richard Smith2d406342011-10-22 21:10:00 +00003222 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003223}
3224
Richard Smith2d406342011-10-22 21:10:00 +00003225bool
Richard Smithfddd3842011-12-30 21:15:51 +00003226VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003227 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003228 QualType EltTy = VT->getElementType();
3229 APValue ZeroElement;
3230 if (EltTy->isIntegerType())
3231 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3232 else
3233 ZeroElement =
3234 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3235
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003236 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003237 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003238}
3239
Richard Smith2d406342011-10-22 21:10:00 +00003240bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003241 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003242 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003243}
3244
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003245//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003246// Array Evaluation
3247//===----------------------------------------------------------------------===//
3248
3249namespace {
3250 class ArrayExprEvaluator
3251 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003252 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003253 APValue &Result;
3254 public:
3255
Richard Smithd62306a2011-11-10 06:34:14 +00003256 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3257 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003258
3259 bool Success(const APValue &V, const Expr *E) {
3260 assert(V.isArray() && "Expected array type");
3261 Result = V;
3262 return true;
3263 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003264
Richard Smithfddd3842011-12-30 21:15:51 +00003265 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003266 const ConstantArrayType *CAT =
3267 Info.Ctx.getAsConstantArrayType(E->getType());
3268 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003269 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003270
3271 Result = APValue(APValue::UninitArray(), 0,
3272 CAT->getSize().getZExtValue());
3273 if (!Result.hasArrayFiller()) return true;
3274
Richard Smithfddd3842011-12-30 21:15:51 +00003275 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003276 LValue Subobject = This;
3277 Subobject.Designator.addIndex(0);
3278 ImplicitValueInitExpr VIE(CAT->getElementType());
3279 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3280 Subobject, &VIE);
3281 }
3282
Richard Smithf3e9e432011-11-07 09:22:26 +00003283 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003284 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003285 };
3286} // end anonymous namespace
3287
Richard Smithd62306a2011-11-10 06:34:14 +00003288static bool EvaluateArray(const Expr *E, const LValue &This,
3289 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003290 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003291 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003292}
3293
3294bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3295 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3296 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003297 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003298
Richard Smithca2cfbf2011-12-22 01:07:19 +00003299 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3300 // an appropriately-typed string literal enclosed in braces.
3301 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3302 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3303 LValue LV;
3304 if (!EvaluateLValue(E->getInit(0), LV, Info))
3305 return false;
3306 uint64_t NumElements = CAT->getSize().getZExtValue();
3307 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3308
3309 // Copy the string literal into the array. FIXME: Do this better.
3310 LV.Designator.addIndex(0);
3311 for (uint64_t I = 0; I < NumElements; ++I) {
3312 CCValue Char;
3313 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3314 CAT->getElementType(), LV, Char))
3315 return false;
3316 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3317 Result.getArrayInitializedElt(I)))
3318 return false;
3319 if (!HandleLValueArrayAdjustment(Info, LV, CAT->getElementType(), 1))
3320 return false;
3321 }
3322 return true;
3323 }
3324
Richard Smithf3e9e432011-11-07 09:22:26 +00003325 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3326 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003327 LValue Subobject = This;
3328 Subobject.Designator.addIndex(0);
3329 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003330 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003331 I != End; ++I, ++Index) {
3332 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3333 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003334 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003335 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3336 return false;
3337 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003338
3339 if (!Result.hasArrayFiller()) return true;
3340 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003341 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3342 // but sometimes does:
3343 // struct S { constexpr S() : p(&p) {} void *p; };
3344 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003345 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003346 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003347}
3348
Richard Smith027bf112011-11-17 22:56:20 +00003349bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3350 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3351 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003352 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003353
3354 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3355 if (!Result.hasArrayFiller())
3356 return true;
3357
3358 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003359
Richard Smithfddd3842011-12-30 21:15:51 +00003360 bool ZeroInit = E->requiresZeroInitialization();
3361 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3362 if (ZeroInit) {
3363 LValue Subobject = This;
3364 Subobject.Designator.addIndex(0);
3365 ImplicitValueInitExpr VIE(CAT->getElementType());
3366 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3367 Subobject, &VIE);
3368 }
3369
Richard Smithcc36f692011-12-22 02:22:31 +00003370 const CXXRecordDecl *RD = FD->getParent();
3371 if (RD->isUnion())
3372 Result.getArrayFiller() = APValue((FieldDecl*)0);
3373 else
3374 Result.getArrayFiller() =
3375 APValue(APValue::UninitStruct(), RD->getNumBases(),
3376 std::distance(RD->field_begin(), RD->field_end()));
3377 return true;
3378 }
3379
Richard Smith027bf112011-11-17 22:56:20 +00003380 const FunctionDecl *Definition = 0;
3381 FD->getBody(Definition);
3382
Richard Smith357362d2011-12-13 06:39:58 +00003383 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3384 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003385
3386 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3387 // but sometimes does:
3388 // struct S { constexpr S() : p(&p) {} void *p; };
3389 // S s[10];
3390 LValue Subobject = This;
3391 Subobject.Designator.addIndex(0);
Richard Smithfddd3842011-12-30 21:15:51 +00003392
3393 if (ZeroInit) {
3394 ImplicitValueInitExpr VIE(CAT->getElementType());
3395 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3396 &VIE))
3397 return false;
3398 }
3399
Richard Smith027bf112011-11-17 22:56:20 +00003400 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003401 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003402 cast<CXXConstructorDecl>(Definition),
3403 Info, Result.getArrayFiller());
3404}
3405
Richard Smithf3e9e432011-11-07 09:22:26 +00003406//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003407// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003408//
3409// As a GNU extension, we support casting pointers to sufficiently-wide integer
3410// types and back in constant folding. Integer values are thus represented
3411// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003412//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003413
3414namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003415class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003416 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003417 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003418public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003419 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003420 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003421
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003422 bool Success(const llvm::APSInt &SI, const Expr *E) {
3423 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003424 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003425 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003426 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003427 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003428 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003429 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003430 return true;
3431 }
3432
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003433 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003434 assert(E->getType()->isIntegralOrEnumerationType() &&
3435 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003436 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003437 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003438 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003439 Result.getInt().setIsUnsigned(
3440 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003441 return true;
3442 }
3443
3444 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003445 assert(E->getType()->isIntegralOrEnumerationType() &&
3446 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003447 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003448 return true;
3449 }
3450
Ken Dyckdbc01912011-03-11 02:13:43 +00003451 bool Success(CharUnits Size, const Expr *E) {
3452 return Success(Size.getQuantity(), E);
3453 }
3454
Richard Smith0b0a0b62011-10-29 20:57:55 +00003455 bool Success(const CCValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00003456 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003457 Result = V;
3458 return true;
3459 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003460 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003461 }
Mike Stump11289f42009-09-09 15:08:12 +00003462
Richard Smithfddd3842011-12-30 21:15:51 +00003463 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003464
Peter Collingbournee9200682011-05-13 03:29:01 +00003465 //===--------------------------------------------------------------------===//
3466 // Visitor Methods
3467 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003468
Chris Lattner7174bf32008-07-12 00:38:25 +00003469 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003470 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003471 }
3472 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003473 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003474 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003475
3476 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3477 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003478 if (CheckReferencedDecl(E, E->getDecl()))
3479 return true;
3480
3481 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003482 }
3483 bool VisitMemberExpr(const MemberExpr *E) {
3484 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003485 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003486 return true;
3487 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003488
3489 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003490 }
3491
Peter Collingbournee9200682011-05-13 03:29:01 +00003492 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003493 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003494 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003495 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003496
Peter Collingbournee9200682011-05-13 03:29:01 +00003497 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003498 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003499
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003500 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003501 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003502 }
Mike Stump11289f42009-09-09 15:08:12 +00003503
Richard Smith4ce706a2011-10-11 21:43:33 +00003504 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003505 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003506 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003507 }
3508
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003509 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003510 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003511 }
3512
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003513 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3514 return Success(E->getValue(), E);
3515 }
3516
John Wiegley6242b6a2011-04-28 00:16:57 +00003517 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3518 return Success(E->getValue(), E);
3519 }
3520
John Wiegleyf9f65842011-04-25 06:54:41 +00003521 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3522 return Success(E->getValue(), E);
3523 }
3524
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003525 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003526 bool VisitUnaryImag(const UnaryOperator *E);
3527
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003528 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003529 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003530
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003531private:
Ken Dyck160146e2010-01-27 17:10:57 +00003532 CharUnits GetAlignOfExpr(const Expr *E);
3533 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003534 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003535 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003536 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003537};
Chris Lattner05706e882008-07-11 18:11:29 +00003538} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003539
Richard Smith11562c52011-10-28 17:51:58 +00003540/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3541/// produce either the integer value or a pointer.
3542///
3543/// GCC has a heinous extension which folds casts between pointer types and
3544/// pointer-sized integral types. We support this by allowing the evaluation of
3545/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3546/// Some simple arithmetic on such values is supported (they are treated much
3547/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003548static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003549 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003550 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003551 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003552}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003553
Richard Smithf57d8cb2011-12-09 22:58:01 +00003554static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003555 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003556 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003557 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003558 if (!Val.isInt()) {
3559 // FIXME: It would be better to produce the diagnostic for casting
3560 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003561 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003562 return false;
3563 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003564 Result = Val.getInt();
3565 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003566}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003567
Richard Smithf57d8cb2011-12-09 22:58:01 +00003568/// Check whether the given declaration can be directly converted to an integral
3569/// rvalue. If not, no diagnostic is produced; there are other things we can
3570/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003571bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003572 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003573 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003574 // Check for signedness/width mismatches between E type and ECD value.
3575 bool SameSign = (ECD->getInitVal().isSigned()
3576 == E->getType()->isSignedIntegerOrEnumerationType());
3577 bool SameWidth = (ECD->getInitVal().getBitWidth()
3578 == Info.Ctx.getIntWidth(E->getType()));
3579 if (SameSign && SameWidth)
3580 return Success(ECD->getInitVal(), E);
3581 else {
3582 // Get rid of mismatch (otherwise Success assertions will fail)
3583 // by computing a new value matching the type of E.
3584 llvm::APSInt Val = ECD->getInitVal();
3585 if (!SameSign)
3586 Val.setIsSigned(!ECD->getInitVal().isSigned());
3587 if (!SameWidth)
3588 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3589 return Success(Val, E);
3590 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003591 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003592 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003593}
3594
Chris Lattner86ee2862008-10-06 06:40:35 +00003595/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3596/// as GCC.
3597static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3598 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003599 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003600 enum gcc_type_class {
3601 no_type_class = -1,
3602 void_type_class, integer_type_class, char_type_class,
3603 enumeral_type_class, boolean_type_class,
3604 pointer_type_class, reference_type_class, offset_type_class,
3605 real_type_class, complex_type_class,
3606 function_type_class, method_type_class,
3607 record_type_class, union_type_class,
3608 array_type_class, string_type_class,
3609 lang_type_class
3610 };
Mike Stump11289f42009-09-09 15:08:12 +00003611
3612 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003613 // ideal, however it is what gcc does.
3614 if (E->getNumArgs() == 0)
3615 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003616
Chris Lattner86ee2862008-10-06 06:40:35 +00003617 QualType ArgTy = E->getArg(0)->getType();
3618 if (ArgTy->isVoidType())
3619 return void_type_class;
3620 else if (ArgTy->isEnumeralType())
3621 return enumeral_type_class;
3622 else if (ArgTy->isBooleanType())
3623 return boolean_type_class;
3624 else if (ArgTy->isCharType())
3625 return string_type_class; // gcc doesn't appear to use char_type_class
3626 else if (ArgTy->isIntegerType())
3627 return integer_type_class;
3628 else if (ArgTy->isPointerType())
3629 return pointer_type_class;
3630 else if (ArgTy->isReferenceType())
3631 return reference_type_class;
3632 else if (ArgTy->isRealType())
3633 return real_type_class;
3634 else if (ArgTy->isComplexType())
3635 return complex_type_class;
3636 else if (ArgTy->isFunctionType())
3637 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003638 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003639 return record_type_class;
3640 else if (ArgTy->isUnionType())
3641 return union_type_class;
3642 else if (ArgTy->isArrayType())
3643 return array_type_class;
3644 else if (ArgTy->isUnionType())
3645 return union_type_class;
3646 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003647 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003648 return -1;
3649}
3650
Richard Smith5fab0c92011-12-28 19:48:30 +00003651/// EvaluateBuiltinConstantPForLValue - Determine the result of
3652/// __builtin_constant_p when applied to the given lvalue.
3653///
3654/// An lvalue is only "constant" if it is a pointer or reference to the first
3655/// character of a string literal.
3656template<typename LValue>
3657static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3658 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3659 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3660}
3661
3662/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3663/// GCC as we can manage.
3664static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3665 QualType ArgType = Arg->getType();
3666
3667 // __builtin_constant_p always has one operand. The rules which gcc follows
3668 // are not precisely documented, but are as follows:
3669 //
3670 // - If the operand is of integral, floating, complex or enumeration type,
3671 // and can be folded to a known value of that type, it returns 1.
3672 // - If the operand and can be folded to a pointer to the first character
3673 // of a string literal (or such a pointer cast to an integral type), it
3674 // returns 1.
3675 //
3676 // Otherwise, it returns 0.
3677 //
3678 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3679 // its support for this does not currently work.
3680 if (ArgType->isIntegralOrEnumerationType()) {
3681 Expr::EvalResult Result;
3682 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3683 return false;
3684
3685 APValue &V = Result.Val;
3686 if (V.getKind() == APValue::Int)
3687 return true;
3688
3689 return EvaluateBuiltinConstantPForLValue(V);
3690 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3691 return Arg->isEvaluatable(Ctx);
3692 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3693 LValue LV;
3694 Expr::EvalStatus Status;
3695 EvalInfo Info(Ctx, Status);
3696 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3697 : EvaluatePointer(Arg, LV, Info)) &&
3698 !Status.HasSideEffects)
3699 return EvaluateBuiltinConstantPForLValue(LV);
3700 }
3701
3702 // Anything else isn't considered to be sufficiently constant.
3703 return false;
3704}
3705
John McCall95007602010-05-10 23:27:23 +00003706/// Retrieves the "underlying object type" of the given expression,
3707/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003708QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3709 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3710 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003711 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003712 } else if (const Expr *E = B.get<const Expr*>()) {
3713 if (isa<CompoundLiteralExpr>(E))
3714 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003715 }
3716
3717 return QualType();
3718}
3719
Peter Collingbournee9200682011-05-13 03:29:01 +00003720bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003721 // TODO: Perhaps we should let LLVM lower this?
3722 LValue Base;
3723 if (!EvaluatePointer(E->getArg(0), Base, Info))
3724 return false;
3725
3726 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003727 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003728
Richard Smithce40ad62011-11-12 22:28:03 +00003729 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003730 if (T.isNull() ||
3731 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003732 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003733 T->isVariablyModifiedType() ||
3734 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003735 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003736
3737 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3738 CharUnits Offset = Base.getLValueOffset();
3739
3740 if (!Offset.isNegative() && Offset <= Size)
3741 Size -= Offset;
3742 else
3743 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003744 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003745}
3746
Peter Collingbournee9200682011-05-13 03:29:01 +00003747bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003748 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003749 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003750 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003751
3752 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003753 if (TryEvaluateBuiltinObjectSize(E))
3754 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003755
Eric Christopher99469702010-01-19 22:58:35 +00003756 // If evaluating the argument has side-effects we can't determine
3757 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003758 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003759 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003760 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003761 return Success(0, E);
3762 }
Mike Stump876387b2009-10-27 22:09:17 +00003763
Richard Smithf57d8cb2011-12-09 22:58:01 +00003764 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003765 }
3766
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003767 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003768 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003769
Richard Smith5fab0c92011-12-28 19:48:30 +00003770 case Builtin::BI__builtin_constant_p:
3771 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00003772
Chris Lattnerd545ad12009-09-23 06:06:36 +00003773 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003774 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003775 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003776 return Success(Operand, E);
3777 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003778
3779 case Builtin::BI__builtin_expect:
3780 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003781
3782 case Builtin::BIstrlen:
3783 case Builtin::BI__builtin_strlen:
3784 // As an extension, we support strlen() and __builtin_strlen() as constant
3785 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003786 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003787 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3788 // The string literal may have embedded null characters. Find the first
3789 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003790 StringRef Str = S->getString();
3791 StringRef::size_type Pos = Str.find(0);
3792 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003793 Str = Str.substr(0, Pos);
3794
3795 return Success(Str.size(), E);
3796 }
3797
Richard Smithf57d8cb2011-12-09 22:58:01 +00003798 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003799
3800 case Builtin::BI__atomic_is_lock_free: {
3801 APSInt SizeVal;
3802 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3803 return false;
3804
3805 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3806 // of two less than the maximum inline atomic width, we know it is
3807 // lock-free. If the size isn't a power of two, or greater than the
3808 // maximum alignment where we promote atomics, we know it is not lock-free
3809 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3810 // the answer can only be determined at runtime; for example, 16-byte
3811 // atomics have lock-free implementations on some, but not all,
3812 // x86-64 processors.
3813
3814 // Check power-of-two.
3815 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3816 if (!Size.isPowerOfTwo())
3817#if 0
3818 // FIXME: Suppress this folding until the ABI for the promotion width
3819 // settles.
3820 return Success(0, E);
3821#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003822 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003823#endif
3824
3825#if 0
3826 // Check against promotion width.
3827 // FIXME: Suppress this folding until the ABI for the promotion width
3828 // settles.
3829 unsigned PromoteWidthBits =
3830 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3831 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3832 return Success(0, E);
3833#endif
3834
3835 // Check against inlining width.
3836 unsigned InlineWidthBits =
3837 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3838 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3839 return Success(1, E);
3840
Richard Smithf57d8cb2011-12-09 22:58:01 +00003841 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003842 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003843 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003844}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003845
Richard Smith8b3497e2011-10-31 01:37:14 +00003846static bool HasSameBase(const LValue &A, const LValue &B) {
3847 if (!A.getLValueBase())
3848 return !B.getLValueBase();
3849 if (!B.getLValueBase())
3850 return false;
3851
Richard Smithce40ad62011-11-12 22:28:03 +00003852 if (A.getLValueBase().getOpaqueValue() !=
3853 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003854 const Decl *ADecl = GetLValueBaseDecl(A);
3855 if (!ADecl)
3856 return false;
3857 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003858 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003859 return false;
3860 }
3861
3862 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003863 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003864}
3865
Chris Lattnere13042c2008-07-11 19:10:17 +00003866bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003867 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003868 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003869
John McCalle3027922010-08-25 11:45:40 +00003870 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003871 VisitIgnoredValue(E->getLHS());
3872 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003873 }
3874
3875 if (E->isLogicalOp()) {
3876 // These need to be handled specially because the operands aren't
3877 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003878 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003879
Richard Smith11562c52011-10-28 17:51:58 +00003880 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003881 // We were able to evaluate the LHS, see if we can get away with not
3882 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003883 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003884 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003885
Richard Smith11562c52011-10-28 17:51:58 +00003886 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003887 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003888 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003889 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003890 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003891 }
3892 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003893 // FIXME: If both evaluations fail, we should produce the diagnostic from
3894 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3895 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003896 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003897 // We can't evaluate the LHS; however, sometimes the result
3898 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003899 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003900 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003901 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003902 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003903
3904 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003905 }
3906 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003907 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003908
Eli Friedman5a332ea2008-11-13 06:09:17 +00003909 return false;
3910 }
3911
Anders Carlssonacc79812008-11-16 07:17:21 +00003912 QualType LHSTy = E->getLHS()->getType();
3913 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003914
3915 if (LHSTy->isAnyComplexType()) {
3916 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003917 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003918
3919 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3920 return false;
3921
3922 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3923 return false;
3924
3925 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003926 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003927 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003928 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003929 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3930
John McCalle3027922010-08-25 11:45:40 +00003931 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003932 return Success((CR_r == APFloat::cmpEqual &&
3933 CR_i == APFloat::cmpEqual), E);
3934 else {
John McCalle3027922010-08-25 11:45:40 +00003935 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003936 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003937 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003938 CR_r == APFloat::cmpLessThan ||
3939 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003940 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003941 CR_i == APFloat::cmpLessThan ||
3942 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003943 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003944 } else {
John McCalle3027922010-08-25 11:45:40 +00003945 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003946 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3947 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3948 else {
John McCalle3027922010-08-25 11:45:40 +00003949 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003950 "Invalid compex comparison.");
3951 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3952 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3953 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003954 }
3955 }
Mike Stump11289f42009-09-09 15:08:12 +00003956
Anders Carlssonacc79812008-11-16 07:17:21 +00003957 if (LHSTy->isRealFloatingType() &&
3958 RHSTy->isRealFloatingType()) {
3959 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003960
Anders Carlssonacc79812008-11-16 07:17:21 +00003961 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3962 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003963
Anders Carlssonacc79812008-11-16 07:17:21 +00003964 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3965 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003966
Anders Carlssonacc79812008-11-16 07:17:21 +00003967 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003968
Anders Carlssonacc79812008-11-16 07:17:21 +00003969 switch (E->getOpcode()) {
3970 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003971 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003972 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003973 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003974 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003975 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003976 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003977 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003978 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003979 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003980 E);
John McCalle3027922010-08-25 11:45:40 +00003981 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003982 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003983 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003984 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003985 || CR == APFloat::cmpLessThan
3986 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003987 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003988 }
Mike Stump11289f42009-09-09 15:08:12 +00003989
Eli Friedmana38da572009-04-28 19:17:36 +00003990 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003991 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003992 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003993 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3994 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003995
John McCall45d55e42010-05-07 21:00:08 +00003996 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003997 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3998 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003999
Richard Smith8b3497e2011-10-31 01:37:14 +00004000 // Reject differing bases from the normal codepath; we special-case
4001 // comparisons to null.
4002 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004003 if (E->getOpcode() == BO_Sub) {
4004 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004005 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4006 return false;
4007 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4008 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4009 if (!LHSExpr || !RHSExpr)
4010 return false;
4011 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4012 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4013 if (!LHSAddrExpr || !RHSAddrExpr)
4014 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004015 // Make sure both labels come from the same function.
4016 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4017 RHSAddrExpr->getLabel()->getDeclContext())
4018 return false;
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004019 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4020 return true;
4021 }
Richard Smith83c68212011-10-31 05:11:32 +00004022 // Inequalities and subtractions between unrelated pointers have
4023 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00004024 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004025 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004026 // A constant address may compare equal to the address of a symbol.
4027 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00004028 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004029 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4030 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004031 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004032 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00004033 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00004034 // distinct. However, we do know that the address of a literal will be
4035 // non-null.
4036 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4037 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004038 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004039 // We can't tell whether weak symbols will end up pointing to the same
4040 // object.
4041 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004042 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004043 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00004044 // (Note that clang defaults to -fmerge-all-constants, which can
4045 // lead to inconsistent results for comparisons involving the address
4046 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00004047 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00004048 }
Eli Friedman64004332009-03-23 04:38:34 +00004049
Richard Smithf3e9e432011-11-07 09:22:26 +00004050 // FIXME: Implement the C++11 restrictions:
4051 // - Pointer subtractions must be on elements of the same array.
4052 // - Pointer comparisons must be between members with the same access.
4053
John McCalle3027922010-08-25 11:45:40 +00004054 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00004055 QualType Type = E->getLHS()->getType();
4056 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004057
Richard Smithd62306a2011-11-10 06:34:14 +00004058 CharUnits ElementSize;
4059 if (!HandleSizeof(Info, ElementType, ElementSize))
4060 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004061
Richard Smithd62306a2011-11-10 06:34:14 +00004062 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00004063 RHSValue.getLValueOffset();
4064 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004065 }
Richard Smith8b3497e2011-10-31 01:37:14 +00004066
4067 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4068 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4069 switch (E->getOpcode()) {
4070 default: llvm_unreachable("missing comparison operator");
4071 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4072 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4073 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4074 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4075 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4076 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004077 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004078 }
4079 }
Douglas Gregorb90df602010-06-16 00:17:44 +00004080 if (!LHSTy->isIntegralOrEnumerationType() ||
4081 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004082 // We can't continue from here for non-integral types.
4083 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004084 }
4085
Anders Carlsson9c181652008-07-08 14:35:21 +00004086 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00004087 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00004088 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004089 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00004090
Richard Smith11562c52011-10-28 17:51:58 +00004091 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004092 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004093 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00004094
4095 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00004096 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00004097 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4098 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00004099 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00004100 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00004101 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00004102 LHSVal.getLValueOffset() -= AdditionalOffset;
4103 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00004104 return true;
4105 }
4106
4107 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00004108 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00004109 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004110 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4111 LHSVal.getInt().getZExtValue());
4112 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00004113 return true;
4114 }
4115
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004116 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4117 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004118 if (!LHSVal.getLValueOffset().isZero() ||
4119 !RHSVal.getLValueOffset().isZero())
4120 return false;
4121 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4122 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4123 if (!LHSExpr || !RHSExpr)
4124 return false;
4125 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4126 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4127 if (!LHSAddrExpr || !RHSAddrExpr)
4128 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004129 // Make sure both labels come from the same function.
4130 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4131 RHSAddrExpr->getLabel()->getDeclContext())
4132 return false;
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004133 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4134 return true;
4135 }
4136
Eli Friedman94c25c62009-03-24 01:14:50 +00004137 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00004138 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004139 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004140
Richard Smith11562c52011-10-28 17:51:58 +00004141 APSInt &LHS = LHSVal.getInt();
4142 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00004143
Anders Carlsson9c181652008-07-08 14:35:21 +00004144 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004145 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004146 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004147 case BO_Mul: return Success(LHS * RHS, E);
4148 case BO_Add: return Success(LHS + RHS, E);
4149 case BO_Sub: return Success(LHS - RHS, E);
4150 case BO_And: return Success(LHS & RHS, E);
4151 case BO_Xor: return Success(LHS ^ RHS, E);
4152 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004153 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00004154 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004155 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004156 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004157 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00004158 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004159 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004160 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004161 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00004162 // During constant-folding, a negative shift is an opposite shift.
4163 if (RHS.isSigned() && RHS.isNegative()) {
4164 RHS = -RHS;
4165 goto shift_right;
4166 }
4167
4168 shift_left:
4169 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00004170 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4171 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004172 }
John McCalle3027922010-08-25 11:45:40 +00004173 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00004174 // During constant-folding, a negative shift is an opposite shift.
4175 if (RHS.isSigned() && RHS.isNegative()) {
4176 RHS = -RHS;
4177 goto shift_left;
4178 }
4179
4180 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00004181 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00004182 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4183 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004184 }
Mike Stump11289f42009-09-09 15:08:12 +00004185
Richard Smith11562c52011-10-28 17:51:58 +00004186 case BO_LT: return Success(LHS < RHS, E);
4187 case BO_GT: return Success(LHS > RHS, E);
4188 case BO_LE: return Success(LHS <= RHS, E);
4189 case BO_GE: return Success(LHS >= RHS, E);
4190 case BO_EQ: return Success(LHS == RHS, E);
4191 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00004192 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004193}
4194
Ken Dyck160146e2010-01-27 17:10:57 +00004195CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00004196 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4197 // the result is the size of the referenced type."
4198 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4199 // result shall be the alignment of the referenced type."
4200 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4201 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00004202
4203 // __alignof is defined to return the preferred alignment.
4204 return Info.Ctx.toCharUnitsFromBits(
4205 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00004206}
4207
Ken Dyck160146e2010-01-27 17:10:57 +00004208CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00004209 E = E->IgnoreParens();
4210
4211 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00004212 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00004213 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004214 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4215 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00004216
Chris Lattner68061312009-01-24 21:53:27 +00004217 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004218 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4219 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00004220
Chris Lattner24aeeab2009-01-24 21:09:06 +00004221 return GetAlignOfType(E->getType());
4222}
4223
4224
Peter Collingbournee190dee2011-03-11 19:24:49 +00004225/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4226/// a result as the expression's type.
4227bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4228 const UnaryExprOrTypeTraitExpr *E) {
4229 switch(E->getKind()) {
4230 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00004231 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00004232 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004233 else
Ken Dyckdbc01912011-03-11 02:13:43 +00004234 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004235 }
Eli Friedman64004332009-03-23 04:38:34 +00004236
Peter Collingbournee190dee2011-03-11 19:24:49 +00004237 case UETT_VecStep: {
4238 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00004239
Peter Collingbournee190dee2011-03-11 19:24:49 +00004240 if (Ty->isVectorType()) {
4241 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00004242
Peter Collingbournee190dee2011-03-11 19:24:49 +00004243 // The vec_step built-in functions that take a 3-component
4244 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4245 if (n == 3)
4246 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00004247
Peter Collingbournee190dee2011-03-11 19:24:49 +00004248 return Success(n, E);
4249 } else
4250 return Success(1, E);
4251 }
4252
4253 case UETT_SizeOf: {
4254 QualType SrcTy = E->getTypeOfArgument();
4255 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4256 // the result is the size of the referenced type."
4257 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4258 // result shall be the alignment of the referenced type."
4259 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4260 SrcTy = Ref->getPointeeType();
4261
Richard Smithd62306a2011-11-10 06:34:14 +00004262 CharUnits Sizeof;
4263 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00004264 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004265 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004266 }
4267 }
4268
4269 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004270 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004271}
4272
Peter Collingbournee9200682011-05-13 03:29:01 +00004273bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00004274 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00004275 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00004276 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004277 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00004278 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00004279 for (unsigned i = 0; i != n; ++i) {
4280 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4281 switch (ON.getKind()) {
4282 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00004283 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00004284 APSInt IdxResult;
4285 if (!EvaluateInteger(Idx, IdxResult, Info))
4286 return false;
4287 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4288 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004289 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004290 CurrentType = AT->getElementType();
4291 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4292 Result += IdxResult.getSExtValue() * ElementSize;
4293 break;
4294 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004295
Douglas Gregor882211c2010-04-28 22:16:22 +00004296 case OffsetOfExpr::OffsetOfNode::Field: {
4297 FieldDecl *MemberDecl = ON.getField();
4298 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004299 if (!RT)
4300 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004301 RecordDecl *RD = RT->getDecl();
4302 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004303 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004304 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004305 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004306 CurrentType = MemberDecl->getType().getNonReferenceType();
4307 break;
4308 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004309
Douglas Gregor882211c2010-04-28 22:16:22 +00004310 case OffsetOfExpr::OffsetOfNode::Identifier:
4311 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004312 return Error(OOE);
4313
Douglas Gregord1702062010-04-29 00:18:15 +00004314 case OffsetOfExpr::OffsetOfNode::Base: {
4315 CXXBaseSpecifier *BaseSpec = ON.getBase();
4316 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004317 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004318
4319 // Find the layout of the class whose base we are looking into.
4320 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004321 if (!RT)
4322 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004323 RecordDecl *RD = RT->getDecl();
4324 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4325
4326 // Find the base class itself.
4327 CurrentType = BaseSpec->getType();
4328 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4329 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004330 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004331
4332 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004333 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004334 break;
4335 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004336 }
4337 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004338 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004339}
4340
Chris Lattnere13042c2008-07-11 19:10:17 +00004341bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004342 switch (E->getOpcode()) {
4343 default:
4344 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4345 // See C99 6.6p3.
4346 return Error(E);
4347 case UO_Extension:
4348 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4349 // If so, we could clear the diagnostic ID.
4350 return Visit(E->getSubExpr());
4351 case UO_Plus:
4352 // The result is just the value.
4353 return Visit(E->getSubExpr());
4354 case UO_Minus: {
4355 if (!Visit(E->getSubExpr()))
4356 return false;
4357 if (!Result.isInt()) return Error(E);
4358 return Success(-Result.getInt(), E);
4359 }
4360 case UO_Not: {
4361 if (!Visit(E->getSubExpr()))
4362 return false;
4363 if (!Result.isInt()) return Error(E);
4364 return Success(~Result.getInt(), E);
4365 }
4366 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004367 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004368 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004369 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004370 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004371 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004372 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004373}
Mike Stump11289f42009-09-09 15:08:12 +00004374
Chris Lattner477c4be2008-07-12 01:15:53 +00004375/// HandleCast - This is used to evaluate implicit or explicit casts where the
4376/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004377bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4378 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004379 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004380 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004381
Eli Friedmanc757de22011-03-25 00:43:55 +00004382 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004383 case CK_BaseToDerived:
4384 case CK_DerivedToBase:
4385 case CK_UncheckedDerivedToBase:
4386 case CK_Dynamic:
4387 case CK_ToUnion:
4388 case CK_ArrayToPointerDecay:
4389 case CK_FunctionToPointerDecay:
4390 case CK_NullToPointer:
4391 case CK_NullToMemberPointer:
4392 case CK_BaseToDerivedMemberPointer:
4393 case CK_DerivedToBaseMemberPointer:
4394 case CK_ConstructorConversion:
4395 case CK_IntegralToPointer:
4396 case CK_ToVoid:
4397 case CK_VectorSplat:
4398 case CK_IntegralToFloating:
4399 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004400 case CK_CPointerToObjCPointerCast:
4401 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004402 case CK_AnyPointerToBlockPointerCast:
4403 case CK_ObjCObjectLValueCast:
4404 case CK_FloatingRealToComplex:
4405 case CK_FloatingComplexToReal:
4406 case CK_FloatingComplexCast:
4407 case CK_FloatingComplexToIntegralComplex:
4408 case CK_IntegralRealToComplex:
4409 case CK_IntegralComplexCast:
4410 case CK_IntegralComplexToFloatingComplex:
4411 llvm_unreachable("invalid cast kind for integral value");
4412
Eli Friedman9faf2f92011-03-25 19:07:11 +00004413 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004414 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004415 case CK_LValueBitCast:
4416 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004417 case CK_ARCProduceObject:
4418 case CK_ARCConsumeObject:
4419 case CK_ARCReclaimReturnedObject:
4420 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004421 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004422
4423 case CK_LValueToRValue:
4424 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004425 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004426
4427 case CK_MemberPointerToBoolean:
4428 case CK_PointerToBoolean:
4429 case CK_IntegralToBoolean:
4430 case CK_FloatingToBoolean:
4431 case CK_FloatingComplexToBoolean:
4432 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004433 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004434 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004435 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004436 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004437 }
4438
Eli Friedmanc757de22011-03-25 00:43:55 +00004439 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004440 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004441 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004442
Eli Friedman742421e2009-02-20 01:15:07 +00004443 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004444 // Allow casts of address-of-label differences if they are no-ops
4445 // or narrowing. (The narrowing case isn't actually guaranteed to
4446 // be constant-evaluatable except in some narrow cases which are hard
4447 // to detect here. We let it through on the assumption the user knows
4448 // what they are doing.)
4449 if (Result.isAddrLabelDiff())
4450 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00004451 // Only allow casts of lvalues if they are lossless.
4452 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4453 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004454
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004455 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004456 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004457 }
Mike Stump11289f42009-09-09 15:08:12 +00004458
Eli Friedmanc757de22011-03-25 00:43:55 +00004459 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004460 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4461
John McCall45d55e42010-05-07 21:00:08 +00004462 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004463 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004464 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004465
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004466 if (LV.getLValueBase()) {
4467 // Only allow based lvalue casts if they are lossless.
4468 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004469 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004470
Richard Smithcf74da72011-11-16 07:18:12 +00004471 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004472 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004473 return true;
4474 }
4475
Ken Dyck02990832010-01-15 12:37:54 +00004476 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4477 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004478 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004479 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004480
Eli Friedmanc757de22011-03-25 00:43:55 +00004481 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004482 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004483 if (!EvaluateComplex(SubExpr, C, Info))
4484 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004485 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004486 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004487
Eli Friedmanc757de22011-03-25 00:43:55 +00004488 case CK_FloatingToIntegral: {
4489 APFloat F(0.0);
4490 if (!EvaluateFloat(SubExpr, F, Info))
4491 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004492
Richard Smith357362d2011-12-13 06:39:58 +00004493 APSInt Value;
4494 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4495 return false;
4496 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004497 }
4498 }
Mike Stump11289f42009-09-09 15:08:12 +00004499
Eli Friedmanc757de22011-03-25 00:43:55 +00004500 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004501 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004502}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004503
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004504bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4505 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004506 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004507 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4508 return false;
4509 if (!LV.isComplexInt())
4510 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004511 return Success(LV.getComplexIntReal(), E);
4512 }
4513
4514 return Visit(E->getSubExpr());
4515}
4516
Eli Friedman4e7a2412009-02-27 04:45:43 +00004517bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004518 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004519 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004520 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4521 return false;
4522 if (!LV.isComplexInt())
4523 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004524 return Success(LV.getComplexIntImag(), E);
4525 }
4526
Richard Smith4a678122011-10-24 18:44:57 +00004527 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004528 return Success(0, E);
4529}
4530
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004531bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4532 return Success(E->getPackLength(), E);
4533}
4534
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004535bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4536 return Success(E->getValue(), E);
4537}
4538
Chris Lattner05706e882008-07-11 18:11:29 +00004539//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004540// Float Evaluation
4541//===----------------------------------------------------------------------===//
4542
4543namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004544class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004545 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004546 APFloat &Result;
4547public:
4548 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004549 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004550
Richard Smith0b0a0b62011-10-29 20:57:55 +00004551 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004552 Result = V.getFloat();
4553 return true;
4554 }
Eli Friedman24c01542008-08-22 00:06:13 +00004555
Richard Smithfddd3842011-12-30 21:15:51 +00004556 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004557 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4558 return true;
4559 }
4560
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004561 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004562
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004563 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004564 bool VisitBinaryOperator(const BinaryOperator *E);
4565 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004566 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004567
John McCallb1fb0d32010-05-07 22:08:54 +00004568 bool VisitUnaryReal(const UnaryOperator *E);
4569 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004570
Richard Smithfddd3842011-12-30 21:15:51 +00004571 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00004572};
4573} // end anonymous namespace
4574
4575static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004576 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004577 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004578}
4579
Jay Foad39c79802011-01-12 09:06:06 +00004580static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004581 QualType ResultTy,
4582 const Expr *Arg,
4583 bool SNaN,
4584 llvm::APFloat &Result) {
4585 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4586 if (!S) return false;
4587
4588 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4589
4590 llvm::APInt fill;
4591
4592 // Treat empty strings as if they were zero.
4593 if (S->getString().empty())
4594 fill = llvm::APInt(32, 0);
4595 else if (S->getString().getAsInteger(0, fill))
4596 return false;
4597
4598 if (SNaN)
4599 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4600 else
4601 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4602 return true;
4603}
4604
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004605bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004606 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004607 default:
4608 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4609
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004610 case Builtin::BI__builtin_huge_val:
4611 case Builtin::BI__builtin_huge_valf:
4612 case Builtin::BI__builtin_huge_vall:
4613 case Builtin::BI__builtin_inf:
4614 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004615 case Builtin::BI__builtin_infl: {
4616 const llvm::fltSemantics &Sem =
4617 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004618 Result = llvm::APFloat::getInf(Sem);
4619 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004620 }
Mike Stump11289f42009-09-09 15:08:12 +00004621
John McCall16291492010-02-28 13:00:19 +00004622 case Builtin::BI__builtin_nans:
4623 case Builtin::BI__builtin_nansf:
4624 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004625 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4626 true, Result))
4627 return Error(E);
4628 return true;
John McCall16291492010-02-28 13:00:19 +00004629
Chris Lattner0b7282e2008-10-06 06:31:58 +00004630 case Builtin::BI__builtin_nan:
4631 case Builtin::BI__builtin_nanf:
4632 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004633 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004634 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004635 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4636 false, Result))
4637 return Error(E);
4638 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004639
4640 case Builtin::BI__builtin_fabs:
4641 case Builtin::BI__builtin_fabsf:
4642 case Builtin::BI__builtin_fabsl:
4643 if (!EvaluateFloat(E->getArg(0), Result, Info))
4644 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004645
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004646 if (Result.isNegative())
4647 Result.changeSign();
4648 return true;
4649
Mike Stump11289f42009-09-09 15:08:12 +00004650 case Builtin::BI__builtin_copysign:
4651 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004652 case Builtin::BI__builtin_copysignl: {
4653 APFloat RHS(0.);
4654 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4655 !EvaluateFloat(E->getArg(1), RHS, Info))
4656 return false;
4657 Result.copySign(RHS);
4658 return true;
4659 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004660 }
4661}
4662
John McCallb1fb0d32010-05-07 22:08:54 +00004663bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004664 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4665 ComplexValue CV;
4666 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4667 return false;
4668 Result = CV.FloatReal;
4669 return true;
4670 }
4671
4672 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004673}
4674
4675bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004676 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4677 ComplexValue CV;
4678 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4679 return false;
4680 Result = CV.FloatImag;
4681 return true;
4682 }
4683
Richard Smith4a678122011-10-24 18:44:57 +00004684 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004685 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4686 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004687 return true;
4688}
4689
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004690bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004691 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004692 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004693 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004694 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004695 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004696 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4697 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004698 Result.changeSign();
4699 return true;
4700 }
4701}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004702
Eli Friedman24c01542008-08-22 00:06:13 +00004703bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004704 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4705 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004706
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004707 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004708 if (!EvaluateFloat(E->getLHS(), Result, Info))
4709 return false;
4710 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4711 return false;
4712
4713 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004714 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004715 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004716 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4717 return true;
John McCalle3027922010-08-25 11:45:40 +00004718 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004719 Result.add(RHS, APFloat::rmNearestTiesToEven);
4720 return true;
John McCalle3027922010-08-25 11:45:40 +00004721 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004722 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4723 return true;
John McCalle3027922010-08-25 11:45:40 +00004724 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004725 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4726 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004727 }
4728}
4729
4730bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4731 Result = E->getValue();
4732 return true;
4733}
4734
Peter Collingbournee9200682011-05-13 03:29:01 +00004735bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4736 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004737
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004738 switch (E->getCastKind()) {
4739 default:
Richard Smith11562c52011-10-28 17:51:58 +00004740 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004741
4742 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004743 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004744 return EvaluateInteger(SubExpr, IntResult, Info) &&
4745 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4746 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004747 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004748
4749 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004750 if (!Visit(SubExpr))
4751 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004752 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4753 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004754 }
John McCalld7646252010-11-14 08:17:51 +00004755
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004756 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004757 ComplexValue V;
4758 if (!EvaluateComplex(SubExpr, V, Info))
4759 return false;
4760 Result = V.getComplexFloatReal();
4761 return true;
4762 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004763 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004764
Richard Smithf57d8cb2011-12-09 22:58:01 +00004765 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004766}
4767
Eli Friedman24c01542008-08-22 00:06:13 +00004768//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004769// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004770//===----------------------------------------------------------------------===//
4771
4772namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004773class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004774 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004775 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004776
Anders Carlsson537969c2008-11-16 20:27:53 +00004777public:
John McCall93d91dc2010-05-07 17:22:02 +00004778 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004779 : ExprEvaluatorBaseTy(info), Result(Result) {}
4780
Richard Smith0b0a0b62011-10-29 20:57:55 +00004781 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004782 Result.setFrom(V);
4783 return true;
4784 }
Mike Stump11289f42009-09-09 15:08:12 +00004785
Anders Carlsson537969c2008-11-16 20:27:53 +00004786 //===--------------------------------------------------------------------===//
4787 // Visitor Methods
4788 //===--------------------------------------------------------------------===//
4789
Peter Collingbournee9200682011-05-13 03:29:01 +00004790 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004791
Peter Collingbournee9200682011-05-13 03:29:01 +00004792 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004793
John McCall93d91dc2010-05-07 17:22:02 +00004794 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004795 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004796 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004797};
4798} // end anonymous namespace
4799
John McCall93d91dc2010-05-07 17:22:02 +00004800static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4801 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004802 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004803 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004804}
4805
Peter Collingbournee9200682011-05-13 03:29:01 +00004806bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4807 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004808
4809 if (SubExpr->getType()->isRealFloatingType()) {
4810 Result.makeComplexFloat();
4811 APFloat &Imag = Result.FloatImag;
4812 if (!EvaluateFloat(SubExpr, Imag, Info))
4813 return false;
4814
4815 Result.FloatReal = APFloat(Imag.getSemantics());
4816 return true;
4817 } else {
4818 assert(SubExpr->getType()->isIntegerType() &&
4819 "Unexpected imaginary literal.");
4820
4821 Result.makeComplexInt();
4822 APSInt &Imag = Result.IntImag;
4823 if (!EvaluateInteger(SubExpr, Imag, Info))
4824 return false;
4825
4826 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4827 return true;
4828 }
4829}
4830
Peter Collingbournee9200682011-05-13 03:29:01 +00004831bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004832
John McCallfcef3cf2010-12-14 17:51:41 +00004833 switch (E->getCastKind()) {
4834 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004835 case CK_BaseToDerived:
4836 case CK_DerivedToBase:
4837 case CK_UncheckedDerivedToBase:
4838 case CK_Dynamic:
4839 case CK_ToUnion:
4840 case CK_ArrayToPointerDecay:
4841 case CK_FunctionToPointerDecay:
4842 case CK_NullToPointer:
4843 case CK_NullToMemberPointer:
4844 case CK_BaseToDerivedMemberPointer:
4845 case CK_DerivedToBaseMemberPointer:
4846 case CK_MemberPointerToBoolean:
4847 case CK_ConstructorConversion:
4848 case CK_IntegralToPointer:
4849 case CK_PointerToIntegral:
4850 case CK_PointerToBoolean:
4851 case CK_ToVoid:
4852 case CK_VectorSplat:
4853 case CK_IntegralCast:
4854 case CK_IntegralToBoolean:
4855 case CK_IntegralToFloating:
4856 case CK_FloatingToIntegral:
4857 case CK_FloatingToBoolean:
4858 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004859 case CK_CPointerToObjCPointerCast:
4860 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004861 case CK_AnyPointerToBlockPointerCast:
4862 case CK_ObjCObjectLValueCast:
4863 case CK_FloatingComplexToReal:
4864 case CK_FloatingComplexToBoolean:
4865 case CK_IntegralComplexToReal:
4866 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004867 case CK_ARCProduceObject:
4868 case CK_ARCConsumeObject:
4869 case CK_ARCReclaimReturnedObject:
4870 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004871 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004872
John McCallfcef3cf2010-12-14 17:51:41 +00004873 case CK_LValueToRValue:
4874 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004875 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004876
4877 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004878 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004879 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004880 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004881
4882 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004883 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004884 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004885 return false;
4886
John McCallfcef3cf2010-12-14 17:51:41 +00004887 Result.makeComplexFloat();
4888 Result.FloatImag = APFloat(Real.getSemantics());
4889 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004890 }
4891
John McCallfcef3cf2010-12-14 17:51:41 +00004892 case CK_FloatingComplexCast: {
4893 if (!Visit(E->getSubExpr()))
4894 return false;
4895
4896 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4897 QualType From
4898 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4899
Richard Smith357362d2011-12-13 06:39:58 +00004900 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4901 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004902 }
4903
4904 case CK_FloatingComplexToIntegralComplex: {
4905 if (!Visit(E->getSubExpr()))
4906 return false;
4907
4908 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4909 QualType From
4910 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4911 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004912 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4913 To, Result.IntReal) &&
4914 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4915 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004916 }
4917
4918 case CK_IntegralRealToComplex: {
4919 APSInt &Real = Result.IntReal;
4920 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4921 return false;
4922
4923 Result.makeComplexInt();
4924 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4925 return true;
4926 }
4927
4928 case CK_IntegralComplexCast: {
4929 if (!Visit(E->getSubExpr()))
4930 return false;
4931
4932 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4933 QualType From
4934 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4935
4936 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4937 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4938 return true;
4939 }
4940
4941 case CK_IntegralComplexToFloatingComplex: {
4942 if (!Visit(E->getSubExpr()))
4943 return false;
4944
4945 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4946 QualType From
4947 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4948 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00004949 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4950 To, Result.FloatReal) &&
4951 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4952 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004953 }
4954 }
4955
4956 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004957 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004958}
4959
John McCall93d91dc2010-05-07 17:22:02 +00004960bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004961 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004962 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4963
John McCall93d91dc2010-05-07 17:22:02 +00004964 if (!Visit(E->getLHS()))
4965 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004966
John McCall93d91dc2010-05-07 17:22:02 +00004967 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004968 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004969 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004970
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004971 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4972 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004973 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004974 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004975 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004976 if (Result.isComplexFloat()) {
4977 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4978 APFloat::rmNearestTiesToEven);
4979 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4980 APFloat::rmNearestTiesToEven);
4981 } else {
4982 Result.getComplexIntReal() += RHS.getComplexIntReal();
4983 Result.getComplexIntImag() += RHS.getComplexIntImag();
4984 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004985 break;
John McCalle3027922010-08-25 11:45:40 +00004986 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004987 if (Result.isComplexFloat()) {
4988 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4989 APFloat::rmNearestTiesToEven);
4990 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4991 APFloat::rmNearestTiesToEven);
4992 } else {
4993 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4994 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4995 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004996 break;
John McCalle3027922010-08-25 11:45:40 +00004997 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004998 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004999 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005000 APFloat &LHS_r = LHS.getComplexFloatReal();
5001 APFloat &LHS_i = LHS.getComplexFloatImag();
5002 APFloat &RHS_r = RHS.getComplexFloatReal();
5003 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00005004
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005005 APFloat Tmp = LHS_r;
5006 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5007 Result.getComplexFloatReal() = Tmp;
5008 Tmp = LHS_i;
5009 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5010 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5011
5012 Tmp = LHS_r;
5013 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5014 Result.getComplexFloatImag() = Tmp;
5015 Tmp = LHS_i;
5016 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5017 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5018 } else {
John McCall93d91dc2010-05-07 17:22:02 +00005019 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00005020 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005021 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5022 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00005023 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005024 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5025 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5026 }
5027 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005028 case BO_Div:
5029 if (Result.isComplexFloat()) {
5030 ComplexValue LHS = Result;
5031 APFloat &LHS_r = LHS.getComplexFloatReal();
5032 APFloat &LHS_i = LHS.getComplexFloatImag();
5033 APFloat &RHS_r = RHS.getComplexFloatReal();
5034 APFloat &RHS_i = RHS.getComplexFloatImag();
5035 APFloat &Res_r = Result.getComplexFloatReal();
5036 APFloat &Res_i = Result.getComplexFloatImag();
5037
5038 APFloat Den = RHS_r;
5039 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5040 APFloat Tmp = RHS_i;
5041 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5042 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5043
5044 Res_r = LHS_r;
5045 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5046 Tmp = LHS_i;
5047 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5048 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5049 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5050
5051 Res_i = LHS_i;
5052 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5053 Tmp = LHS_r;
5054 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5055 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5056 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5057 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005058 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5059 return Error(E, diag::note_expr_divide_by_zero);
5060
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005061 ComplexValue LHS = Result;
5062 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5063 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5064 Result.getComplexIntReal() =
5065 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5066 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5067 Result.getComplexIntImag() =
5068 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5069 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5070 }
5071 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005072 }
5073
John McCall93d91dc2010-05-07 17:22:02 +00005074 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005075}
5076
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005077bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5078 // Get the operand value into 'Result'.
5079 if (!Visit(E->getSubExpr()))
5080 return false;
5081
5082 switch (E->getOpcode()) {
5083 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005084 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005085 case UO_Extension:
5086 return true;
5087 case UO_Plus:
5088 // The result is always just the subexpr.
5089 return true;
5090 case UO_Minus:
5091 if (Result.isComplexFloat()) {
5092 Result.getComplexFloatReal().changeSign();
5093 Result.getComplexFloatImag().changeSign();
5094 }
5095 else {
5096 Result.getComplexIntReal() = -Result.getComplexIntReal();
5097 Result.getComplexIntImag() = -Result.getComplexIntImag();
5098 }
5099 return true;
5100 case UO_Not:
5101 if (Result.isComplexFloat())
5102 Result.getComplexFloatImag().changeSign();
5103 else
5104 Result.getComplexIntImag() = -Result.getComplexIntImag();
5105 return true;
5106 }
5107}
5108
Anders Carlsson537969c2008-11-16 20:27:53 +00005109//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00005110// Void expression evaluation, primarily for a cast to void on the LHS of a
5111// comma operator
5112//===----------------------------------------------------------------------===//
5113
5114namespace {
5115class VoidExprEvaluator
5116 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5117public:
5118 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5119
5120 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00005121
5122 bool VisitCastExpr(const CastExpr *E) {
5123 switch (E->getCastKind()) {
5124 default:
5125 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5126 case CK_ToVoid:
5127 VisitIgnoredValue(E->getSubExpr());
5128 return true;
5129 }
5130 }
5131};
5132} // end anonymous namespace
5133
5134static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5135 assert(E->isRValue() && E->getType()->isVoidType());
5136 return VoidExprEvaluator(Info).Visit(E);
5137}
5138
5139//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00005140// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00005141//===----------------------------------------------------------------------===//
5142
Richard Smith0b0a0b62011-10-29 20:57:55 +00005143static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005144 // In C, function designators are not lvalues, but we evaluate them as if they
5145 // are.
5146 if (E->isGLValue() || E->getType()->isFunctionType()) {
5147 LValue LV;
5148 if (!EvaluateLValue(E, LV, Info))
5149 return false;
5150 LV.moveInto(Result);
5151 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005152 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005153 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005154 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005155 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005156 return false;
John McCall45d55e42010-05-07 21:00:08 +00005157 } else if (E->getType()->hasPointerRepresentation()) {
5158 LValue LV;
5159 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005160 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005161 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00005162 } else if (E->getType()->isRealFloatingType()) {
5163 llvm::APFloat F(0.0);
5164 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005165 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005166 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00005167 } else if (E->getType()->isAnyComplexType()) {
5168 ComplexValue C;
5169 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005170 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005171 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00005172 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00005173 MemberPtr P;
5174 if (!EvaluateMemberPointer(E, P, Info))
5175 return false;
5176 P.moveInto(Result);
5177 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00005178 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005179 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005180 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005181 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00005182 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005183 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00005184 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005185 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005186 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005187 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5188 return false;
5189 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00005190 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00005191 if (Info.getLangOpts().CPlusPlus0x)
5192 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5193 << E->getType();
5194 else
5195 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00005196 if (!EvaluateVoid(E, Info))
5197 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005198 } else if (Info.getLangOpts().CPlusPlus0x) {
5199 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5200 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005201 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00005202 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00005203 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005204 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005205
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00005206 return true;
5207}
5208
Richard Smithed5165f2011-11-04 05:33:44 +00005209/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5210/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5211/// since later initializers for an object can indirectly refer to subobjects
5212/// which were initialized earlier.
5213static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00005214 const LValue &This, const Expr *E,
5215 CheckConstantExpressionKind CCEK) {
Richard Smithfddd3842011-12-30 21:15:51 +00005216 if (!CheckLiteralType(Info, E))
5217 return false;
5218
5219 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00005220 // Evaluate arrays and record types in-place, so that later initializers can
5221 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00005222 if (E->getType()->isArrayType())
5223 return EvaluateArray(E, This, Result, Info);
5224 else if (E->getType()->isRecordType())
5225 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00005226 }
5227
5228 // For any other type, in-place evaluation is unimportant.
5229 CCValue CoreConstResult;
5230 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00005231 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00005232}
5233
Richard Smithf57d8cb2011-12-09 22:58:01 +00005234/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5235/// lvalue-to-rvalue cast if it is an lvalue.
5236static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00005237 if (!CheckLiteralType(Info, E))
5238 return false;
5239
Richard Smithf57d8cb2011-12-09 22:58:01 +00005240 CCValue Value;
5241 if (!::Evaluate(Value, Info, E))
5242 return false;
5243
5244 if (E->isGLValue()) {
5245 LValue LV;
5246 LV.setFrom(Value);
5247 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5248 return false;
5249 }
5250
5251 // Check this core constant expression is a constant expression, and if so,
5252 // convert it to one.
5253 return CheckConstantExpression(Info, E, Value, Result);
5254}
Richard Smith11562c52011-10-28 17:51:58 +00005255
Richard Smith7b553f12011-10-29 00:50:52 +00005256/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00005257/// any crazy technique (that has nothing to do with language standards) that
5258/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00005259/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5260/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00005261bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00005262 // Fast-path evaluations of integer literals, since we sometimes see files
5263 // containing vast quantities of these.
5264 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5265 Result.Val = APValue(APSInt(L->getValue(),
5266 L->getType()->isUnsignedIntegerType()));
5267 return true;
5268 }
5269
Richard Smith5686e752011-11-10 03:30:42 +00005270 // FIXME: Evaluating initializers for large arrays can cause performance
5271 // problems, and we don't use such values yet. Once we have a more efficient
5272 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00005273 // The same problem affects large records.
5274 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5275 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00005276 return false;
5277
Richard Smithd62306a2011-11-10 06:34:14 +00005278 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005279 EvalInfo Info(Ctx, Result);
5280 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00005281}
5282
Jay Foad39c79802011-01-12 09:06:06 +00005283bool Expr::EvaluateAsBooleanCondition(bool &Result,
5284 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005285 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00005286 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00005287 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00005288 Result);
John McCall1be1c632010-01-05 23:42:56 +00005289}
5290
Richard Smith5fab0c92011-12-28 19:48:30 +00005291bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5292 SideEffectsKind AllowSideEffects) const {
5293 if (!getType()->isIntegralOrEnumerationType())
5294 return false;
5295
Richard Smith11562c52011-10-28 17:51:58 +00005296 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00005297 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5298 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00005299 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005300
Richard Smith11562c52011-10-28 17:51:58 +00005301 Result = ExprResult.Val.getInt();
5302 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00005303}
5304
Jay Foad39c79802011-01-12 09:06:06 +00005305bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00005306 EvalInfo Info(Ctx, Result);
5307
John McCall45d55e42010-05-07 21:00:08 +00005308 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005309 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005310 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5311 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005312}
5313
Richard Smithd0b4dd62011-12-19 06:19:21 +00005314bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5315 const VarDecl *VD,
5316 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5317 Expr::EvalStatus EStatus;
5318 EStatus.Diag = &Notes;
5319
5320 EvalInfo InitInfo(Ctx, EStatus);
5321 InitInfo.setEvaluatingDecl(VD, Value);
5322
Richard Smithfddd3842011-12-30 21:15:51 +00005323 if (!CheckLiteralType(InitInfo, this))
5324 return false;
5325
Richard Smithd0b4dd62011-12-19 06:19:21 +00005326 LValue LVal;
5327 LVal.set(VD);
5328
Richard Smithfddd3842011-12-30 21:15:51 +00005329 // C++11 [basic.start.init]p2:
5330 // Variables with static storage duration or thread storage duration shall be
5331 // zero-initialized before any other initialization takes place.
5332 // This behavior is not present in C.
5333 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5334 !VD->getType()->isReferenceType()) {
5335 ImplicitValueInitExpr VIE(VD->getType());
5336 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5337 return false;
5338 }
5339
Richard Smithd0b4dd62011-12-19 06:19:21 +00005340 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5341 !EStatus.HasSideEffects;
5342}
5343
Richard Smith7b553f12011-10-29 00:50:52 +00005344/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5345/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005346bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005347 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005348 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005349}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005350
Jay Foad39c79802011-01-12 09:06:06 +00005351bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005352 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005353}
5354
Richard Smithcaf33902011-10-10 18:28:20 +00005355APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005356 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005357 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005358 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005359 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005360 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005361
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005362 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005363}
John McCall864e3962010-05-07 05:32:02 +00005364
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005365 bool Expr::EvalResult::isGlobalLValue() const {
5366 assert(Val.isLValue());
5367 return IsGlobalLValue(Val.getLValueBase());
5368 }
5369
5370
John McCall864e3962010-05-07 05:32:02 +00005371/// isIntegerConstantExpr - this recursive routine will test if an expression is
5372/// an integer constant expression.
5373
5374/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5375/// comma, etc
5376///
5377/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5378/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5379/// cast+dereference.
5380
5381// CheckICE - This function does the fundamental ICE checking: the returned
5382// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5383// Note that to reduce code duplication, this helper does no evaluation
5384// itself; the caller checks whether the expression is evaluatable, and
5385// in the rare cases where CheckICE actually cares about the evaluated
5386// value, it calls into Evalute.
5387//
5388// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005389// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005390// 1: This expression is not an ICE, but if it isn't evaluated, it's
5391// a legal subexpression for an ICE. This return value is used to handle
5392// the comma operator in C99 mode.
5393// 2: This expression is not an ICE, and is not a legal subexpression for one.
5394
Dan Gohman28ade552010-07-26 21:25:24 +00005395namespace {
5396
John McCall864e3962010-05-07 05:32:02 +00005397struct ICEDiag {
5398 unsigned Val;
5399 SourceLocation Loc;
5400
5401 public:
5402 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5403 ICEDiag() : Val(0) {}
5404};
5405
Dan Gohman28ade552010-07-26 21:25:24 +00005406}
5407
5408static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005409
5410static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5411 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005412 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005413 !EVResult.Val.isInt()) {
5414 return ICEDiag(2, E->getLocStart());
5415 }
5416 return NoDiag();
5417}
5418
5419static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5420 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005421 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005422 return ICEDiag(2, E->getLocStart());
5423 }
5424
5425 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005426#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005427#define STMT(Node, Base) case Expr::Node##Class:
5428#define EXPR(Node, Base)
5429#include "clang/AST/StmtNodes.inc"
5430 case Expr::PredefinedExprClass:
5431 case Expr::FloatingLiteralClass:
5432 case Expr::ImaginaryLiteralClass:
5433 case Expr::StringLiteralClass:
5434 case Expr::ArraySubscriptExprClass:
5435 case Expr::MemberExprClass:
5436 case Expr::CompoundAssignOperatorClass:
5437 case Expr::CompoundLiteralExprClass:
5438 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005439 case Expr::DesignatedInitExprClass:
5440 case Expr::ImplicitValueInitExprClass:
5441 case Expr::ParenListExprClass:
5442 case Expr::VAArgExprClass:
5443 case Expr::AddrLabelExprClass:
5444 case Expr::StmtExprClass:
5445 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005446 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005447 case Expr::CXXDynamicCastExprClass:
5448 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005449 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005450 case Expr::CXXNullPtrLiteralExprClass:
5451 case Expr::CXXThisExprClass:
5452 case Expr::CXXThrowExprClass:
5453 case Expr::CXXNewExprClass:
5454 case Expr::CXXDeleteExprClass:
5455 case Expr::CXXPseudoDestructorExprClass:
5456 case Expr::UnresolvedLookupExprClass:
5457 case Expr::DependentScopeDeclRefExprClass:
5458 case Expr::CXXConstructExprClass:
5459 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005460 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005461 case Expr::CXXTemporaryObjectExprClass:
5462 case Expr::CXXUnresolvedConstructExprClass:
5463 case Expr::CXXDependentScopeMemberExprClass:
5464 case Expr::UnresolvedMemberExprClass:
5465 case Expr::ObjCStringLiteralClass:
5466 case Expr::ObjCEncodeExprClass:
5467 case Expr::ObjCMessageExprClass:
5468 case Expr::ObjCSelectorExprClass:
5469 case Expr::ObjCProtocolExprClass:
5470 case Expr::ObjCIvarRefExprClass:
5471 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005472 case Expr::ObjCIsaExprClass:
5473 case Expr::ShuffleVectorExprClass:
5474 case Expr::BlockExprClass:
5475 case Expr::BlockDeclRefExprClass:
5476 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005477 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005478 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005479 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005480 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005481 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005482 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005483 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005484 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005485 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005486 return ICEDiag(2, E->getLocStart());
5487
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005488 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005489 case Expr::GNUNullExprClass:
5490 // GCC considers the GNU __null value to be an integral constant expression.
5491 return NoDiag();
5492
John McCall7c454bb2011-07-15 05:09:51 +00005493 case Expr::SubstNonTypeTemplateParmExprClass:
5494 return
5495 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5496
John McCall864e3962010-05-07 05:32:02 +00005497 case Expr::ParenExprClass:
5498 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005499 case Expr::GenericSelectionExprClass:
5500 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005501 case Expr::IntegerLiteralClass:
5502 case Expr::CharacterLiteralClass:
5503 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005504 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005505 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005506 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005507 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005508 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005509 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005510 return NoDiag();
5511 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005512 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005513 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5514 // constant expressions, but they can never be ICEs because an ICE cannot
5515 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005516 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005517 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005518 return CheckEvalInICE(E, Ctx);
5519 return ICEDiag(2, E->getLocStart());
5520 }
5521 case Expr::DeclRefExprClass:
5522 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5523 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005524 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005525 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5526
5527 // Parameter variables are never constants. Without this check,
5528 // getAnyInitializer() can find a default argument, which leads
5529 // to chaos.
5530 if (isa<ParmVarDecl>(D))
5531 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5532
5533 // C++ 7.1.5.1p2
5534 // A variable of non-volatile const-qualified integral or enumeration
5535 // type initialized by an ICE can be used in ICEs.
5536 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005537 if (!Dcl->getType()->isIntegralOrEnumerationType())
5538 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5539
Richard Smithd0b4dd62011-12-19 06:19:21 +00005540 const VarDecl *VD;
5541 // Look for a declaration of this variable that has an initializer, and
5542 // check whether it is an ICE.
5543 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5544 return NoDiag();
5545 else
5546 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005547 }
5548 }
5549 return ICEDiag(2, E->getLocStart());
5550 case Expr::UnaryOperatorClass: {
5551 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5552 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005553 case UO_PostInc:
5554 case UO_PostDec:
5555 case UO_PreInc:
5556 case UO_PreDec:
5557 case UO_AddrOf:
5558 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005559 // C99 6.6/3 allows increment and decrement within unevaluated
5560 // subexpressions of constant expressions, but they can never be ICEs
5561 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005562 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005563 case UO_Extension:
5564 case UO_LNot:
5565 case UO_Plus:
5566 case UO_Minus:
5567 case UO_Not:
5568 case UO_Real:
5569 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005570 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005571 }
5572
5573 // OffsetOf falls through here.
5574 }
5575 case Expr::OffsetOfExprClass: {
5576 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005577 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005578 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005579 // compliance: we should warn earlier for offsetof expressions with
5580 // array subscripts that aren't ICEs, and if the array subscripts
5581 // are ICEs, the value of the offsetof must be an integer constant.
5582 return CheckEvalInICE(E, Ctx);
5583 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005584 case Expr::UnaryExprOrTypeTraitExprClass: {
5585 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5586 if ((Exp->getKind() == UETT_SizeOf) &&
5587 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005588 return ICEDiag(2, E->getLocStart());
5589 return NoDiag();
5590 }
5591 case Expr::BinaryOperatorClass: {
5592 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5593 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005594 case BO_PtrMemD:
5595 case BO_PtrMemI:
5596 case BO_Assign:
5597 case BO_MulAssign:
5598 case BO_DivAssign:
5599 case BO_RemAssign:
5600 case BO_AddAssign:
5601 case BO_SubAssign:
5602 case BO_ShlAssign:
5603 case BO_ShrAssign:
5604 case BO_AndAssign:
5605 case BO_XorAssign:
5606 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005607 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5608 // constant expressions, but they can never be ICEs because an ICE cannot
5609 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005610 return ICEDiag(2, E->getLocStart());
5611
John McCalle3027922010-08-25 11:45:40 +00005612 case BO_Mul:
5613 case BO_Div:
5614 case BO_Rem:
5615 case BO_Add:
5616 case BO_Sub:
5617 case BO_Shl:
5618 case BO_Shr:
5619 case BO_LT:
5620 case BO_GT:
5621 case BO_LE:
5622 case BO_GE:
5623 case BO_EQ:
5624 case BO_NE:
5625 case BO_And:
5626 case BO_Xor:
5627 case BO_Or:
5628 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005629 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5630 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005631 if (Exp->getOpcode() == BO_Div ||
5632 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005633 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005634 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005635 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005636 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005637 if (REval == 0)
5638 return ICEDiag(1, E->getLocStart());
5639 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005640 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005641 if (LEval.isMinSignedValue())
5642 return ICEDiag(1, E->getLocStart());
5643 }
5644 }
5645 }
John McCalle3027922010-08-25 11:45:40 +00005646 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005647 if (Ctx.getLangOptions().C99) {
5648 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5649 // if it isn't evaluated.
5650 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5651 return ICEDiag(1, E->getLocStart());
5652 } else {
5653 // In both C89 and C++, commas in ICEs are illegal.
5654 return ICEDiag(2, E->getLocStart());
5655 }
5656 }
5657 if (LHSResult.Val >= RHSResult.Val)
5658 return LHSResult;
5659 return RHSResult;
5660 }
John McCalle3027922010-08-25 11:45:40 +00005661 case BO_LAnd:
5662 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005663 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5664 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5665 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5666 // Rare case where the RHS has a comma "side-effect"; we need
5667 // to actually check the condition to see whether the side
5668 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005669 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005670 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005671 return RHSResult;
5672 return NoDiag();
5673 }
5674
5675 if (LHSResult.Val >= RHSResult.Val)
5676 return LHSResult;
5677 return RHSResult;
5678 }
5679 }
5680 }
5681 case Expr::ImplicitCastExprClass:
5682 case Expr::CStyleCastExprClass:
5683 case Expr::CXXFunctionalCastExprClass:
5684 case Expr::CXXStaticCastExprClass:
5685 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005686 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005687 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005688 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005689 if (isa<ExplicitCastExpr>(E)) {
5690 if (const FloatingLiteral *FL
5691 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5692 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5693 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5694 APSInt IgnoredVal(DestWidth, !DestSigned);
5695 bool Ignored;
5696 // If the value does not fit in the destination type, the behavior is
5697 // undefined, so we are not required to treat it as a constant
5698 // expression.
5699 if (FL->getValue().convertToInteger(IgnoredVal,
5700 llvm::APFloat::rmTowardZero,
5701 &Ignored) & APFloat::opInvalidOp)
5702 return ICEDiag(2, E->getLocStart());
5703 return NoDiag();
5704 }
5705 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005706 switch (cast<CastExpr>(E)->getCastKind()) {
5707 case CK_LValueToRValue:
5708 case CK_NoOp:
5709 case CK_IntegralToBoolean:
5710 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005711 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005712 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005713 return ICEDiag(2, E->getLocStart());
5714 }
John McCall864e3962010-05-07 05:32:02 +00005715 }
John McCallc07a0c72011-02-17 10:25:35 +00005716 case Expr::BinaryConditionalOperatorClass: {
5717 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5718 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5719 if (CommonResult.Val == 2) return CommonResult;
5720 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5721 if (FalseResult.Val == 2) return FalseResult;
5722 if (CommonResult.Val == 1) return CommonResult;
5723 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005724 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005725 return FalseResult;
5726 }
John McCall864e3962010-05-07 05:32:02 +00005727 case Expr::ConditionalOperatorClass: {
5728 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5729 // If the condition (ignoring parens) is a __builtin_constant_p call,
5730 // then only the true side is actually considered in an integer constant
5731 // expression, and it is fully evaluated. This is an important GNU
5732 // extension. See GCC PR38377 for discussion.
5733 if (const CallExpr *CallCE
5734 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00005735 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5736 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00005737 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005738 if (CondResult.Val == 2)
5739 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005740
Richard Smithf57d8cb2011-12-09 22:58:01 +00005741 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5742 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005743
John McCall864e3962010-05-07 05:32:02 +00005744 if (TrueResult.Val == 2)
5745 return TrueResult;
5746 if (FalseResult.Val == 2)
5747 return FalseResult;
5748 if (CondResult.Val == 1)
5749 return CondResult;
5750 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5751 return NoDiag();
5752 // Rare case where the diagnostics depend on which side is evaluated
5753 // Note that if we get here, CondResult is 0, and at least one of
5754 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005755 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005756 return FalseResult;
5757 }
5758 return TrueResult;
5759 }
5760 case Expr::CXXDefaultArgExprClass:
5761 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5762 case Expr::ChooseExprClass: {
5763 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5764 }
5765 }
5766
5767 // Silence a GCC warning
5768 return ICEDiag(2, E->getLocStart());
5769}
5770
Richard Smithf57d8cb2011-12-09 22:58:01 +00005771/// Evaluate an expression as a C++11 integral constant expression.
5772static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5773 const Expr *E,
5774 llvm::APSInt *Value,
5775 SourceLocation *Loc) {
5776 if (!E->getType()->isIntegralOrEnumerationType()) {
5777 if (Loc) *Loc = E->getExprLoc();
5778 return false;
5779 }
5780
5781 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005782 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5783 Result.Diag = &Diags;
5784 EvalInfo Info(Ctx, Result);
5785
5786 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5787 if (!Diags.empty()) {
5788 IsICE = false;
5789 if (Loc) *Loc = Diags[0].first;
5790 } else if (!IsICE && Loc) {
5791 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005792 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005793
5794 if (!IsICE)
5795 return false;
5796
5797 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5798 if (Value) *Value = Result.Val.getInt();
5799 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005800}
5801
Richard Smith92b1ce02011-12-12 09:28:41 +00005802bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005803 if (Ctx.getLangOptions().CPlusPlus0x)
5804 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5805
John McCall864e3962010-05-07 05:32:02 +00005806 ICEDiag d = CheckICE(this, Ctx);
5807 if (d.Val != 0) {
5808 if (Loc) *Loc = d.Loc;
5809 return false;
5810 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005811 return true;
5812}
5813
5814bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5815 SourceLocation *Loc, bool isEvaluated) const {
5816 if (Ctx.getLangOptions().CPlusPlus0x)
5817 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5818
5819 if (!isIntegerConstantExpr(Ctx, Loc))
5820 return false;
5821 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005822 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005823 return true;
5824}