blob: 4aed81215c66fa28114909c58576794be5c1a73d [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) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000213
Richard Smithfec09922011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000217 }
Richard Smith96e0c102011-11-04 02:25:55 +0000218 SubobjectDesignator &getLValueDesignator() {
219 assert(getKind() == LValue);
220 return Designator;
221 }
222 const SubobjectDesignator &getLValueDesignator() const {
223 return const_cast<CCValue*>(this)->getLValueDesignator();
224 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000225 };
226
Richard Smith254a73d2011-10-28 22:34:42 +0000227 /// A stack frame in the constexpr call stack.
228 struct CallStackFrame {
229 EvalInfo &Info;
230
231 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000233
Richard Smithf6f003a2011-12-16 19:06:07 +0000234 /// CallLoc - The location of the call expression for this call.
235 SourceLocation CallLoc;
236
237 /// Callee - The function which was called.
238 const FunctionDecl *Callee;
239
Richard Smithd62306a2011-11-10 06:34:14 +0000240 /// This - The binding for the this pointer in this call, if any.
241 const LValue *This;
242
Richard Smith254a73d2011-10-28 22:34:42 +0000243 /// ParmBindings - Parameter bindings for this function call, indexed by
244 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000245 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000246
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000247 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
248 typedef MapTy::const_iterator temp_iterator;
249 /// Temporaries - Temporary lvalues materialized within this stack frame.
250 MapTy Temporaries;
251
Richard Smithf6f003a2011-12-16 19:06:07 +0000252 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
253 const FunctionDecl *Callee, const LValue *This,
Richard Smithd62306a2011-11-10 06:34:14 +0000254 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000255 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000256 };
257
Richard Smith92b1ce02011-12-12 09:28:41 +0000258 /// A partial diagnostic which we might know in advance that we are not going
259 /// to emit.
260 class OptionalDiagnostic {
261 PartialDiagnostic *Diag;
262
263 public:
264 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
265
266 template<typename T>
267 OptionalDiagnostic &operator<<(const T &v) {
268 if (Diag)
269 *Diag << v;
270 return *this;
271 }
272 };
273
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000274 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000275 ASTContext &Ctx;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000276
277 /// EvalStatus - Contains information about the evaluation.
278 Expr::EvalStatus &EvalStatus;
279
280 /// CurrentCall - The top of the constexpr call stack.
281 CallStackFrame *CurrentCall;
282
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000283 /// CallStackDepth - The number of calls in the call stack right now.
284 unsigned CallStackDepth;
285
286 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
287 /// OpaqueValues - Values used as the common expression in a
288 /// BinaryConditionalOperator.
289 MapTy OpaqueValues;
290
291 /// BottomFrame - The frame in which evaluation started. This must be
292 /// initialized last.
293 CallStackFrame BottomFrame;
294
Richard Smithd62306a2011-11-10 06:34:14 +0000295 /// EvaluatingDecl - This is the declaration whose initializer is being
296 /// evaluated, if any.
297 const VarDecl *EvaluatingDecl;
298
299 /// EvaluatingDeclValue - This is the value being constructed for the
300 /// declaration whose initializer is being evaluated, if any.
301 APValue *EvaluatingDeclValue;
302
Richard Smith357362d2011-12-13 06:39:58 +0000303 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
304 /// notes attached to it will also be stored, otherwise they will not be.
305 bool HasActiveDiagnostic;
306
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000307
308 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000309 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithf6f003a2011-12-16 19:06:07 +0000310 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
311 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000313 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
314 MapTy::const_iterator i = OpaqueValues.find(e);
315 if (i == OpaqueValues.end()) return 0;
316 return &i->second;
317 }
318
Richard Smithd62306a2011-11-10 06:34:14 +0000319 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
320 EvaluatingDecl = VD;
321 EvaluatingDeclValue = &Value;
322 }
323
Richard Smith9a568822011-11-21 19:36:32 +0000324 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
325
Richard Smith357362d2011-12-13 06:39:58 +0000326 bool CheckCallLimit(SourceLocation Loc) {
327 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
328 return true;
329 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
330 << getLangOpts().ConstexprCallDepth;
331 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000332 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000333
Richard Smith357362d2011-12-13 06:39:58 +0000334 private:
335 /// Add a diagnostic to the diagnostics list.
336 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
337 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
338 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
339 return EvalStatus.Diag->back().second;
340 }
341
Richard Smithf6f003a2011-12-16 19:06:07 +0000342 /// Add notes containing a call stack to the current point of evaluation.
343 void addCallStack(unsigned Limit);
344
Richard Smith357362d2011-12-13 06:39:58 +0000345 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000346 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
348 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000349 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000350 // If we have a prior diagnostic, it will be noting that the expression
351 // isn't a constant expression. This diagnostic is more important.
352 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000353 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000354 unsigned CallStackNotes = CallStackDepth - 1;
355 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
356 if (Limit)
357 CallStackNotes = std::min(CallStackNotes, Limit + 1);
358
Richard Smith357362d2011-12-13 06:39:58 +0000359 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000360 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000361 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
362 addDiag(Loc, DiagId);
363 addCallStack(Limit);
364 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000365 }
Richard Smith357362d2011-12-13 06:39:58 +0000366 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000367 return OptionalDiagnostic();
368 }
369
370 /// Diagnose that the evaluation does not produce a C++11 core constant
371 /// expression.
Richard Smithf2b681b2011-12-21 05:04:46 +0000372 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
373 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000374 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000375 // Don't override a previous diagnostic.
376 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
377 return OptionalDiagnostic();
Richard Smith357362d2011-12-13 06:39:58 +0000378 return Diag(Loc, DiagId, ExtraNotes);
379 }
380
381 /// Add a note to a prior diagnostic.
382 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
383 if (!HasActiveDiagnostic)
384 return OptionalDiagnostic();
385 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000386 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000387
388 /// Add a stack of notes to a prior diagnostic.
389 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
390 if (HasActiveDiagnostic) {
391 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
392 Diags.begin(), Diags.end());
393 }
394 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000395 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000396}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000397
Richard Smithf6f003a2011-12-16 19:06:07 +0000398CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
399 const FunctionDecl *Callee, const LValue *This,
400 const CCValue *Arguments)
401 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
402 This(This), Arguments(Arguments) {
403 Info.CurrentCall = this;
404 ++Info.CallStackDepth;
405}
406
407CallStackFrame::~CallStackFrame() {
408 assert(Info.CurrentCall == this && "calls retired out of order");
409 --Info.CallStackDepth;
410 Info.CurrentCall = Caller;
411}
412
413/// Produce a string describing the given constexpr call.
414static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
415 unsigned ArgIndex = 0;
416 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
417 !isa<CXXConstructorDecl>(Frame->Callee);
418
419 if (!IsMemberCall)
420 Out << *Frame->Callee << '(';
421
422 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
423 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
424 if (ArgIndex > IsMemberCall)
425 Out << ", ";
426
427 const ParmVarDecl *Param = *I;
428 const CCValue &Arg = Frame->Arguments[ArgIndex];
429 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
430 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
431 else {
432 // Deliberately slice off the frame to form an APValue we can print.
433 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
434 Arg.getLValueDesignator().Entries,
435 Arg.getLValueDesignator().OnePastTheEnd);
436 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
437 }
438
439 if (ArgIndex == 0 && IsMemberCall)
440 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000441 }
442
Richard Smithf6f003a2011-12-16 19:06:07 +0000443 Out << ')';
444}
445
446void EvalInfo::addCallStack(unsigned Limit) {
447 // Determine which calls to skip, if any.
448 unsigned ActiveCalls = CallStackDepth - 1;
449 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
450 if (Limit && Limit < ActiveCalls) {
451 SkipStart = Limit / 2 + Limit % 2;
452 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000453 }
454
Richard Smithf6f003a2011-12-16 19:06:07 +0000455 // Walk the call stack and add the diagnostics.
456 unsigned CallIdx = 0;
457 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
458 Frame = Frame->Caller, ++CallIdx) {
459 // Skip this call?
460 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
461 if (CallIdx == SkipStart) {
462 // Note that we're skipping calls.
463 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
464 << unsigned(ActiveCalls - Limit);
465 }
466 continue;
467 }
468
469 llvm::SmallVector<char, 128> Buffer;
470 llvm::raw_svector_ostream Out(Buffer);
471 describeCall(Frame, Out);
472 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
473 }
474}
475
476namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000477 struct ComplexValue {
478 private:
479 bool IsInt;
480
481 public:
482 APSInt IntReal, IntImag;
483 APFloat FloatReal, FloatImag;
484
485 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
486
487 void makeComplexFloat() { IsInt = false; }
488 bool isComplexFloat() const { return !IsInt; }
489 APFloat &getComplexFloatReal() { return FloatReal; }
490 APFloat &getComplexFloatImag() { return FloatImag; }
491
492 void makeComplexInt() { IsInt = true; }
493 bool isComplexInt() const { return IsInt; }
494 APSInt &getComplexIntReal() { return IntReal; }
495 APSInt &getComplexIntImag() { return IntImag; }
496
Richard Smith0b0a0b62011-10-29 20:57:55 +0000497 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000498 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000499 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000500 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000501 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000502 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000503 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000504 assert(v.isComplexFloat() || v.isComplexInt());
505 if (v.isComplexFloat()) {
506 makeComplexFloat();
507 FloatReal = v.getComplexFloatReal();
508 FloatImag = v.getComplexFloatImag();
509 } else {
510 makeComplexInt();
511 IntReal = v.getComplexIntReal();
512 IntImag = v.getComplexIntImag();
513 }
514 }
John McCall93d91dc2010-05-07 17:22:02 +0000515 };
John McCall45d55e42010-05-07 21:00:08 +0000516
517 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000518 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000519 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000520 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000521 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000522
Richard Smithce40ad62011-11-12 22:28:03 +0000523 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000524 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000525 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000526 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000527 SubobjectDesignator &getLValueDesignator() { return Designator; }
528 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000529
Richard Smith0b0a0b62011-10-29 20:57:55 +0000530 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000531 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000532 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000533 void setFrom(const CCValue &V) {
534 assert(V.isLValue());
535 Base = V.getLValueBase();
536 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000537 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000538 Designator = V.getLValueDesignator();
539 }
540
Richard Smithce40ad62011-11-12 22:28:03 +0000541 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
542 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000543 Offset = CharUnits::Zero();
544 Frame = F;
545 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000546 }
John McCall45d55e42010-05-07 21:00:08 +0000547 };
Richard Smith027bf112011-11-17 22:56:20 +0000548
549 struct MemberPtr {
550 MemberPtr() {}
551 explicit MemberPtr(const ValueDecl *Decl) :
552 DeclAndIsDerivedMember(Decl, false), Path() {}
553
554 /// The member or (direct or indirect) field referred to by this member
555 /// pointer, or 0 if this is a null member pointer.
556 const ValueDecl *getDecl() const {
557 return DeclAndIsDerivedMember.getPointer();
558 }
559 /// Is this actually a member of some type derived from the relevant class?
560 bool isDerivedMember() const {
561 return DeclAndIsDerivedMember.getInt();
562 }
563 /// Get the class which the declaration actually lives in.
564 const CXXRecordDecl *getContainingRecord() const {
565 return cast<CXXRecordDecl>(
566 DeclAndIsDerivedMember.getPointer()->getDeclContext());
567 }
568
569 void moveInto(CCValue &V) const {
570 V = CCValue(getDecl(), isDerivedMember(), Path);
571 }
572 void setFrom(const CCValue &V) {
573 assert(V.isMemberPointer());
574 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
575 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
576 Path.clear();
577 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
578 Path.insert(Path.end(), P.begin(), P.end());
579 }
580
581 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
582 /// whether the member is a member of some class derived from the class type
583 /// of the member pointer.
584 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
585 /// Path - The path of base/derived classes from the member declaration's
586 /// class (exclusive) to the class type of the member pointer (inclusive).
587 SmallVector<const CXXRecordDecl*, 4> Path;
588
589 /// Perform a cast towards the class of the Decl (either up or down the
590 /// hierarchy).
591 bool castBack(const CXXRecordDecl *Class) {
592 assert(!Path.empty());
593 const CXXRecordDecl *Expected;
594 if (Path.size() >= 2)
595 Expected = Path[Path.size() - 2];
596 else
597 Expected = getContainingRecord();
598 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
599 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
600 // if B does not contain the original member and is not a base or
601 // derived class of the class containing the original member, the result
602 // of the cast is undefined.
603 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
604 // (D::*). We consider that to be a language defect.
605 return false;
606 }
607 Path.pop_back();
608 return true;
609 }
610 /// Perform a base-to-derived member pointer cast.
611 bool castToDerived(const CXXRecordDecl *Derived) {
612 if (!getDecl())
613 return true;
614 if (!isDerivedMember()) {
615 Path.push_back(Derived);
616 return true;
617 }
618 if (!castBack(Derived))
619 return false;
620 if (Path.empty())
621 DeclAndIsDerivedMember.setInt(false);
622 return true;
623 }
624 /// Perform a derived-to-base member pointer cast.
625 bool castToBase(const CXXRecordDecl *Base) {
626 if (!getDecl())
627 return true;
628 if (Path.empty())
629 DeclAndIsDerivedMember.setInt(true);
630 if (isDerivedMember()) {
631 Path.push_back(Base);
632 return true;
633 }
634 return castBack(Base);
635 }
636 };
Richard Smith357362d2011-12-13 06:39:58 +0000637
638 /// Kinds of constant expression checking, for diagnostics.
639 enum CheckConstantExpressionKind {
640 CCEK_Constant, ///< A normal constant.
641 CCEK_ReturnValue, ///< A constexpr function return value.
642 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
643 };
John McCall93d91dc2010-05-07 17:22:02 +0000644}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000645
Richard Smith0b0a0b62011-10-29 20:57:55 +0000646static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000647static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +0000648 const LValue &This, const Expr *E,
649 CheckConstantExpressionKind CCEK
650 = CCEK_Constant);
John McCall45d55e42010-05-07 21:00:08 +0000651static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
652static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000653static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
654 EvalInfo &Info);
655static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000656static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000657static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000658 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000659static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000660static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000661
662//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000663// Misc utilities
664//===----------------------------------------------------------------------===//
665
Richard Smithd62306a2011-11-10 06:34:14 +0000666/// Should this call expression be treated as a string literal?
667static bool IsStringLiteralCall(const CallExpr *E) {
668 unsigned Builtin = E->isBuiltinCall();
669 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
670 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
671}
672
Richard Smithce40ad62011-11-12 22:28:03 +0000673static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000674 // C++11 [expr.const]p3 An address constant expression is a prvalue core
675 // constant expression of pointer type that evaluates to...
676
677 // ... a null pointer value, or a prvalue core constant expression of type
678 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000679 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000680
Richard Smithce40ad62011-11-12 22:28:03 +0000681 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
682 // ... the address of an object with static storage duration,
683 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
684 return VD->hasGlobalStorage();
685 // ... the address of a function,
686 return isa<FunctionDecl>(D);
687 }
688
689 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000690 switch (E->getStmtClass()) {
691 default:
692 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000693 case Expr::CompoundLiteralExprClass:
694 return cast<CompoundLiteralExpr>(E)->isFileScope();
695 // A string literal has static storage duration.
696 case Expr::StringLiteralClass:
697 case Expr::PredefinedExprClass:
698 case Expr::ObjCStringLiteralClass:
699 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000700 case Expr::CXXTypeidExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000701 return true;
702 case Expr::CallExprClass:
703 return IsStringLiteralCall(cast<CallExpr>(E));
704 // For GCC compatibility, &&label has static storage duration.
705 case Expr::AddrLabelExprClass:
706 return true;
707 // A Block literal expression may be used as the initialization value for
708 // Block variables at global or local static scope.
709 case Expr::BlockExprClass:
710 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
711 }
John McCall95007602010-05-10 23:27:23 +0000712}
713
Richard Smith80815602011-11-07 05:07:52 +0000714/// Check that this reference or pointer core constant expression is a valid
715/// value for a constant expression. Type T should be either LValue or CCValue.
716template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000717static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000718 const T &LVal, APValue &Value,
719 CheckConstantExpressionKind CCEK) {
720 APValue::LValueBase Base = LVal.getLValueBase();
721 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
722
723 if (!IsGlobalLValue(Base)) {
724 if (Info.getLangOpts().CPlusPlus0x) {
725 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
726 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
727 << E->isGLValue() << !Designator.Entries.empty()
728 << !!VD << CCEK << VD;
729 if (VD)
730 Info.Note(VD->getLocation(), diag::note_declared_at);
731 else
732 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
733 diag::note_constexpr_temporary_here);
734 } else {
Richard Smithf2b681b2011-12-21 05:04:46 +0000735 Info.Diag(E->getExprLoc());
Richard Smith357362d2011-12-13 06:39:58 +0000736 }
Richard Smith80815602011-11-07 05:07:52 +0000737 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000738 }
Richard Smith80815602011-11-07 05:07:52 +0000739
Richard Smith80815602011-11-07 05:07:52 +0000740 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000741 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000742 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith357362d2011-12-13 06:39:58 +0000743 // FIXME: This is not a core constant expression. We should have already
744 // produced a CCE diagnostic.
Richard Smith80815602011-11-07 05:07:52 +0000745 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
746 APValue::NoLValuePath());
747 return true;
748 }
749
Richard Smith357362d2011-12-13 06:39:58 +0000750 // Does this refer one past the end of some object?
751 // This is technically not an address constant expression nor a reference
752 // constant expression, but we allow it for address constant expressions.
753 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
754 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
755 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
756 << !Designator.Entries.empty() << !!VD << VD;
757 if (VD)
758 Info.Note(VD->getLocation(), diag::note_declared_at);
759 else
760 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
761 diag::note_constexpr_temporary_here);
762 return false;
763 }
764
Richard Smith80815602011-11-07 05:07:52 +0000765 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000766 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000767 return true;
768}
769
Richard Smithfddd3842011-12-30 21:15:51 +0000770/// Check that this core constant expression is of literal type, and if not,
771/// produce an appropriate diagnostic.
772static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
773 if (!E->isRValue() || E->getType()->isLiteralType())
774 return true;
775
776 // Prvalue constant expressions must be of literal types.
777 if (Info.getLangOpts().CPlusPlus0x)
778 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
779 << E->getType();
780 else
781 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
782 return false;
783}
784
Richard Smith0b0a0b62011-10-29 20:57:55 +0000785/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000786/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithfddd3842011-12-30 21:15:51 +0000787/// If not, report an appropriate diagnostic. Does not check that the expression
788/// is of literal type.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000789static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000790 const CCValue &CCValue, APValue &Value,
791 CheckConstantExpressionKind CCEK
792 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000793 if (!CCValue.isLValue()) {
794 Value = CCValue;
795 return true;
796 }
Richard Smith357362d2011-12-13 06:39:58 +0000797 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000798}
799
Richard Smith83c68212011-10-31 05:11:32 +0000800const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000801 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000802}
803
804static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000805 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000806}
807
Richard Smithcecf1842011-11-01 21:06:14 +0000808static bool IsWeakLValue(const LValue &Value) {
809 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000810 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000811}
812
Richard Smith027bf112011-11-17 22:56:20 +0000813static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000814 // A null base expression indicates a null pointer. These are always
815 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000816 if (!Value.getLValueBase()) {
817 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000818 return true;
819 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000820
John McCall95007602010-05-10 23:27:23 +0000821 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000822 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000823 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000824
Richard Smith027bf112011-11-17 22:56:20 +0000825 // We have a non-null base. These are generally known to be true, but if it's
826 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000827 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000828 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000829 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000830}
831
Richard Smith0b0a0b62011-10-29 20:57:55 +0000832static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000833 switch (Val.getKind()) {
834 case APValue::Uninitialized:
835 return false;
836 case APValue::Int:
837 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000838 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000839 case APValue::Float:
840 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000841 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000842 case APValue::ComplexInt:
843 Result = Val.getComplexIntReal().getBoolValue() ||
844 Val.getComplexIntImag().getBoolValue();
845 return true;
846 case APValue::ComplexFloat:
847 Result = !Val.getComplexFloatReal().isZero() ||
848 !Val.getComplexFloatImag().isZero();
849 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000850 case APValue::LValue:
851 return EvalPointerValueAsBool(Val, Result);
852 case APValue::MemberPointer:
853 Result = Val.getMemberPointerDecl();
854 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000855 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000856 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000857 case APValue::Struct:
858 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000859 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000860 }
861
Richard Smith11562c52011-10-28 17:51:58 +0000862 llvm_unreachable("unknown APValue kind");
863}
864
865static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
866 EvalInfo &Info) {
867 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000868 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000869 if (!Evaluate(Val, Info, E))
870 return false;
871 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000872}
873
Richard Smith357362d2011-12-13 06:39:58 +0000874template<typename T>
875static bool HandleOverflow(EvalInfo &Info, const Expr *E,
876 const T &SrcValue, QualType DestType) {
877 llvm::SmallVector<char, 32> Buffer;
878 SrcValue.toString(Buffer);
879 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
880 << StringRef(Buffer.data(), Buffer.size()) << DestType;
881 return false;
882}
883
884static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
885 QualType SrcType, const APFloat &Value,
886 QualType DestType, APSInt &Result) {
887 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000888 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000889 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000890
Richard Smith357362d2011-12-13 06:39:58 +0000891 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000892 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000893 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
894 & APFloat::opInvalidOp)
895 return HandleOverflow(Info, E, Value, DestType);
896 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000897}
898
Richard Smith357362d2011-12-13 06:39:58 +0000899static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
900 QualType SrcType, QualType DestType,
901 APFloat &Result) {
902 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000903 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000904 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
905 APFloat::rmNearestTiesToEven, &ignored)
906 & APFloat::opOverflow)
907 return HandleOverflow(Info, E, Value, DestType);
908 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000909}
910
Mike Stump11289f42009-09-09 15:08:12 +0000911static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000912 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000913 unsigned DestWidth = Ctx.getIntWidth(DestType);
914 APSInt Result = Value;
915 // Figure out if this is a truncate, extend or noop cast.
916 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000917 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000918 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000919 return Result;
920}
921
Richard Smith357362d2011-12-13 06:39:58 +0000922static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
923 QualType SrcType, const APSInt &Value,
924 QualType DestType, APFloat &Result) {
925 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
926 if (Result.convertFromAPInt(Value, Value.isSigned(),
927 APFloat::rmNearestTiesToEven)
928 & APFloat::opOverflow)
929 return HandleOverflow(Info, E, Value, DestType);
930 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000931}
932
Eli Friedman803acb32011-12-22 03:51:45 +0000933static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
934 llvm::APInt &Res) {
935 CCValue SVal;
936 if (!Evaluate(SVal, Info, E))
937 return false;
938 if (SVal.isInt()) {
939 Res = SVal.getInt();
940 return true;
941 }
942 if (SVal.isFloat()) {
943 Res = SVal.getFloat().bitcastToAPInt();
944 return true;
945 }
946 if (SVal.isVector()) {
947 QualType VecTy = E->getType();
948 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
949 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
950 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
951 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
952 Res = llvm::APInt::getNullValue(VecSize);
953 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
954 APValue &Elt = SVal.getVectorElt(i);
955 llvm::APInt EltAsInt;
956 if (Elt.isInt()) {
957 EltAsInt = Elt.getInt();
958 } else if (Elt.isFloat()) {
959 EltAsInt = Elt.getFloat().bitcastToAPInt();
960 } else {
961 // Don't try to handle vectors of anything other than int or float
962 // (not sure if it's possible to hit this case).
963 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
964 return false;
965 }
966 unsigned BaseEltSize = EltAsInt.getBitWidth();
967 if (BigEndian)
968 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
969 else
970 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
971 }
972 return true;
973 }
974 // Give up if the input isn't an int, float, or vector. For example, we
975 // reject "(v4i16)(intptr_t)&a".
976 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
977 return false;
978}
979
Richard Smith027bf112011-11-17 22:56:20 +0000980static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
981 const CXXRecordDecl *&MostDerivedType,
982 unsigned &MostDerivedPathLength,
983 bool &MostDerivedIsArrayElement) {
984 const SubobjectDesignator &D = LVal.Designator;
985 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000986 return false;
987
Richard Smith027bf112011-11-17 22:56:20 +0000988 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000989
990 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000991 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000992 MostDerivedPathLength = 0;
993 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000994
995 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
996 bool IsArray = T && T->isArrayType();
997 if (IsArray)
998 T = T->getBaseElementTypeUnsafe();
999 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
1000 T = FD->getType().getTypePtr();
1001 else
1002 T = 0;
1003
1004 if (T) {
1005 MostDerivedType = T->getAsCXXRecordDecl();
1006 MostDerivedPathLength = I + 1;
1007 MostDerivedIsArrayElement = IsArray;
1008 }
1009 }
1010
Richard Smithd62306a2011-11-10 06:34:14 +00001011 // (B*)&d + 1 has no most-derived object.
1012 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
1013 return false;
1014
Richard Smith027bf112011-11-17 22:56:20 +00001015 return MostDerivedType != 0;
1016}
1017
1018static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
1019 const RecordDecl *TruncatedType,
1020 unsigned TruncatedElements,
1021 bool IsArrayElement) {
1022 SubobjectDesignator &D = Result.Designator;
1023 const RecordDecl *RD = TruncatedType;
1024 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +00001025 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1026 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001027 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001028 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001029 else
Richard Smithd62306a2011-11-10 06:34:14 +00001030 Result.Offset -= Layout.getBaseClassOffset(Base);
1031 RD = Base;
1032 }
Richard Smith027bf112011-11-17 22:56:20 +00001033 D.Entries.resize(TruncatedElements);
1034 D.ArrayElement = IsArrayElement;
1035}
1036
1037/// If the given LValue refers to a base subobject of some object, find the most
1038/// derived object and the corresponding complete record type. This is necessary
1039/// in order to find the offset of a virtual base class.
1040static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
1041 const CXXRecordDecl *&MostDerivedType) {
1042 unsigned MostDerivedPathLength;
1043 bool MostDerivedIsArrayElement;
1044 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1045 MostDerivedPathLength, MostDerivedIsArrayElement))
1046 return false;
1047
1048 // Remove the trailing base class path entries and their offsets.
1049 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
1050 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +00001051 return true;
1052}
1053
1054static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
1055 const CXXRecordDecl *Derived,
1056 const CXXRecordDecl *Base,
1057 const ASTRecordLayout *RL = 0) {
1058 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1059 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1060 Obj.Designator.addDecl(Base, /*Virtual*/ false);
1061}
1062
1063static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1064 const CXXRecordDecl *DerivedDecl,
1065 const CXXBaseSpecifier *Base) {
1066 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1067
1068 if (!Base->isVirtual()) {
1069 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1070 return true;
1071 }
1072
1073 // Extract most-derived object and corresponding type.
1074 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1075 return false;
1076
1077 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1078 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1079 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1080 return true;
1081}
1082
1083/// Update LVal to refer to the given field, which must be a member of the type
1084/// currently described by LVal.
1085static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1086 const FieldDecl *FD,
1087 const ASTRecordLayout *RL = 0) {
1088 if (!RL)
1089 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1090
1091 unsigned I = FD->getFieldIndex();
1092 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1093 LVal.Designator.addDecl(FD);
1094}
1095
1096/// Get the size of the given type in char units.
1097static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1098 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1099 // extension.
1100 if (Type->isVoidType() || Type->isFunctionType()) {
1101 Size = CharUnits::One();
1102 return true;
1103 }
1104
1105 if (!Type->isConstantSizeType()) {
1106 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1107 return false;
1108 }
1109
1110 Size = Info.Ctx.getTypeSizeInChars(Type);
1111 return true;
1112}
1113
1114/// Update a pointer value to model pointer arithmetic.
1115/// \param Info - Information about the ongoing evaluation.
1116/// \param LVal - The pointer value to be updated.
1117/// \param EltTy - The pointee type represented by LVal.
1118/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1119static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1120 QualType EltTy, int64_t Adjustment) {
1121 CharUnits SizeOfPointee;
1122 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1123 return false;
1124
1125 // Compute the new offset in the appropriate width.
1126 LVal.Offset += Adjustment * SizeOfPointee;
1127 LVal.Designator.adjustIndex(Adjustment);
1128 return true;
1129}
1130
Richard Smith27908702011-10-24 17:54:18 +00001131/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001132static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1133 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001134 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001135 // If this is a parameter to an active constexpr function call, perform
1136 // argument substitution.
1137 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001138 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001139 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001140 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001141 }
Richard Smithfec09922011-11-01 16:57:24 +00001142 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1143 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001144 }
Richard Smith27908702011-10-24 17:54:18 +00001145
Richard Smithd0b4dd62011-12-19 06:19:21 +00001146 // Dig out the initializer, and use the declaration which it's attached to.
1147 const Expr *Init = VD->getAnyInitializer(VD);
1148 if (!Init || Init->isValueDependent()) {
1149 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1150 return false;
1151 }
1152
Richard Smithd62306a2011-11-10 06:34:14 +00001153 // If we're currently evaluating the initializer of this declaration, use that
1154 // in-flight value.
1155 if (Info.EvaluatingDecl == VD) {
1156 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1157 return !Result.isUninit();
1158 }
1159
Richard Smithcecf1842011-11-01 21:06:14 +00001160 // Never evaluate the initializer of a weak variable. We can't be sure that
1161 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001162 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001163 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001164 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001165 }
Richard Smithcecf1842011-11-01 21:06:14 +00001166
Richard Smithd0b4dd62011-12-19 06:19:21 +00001167 // Check that we can fold the initializer. In C++, we will have already done
1168 // this in the cases where it matters for conformance.
1169 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1170 if (!VD->evaluateValue(Notes)) {
1171 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1172 Notes.size() + 1) << VD;
1173 Info.Note(VD->getLocation(), diag::note_declared_at);
1174 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001175 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001176 } else if (!VD->checkInitIsICE()) {
1177 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1178 Notes.size() + 1) << VD;
1179 Info.Note(VD->getLocation(), diag::note_declared_at);
1180 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001181 }
Richard Smith27908702011-10-24 17:54:18 +00001182
Richard Smithd0b4dd62011-12-19 06:19:21 +00001183 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001184 return true;
Richard Smith27908702011-10-24 17:54:18 +00001185}
1186
Richard Smith11562c52011-10-28 17:51:58 +00001187static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001188 Qualifiers Quals = T.getQualifiers();
1189 return Quals.hasConst() && !Quals.hasVolatile();
1190}
1191
Richard Smithe97cbd72011-11-11 04:05:33 +00001192/// Get the base index of the given base class within an APValue representing
1193/// the given derived class.
1194static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1195 const CXXRecordDecl *Base) {
1196 Base = Base->getCanonicalDecl();
1197 unsigned Index = 0;
1198 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1199 E = Derived->bases_end(); I != E; ++I, ++Index) {
1200 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1201 return Index;
1202 }
1203
1204 llvm_unreachable("base class missing from derived class's bases list");
1205}
1206
Richard Smithf3e9e432011-11-07 09:22:26 +00001207/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001208static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1209 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001210 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001211 if (Sub.Invalid) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001212 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001213 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001214 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001215 if (Sub.OnePastTheEnd) {
1216 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001217 (unsigned)diag::note_constexpr_read_past_end :
1218 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001219 return false;
1220 }
Richard Smith6804be52011-11-11 08:28:03 +00001221 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001222 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001223
1224 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1225 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001226 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001227 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001228 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001229 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001230 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001231 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001232 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001233 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001234 // Note, it should not be possible to form a pointer with a valid
1235 // designator which points more than one past the end of the array.
1236 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001237 (unsigned)diag::note_constexpr_read_past_end :
1238 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001239 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001240 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001241 if (O->getArrayInitializedElts() > Index)
1242 O = &O->getArrayInitializedElt(Index);
1243 else
1244 O = &O->getArrayFiller();
1245 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001246 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1247 // Next subobject is a class, struct or union field.
1248 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1249 if (RD->isUnion()) {
1250 const FieldDecl *UnionField = O->getUnionField();
1251 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001252 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001253 Info.Diag(E->getExprLoc(),
1254 diag::note_constexpr_read_inactive_union_member)
1255 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001256 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001257 }
Richard Smithd62306a2011-11-10 06:34:14 +00001258 O = &O->getUnionValue();
1259 } else
1260 O = &O->getStructField(Field->getFieldIndex());
1261 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001262
1263 if (ObjType.isVolatileQualified()) {
1264 if (Info.getLangOpts().CPlusPlus) {
1265 // FIXME: Include a description of the path to the volatile subobject.
1266 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1267 << 2 << Field;
1268 Info.Note(Field->getLocation(), diag::note_declared_at);
1269 } else {
1270 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1271 }
1272 return false;
1273 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001274 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001275 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001276 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1277 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1278 O = &O->getStructBase(getBaseIndex(Derived, Base));
1279 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001280 }
Richard Smithd62306a2011-11-10 06:34:14 +00001281
Richard Smithf57d8cb2011-12-09 22:58:01 +00001282 if (O->isUninit()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001283 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001284 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001285 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001286 }
1287
Richard Smithf3e9e432011-11-07 09:22:26 +00001288 Obj = CCValue(*O, CCValue::GlobalValue());
1289 return true;
1290}
1291
Richard Smithd62306a2011-11-10 06:34:14 +00001292/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1293/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1294/// for looking up the glvalue referred to by an entity of reference type.
1295///
1296/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001297/// \param Conv - The expression for which we are performing the conversion.
1298/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001299/// \param Type - The type we expect this conversion to produce.
1300/// \param LVal - The glvalue on which we are attempting to perform this action.
1301/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001302static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1303 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001304 const LValue &LVal, CCValue &RVal) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001305 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1306 if (!Info.getLangOpts().CPlusPlus)
1307 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1308
Richard Smithce40ad62011-11-12 22:28:03 +00001309 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001310 CallStackFrame *Frame = LVal.Frame;
Richard Smithf2b681b2011-12-21 05:04:46 +00001311 SourceLocation Loc = Conv->getExprLoc();
Richard Smith11562c52011-10-28 17:51:58 +00001312
Richard Smithf57d8cb2011-12-09 22:58:01 +00001313 if (!LVal.Base) {
1314 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithf2b681b2011-12-21 05:04:46 +00001315 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1316 return false;
1317 }
1318
1319 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1320 // is not a constant expression (even if the object is non-volatile). We also
1321 // apply this rule to C++98, in order to conform to the expected 'volatile'
1322 // semantics.
1323 if (Type.isVolatileQualified()) {
1324 if (Info.getLangOpts().CPlusPlus)
1325 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1326 else
1327 Info.Diag(Loc);
Richard Smith11562c52011-10-28 17:51:58 +00001328 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001329 }
Richard Smith11562c52011-10-28 17:51:58 +00001330
Richard Smithce40ad62011-11-12 22:28:03 +00001331 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001332 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1333 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001334 // expressions are constant expressions too. Inside constexpr functions,
1335 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001336 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001337 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001338 if (!VD || VD->isInvalidDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001339 Info.Diag(Loc);
Richard Smith96e0c102011-11-04 02:25:55 +00001340 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001341 }
1342
Richard Smithf2b681b2011-12-21 05:04:46 +00001343 // DR1313: If the object is volatile-qualified but the glvalue was not,
1344 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001345 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001346 if (VT.isVolatileQualified()) {
1347 if (Info.getLangOpts().CPlusPlus) {
1348 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1349 Info.Note(VD->getLocation(), diag::note_declared_at);
1350 } else {
1351 Info.Diag(Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001352 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001353 return false;
1354 }
1355
1356 if (!isa<ParmVarDecl>(VD)) {
1357 if (VD->isConstexpr()) {
1358 // OK, we can read this variable.
1359 } else if (VT->isIntegralOrEnumerationType()) {
1360 if (!VT.isConstQualified()) {
1361 if (Info.getLangOpts().CPlusPlus) {
1362 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1363 Info.Note(VD->getLocation(), diag::note_declared_at);
1364 } else {
1365 Info.Diag(Loc);
1366 }
1367 return false;
1368 }
1369 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1370 // We support folding of const floating-point types, in order to make
1371 // static const data members of such types (supported as an extension)
1372 // more useful.
1373 if (Info.getLangOpts().CPlusPlus0x) {
1374 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1375 Info.Note(VD->getLocation(), diag::note_declared_at);
1376 } else {
1377 Info.CCEDiag(Loc);
1378 }
1379 } else {
1380 // FIXME: Allow folding of values of any literal type in all languages.
1381 if (Info.getLangOpts().CPlusPlus0x) {
1382 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1383 Info.Note(VD->getLocation(), diag::note_declared_at);
1384 } else {
1385 Info.Diag(Loc);
1386 }
Richard Smith96e0c102011-11-04 02:25:55 +00001387 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001388 }
Richard Smith96e0c102011-11-04 02:25:55 +00001389 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001390
Richard Smithf57d8cb2011-12-09 22:58:01 +00001391 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001392 return false;
1393
Richard Smith0b0a0b62011-10-29 20:57:55 +00001394 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001395 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001396
1397 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1398 // conversion. This happens when the declaration and the lvalue should be
1399 // considered synonymous, for instance when initializing an array of char
1400 // from a string literal. Continue as if the initializer lvalue was the
1401 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001402 assert(RVal.getLValueOffset().isZero() &&
1403 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001404 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001405 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001406 }
1407
Richard Smithf2b681b2011-12-21 05:04:46 +00001408 // Volatile temporary objects cannot be read in constant expressions.
1409 if (Base->getType().isVolatileQualified()) {
1410 if (Info.getLangOpts().CPlusPlus) {
1411 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1412 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1413 } else {
1414 Info.Diag(Loc);
1415 }
1416 return false;
1417 }
1418
Richard Smith96e0c102011-11-04 02:25:55 +00001419 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1420 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1421 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001422 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001423 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001424 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001425 }
Richard Smith96e0c102011-11-04 02:25:55 +00001426
1427 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001428 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf2b681b2011-12-21 05:04:46 +00001429 const ConstantArrayType *CAT =
1430 Info.Ctx.getAsConstantArrayType(S->getType());
1431 if (Index >= CAT->getSize().getZExtValue()) {
1432 // Note, it should not be possible to form a pointer which points more
1433 // than one past the end of the array without producing a prior const expr
1434 // diagnostic.
1435 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith96e0c102011-11-04 02:25:55 +00001436 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001437 }
Richard Smith96e0c102011-11-04 02:25:55 +00001438 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1439 Type->isUnsignedIntegerType());
1440 if (Index < S->getLength())
1441 Value = S->getCodeUnit(Index);
1442 RVal = CCValue(Value);
1443 return true;
1444 }
1445
Richard Smithf3e9e432011-11-07 09:22:26 +00001446 if (Frame) {
1447 // If this is a temporary expression with a nontrivial initializer, grab the
1448 // value from the relevant stack frame.
1449 RVal = Frame->Temporaries[Base];
1450 } else if (const CompoundLiteralExpr *CLE
1451 = dyn_cast<CompoundLiteralExpr>(Base)) {
1452 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1453 // initializer until now for such expressions. Such an expression can't be
1454 // an ICE in C, so this only matters for fold.
1455 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1456 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1457 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001458 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001459 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001460 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001461 }
Richard Smith96e0c102011-11-04 02:25:55 +00001462
Richard Smithf57d8cb2011-12-09 22:58:01 +00001463 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1464 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001465}
1466
Richard Smithe97cbd72011-11-11 04:05:33 +00001467/// Build an lvalue for the object argument of a member function call.
1468static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1469 LValue &This) {
1470 if (Object->getType()->isPointerType())
1471 return EvaluatePointer(Object, This, Info);
1472
1473 if (Object->isGLValue())
1474 return EvaluateLValue(Object, This, Info);
1475
Richard Smith027bf112011-11-17 22:56:20 +00001476 if (Object->getType()->isLiteralType())
1477 return EvaluateTemporary(Object, This, Info);
1478
1479 return false;
1480}
1481
1482/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1483/// lvalue referring to the result.
1484///
1485/// \param Info - Information about the ongoing evaluation.
1486/// \param BO - The member pointer access operation.
1487/// \param LV - Filled in with a reference to the resulting object.
1488/// \param IncludeMember - Specifies whether the member itself is included in
1489/// the resulting LValue subobject designator. This is not possible when
1490/// creating a bound member function.
1491/// \return The field or method declaration to which the member pointer refers,
1492/// or 0 if evaluation fails.
1493static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1494 const BinaryOperator *BO,
1495 LValue &LV,
1496 bool IncludeMember = true) {
1497 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1498
1499 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1500 return 0;
1501
1502 MemberPtr MemPtr;
1503 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1504 return 0;
1505
1506 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1507 // member value, the behavior is undefined.
1508 if (!MemPtr.getDecl())
1509 return 0;
1510
1511 if (MemPtr.isDerivedMember()) {
1512 // This is a member of some derived class. Truncate LV appropriately.
1513 const CXXRecordDecl *MostDerivedType;
1514 unsigned MostDerivedPathLength;
1515 bool MostDerivedIsArrayElement;
1516 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1517 MostDerivedIsArrayElement))
1518 return 0;
1519
1520 // The end of the derived-to-base path for the base object must match the
1521 // derived-to-base path for the member pointer.
1522 if (MostDerivedPathLength + MemPtr.Path.size() >
1523 LV.Designator.Entries.size())
1524 return 0;
1525 unsigned PathLengthToMember =
1526 LV.Designator.Entries.size() - MemPtr.Path.size();
1527 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1528 const CXXRecordDecl *LVDecl = getAsBaseClass(
1529 LV.Designator.Entries[PathLengthToMember + I]);
1530 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1531 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1532 return 0;
1533 }
1534
1535 // Truncate the lvalue to the appropriate derived class.
1536 bool ResultIsArray = false;
1537 if (PathLengthToMember == MostDerivedPathLength)
1538 ResultIsArray = MostDerivedIsArrayElement;
1539 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1540 PathLengthToMember, ResultIsArray);
1541 } else if (!MemPtr.Path.empty()) {
1542 // Extend the LValue path with the member pointer's path.
1543 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1544 MemPtr.Path.size() + IncludeMember);
1545
1546 // Walk down to the appropriate base class.
1547 QualType LVType = BO->getLHS()->getType();
1548 if (const PointerType *PT = LVType->getAs<PointerType>())
1549 LVType = PT->getPointeeType();
1550 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1551 assert(RD && "member pointer access on non-class-type expression");
1552 // The first class in the path is that of the lvalue.
1553 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1554 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1555 HandleLValueDirectBase(Info, LV, RD, Base);
1556 RD = Base;
1557 }
1558 // Finally cast to the class containing the member.
1559 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1560 }
1561
1562 // Add the member. Note that we cannot build bound member functions here.
1563 if (IncludeMember) {
1564 // FIXME: Deal with IndirectFieldDecls.
1565 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1566 if (!FD) return 0;
1567 HandleLValueMember(Info, LV, FD);
1568 }
1569
1570 return MemPtr.getDecl();
1571}
1572
1573/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1574/// the provided lvalue, which currently refers to the base object.
1575static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1576 LValue &Result) {
1577 const CXXRecordDecl *MostDerivedType;
1578 unsigned MostDerivedPathLength;
1579 bool MostDerivedIsArrayElement;
1580
1581 // Check this cast doesn't take us outside the object.
1582 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1583 MostDerivedPathLength,
1584 MostDerivedIsArrayElement))
1585 return false;
1586 SubobjectDesignator &D = Result.Designator;
1587 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1588 return false;
1589
1590 // Check the type of the final cast. We don't need to check the path,
1591 // since a cast can only be formed if the path is unique.
1592 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1593 bool ResultIsArray = false;
1594 QualType TargetQT = E->getType();
1595 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1596 TargetQT = PT->getPointeeType();
1597 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1598 const CXXRecordDecl *FinalType;
1599 if (NewEntriesSize == MostDerivedPathLength) {
1600 ResultIsArray = MostDerivedIsArrayElement;
1601 FinalType = MostDerivedType;
1602 } else
1603 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1604 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1605 return false;
1606
1607 // Truncate the lvalue to the appropriate derived class.
1608 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1609 ResultIsArray);
1610 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001611}
1612
Mike Stump876387b2009-10-27 22:09:17 +00001613namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001614enum EvalStmtResult {
1615 /// Evaluation failed.
1616 ESR_Failed,
1617 /// Hit a 'return' statement.
1618 ESR_Returned,
1619 /// Evaluation succeeded.
1620 ESR_Succeeded
1621};
1622}
1623
1624// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001625static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001626 const Stmt *S) {
1627 switch (S->getStmtClass()) {
1628 default:
1629 return ESR_Failed;
1630
1631 case Stmt::NullStmtClass:
1632 case Stmt::DeclStmtClass:
1633 return ESR_Succeeded;
1634
Richard Smith357362d2011-12-13 06:39:58 +00001635 case Stmt::ReturnStmtClass: {
1636 CCValue CCResult;
1637 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1638 if (!Evaluate(CCResult, Info, RetExpr) ||
1639 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1640 CCEK_ReturnValue))
1641 return ESR_Failed;
1642 return ESR_Returned;
1643 }
Richard Smith254a73d2011-10-28 22:34:42 +00001644
1645 case Stmt::CompoundStmtClass: {
1646 const CompoundStmt *CS = cast<CompoundStmt>(S);
1647 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1648 BE = CS->body_end(); BI != BE; ++BI) {
1649 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1650 if (ESR != ESR_Succeeded)
1651 return ESR;
1652 }
1653 return ESR_Succeeded;
1654 }
1655 }
1656}
1657
Richard Smithcc36f692011-12-22 02:22:31 +00001658/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1659/// default constructor. If so, we'll fold it whether or not it's marked as
1660/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1661/// so we need special handling.
1662static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00001663 const CXXConstructorDecl *CD,
1664 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00001665 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1666 return false;
1667
1668 if (!CD->isConstexpr()) {
1669 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smithfddd3842011-12-30 21:15:51 +00001670 // Value-initialization does not call a trivial default constructor, so
1671 // such a call is a core constant expression whether or not the
1672 // constructor is constexpr.
1673 if (!IsValueInitialization) {
1674 // FIXME: If DiagDecl is an implicitly-declared special member function,
1675 // we should be much more explicit about why it's not constexpr.
1676 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1677 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1678 Info.Note(CD->getLocation(), diag::note_declared_at);
1679 }
Richard Smithcc36f692011-12-22 02:22:31 +00001680 } else {
1681 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1682 }
1683 }
1684 return true;
1685}
1686
Richard Smith357362d2011-12-13 06:39:58 +00001687/// CheckConstexprFunction - Check that a function can be called in a constant
1688/// expression.
1689static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1690 const FunctionDecl *Declaration,
1691 const FunctionDecl *Definition) {
1692 // Can we evaluate this function call?
1693 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1694 return true;
1695
1696 if (Info.getLangOpts().CPlusPlus0x) {
1697 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001698 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1699 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001700 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1701 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1702 << DiagDecl;
1703 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1704 } else {
1705 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1706 }
1707 return false;
1708}
1709
Richard Smithd62306a2011-11-10 06:34:14 +00001710namespace {
Richard Smith60494462011-11-11 05:48:57 +00001711typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001712}
1713
1714/// EvaluateArgs - Evaluate the arguments to a function call.
1715static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1716 EvalInfo &Info) {
1717 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1718 I != E; ++I)
1719 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1720 return false;
1721 return true;
1722}
1723
Richard Smith254a73d2011-10-28 22:34:42 +00001724/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001725static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1726 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001727 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001728 EvalInfo &Info, APValue &Result) {
1729 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001730 return false;
1731
Richard Smithd62306a2011-11-10 06:34:14 +00001732 ArgVector ArgValues(Args.size());
1733 if (!EvaluateArgs(Args, ArgValues, Info))
1734 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001735
Richard Smithf6f003a2011-12-16 19:06:07 +00001736 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1737 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001738 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1739}
1740
Richard Smithd62306a2011-11-10 06:34:14 +00001741/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001742static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001743 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001744 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00001745 EvalInfo &Info, APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001746 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001747 return false;
1748
1749 ArgVector ArgValues(Args.size());
1750 if (!EvaluateArgs(Args, ArgValues, Info))
1751 return false;
1752
Richard Smithf6f003a2011-12-16 19:06:07 +00001753 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1754 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001755
1756 // If it's a delegating constructor, just delegate.
1757 if (Definition->isDelegatingConstructor()) {
1758 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1759 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1760 }
1761
1762 // Reserve space for the struct members.
1763 const CXXRecordDecl *RD = Definition->getParent();
Richard Smithfddd3842011-12-30 21:15:51 +00001764 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00001765 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1766 std::distance(RD->field_begin(), RD->field_end()));
1767
1768 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1769
1770 unsigned BasesSeen = 0;
1771#ifndef NDEBUG
1772 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1773#endif
1774 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1775 E = Definition->init_end(); I != E; ++I) {
1776 if ((*I)->isBaseInitializer()) {
1777 QualType BaseType((*I)->getBaseClass(), 0);
1778#ifndef NDEBUG
1779 // Non-virtual base classes are initialized in the order in the class
1780 // definition. We cannot have a virtual base class for a literal type.
1781 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1782 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1783 "base class initializers not in expected order");
1784 ++BaseIt;
1785#endif
1786 LValue Subobject = This;
1787 HandleLValueDirectBase(Info, Subobject, RD,
1788 BaseType->getAsCXXRecordDecl(), &Layout);
1789 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1790 Subobject, (*I)->getInit()))
1791 return false;
1792 } else if (FieldDecl *FD = (*I)->getMember()) {
1793 LValue Subobject = This;
1794 HandleLValueMember(Info, Subobject, FD, &Layout);
1795 if (RD->isUnion()) {
1796 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001797 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1798 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001799 return false;
1800 } else if (!EvaluateConstantExpression(
1801 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001802 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001803 return false;
1804 } else {
1805 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001806 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001807 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001808 return false;
1809 }
1810 }
1811
1812 return true;
1813}
1814
Richard Smith254a73d2011-10-28 22:34:42 +00001815namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001816class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001817 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001818 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001819public:
1820
Richard Smith725810a2011-10-16 21:26:27 +00001821 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001822
1823 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001824 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001825 return true;
1826 }
1827
Peter Collingbournee9200682011-05-13 03:29:01 +00001828 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1829 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001830 return Visit(E->getResultExpr());
1831 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001832 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001833 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001834 return true;
1835 return false;
1836 }
John McCall31168b02011-06-15 23:02:42 +00001837 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001838 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001839 return true;
1840 return false;
1841 }
1842 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001843 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001844 return true;
1845 return false;
1846 }
1847
Mike Stump876387b2009-10-27 22:09:17 +00001848 // We don't want to evaluate BlockExprs multiple times, as they generate
1849 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001850 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1851 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1852 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001853 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001854 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1855 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1856 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1857 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1858 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1859 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001860 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001861 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001862 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001863 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001864 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001865 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1866 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1867 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1868 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001869 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001870 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1871 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1872 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1873 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1874 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001875 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001876 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001877 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001878 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001879 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001880
1881 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001882 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001883 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1884 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001885 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001886 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001887 return false;
1888 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001889
Peter Collingbournee9200682011-05-13 03:29:01 +00001890 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001891};
1892
John McCallc07a0c72011-02-17 10:25:35 +00001893class OpaqueValueEvaluation {
1894 EvalInfo &info;
1895 OpaqueValueExpr *opaqueValue;
1896
1897public:
1898 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1899 Expr *value)
1900 : info(info), opaqueValue(opaqueValue) {
1901
1902 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001903 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001904 this->opaqueValue = 0;
1905 return;
1906 }
John McCallc07a0c72011-02-17 10:25:35 +00001907 }
1908
1909 bool hasError() const { return opaqueValue == 0; }
1910
1911 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001912 // FIXME: This will not work for recursive constexpr functions using opaque
1913 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001914 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1915 }
1916};
1917
Mike Stump876387b2009-10-27 22:09:17 +00001918} // end anonymous namespace
1919
Eli Friedman9a156e52008-11-12 09:44:48 +00001920//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001921// Generic Evaluation
1922//===----------------------------------------------------------------------===//
1923namespace {
1924
Richard Smithf57d8cb2011-12-09 22:58:01 +00001925// FIXME: RetTy is always bool. Remove it.
1926template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001927class ExprEvaluatorBase
1928 : public ConstStmtVisitor<Derived, RetTy> {
1929private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001930 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001931 return static_cast<Derived*>(this)->Success(V, E);
1932 }
Richard Smithfddd3842011-12-30 21:15:51 +00001933 RetTy DerivedZeroInitialization(const Expr *E) {
1934 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001935 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001936
1937protected:
1938 EvalInfo &Info;
1939 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1940 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1941
Richard Smith92b1ce02011-12-12 09:28:41 +00001942 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001943 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001944 }
1945
1946 /// Report an evaluation error. This should only be called when an error is
1947 /// first discovered. When propagating an error, just return false.
1948 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001949 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001950 return false;
1951 }
1952 bool Error(const Expr *E) {
1953 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1954 }
1955
Richard Smithfddd3842011-12-30 21:15:51 +00001956 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001957
Peter Collingbournee9200682011-05-13 03:29:01 +00001958public:
1959 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1960
1961 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001962 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001963 }
1964 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001965 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001966 }
1967
1968 RetTy VisitParenExpr(const ParenExpr *E)
1969 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1970 RetTy VisitUnaryExtension(const UnaryOperator *E)
1971 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1972 RetTy VisitUnaryPlus(const UnaryOperator *E)
1973 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1974 RetTy VisitChooseExpr(const ChooseExpr *E)
1975 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1976 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1977 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001978 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1979 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001980 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1981 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00001982 // We cannot create any objects for which cleanups are required, so there is
1983 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1984 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1985 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001986
Richard Smith6d6ecc32011-12-12 12:46:16 +00001987 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1988 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1989 return static_cast<Derived*>(this)->VisitCastExpr(E);
1990 }
1991 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1992 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1993 return static_cast<Derived*>(this)->VisitCastExpr(E);
1994 }
1995
Richard Smith027bf112011-11-17 22:56:20 +00001996 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1997 switch (E->getOpcode()) {
1998 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001999 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002000
2001 case BO_Comma:
2002 VisitIgnoredValue(E->getLHS());
2003 return StmtVisitorTy::Visit(E->getRHS());
2004
2005 case BO_PtrMemD:
2006 case BO_PtrMemI: {
2007 LValue Obj;
2008 if (!HandleMemberPointerAccess(Info, E, Obj))
2009 return false;
2010 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002011 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002012 return false;
2013 return DerivedSuccess(Result, E);
2014 }
2015 }
2016 }
2017
Peter Collingbournee9200682011-05-13 03:29:01 +00002018 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2019 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2020 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002021 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002022
2023 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00002024 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002025 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002026
2027 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2028 }
2029
2030 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2031 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002032 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002033 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002034
Richard Smith11562c52011-10-28 17:51:58 +00002035 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00002036 return StmtVisitorTy::Visit(EvalExpr);
2037 }
2038
2039 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002040 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002041 if (!Value) {
2042 const Expr *Source = E->getSourceExpr();
2043 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002044 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002045 if (Source == E) { // sanity checking.
2046 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002047 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002048 }
2049 return StmtVisitorTy::Visit(Source);
2050 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00002051 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002052 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002053
Richard Smith254a73d2011-10-28 22:34:42 +00002054 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002055 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002056 QualType CalleeType = Callee->getType();
2057
Richard Smith254a73d2011-10-28 22:34:42 +00002058 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002059 LValue *This = 0, ThisVal;
2060 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00002061
Richard Smithe97cbd72011-11-11 04:05:33 +00002062 // Extract function decl and 'this' pointer from the callee.
2063 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002064 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002065 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2066 // Explicit bound member calls, such as x.f() or p->g();
2067 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002068 return false;
2069 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002070 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002071 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2072 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002073 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2074 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002075 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002076 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002077 return Error(Callee);
2078
2079 FD = dyn_cast<FunctionDecl>(Member);
2080 if (!FD)
2081 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002082 } else if (CalleeType->isFunctionPointerType()) {
2083 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002084 if (!Evaluate(Call, Info, Callee))
2085 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002086
Richard Smithf57d8cb2011-12-09 22:58:01 +00002087 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
2088 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002089 FD = dyn_cast_or_null<FunctionDecl>(
2090 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002091 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002092 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002093
2094 // Overloaded operator calls to member functions are represented as normal
2095 // calls with '*this' as the first argument.
2096 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2097 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002098 // FIXME: When selecting an implicit conversion for an overloaded
2099 // operator delete, we sometimes try to evaluate calls to conversion
2100 // operators without a 'this' parameter!
2101 if (Args.empty())
2102 return Error(E);
2103
Richard Smithe97cbd72011-11-11 04:05:33 +00002104 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2105 return false;
2106 This = &ThisVal;
2107 Args = Args.slice(1);
2108 }
2109
2110 // Don't call function pointers which have been cast to some other type.
2111 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002112 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002113 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002114 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002115
Richard Smith357362d2011-12-13 06:39:58 +00002116 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002117 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002118 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002119
Richard Smith357362d2011-12-13 06:39:58 +00002120 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002121 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002122 return false;
2123
2124 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002125 }
2126
Richard Smith11562c52011-10-28 17:51:58 +00002127 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2128 return StmtVisitorTy::Visit(E->getInitializer());
2129 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002130 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002131 if (E->getNumInits() == 0)
2132 return DerivedZeroInitialization(E);
2133 if (E->getNumInits() == 1)
2134 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002135 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002136 }
2137 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002138 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002139 }
2140 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002141 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002142 }
Richard Smith027bf112011-11-17 22:56:20 +00002143 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002144 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002145 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002146
Richard Smithd62306a2011-11-10 06:34:14 +00002147 /// A member expression where the object is a prvalue is itself a prvalue.
2148 RetTy VisitMemberExpr(const MemberExpr *E) {
2149 assert(!E->isArrow() && "missing call to bound member function?");
2150
2151 CCValue Val;
2152 if (!Evaluate(Val, Info, E->getBase()))
2153 return false;
2154
2155 QualType BaseTy = E->getBase()->getType();
2156
2157 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002158 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002159 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2160 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2161 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2162
2163 SubobjectDesignator Designator;
2164 Designator.addDecl(FD);
2165
Richard Smithf57d8cb2011-12-09 22:58:01 +00002166 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002167 DerivedSuccess(Val, E);
2168 }
2169
Richard Smith11562c52011-10-28 17:51:58 +00002170 RetTy VisitCastExpr(const CastExpr *E) {
2171 switch (E->getCastKind()) {
2172 default:
2173 break;
2174
2175 case CK_NoOp:
2176 return StmtVisitorTy::Visit(E->getSubExpr());
2177
2178 case CK_LValueToRValue: {
2179 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002180 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2181 return false;
2182 CCValue RVal;
2183 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2184 return false;
2185 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002186 }
2187 }
2188
Richard Smithf57d8cb2011-12-09 22:58:01 +00002189 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002190 }
2191
Richard Smith4a678122011-10-24 18:44:57 +00002192 /// Visit a value which is evaluated, but whose value is ignored.
2193 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002194 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002195 if (!Evaluate(Scratch, Info, E))
2196 Info.EvalStatus.HasSideEffects = true;
2197 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002198};
2199
2200}
2201
2202//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002203// Common base class for lvalue and temporary evaluation.
2204//===----------------------------------------------------------------------===//
2205namespace {
2206template<class Derived>
2207class LValueExprEvaluatorBase
2208 : public ExprEvaluatorBase<Derived, bool> {
2209protected:
2210 LValue &Result;
2211 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2212 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2213
2214 bool Success(APValue::LValueBase B) {
2215 Result.set(B);
2216 return true;
2217 }
2218
2219public:
2220 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2221 ExprEvaluatorBaseTy(Info), Result(Result) {}
2222
2223 bool Success(const CCValue &V, const Expr *E) {
2224 Result.setFrom(V);
2225 return true;
2226 }
Richard Smith027bf112011-11-17 22:56:20 +00002227
2228 bool CheckValidLValue() {
2229 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2230 // there are no null references, nor once-past-the-end references.
2231 // FIXME: Check for one-past-the-end array indices
2232 return Result.Base && !Result.Designator.Invalid &&
2233 !Result.Designator.OnePastTheEnd;
2234 }
2235
2236 bool VisitMemberExpr(const MemberExpr *E) {
2237 // Handle non-static data members.
2238 QualType BaseTy;
2239 if (E->isArrow()) {
2240 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2241 return false;
2242 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002243 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002244 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002245 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2246 return false;
2247 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002248 } else {
2249 if (!this->Visit(E->getBase()))
2250 return false;
2251 BaseTy = E->getBase()->getType();
2252 }
2253 // FIXME: In C++11, require the result to be a valid lvalue.
2254
2255 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2256 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002257 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002258 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2259 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2260 (void)BaseTy;
2261
2262 HandleLValueMember(this->Info, Result, FD);
2263
2264 if (FD->getType()->isReferenceType()) {
2265 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002266 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002267 RefValue))
2268 return false;
2269 return Success(RefValue, E);
2270 }
2271 return true;
2272 }
2273
2274 bool VisitBinaryOperator(const BinaryOperator *E) {
2275 switch (E->getOpcode()) {
2276 default:
2277 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2278
2279 case BO_PtrMemD:
2280 case BO_PtrMemI:
2281 return HandleMemberPointerAccess(this->Info, E, Result);
2282 }
2283 }
2284
2285 bool VisitCastExpr(const CastExpr *E) {
2286 switch (E->getCastKind()) {
2287 default:
2288 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2289
2290 case CK_DerivedToBase:
2291 case CK_UncheckedDerivedToBase: {
2292 if (!this->Visit(E->getSubExpr()))
2293 return false;
2294 if (!CheckValidLValue())
2295 return false;
2296
2297 // Now figure out the necessary offset to add to the base LV to get from
2298 // the derived class to the base class.
2299 QualType Type = E->getSubExpr()->getType();
2300
2301 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2302 PathE = E->path_end(); PathI != PathE; ++PathI) {
2303 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2304 *PathI))
2305 return false;
2306 Type = (*PathI)->getType();
2307 }
2308
2309 return true;
2310 }
2311 }
2312 }
2313};
2314}
2315
2316//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002317// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002318//
2319// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2320// function designators (in C), decl references to void objects (in C), and
2321// temporaries (if building with -Wno-address-of-temporary).
2322//
2323// LValue evaluation produces values comprising a base expression of one of the
2324// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002325// - Declarations
2326// * VarDecl
2327// * FunctionDecl
2328// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002329// * CompoundLiteralExpr in C
2330// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002331// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002332// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002333// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002334// * ObjCEncodeExpr
2335// * AddrLabelExpr
2336// * BlockExpr
2337// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002338// - Locals and temporaries
2339// * Any Expr, with a Frame indicating the function in which the temporary was
2340// evaluated.
2341// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002342//===----------------------------------------------------------------------===//
2343namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002344class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002345 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002346public:
Richard Smith027bf112011-11-17 22:56:20 +00002347 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2348 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002349
Richard Smith11562c52011-10-28 17:51:58 +00002350 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2351
Peter Collingbournee9200682011-05-13 03:29:01 +00002352 bool VisitDeclRefExpr(const DeclRefExpr *E);
2353 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002354 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002355 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2356 bool VisitMemberExpr(const MemberExpr *E);
2357 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2358 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002359 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002360 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2361 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002362
Peter Collingbournee9200682011-05-13 03:29:01 +00002363 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002364 switch (E->getCastKind()) {
2365 default:
Richard Smith027bf112011-11-17 22:56:20 +00002366 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002367
Eli Friedmance3e02a2011-10-11 00:13:24 +00002368 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002369 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002370 if (!Visit(E->getSubExpr()))
2371 return false;
2372 Result.Designator.setInvalid();
2373 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002374
Richard Smith027bf112011-11-17 22:56:20 +00002375 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002376 if (!Visit(E->getSubExpr()))
2377 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002378 if (!CheckValidLValue())
2379 return false;
2380 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002381 }
2382 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002383
Eli Friedman449fe542009-03-23 04:56:01 +00002384 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002385
Eli Friedman9a156e52008-11-12 09:44:48 +00002386};
2387} // end anonymous namespace
2388
Richard Smith11562c52011-10-28 17:51:58 +00002389/// Evaluate an expression as an lvalue. This can be legitimately called on
2390/// expressions which are not glvalues, in a few cases:
2391/// * function designators in C,
2392/// * "extern void" objects,
2393/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002394static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002395 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2396 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2397 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002398 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002399}
2400
Peter Collingbournee9200682011-05-13 03:29:01 +00002401bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002402 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2403 return Success(FD);
2404 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002405 return VisitVarDecl(E, VD);
2406 return Error(E);
2407}
Richard Smith733237d2011-10-24 23:14:33 +00002408
Richard Smith11562c52011-10-28 17:51:58 +00002409bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002410 if (!VD->getType()->isReferenceType()) {
2411 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002412 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002413 return true;
2414 }
Richard Smithce40ad62011-11-12 22:28:03 +00002415 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002416 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002417
Richard Smith0b0a0b62011-10-29 20:57:55 +00002418 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002419 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2420 return false;
2421 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002422}
2423
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002424bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2425 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002426 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002427 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002428 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2429
2430 Result.set(E, Info.CurrentCall);
2431 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2432 Result, E->GetTemporaryExpr());
2433 }
2434
2435 // Materialization of an lvalue temporary occurs when we need to force a copy
2436 // (for instance, if it's a bitfield).
2437 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2438 if (!Visit(E->GetTemporaryExpr()))
2439 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002440 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002441 Info.CurrentCall->Temporaries[E]))
2442 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002443 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002444 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002445}
2446
Peter Collingbournee9200682011-05-13 03:29:01 +00002447bool
2448LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002449 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2450 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2451 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002452 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002453}
2454
Richard Smith6e525142011-12-27 12:18:28 +00002455bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2456 if (E->isTypeOperand())
2457 return Success(E);
2458 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2459 if (RD && RD->isPolymorphic()) {
2460 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2461 << E->getExprOperand()->getType()
2462 << E->getExprOperand()->getSourceRange();
2463 return false;
2464 }
2465 return Success(E);
2466}
2467
Peter Collingbournee9200682011-05-13 03:29:01 +00002468bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002469 // Handle static data members.
2470 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2471 VisitIgnoredValue(E->getBase());
2472 return VisitVarDecl(E, VD);
2473 }
2474
Richard Smith254a73d2011-10-28 22:34:42 +00002475 // Handle static member functions.
2476 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2477 if (MD->isStatic()) {
2478 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002479 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002480 }
2481 }
2482
Richard Smithd62306a2011-11-10 06:34:14 +00002483 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002484 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002485}
2486
Peter Collingbournee9200682011-05-13 03:29:01 +00002487bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002488 // FIXME: Deal with vectors as array subscript bases.
2489 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002490 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002491
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002492 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002493 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002494
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002495 APSInt Index;
2496 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002497 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002498 int64_t IndexValue
2499 = Index.isSigned() ? Index.getSExtValue()
2500 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002501
Richard Smith027bf112011-11-17 22:56:20 +00002502 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002503 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002504}
Eli Friedman9a156e52008-11-12 09:44:48 +00002505
Peter Collingbournee9200682011-05-13 03:29:01 +00002506bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002507 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002508 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002509}
2510
Eli Friedman9a156e52008-11-12 09:44:48 +00002511//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002512// Pointer Evaluation
2513//===----------------------------------------------------------------------===//
2514
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002515namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002516class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002517 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002518 LValue &Result;
2519
Peter Collingbournee9200682011-05-13 03:29:01 +00002520 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002521 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002522 return true;
2523 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002524public:
Mike Stump11289f42009-09-09 15:08:12 +00002525
John McCall45d55e42010-05-07 21:00:08 +00002526 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002527 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002528
Richard Smith0b0a0b62011-10-29 20:57:55 +00002529 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002530 Result.setFrom(V);
2531 return true;
2532 }
Richard Smithfddd3842011-12-30 21:15:51 +00002533 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002534 return Success((Expr*)0);
2535 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002536
John McCall45d55e42010-05-07 21:00:08 +00002537 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002538 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002539 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002540 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002541 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002542 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002543 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002544 bool VisitCallExpr(const CallExpr *E);
2545 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002546 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002547 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002548 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002549 }
Richard Smithd62306a2011-11-10 06:34:14 +00002550 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2551 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002552 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002553 Result = *Info.CurrentCall->This;
2554 return true;
2555 }
John McCallc07a0c72011-02-17 10:25:35 +00002556
Eli Friedman449fe542009-03-23 04:56:01 +00002557 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002558};
Chris Lattner05706e882008-07-11 18:11:29 +00002559} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002560
John McCall45d55e42010-05-07 21:00:08 +00002561static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002562 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002563 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002564}
2565
John McCall45d55e42010-05-07 21:00:08 +00002566bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002567 if (E->getOpcode() != BO_Add &&
2568 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002569 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002570
Chris Lattner05706e882008-07-11 18:11:29 +00002571 const Expr *PExp = E->getLHS();
2572 const Expr *IExp = E->getRHS();
2573 if (IExp->getType()->isPointerType())
2574 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002575
John McCall45d55e42010-05-07 21:00:08 +00002576 if (!EvaluatePointer(PExp, Result, Info))
2577 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002578
John McCall45d55e42010-05-07 21:00:08 +00002579 llvm::APSInt Offset;
2580 if (!EvaluateInteger(IExp, Offset, Info))
2581 return false;
2582 int64_t AdditionalOffset
2583 = Offset.isSigned() ? Offset.getSExtValue()
2584 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002585 if (E->getOpcode() == BO_Sub)
2586 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002587
Richard Smithd62306a2011-11-10 06:34:14 +00002588 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002589 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002590 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002591}
Eli Friedman9a156e52008-11-12 09:44:48 +00002592
John McCall45d55e42010-05-07 21:00:08 +00002593bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2594 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002595}
Mike Stump11289f42009-09-09 15:08:12 +00002596
Peter Collingbournee9200682011-05-13 03:29:01 +00002597bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2598 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002599
Eli Friedman847a2bc2009-12-27 05:43:15 +00002600 switch (E->getCastKind()) {
2601 default:
2602 break;
2603
John McCalle3027922010-08-25 11:45:40 +00002604 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002605 case CK_CPointerToObjCPointerCast:
2606 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002607 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002608 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2609 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2610 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002611 if (!E->getType()->isVoidPointerType()) {
2612 if (SubExpr->getType()->isVoidPointerType())
2613 CCEDiag(E, diag::note_constexpr_invalid_cast)
2614 << 3 << SubExpr->getType();
2615 else
2616 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2617 }
Richard Smith96e0c102011-11-04 02:25:55 +00002618 if (!Visit(SubExpr))
2619 return false;
2620 Result.Designator.setInvalid();
2621 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002622
Anders Carlsson18275092010-10-31 20:41:46 +00002623 case CK_DerivedToBase:
2624 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002625 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002626 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002627 if (!Result.Base && Result.Offset.isZero())
2628 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002629
Richard Smithd62306a2011-11-10 06:34:14 +00002630 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002631 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002632 QualType Type =
2633 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002634
Richard Smithd62306a2011-11-10 06:34:14 +00002635 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002636 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002637 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002638 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002639 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002640 }
2641
Anders Carlsson18275092010-10-31 20:41:46 +00002642 return true;
2643 }
2644
Richard Smith027bf112011-11-17 22:56:20 +00002645 case CK_BaseToDerived:
2646 if (!Visit(E->getSubExpr()))
2647 return false;
2648 if (!Result.Base && Result.Offset.isZero())
2649 return true;
2650 return HandleBaseToDerivedCast(Info, E, Result);
2651
Richard Smith0b0a0b62011-10-29 20:57:55 +00002652 case CK_NullToPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002653 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002654
John McCalle3027922010-08-25 11:45:40 +00002655 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002656 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2657
Richard Smith0b0a0b62011-10-29 20:57:55 +00002658 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002659 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002660 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002661
John McCall45d55e42010-05-07 21:00:08 +00002662 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002663 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2664 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002665 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002666 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002667 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002668 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002669 return true;
2670 } else {
2671 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002672 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002673 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002674 }
2675 }
John McCalle3027922010-08-25 11:45:40 +00002676 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002677 if (SubExpr->isGLValue()) {
2678 if (!EvaluateLValue(SubExpr, Result, Info))
2679 return false;
2680 } else {
2681 Result.set(SubExpr, Info.CurrentCall);
2682 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2683 Info, Result, SubExpr))
2684 return false;
2685 }
Richard Smith96e0c102011-11-04 02:25:55 +00002686 // The result is a pointer to the first element of the array.
2687 Result.Designator.addIndex(0);
2688 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002689
John McCalle3027922010-08-25 11:45:40 +00002690 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002691 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002692 }
2693
Richard Smith11562c52011-10-28 17:51:58 +00002694 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002695}
Chris Lattner05706e882008-07-11 18:11:29 +00002696
Peter Collingbournee9200682011-05-13 03:29:01 +00002697bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002698 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002699 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002700
Peter Collingbournee9200682011-05-13 03:29:01 +00002701 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002702}
Chris Lattner05706e882008-07-11 18:11:29 +00002703
2704//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002705// Member Pointer Evaluation
2706//===----------------------------------------------------------------------===//
2707
2708namespace {
2709class MemberPointerExprEvaluator
2710 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2711 MemberPtr &Result;
2712
2713 bool Success(const ValueDecl *D) {
2714 Result = MemberPtr(D);
2715 return true;
2716 }
2717public:
2718
2719 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2720 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2721
2722 bool Success(const CCValue &V, const Expr *E) {
2723 Result.setFrom(V);
2724 return true;
2725 }
Richard Smithfddd3842011-12-30 21:15:51 +00002726 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002727 return Success((const ValueDecl*)0);
2728 }
2729
2730 bool VisitCastExpr(const CastExpr *E);
2731 bool VisitUnaryAddrOf(const UnaryOperator *E);
2732};
2733} // end anonymous namespace
2734
2735static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2736 EvalInfo &Info) {
2737 assert(E->isRValue() && E->getType()->isMemberPointerType());
2738 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2739}
2740
2741bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2742 switch (E->getCastKind()) {
2743 default:
2744 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2745
2746 case CK_NullToMemberPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002747 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002748
2749 case CK_BaseToDerivedMemberPointer: {
2750 if (!Visit(E->getSubExpr()))
2751 return false;
2752 if (E->path_empty())
2753 return true;
2754 // Base-to-derived member pointer casts store the path in derived-to-base
2755 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2756 // the wrong end of the derived->base arc, so stagger the path by one class.
2757 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2758 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2759 PathI != PathE; ++PathI) {
2760 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2761 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2762 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002763 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002764 }
2765 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2766 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002767 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002768 return true;
2769 }
2770
2771 case CK_DerivedToBaseMemberPointer:
2772 if (!Visit(E->getSubExpr()))
2773 return false;
2774 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2775 PathE = E->path_end(); PathI != PathE; ++PathI) {
2776 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2777 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2778 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002779 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002780 }
2781 return true;
2782 }
2783}
2784
2785bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2786 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2787 // member can be formed.
2788 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2789}
2790
2791//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002792// Record Evaluation
2793//===----------------------------------------------------------------------===//
2794
2795namespace {
2796 class RecordExprEvaluator
2797 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2798 const LValue &This;
2799 APValue &Result;
2800 public:
2801
2802 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2803 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2804
2805 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002806 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002807 }
Richard Smithfddd3842011-12-30 21:15:51 +00002808 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002809
Richard Smithe97cbd72011-11-11 04:05:33 +00002810 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002811 bool VisitInitListExpr(const InitListExpr *E);
2812 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2813 };
2814}
2815
Richard Smithfddd3842011-12-30 21:15:51 +00002816/// Perform zero-initialization on an object of non-union class type.
2817/// C++11 [dcl.init]p5:
2818/// To zero-initialize an object or reference of type T means:
2819/// [...]
2820/// -- if T is a (possibly cv-qualified) non-union class type,
2821/// each non-static data member and each base-class subobject is
2822/// zero-initialized
2823static bool HandleClassZeroInitialization(EvalInfo &Info, const RecordDecl *RD,
2824 const LValue &This, APValue &Result) {
2825 assert(!RD->isUnion() && "Expected non-union class type");
2826 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2827 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2828 std::distance(RD->field_begin(), RD->field_end()));
2829
2830 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2831
2832 if (CD) {
2833 unsigned Index = 0;
2834 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
2835 E = CD->bases_end(); I != E; ++I, ++Index) {
2836 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2837 LValue Subobject = This;
2838 HandleLValueDirectBase(Info, Subobject, CD, Base, &Layout);
2839 if (!HandleClassZeroInitialization(Info, Base, Subobject,
2840 Result.getStructBase(Index)))
2841 return false;
2842 }
2843 }
2844
2845 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2846 I != E; ++I) {
2847 // -- if T is a reference type, no initialization is performed.
2848 if ((*I)->getType()->isReferenceType())
2849 continue;
2850
2851 LValue Subobject = This;
2852 HandleLValueMember(Info, Subobject, *I, &Layout);
2853
2854 ImplicitValueInitExpr VIE((*I)->getType());
2855 if (!EvaluateConstantExpression(
2856 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2857 return false;
2858 }
2859
2860 return true;
2861}
2862
2863bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2864 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2865 if (RD->isUnion()) {
2866 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2867 // object's first non-static named data member is zero-initialized
2868 RecordDecl::field_iterator I = RD->field_begin();
2869 if (I == RD->field_end()) {
2870 Result = APValue((const FieldDecl*)0);
2871 return true;
2872 }
2873
2874 LValue Subobject = This;
2875 HandleLValueMember(Info, Subobject, *I);
2876 Result = APValue(*I);
2877 ImplicitValueInitExpr VIE((*I)->getType());
2878 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2879 Subobject, &VIE);
2880 }
2881
2882 return HandleClassZeroInitialization(Info, RD, This, Result);
2883}
2884
Richard Smithe97cbd72011-11-11 04:05:33 +00002885bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2886 switch (E->getCastKind()) {
2887 default:
2888 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2889
2890 case CK_ConstructorConversion:
2891 return Visit(E->getSubExpr());
2892
2893 case CK_DerivedToBase:
2894 case CK_UncheckedDerivedToBase: {
2895 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002896 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002897 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002898 if (!DerivedObject.isStruct())
2899 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002900
2901 // Derived-to-base rvalue conversion: just slice off the derived part.
2902 APValue *Value = &DerivedObject;
2903 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2904 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2905 PathE = E->path_end(); PathI != PathE; ++PathI) {
2906 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2907 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2908 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2909 RD = Base;
2910 }
2911 Result = *Value;
2912 return true;
2913 }
2914 }
2915}
2916
Richard Smithd62306a2011-11-10 06:34:14 +00002917bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2918 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2919 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2920
2921 if (RD->isUnion()) {
2922 Result = APValue(E->getInitializedFieldInUnion());
2923 if (!E->getNumInits())
2924 return true;
2925 LValue Subobject = This;
2926 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2927 &Layout);
2928 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2929 Subobject, E->getInit(0));
2930 }
2931
2932 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2933 "initializer list for class with base classes");
2934 Result = APValue(APValue::UninitStruct(), 0,
2935 std::distance(RD->field_begin(), RD->field_end()));
2936 unsigned ElementNo = 0;
2937 for (RecordDecl::field_iterator Field = RD->field_begin(),
2938 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2939 // Anonymous bit-fields are not considered members of the class for
2940 // purposes of aggregate initialization.
2941 if (Field->isUnnamedBitfield())
2942 continue;
2943
2944 LValue Subobject = This;
2945 HandleLValueMember(Info, Subobject, *Field, &Layout);
2946
2947 if (ElementNo < E->getNumInits()) {
2948 if (!EvaluateConstantExpression(
2949 Result.getStructField((*Field)->getFieldIndex()),
2950 Info, Subobject, E->getInit(ElementNo++)))
2951 return false;
2952 } else {
2953 // Perform an implicit value-initialization for members beyond the end of
2954 // the initializer list.
2955 ImplicitValueInitExpr VIE(Field->getType());
2956 if (!EvaluateConstantExpression(
2957 Result.getStructField((*Field)->getFieldIndex()),
2958 Info, Subobject, &VIE))
2959 return false;
2960 }
2961 }
2962
2963 return true;
2964}
2965
2966bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2967 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithfddd3842011-12-30 21:15:51 +00002968 bool ZeroInit = E->requiresZeroInitialization();
2969 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
2970 if (ZeroInit)
2971 return ZeroInitialization(E);
2972
Richard Smithcc36f692011-12-22 02:22:31 +00002973 const CXXRecordDecl *RD = FD->getParent();
2974 if (RD->isUnion())
2975 Result = APValue((FieldDecl*)0);
2976 else
2977 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2978 std::distance(RD->field_begin(), RD->field_end()));
2979 return true;
2980 }
2981
Richard Smithd62306a2011-11-10 06:34:14 +00002982 const FunctionDecl *Definition = 0;
2983 FD->getBody(Definition);
2984
Richard Smith357362d2011-12-13 06:39:58 +00002985 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2986 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002987
2988 // FIXME: Elide the copy/move construction wherever we can.
Richard Smithfddd3842011-12-30 21:15:51 +00002989 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00002990 if (const MaterializeTemporaryExpr *ME
2991 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2992 return Visit(ME->GetTemporaryExpr());
2993
Richard Smithfddd3842011-12-30 21:15:51 +00002994 if (ZeroInit && !ZeroInitialization(E))
2995 return false;
2996
Richard Smithd62306a2011-11-10 06:34:14 +00002997 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002998 return HandleConstructorCall(E, This, Args,
2999 cast<CXXConstructorDecl>(Definition), Info,
3000 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003001}
3002
3003static bool EvaluateRecord(const Expr *E, const LValue &This,
3004 APValue &Result, EvalInfo &Info) {
3005 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003006 "can't evaluate expression as a record rvalue");
3007 return RecordExprEvaluator(Info, This, Result).Visit(E);
3008}
3009
3010//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003011// Temporary Evaluation
3012//
3013// Temporaries are represented in the AST as rvalues, but generally behave like
3014// lvalues. The full-object of which the temporary is a subobject is implicitly
3015// materialized so that a reference can bind to it.
3016//===----------------------------------------------------------------------===//
3017namespace {
3018class TemporaryExprEvaluator
3019 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3020public:
3021 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3022 LValueExprEvaluatorBaseTy(Info, Result) {}
3023
3024 /// Visit an expression which constructs the value of this temporary.
3025 bool VisitConstructExpr(const Expr *E) {
3026 Result.set(E, Info.CurrentCall);
3027 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3028 Result, E);
3029 }
3030
3031 bool VisitCastExpr(const CastExpr *E) {
3032 switch (E->getCastKind()) {
3033 default:
3034 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3035
3036 case CK_ConstructorConversion:
3037 return VisitConstructExpr(E->getSubExpr());
3038 }
3039 }
3040 bool VisitInitListExpr(const InitListExpr *E) {
3041 return VisitConstructExpr(E);
3042 }
3043 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3044 return VisitConstructExpr(E);
3045 }
3046 bool VisitCallExpr(const CallExpr *E) {
3047 return VisitConstructExpr(E);
3048 }
3049};
3050} // end anonymous namespace
3051
3052/// Evaluate an expression of record type as a temporary.
3053static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003054 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003055 return TemporaryExprEvaluator(Info, Result).Visit(E);
3056}
3057
3058//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003059// Vector Evaluation
3060//===----------------------------------------------------------------------===//
3061
3062namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003063 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003064 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3065 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003066 public:
Mike Stump11289f42009-09-09 15:08:12 +00003067
Richard Smith2d406342011-10-22 21:10:00 +00003068 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3069 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003070
Richard Smith2d406342011-10-22 21:10:00 +00003071 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3072 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3073 // FIXME: remove this APValue copy.
3074 Result = APValue(V.data(), V.size());
3075 return true;
3076 }
Richard Smithed5165f2011-11-04 05:33:44 +00003077 bool Success(const CCValue &V, const Expr *E) {
3078 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003079 Result = V;
3080 return true;
3081 }
Richard Smithfddd3842011-12-30 21:15:51 +00003082 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003083
Richard Smith2d406342011-10-22 21:10:00 +00003084 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003085 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003086 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003087 bool VisitInitListExpr(const InitListExpr *E);
3088 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003089 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003090 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003091 // shufflevector, ExtVectorElementExpr
3092 // (Note that these require implementing conversions
3093 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003094 };
3095} // end anonymous namespace
3096
3097static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003098 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003099 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003100}
3101
Richard Smith2d406342011-10-22 21:10:00 +00003102bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3103 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003104 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003105
Richard Smith161f09a2011-12-06 22:44:34 +00003106 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003107 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003108
Eli Friedmanc757de22011-03-25 00:43:55 +00003109 switch (E->getCastKind()) {
3110 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003111 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003112 if (SETy->isIntegerType()) {
3113 APSInt IntResult;
3114 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003115 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003116 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003117 } else if (SETy->isRealFloatingType()) {
3118 APFloat F(0.0);
3119 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003120 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003121 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003122 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003123 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003124 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003125
3126 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003127 SmallVector<APValue, 4> Elts(NElts, Val);
3128 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003129 }
Eli Friedman803acb32011-12-22 03:51:45 +00003130 case CK_BitCast: {
3131 // Evaluate the operand into an APInt we can extract from.
3132 llvm::APInt SValInt;
3133 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3134 return false;
3135 // Extract the elements
3136 QualType EltTy = VTy->getElementType();
3137 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3138 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3139 SmallVector<APValue, 4> Elts;
3140 if (EltTy->isRealFloatingType()) {
3141 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3142 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3143 unsigned FloatEltSize = EltSize;
3144 if (&Sem == &APFloat::x87DoubleExtended)
3145 FloatEltSize = 80;
3146 for (unsigned i = 0; i < NElts; i++) {
3147 llvm::APInt Elt;
3148 if (BigEndian)
3149 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3150 else
3151 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3152 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3153 }
3154 } else if (EltTy->isIntegerType()) {
3155 for (unsigned i = 0; i < NElts; i++) {
3156 llvm::APInt Elt;
3157 if (BigEndian)
3158 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3159 else
3160 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3161 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3162 }
3163 } else {
3164 return Error(E);
3165 }
3166 return Success(Elts, E);
3167 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003168 default:
Richard Smith11562c52011-10-28 17:51:58 +00003169 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003170 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003171}
3172
Richard Smith2d406342011-10-22 21:10:00 +00003173bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003174VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003175 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003176 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003177 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003178
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003179 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003180 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003181
Eli Friedmanb9c71292012-01-03 23:24:20 +00003182 // The number of initializers can be less than the number of
3183 // vector elements. For OpenCL, this can be due to nested vector
3184 // initialization. For GCC compatibility, missing trailing elements
3185 // should be initialized with zeroes.
3186 unsigned CountInits = 0, CountElts = 0;
3187 while (CountElts < NumElements) {
3188 // Handle nested vector initialization.
3189 if (CountInits < NumInits
3190 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3191 APValue v;
3192 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3193 return Error(E);
3194 unsigned vlen = v.getVectorLength();
3195 for (unsigned j = 0; j < vlen; j++)
3196 Elements.push_back(v.getVectorElt(j));
3197 CountElts += vlen;
3198 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003199 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003200 if (CountInits < NumInits) {
3201 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3202 return Error(E);
3203 } else // trailing integer zero.
3204 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3205 Elements.push_back(APValue(sInt));
3206 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003207 } else {
3208 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003209 if (CountInits < NumInits) {
3210 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3211 return Error(E);
3212 } else // trailing float zero.
3213 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3214 Elements.push_back(APValue(f));
3215 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003216 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003217 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003218 }
Richard Smith2d406342011-10-22 21:10:00 +00003219 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003220}
3221
Richard Smith2d406342011-10-22 21:10:00 +00003222bool
Richard Smithfddd3842011-12-30 21:15:51 +00003223VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003224 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003225 QualType EltTy = VT->getElementType();
3226 APValue ZeroElement;
3227 if (EltTy->isIntegerType())
3228 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3229 else
3230 ZeroElement =
3231 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3232
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003233 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003234 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003235}
3236
Richard Smith2d406342011-10-22 21:10:00 +00003237bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003238 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003239 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003240}
3241
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003242//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003243// Array Evaluation
3244//===----------------------------------------------------------------------===//
3245
3246namespace {
3247 class ArrayExprEvaluator
3248 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003249 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003250 APValue &Result;
3251 public:
3252
Richard Smithd62306a2011-11-10 06:34:14 +00003253 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3254 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003255
3256 bool Success(const APValue &V, const Expr *E) {
3257 assert(V.isArray() && "Expected array type");
3258 Result = V;
3259 return true;
3260 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003261
Richard Smithfddd3842011-12-30 21:15:51 +00003262 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003263 const ConstantArrayType *CAT =
3264 Info.Ctx.getAsConstantArrayType(E->getType());
3265 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003266 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003267
3268 Result = APValue(APValue::UninitArray(), 0,
3269 CAT->getSize().getZExtValue());
3270 if (!Result.hasArrayFiller()) return true;
3271
Richard Smithfddd3842011-12-30 21:15:51 +00003272 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003273 LValue Subobject = This;
3274 Subobject.Designator.addIndex(0);
3275 ImplicitValueInitExpr VIE(CAT->getElementType());
3276 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3277 Subobject, &VIE);
3278 }
3279
Richard Smithf3e9e432011-11-07 09:22:26 +00003280 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003281 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003282 };
3283} // end anonymous namespace
3284
Richard Smithd62306a2011-11-10 06:34:14 +00003285static bool EvaluateArray(const Expr *E, const LValue &This,
3286 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003287 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003288 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003289}
3290
3291bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3292 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3293 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003294 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003295
Richard Smithca2cfbf2011-12-22 01:07:19 +00003296 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3297 // an appropriately-typed string literal enclosed in braces.
3298 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3299 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3300 LValue LV;
3301 if (!EvaluateLValue(E->getInit(0), LV, Info))
3302 return false;
3303 uint64_t NumElements = CAT->getSize().getZExtValue();
3304 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3305
3306 // Copy the string literal into the array. FIXME: Do this better.
3307 LV.Designator.addIndex(0);
3308 for (uint64_t I = 0; I < NumElements; ++I) {
3309 CCValue Char;
3310 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3311 CAT->getElementType(), LV, Char))
3312 return false;
3313 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3314 Result.getArrayInitializedElt(I)))
3315 return false;
3316 if (!HandleLValueArrayAdjustment(Info, LV, CAT->getElementType(), 1))
3317 return false;
3318 }
3319 return true;
3320 }
3321
Richard Smithf3e9e432011-11-07 09:22:26 +00003322 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3323 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003324 LValue Subobject = This;
3325 Subobject.Designator.addIndex(0);
3326 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003327 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003328 I != End; ++I, ++Index) {
3329 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3330 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003331 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003332 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3333 return false;
3334 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003335
3336 if (!Result.hasArrayFiller()) return true;
3337 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003338 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3339 // but sometimes does:
3340 // struct S { constexpr S() : p(&p) {} void *p; };
3341 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003342 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003343 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003344}
3345
Richard Smith027bf112011-11-17 22:56:20 +00003346bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3347 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3348 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003349 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003350
3351 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3352 if (!Result.hasArrayFiller())
3353 return true;
3354
3355 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003356
Richard Smithfddd3842011-12-30 21:15:51 +00003357 bool ZeroInit = E->requiresZeroInitialization();
3358 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3359 if (ZeroInit) {
3360 LValue Subobject = This;
3361 Subobject.Designator.addIndex(0);
3362 ImplicitValueInitExpr VIE(CAT->getElementType());
3363 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3364 Subobject, &VIE);
3365 }
3366
Richard Smithcc36f692011-12-22 02:22:31 +00003367 const CXXRecordDecl *RD = FD->getParent();
3368 if (RD->isUnion())
3369 Result.getArrayFiller() = APValue((FieldDecl*)0);
3370 else
3371 Result.getArrayFiller() =
3372 APValue(APValue::UninitStruct(), RD->getNumBases(),
3373 std::distance(RD->field_begin(), RD->field_end()));
3374 return true;
3375 }
3376
Richard Smith027bf112011-11-17 22:56:20 +00003377 const FunctionDecl *Definition = 0;
3378 FD->getBody(Definition);
3379
Richard Smith357362d2011-12-13 06:39:58 +00003380 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3381 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003382
3383 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3384 // but sometimes does:
3385 // struct S { constexpr S() : p(&p) {} void *p; };
3386 // S s[10];
3387 LValue Subobject = This;
3388 Subobject.Designator.addIndex(0);
Richard Smithfddd3842011-12-30 21:15:51 +00003389
3390 if (ZeroInit) {
3391 ImplicitValueInitExpr VIE(CAT->getElementType());
3392 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3393 &VIE))
3394 return false;
3395 }
3396
Richard Smith027bf112011-11-17 22:56:20 +00003397 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003398 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003399 cast<CXXConstructorDecl>(Definition),
3400 Info, Result.getArrayFiller());
3401}
3402
Richard Smithf3e9e432011-11-07 09:22:26 +00003403//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003404// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003405//
3406// As a GNU extension, we support casting pointers to sufficiently-wide integer
3407// types and back in constant folding. Integer values are thus represented
3408// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003409//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003410
3411namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003412class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003413 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003414 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003415public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003416 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003417 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003418
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003419 bool Success(const llvm::APSInt &SI, const Expr *E) {
3420 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003421 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003422 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003423 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003424 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003425 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003426 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003427 return true;
3428 }
3429
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003430 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003431 assert(E->getType()->isIntegralOrEnumerationType() &&
3432 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003433 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003434 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003435 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003436 Result.getInt().setIsUnsigned(
3437 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003438 return true;
3439 }
3440
3441 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003442 assert(E->getType()->isIntegralOrEnumerationType() &&
3443 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003444 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003445 return true;
3446 }
3447
Ken Dyckdbc01912011-03-11 02:13:43 +00003448 bool Success(CharUnits Size, const Expr *E) {
3449 return Success(Size.getQuantity(), E);
3450 }
3451
Richard Smith0b0a0b62011-10-29 20:57:55 +00003452 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003453 if (V.isLValue()) {
3454 Result = V;
3455 return true;
3456 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003457 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003458 }
Mike Stump11289f42009-09-09 15:08:12 +00003459
Richard Smithfddd3842011-12-30 21:15:51 +00003460 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003461
Peter Collingbournee9200682011-05-13 03:29:01 +00003462 //===--------------------------------------------------------------------===//
3463 // Visitor Methods
3464 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003465
Chris Lattner7174bf32008-07-12 00:38:25 +00003466 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003467 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003468 }
3469 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003470 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003471 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003472
3473 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3474 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003475 if (CheckReferencedDecl(E, E->getDecl()))
3476 return true;
3477
3478 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003479 }
3480 bool VisitMemberExpr(const MemberExpr *E) {
3481 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003482 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003483 return true;
3484 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003485
3486 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003487 }
3488
Peter Collingbournee9200682011-05-13 03:29:01 +00003489 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003490 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003491 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003492 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003493
Peter Collingbournee9200682011-05-13 03:29:01 +00003494 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003495 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003496
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003497 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003498 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003499 }
Mike Stump11289f42009-09-09 15:08:12 +00003500
Richard Smith4ce706a2011-10-11 21:43:33 +00003501 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003502 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003503 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003504 }
3505
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003506 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003507 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003508 }
3509
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003510 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3511 return Success(E->getValue(), E);
3512 }
3513
John Wiegley6242b6a2011-04-28 00:16:57 +00003514 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3515 return Success(E->getValue(), E);
3516 }
3517
John Wiegleyf9f65842011-04-25 06:54:41 +00003518 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3519 return Success(E->getValue(), E);
3520 }
3521
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003522 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003523 bool VisitUnaryImag(const UnaryOperator *E);
3524
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003525 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003526 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003527
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003528private:
Ken Dyck160146e2010-01-27 17:10:57 +00003529 CharUnits GetAlignOfExpr(const Expr *E);
3530 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003531 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003532 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003533 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003534};
Chris Lattner05706e882008-07-11 18:11:29 +00003535} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003536
Richard Smith11562c52011-10-28 17:51:58 +00003537/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3538/// produce either the integer value or a pointer.
3539///
3540/// GCC has a heinous extension which folds casts between pointer types and
3541/// pointer-sized integral types. We support this by allowing the evaluation of
3542/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3543/// Some simple arithmetic on such values is supported (they are treated much
3544/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003545static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003546 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003547 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003548 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003549}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003550
Richard Smithf57d8cb2011-12-09 22:58:01 +00003551static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003552 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003553 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003554 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003555 if (!Val.isInt()) {
3556 // FIXME: It would be better to produce the diagnostic for casting
3557 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003558 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003559 return false;
3560 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003561 Result = Val.getInt();
3562 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003563}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003564
Richard Smithf57d8cb2011-12-09 22:58:01 +00003565/// Check whether the given declaration can be directly converted to an integral
3566/// rvalue. If not, no diagnostic is produced; there are other things we can
3567/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003568bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003569 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003570 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003571 // Check for signedness/width mismatches between E type and ECD value.
3572 bool SameSign = (ECD->getInitVal().isSigned()
3573 == E->getType()->isSignedIntegerOrEnumerationType());
3574 bool SameWidth = (ECD->getInitVal().getBitWidth()
3575 == Info.Ctx.getIntWidth(E->getType()));
3576 if (SameSign && SameWidth)
3577 return Success(ECD->getInitVal(), E);
3578 else {
3579 // Get rid of mismatch (otherwise Success assertions will fail)
3580 // by computing a new value matching the type of E.
3581 llvm::APSInt Val = ECD->getInitVal();
3582 if (!SameSign)
3583 Val.setIsSigned(!ECD->getInitVal().isSigned());
3584 if (!SameWidth)
3585 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3586 return Success(Val, E);
3587 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003588 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003589 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003590}
3591
Chris Lattner86ee2862008-10-06 06:40:35 +00003592/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3593/// as GCC.
3594static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3595 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003596 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003597 enum gcc_type_class {
3598 no_type_class = -1,
3599 void_type_class, integer_type_class, char_type_class,
3600 enumeral_type_class, boolean_type_class,
3601 pointer_type_class, reference_type_class, offset_type_class,
3602 real_type_class, complex_type_class,
3603 function_type_class, method_type_class,
3604 record_type_class, union_type_class,
3605 array_type_class, string_type_class,
3606 lang_type_class
3607 };
Mike Stump11289f42009-09-09 15:08:12 +00003608
3609 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003610 // ideal, however it is what gcc does.
3611 if (E->getNumArgs() == 0)
3612 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003613
Chris Lattner86ee2862008-10-06 06:40:35 +00003614 QualType ArgTy = E->getArg(0)->getType();
3615 if (ArgTy->isVoidType())
3616 return void_type_class;
3617 else if (ArgTy->isEnumeralType())
3618 return enumeral_type_class;
3619 else if (ArgTy->isBooleanType())
3620 return boolean_type_class;
3621 else if (ArgTy->isCharType())
3622 return string_type_class; // gcc doesn't appear to use char_type_class
3623 else if (ArgTy->isIntegerType())
3624 return integer_type_class;
3625 else if (ArgTy->isPointerType())
3626 return pointer_type_class;
3627 else if (ArgTy->isReferenceType())
3628 return reference_type_class;
3629 else if (ArgTy->isRealType())
3630 return real_type_class;
3631 else if (ArgTy->isComplexType())
3632 return complex_type_class;
3633 else if (ArgTy->isFunctionType())
3634 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003635 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003636 return record_type_class;
3637 else if (ArgTy->isUnionType())
3638 return union_type_class;
3639 else if (ArgTy->isArrayType())
3640 return array_type_class;
3641 else if (ArgTy->isUnionType())
3642 return union_type_class;
3643 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003644 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003645 return -1;
3646}
3647
Richard Smith5fab0c92011-12-28 19:48:30 +00003648/// EvaluateBuiltinConstantPForLValue - Determine the result of
3649/// __builtin_constant_p when applied to the given lvalue.
3650///
3651/// An lvalue is only "constant" if it is a pointer or reference to the first
3652/// character of a string literal.
3653template<typename LValue>
3654static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3655 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3656 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3657}
3658
3659/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3660/// GCC as we can manage.
3661static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3662 QualType ArgType = Arg->getType();
3663
3664 // __builtin_constant_p always has one operand. The rules which gcc follows
3665 // are not precisely documented, but are as follows:
3666 //
3667 // - If the operand is of integral, floating, complex or enumeration type,
3668 // and can be folded to a known value of that type, it returns 1.
3669 // - If the operand and can be folded to a pointer to the first character
3670 // of a string literal (or such a pointer cast to an integral type), it
3671 // returns 1.
3672 //
3673 // Otherwise, it returns 0.
3674 //
3675 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3676 // its support for this does not currently work.
3677 if (ArgType->isIntegralOrEnumerationType()) {
3678 Expr::EvalResult Result;
3679 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3680 return false;
3681
3682 APValue &V = Result.Val;
3683 if (V.getKind() == APValue::Int)
3684 return true;
3685
3686 return EvaluateBuiltinConstantPForLValue(V);
3687 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3688 return Arg->isEvaluatable(Ctx);
3689 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3690 LValue LV;
3691 Expr::EvalStatus Status;
3692 EvalInfo Info(Ctx, Status);
3693 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3694 : EvaluatePointer(Arg, LV, Info)) &&
3695 !Status.HasSideEffects)
3696 return EvaluateBuiltinConstantPForLValue(LV);
3697 }
3698
3699 // Anything else isn't considered to be sufficiently constant.
3700 return false;
3701}
3702
John McCall95007602010-05-10 23:27:23 +00003703/// Retrieves the "underlying object type" of the given expression,
3704/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003705QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3706 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3707 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003708 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003709 } else if (const Expr *E = B.get<const Expr*>()) {
3710 if (isa<CompoundLiteralExpr>(E))
3711 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003712 }
3713
3714 return QualType();
3715}
3716
Peter Collingbournee9200682011-05-13 03:29:01 +00003717bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003718 // TODO: Perhaps we should let LLVM lower this?
3719 LValue Base;
3720 if (!EvaluatePointer(E->getArg(0), Base, Info))
3721 return false;
3722
3723 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003724 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003725
Richard Smithce40ad62011-11-12 22:28:03 +00003726 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003727 if (T.isNull() ||
3728 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003729 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003730 T->isVariablyModifiedType() ||
3731 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003732 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003733
3734 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3735 CharUnits Offset = Base.getLValueOffset();
3736
3737 if (!Offset.isNegative() && Offset <= Size)
3738 Size -= Offset;
3739 else
3740 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003741 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003742}
3743
Peter Collingbournee9200682011-05-13 03:29:01 +00003744bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003745 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003746 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003747 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003748
3749 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003750 if (TryEvaluateBuiltinObjectSize(E))
3751 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003752
Eric Christopher99469702010-01-19 22:58:35 +00003753 // If evaluating the argument has side-effects we can't determine
3754 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003755 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003756 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003757 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003758 return Success(0, E);
3759 }
Mike Stump876387b2009-10-27 22:09:17 +00003760
Richard Smithf57d8cb2011-12-09 22:58:01 +00003761 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003762 }
3763
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003764 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003765 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003766
Richard Smith5fab0c92011-12-28 19:48:30 +00003767 case Builtin::BI__builtin_constant_p:
3768 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00003769
Chris Lattnerd545ad12009-09-23 06:06:36 +00003770 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003771 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003772 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003773 return Success(Operand, E);
3774 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003775
3776 case Builtin::BI__builtin_expect:
3777 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003778
3779 case Builtin::BIstrlen:
3780 case Builtin::BI__builtin_strlen:
3781 // As an extension, we support strlen() and __builtin_strlen() as constant
3782 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003783 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003784 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3785 // The string literal may have embedded null characters. Find the first
3786 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003787 StringRef Str = S->getString();
3788 StringRef::size_type Pos = Str.find(0);
3789 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003790 Str = Str.substr(0, Pos);
3791
3792 return Success(Str.size(), E);
3793 }
3794
Richard Smithf57d8cb2011-12-09 22:58:01 +00003795 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003796
3797 case Builtin::BI__atomic_is_lock_free: {
3798 APSInt SizeVal;
3799 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3800 return false;
3801
3802 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3803 // of two less than the maximum inline atomic width, we know it is
3804 // lock-free. If the size isn't a power of two, or greater than the
3805 // maximum alignment where we promote atomics, we know it is not lock-free
3806 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3807 // the answer can only be determined at runtime; for example, 16-byte
3808 // atomics have lock-free implementations on some, but not all,
3809 // x86-64 processors.
3810
3811 // Check power-of-two.
3812 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3813 if (!Size.isPowerOfTwo())
3814#if 0
3815 // FIXME: Suppress this folding until the ABI for the promotion width
3816 // settles.
3817 return Success(0, E);
3818#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003819 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003820#endif
3821
3822#if 0
3823 // Check against promotion width.
3824 // FIXME: Suppress this folding until the ABI for the promotion width
3825 // settles.
3826 unsigned PromoteWidthBits =
3827 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3828 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3829 return Success(0, E);
3830#endif
3831
3832 // Check against inlining width.
3833 unsigned InlineWidthBits =
3834 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3835 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3836 return Success(1, E);
3837
Richard Smithf57d8cb2011-12-09 22:58:01 +00003838 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003839 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003840 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003841}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003842
Richard Smith8b3497e2011-10-31 01:37:14 +00003843static bool HasSameBase(const LValue &A, const LValue &B) {
3844 if (!A.getLValueBase())
3845 return !B.getLValueBase();
3846 if (!B.getLValueBase())
3847 return false;
3848
Richard Smithce40ad62011-11-12 22:28:03 +00003849 if (A.getLValueBase().getOpaqueValue() !=
3850 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003851 const Decl *ADecl = GetLValueBaseDecl(A);
3852 if (!ADecl)
3853 return false;
3854 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003855 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003856 return false;
3857 }
3858
3859 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003860 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003861}
3862
Chris Lattnere13042c2008-07-11 19:10:17 +00003863bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003864 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003865 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003866
John McCalle3027922010-08-25 11:45:40 +00003867 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003868 VisitIgnoredValue(E->getLHS());
3869 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003870 }
3871
3872 if (E->isLogicalOp()) {
3873 // These need to be handled specially because the operands aren't
3874 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003875 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003876
Richard Smith11562c52011-10-28 17:51:58 +00003877 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003878 // We were able to evaluate the LHS, see if we can get away with not
3879 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003880 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003881 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003882
Richard Smith11562c52011-10-28 17:51:58 +00003883 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003884 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003885 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003886 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003887 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003888 }
3889 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003890 // FIXME: If both evaluations fail, we should produce the diagnostic from
3891 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3892 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003893 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003894 // We can't evaluate the LHS; however, sometimes the result
3895 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003896 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003897 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003898 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003899 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003900
3901 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003902 }
3903 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003904 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003905
Eli Friedman5a332ea2008-11-13 06:09:17 +00003906 return false;
3907 }
3908
Anders Carlssonacc79812008-11-16 07:17:21 +00003909 QualType LHSTy = E->getLHS()->getType();
3910 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003911
3912 if (LHSTy->isAnyComplexType()) {
3913 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003914 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003915
3916 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3917 return false;
3918
3919 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3920 return false;
3921
3922 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003923 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003924 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003925 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003926 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3927
John McCalle3027922010-08-25 11:45:40 +00003928 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003929 return Success((CR_r == APFloat::cmpEqual &&
3930 CR_i == APFloat::cmpEqual), E);
3931 else {
John McCalle3027922010-08-25 11:45:40 +00003932 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003933 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003934 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003935 CR_r == APFloat::cmpLessThan ||
3936 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003937 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003938 CR_i == APFloat::cmpLessThan ||
3939 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003940 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003941 } else {
John McCalle3027922010-08-25 11:45:40 +00003942 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003943 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3944 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3945 else {
John McCalle3027922010-08-25 11:45:40 +00003946 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003947 "Invalid compex comparison.");
3948 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3949 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3950 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003951 }
3952 }
Mike Stump11289f42009-09-09 15:08:12 +00003953
Anders Carlssonacc79812008-11-16 07:17:21 +00003954 if (LHSTy->isRealFloatingType() &&
3955 RHSTy->isRealFloatingType()) {
3956 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003957
Anders Carlssonacc79812008-11-16 07:17:21 +00003958 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3959 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003960
Anders Carlssonacc79812008-11-16 07:17:21 +00003961 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3962 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003963
Anders Carlssonacc79812008-11-16 07:17:21 +00003964 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003965
Anders Carlssonacc79812008-11-16 07:17:21 +00003966 switch (E->getOpcode()) {
3967 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003968 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003969 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003970 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003971 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003972 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003973 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003974 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003975 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003976 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003977 E);
John McCalle3027922010-08-25 11:45:40 +00003978 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003979 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003980 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003981 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003982 || CR == APFloat::cmpLessThan
3983 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003984 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003985 }
Mike Stump11289f42009-09-09 15:08:12 +00003986
Eli Friedmana38da572009-04-28 19:17:36 +00003987 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003988 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003989 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003990 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3991 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003992
John McCall45d55e42010-05-07 21:00:08 +00003993 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003994 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3995 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003996
Richard Smith8b3497e2011-10-31 01:37:14 +00003997 // Reject differing bases from the normal codepath; we special-case
3998 // comparisons to null.
3999 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00004000 // Inequalities and subtractions between unrelated pointers have
4001 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00004002 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004003 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004004 // A constant address may compare equal to the address of a symbol.
4005 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00004006 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004007 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4008 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004009 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004010 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00004011 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00004012 // distinct. However, we do know that the address of a literal will be
4013 // non-null.
4014 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4015 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004016 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004017 // We can't tell whether weak symbols will end up pointing to the same
4018 // object.
4019 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004020 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004021 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00004022 // (Note that clang defaults to -fmerge-all-constants, which can
4023 // lead to inconsistent results for comparisons involving the address
4024 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00004025 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00004026 }
Eli Friedman64004332009-03-23 04:38:34 +00004027
Richard Smithf3e9e432011-11-07 09:22:26 +00004028 // FIXME: Implement the C++11 restrictions:
4029 // - Pointer subtractions must be on elements of the same array.
4030 // - Pointer comparisons must be between members with the same access.
4031
John McCalle3027922010-08-25 11:45:40 +00004032 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00004033 QualType Type = E->getLHS()->getType();
4034 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004035
Richard Smithd62306a2011-11-10 06:34:14 +00004036 CharUnits ElementSize;
4037 if (!HandleSizeof(Info, ElementType, ElementSize))
4038 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004039
Richard Smithd62306a2011-11-10 06:34:14 +00004040 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00004041 RHSValue.getLValueOffset();
4042 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004043 }
Richard Smith8b3497e2011-10-31 01:37:14 +00004044
4045 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4046 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4047 switch (E->getOpcode()) {
4048 default: llvm_unreachable("missing comparison operator");
4049 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4050 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4051 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4052 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4053 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4054 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004055 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004056 }
4057 }
Douglas Gregorb90df602010-06-16 00:17:44 +00004058 if (!LHSTy->isIntegralOrEnumerationType() ||
4059 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004060 // We can't continue from here for non-integral types.
4061 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004062 }
4063
Anders Carlsson9c181652008-07-08 14:35:21 +00004064 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00004065 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00004066 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004067 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00004068
Richard Smith11562c52011-10-28 17:51:58 +00004069 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004070 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004071 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00004072
4073 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00004074 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00004075 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4076 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00004077 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00004078 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00004079 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00004080 LHSVal.getLValueOffset() -= AdditionalOffset;
4081 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00004082 return true;
4083 }
4084
4085 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00004086 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00004087 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004088 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4089 LHSVal.getInt().getZExtValue());
4090 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00004091 return true;
4092 }
4093
4094 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00004095 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004096 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004097
Richard Smith11562c52011-10-28 17:51:58 +00004098 APSInt &LHS = LHSVal.getInt();
4099 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00004100
Anders Carlsson9c181652008-07-08 14:35:21 +00004101 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004102 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004103 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004104 case BO_Mul: return Success(LHS * RHS, E);
4105 case BO_Add: return Success(LHS + RHS, E);
4106 case BO_Sub: return Success(LHS - RHS, E);
4107 case BO_And: return Success(LHS & RHS, E);
4108 case BO_Xor: return Success(LHS ^ RHS, E);
4109 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004110 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00004111 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004112 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004113 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004114 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00004115 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004116 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004117 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004118 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00004119 // During constant-folding, a negative shift is an opposite shift.
4120 if (RHS.isSigned() && RHS.isNegative()) {
4121 RHS = -RHS;
4122 goto shift_right;
4123 }
4124
4125 shift_left:
4126 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00004127 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4128 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004129 }
John McCalle3027922010-08-25 11:45:40 +00004130 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00004131 // During constant-folding, a negative shift is an opposite shift.
4132 if (RHS.isSigned() && RHS.isNegative()) {
4133 RHS = -RHS;
4134 goto shift_left;
4135 }
4136
4137 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00004138 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00004139 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4140 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004141 }
Mike Stump11289f42009-09-09 15:08:12 +00004142
Richard Smith11562c52011-10-28 17:51:58 +00004143 case BO_LT: return Success(LHS < RHS, E);
4144 case BO_GT: return Success(LHS > RHS, E);
4145 case BO_LE: return Success(LHS <= RHS, E);
4146 case BO_GE: return Success(LHS >= RHS, E);
4147 case BO_EQ: return Success(LHS == RHS, E);
4148 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00004149 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004150}
4151
Ken Dyck160146e2010-01-27 17:10:57 +00004152CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00004153 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4154 // the result is the size of the referenced type."
4155 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4156 // result shall be the alignment of the referenced type."
4157 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4158 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00004159
4160 // __alignof is defined to return the preferred alignment.
4161 return Info.Ctx.toCharUnitsFromBits(
4162 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00004163}
4164
Ken Dyck160146e2010-01-27 17:10:57 +00004165CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00004166 E = E->IgnoreParens();
4167
4168 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00004169 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00004170 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004171 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4172 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00004173
Chris Lattner68061312009-01-24 21:53:27 +00004174 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004175 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4176 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00004177
Chris Lattner24aeeab2009-01-24 21:09:06 +00004178 return GetAlignOfType(E->getType());
4179}
4180
4181
Peter Collingbournee190dee2011-03-11 19:24:49 +00004182/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4183/// a result as the expression's type.
4184bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4185 const UnaryExprOrTypeTraitExpr *E) {
4186 switch(E->getKind()) {
4187 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00004188 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00004189 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004190 else
Ken Dyckdbc01912011-03-11 02:13:43 +00004191 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004192 }
Eli Friedman64004332009-03-23 04:38:34 +00004193
Peter Collingbournee190dee2011-03-11 19:24:49 +00004194 case UETT_VecStep: {
4195 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00004196
Peter Collingbournee190dee2011-03-11 19:24:49 +00004197 if (Ty->isVectorType()) {
4198 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00004199
Peter Collingbournee190dee2011-03-11 19:24:49 +00004200 // The vec_step built-in functions that take a 3-component
4201 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4202 if (n == 3)
4203 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00004204
Peter Collingbournee190dee2011-03-11 19:24:49 +00004205 return Success(n, E);
4206 } else
4207 return Success(1, E);
4208 }
4209
4210 case UETT_SizeOf: {
4211 QualType SrcTy = E->getTypeOfArgument();
4212 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4213 // the result is the size of the referenced type."
4214 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4215 // result shall be the alignment of the referenced type."
4216 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4217 SrcTy = Ref->getPointeeType();
4218
Richard Smithd62306a2011-11-10 06:34:14 +00004219 CharUnits Sizeof;
4220 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00004221 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004222 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004223 }
4224 }
4225
4226 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004227 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004228}
4229
Peter Collingbournee9200682011-05-13 03:29:01 +00004230bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00004231 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00004232 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00004233 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004234 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00004235 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00004236 for (unsigned i = 0; i != n; ++i) {
4237 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4238 switch (ON.getKind()) {
4239 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00004240 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00004241 APSInt IdxResult;
4242 if (!EvaluateInteger(Idx, IdxResult, Info))
4243 return false;
4244 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4245 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004246 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004247 CurrentType = AT->getElementType();
4248 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4249 Result += IdxResult.getSExtValue() * ElementSize;
4250 break;
4251 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004252
Douglas Gregor882211c2010-04-28 22:16:22 +00004253 case OffsetOfExpr::OffsetOfNode::Field: {
4254 FieldDecl *MemberDecl = ON.getField();
4255 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004256 if (!RT)
4257 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004258 RecordDecl *RD = RT->getDecl();
4259 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004260 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004261 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004262 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004263 CurrentType = MemberDecl->getType().getNonReferenceType();
4264 break;
4265 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004266
Douglas Gregor882211c2010-04-28 22:16:22 +00004267 case OffsetOfExpr::OffsetOfNode::Identifier:
4268 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004269 return Error(OOE);
4270
Douglas Gregord1702062010-04-29 00:18:15 +00004271 case OffsetOfExpr::OffsetOfNode::Base: {
4272 CXXBaseSpecifier *BaseSpec = ON.getBase();
4273 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004274 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004275
4276 // Find the layout of the class whose base we are looking into.
4277 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004278 if (!RT)
4279 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004280 RecordDecl *RD = RT->getDecl();
4281 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4282
4283 // Find the base class itself.
4284 CurrentType = BaseSpec->getType();
4285 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4286 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004287 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004288
4289 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004290 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004291 break;
4292 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004293 }
4294 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004295 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004296}
4297
Chris Lattnere13042c2008-07-11 19:10:17 +00004298bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004299 switch (E->getOpcode()) {
4300 default:
4301 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4302 // See C99 6.6p3.
4303 return Error(E);
4304 case UO_Extension:
4305 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4306 // If so, we could clear the diagnostic ID.
4307 return Visit(E->getSubExpr());
4308 case UO_Plus:
4309 // The result is just the value.
4310 return Visit(E->getSubExpr());
4311 case UO_Minus: {
4312 if (!Visit(E->getSubExpr()))
4313 return false;
4314 if (!Result.isInt()) return Error(E);
4315 return Success(-Result.getInt(), E);
4316 }
4317 case UO_Not: {
4318 if (!Visit(E->getSubExpr()))
4319 return false;
4320 if (!Result.isInt()) return Error(E);
4321 return Success(~Result.getInt(), E);
4322 }
4323 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004324 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004325 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004326 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004327 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004328 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004329 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004330}
Mike Stump11289f42009-09-09 15:08:12 +00004331
Chris Lattner477c4be2008-07-12 01:15:53 +00004332/// HandleCast - This is used to evaluate implicit or explicit casts where the
4333/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004334bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4335 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004336 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004337 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004338
Eli Friedmanc757de22011-03-25 00:43:55 +00004339 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004340 case CK_BaseToDerived:
4341 case CK_DerivedToBase:
4342 case CK_UncheckedDerivedToBase:
4343 case CK_Dynamic:
4344 case CK_ToUnion:
4345 case CK_ArrayToPointerDecay:
4346 case CK_FunctionToPointerDecay:
4347 case CK_NullToPointer:
4348 case CK_NullToMemberPointer:
4349 case CK_BaseToDerivedMemberPointer:
4350 case CK_DerivedToBaseMemberPointer:
4351 case CK_ConstructorConversion:
4352 case CK_IntegralToPointer:
4353 case CK_ToVoid:
4354 case CK_VectorSplat:
4355 case CK_IntegralToFloating:
4356 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004357 case CK_CPointerToObjCPointerCast:
4358 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004359 case CK_AnyPointerToBlockPointerCast:
4360 case CK_ObjCObjectLValueCast:
4361 case CK_FloatingRealToComplex:
4362 case CK_FloatingComplexToReal:
4363 case CK_FloatingComplexCast:
4364 case CK_FloatingComplexToIntegralComplex:
4365 case CK_IntegralRealToComplex:
4366 case CK_IntegralComplexCast:
4367 case CK_IntegralComplexToFloatingComplex:
4368 llvm_unreachable("invalid cast kind for integral value");
4369
Eli Friedman9faf2f92011-03-25 19:07:11 +00004370 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004371 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004372 case CK_LValueBitCast:
4373 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004374 case CK_ARCProduceObject:
4375 case CK_ARCConsumeObject:
4376 case CK_ARCReclaimReturnedObject:
4377 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004378 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004379
4380 case CK_LValueToRValue:
4381 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004382 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004383
4384 case CK_MemberPointerToBoolean:
4385 case CK_PointerToBoolean:
4386 case CK_IntegralToBoolean:
4387 case CK_FloatingToBoolean:
4388 case CK_FloatingComplexToBoolean:
4389 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004390 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004391 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004392 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004393 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004394 }
4395
Eli Friedmanc757de22011-03-25 00:43:55 +00004396 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004397 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004398 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004399
Eli Friedman742421e2009-02-20 01:15:07 +00004400 if (!Result.isInt()) {
4401 // Only allow casts of lvalues if they are lossless.
4402 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4403 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004404
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004405 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004406 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004407 }
Mike Stump11289f42009-09-09 15:08:12 +00004408
Eli Friedmanc757de22011-03-25 00:43:55 +00004409 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004410 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4411
John McCall45d55e42010-05-07 21:00:08 +00004412 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004413 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004414 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004415
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004416 if (LV.getLValueBase()) {
4417 // Only allow based lvalue casts if they are lossless.
4418 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004419 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004420
Richard Smithcf74da72011-11-16 07:18:12 +00004421 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004422 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004423 return true;
4424 }
4425
Ken Dyck02990832010-01-15 12:37:54 +00004426 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4427 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004428 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004429 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004430
Eli Friedmanc757de22011-03-25 00:43:55 +00004431 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004432 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004433 if (!EvaluateComplex(SubExpr, C, Info))
4434 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004435 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004436 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004437
Eli Friedmanc757de22011-03-25 00:43:55 +00004438 case CK_FloatingToIntegral: {
4439 APFloat F(0.0);
4440 if (!EvaluateFloat(SubExpr, F, Info))
4441 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004442
Richard Smith357362d2011-12-13 06:39:58 +00004443 APSInt Value;
4444 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4445 return false;
4446 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004447 }
4448 }
Mike Stump11289f42009-09-09 15:08:12 +00004449
Eli Friedmanc757de22011-03-25 00:43:55 +00004450 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004451 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004452}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004453
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004454bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4455 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004456 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004457 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4458 return false;
4459 if (!LV.isComplexInt())
4460 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004461 return Success(LV.getComplexIntReal(), E);
4462 }
4463
4464 return Visit(E->getSubExpr());
4465}
4466
Eli Friedman4e7a2412009-02-27 04:45:43 +00004467bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004468 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004469 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004470 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4471 return false;
4472 if (!LV.isComplexInt())
4473 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004474 return Success(LV.getComplexIntImag(), E);
4475 }
4476
Richard Smith4a678122011-10-24 18:44:57 +00004477 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004478 return Success(0, E);
4479}
4480
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004481bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4482 return Success(E->getPackLength(), E);
4483}
4484
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004485bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4486 return Success(E->getValue(), E);
4487}
4488
Chris Lattner05706e882008-07-11 18:11:29 +00004489//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004490// Float Evaluation
4491//===----------------------------------------------------------------------===//
4492
4493namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004494class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004495 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004496 APFloat &Result;
4497public:
4498 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004499 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004500
Richard Smith0b0a0b62011-10-29 20:57:55 +00004501 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004502 Result = V.getFloat();
4503 return true;
4504 }
Eli Friedman24c01542008-08-22 00:06:13 +00004505
Richard Smithfddd3842011-12-30 21:15:51 +00004506 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004507 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4508 return true;
4509 }
4510
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004511 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004512
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004513 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004514 bool VisitBinaryOperator(const BinaryOperator *E);
4515 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004516 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004517
John McCallb1fb0d32010-05-07 22:08:54 +00004518 bool VisitUnaryReal(const UnaryOperator *E);
4519 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004520
Richard Smithfddd3842011-12-30 21:15:51 +00004521 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00004522};
4523} // end anonymous namespace
4524
4525static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004526 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004527 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004528}
4529
Jay Foad39c79802011-01-12 09:06:06 +00004530static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004531 QualType ResultTy,
4532 const Expr *Arg,
4533 bool SNaN,
4534 llvm::APFloat &Result) {
4535 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4536 if (!S) return false;
4537
4538 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4539
4540 llvm::APInt fill;
4541
4542 // Treat empty strings as if they were zero.
4543 if (S->getString().empty())
4544 fill = llvm::APInt(32, 0);
4545 else if (S->getString().getAsInteger(0, fill))
4546 return false;
4547
4548 if (SNaN)
4549 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4550 else
4551 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4552 return true;
4553}
4554
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004555bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004556 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004557 default:
4558 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4559
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004560 case Builtin::BI__builtin_huge_val:
4561 case Builtin::BI__builtin_huge_valf:
4562 case Builtin::BI__builtin_huge_vall:
4563 case Builtin::BI__builtin_inf:
4564 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004565 case Builtin::BI__builtin_infl: {
4566 const llvm::fltSemantics &Sem =
4567 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004568 Result = llvm::APFloat::getInf(Sem);
4569 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004570 }
Mike Stump11289f42009-09-09 15:08:12 +00004571
John McCall16291492010-02-28 13:00:19 +00004572 case Builtin::BI__builtin_nans:
4573 case Builtin::BI__builtin_nansf:
4574 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004575 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4576 true, Result))
4577 return Error(E);
4578 return true;
John McCall16291492010-02-28 13:00:19 +00004579
Chris Lattner0b7282e2008-10-06 06:31:58 +00004580 case Builtin::BI__builtin_nan:
4581 case Builtin::BI__builtin_nanf:
4582 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004583 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004584 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004585 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4586 false, Result))
4587 return Error(E);
4588 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004589
4590 case Builtin::BI__builtin_fabs:
4591 case Builtin::BI__builtin_fabsf:
4592 case Builtin::BI__builtin_fabsl:
4593 if (!EvaluateFloat(E->getArg(0), Result, Info))
4594 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004595
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004596 if (Result.isNegative())
4597 Result.changeSign();
4598 return true;
4599
Mike Stump11289f42009-09-09 15:08:12 +00004600 case Builtin::BI__builtin_copysign:
4601 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004602 case Builtin::BI__builtin_copysignl: {
4603 APFloat RHS(0.);
4604 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4605 !EvaluateFloat(E->getArg(1), RHS, Info))
4606 return false;
4607 Result.copySign(RHS);
4608 return true;
4609 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004610 }
4611}
4612
John McCallb1fb0d32010-05-07 22:08:54 +00004613bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004614 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4615 ComplexValue CV;
4616 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4617 return false;
4618 Result = CV.FloatReal;
4619 return true;
4620 }
4621
4622 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004623}
4624
4625bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004626 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4627 ComplexValue CV;
4628 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4629 return false;
4630 Result = CV.FloatImag;
4631 return true;
4632 }
4633
Richard Smith4a678122011-10-24 18:44:57 +00004634 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004635 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4636 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004637 return true;
4638}
4639
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004640bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004641 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004642 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004643 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004644 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004645 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004646 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4647 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004648 Result.changeSign();
4649 return true;
4650 }
4651}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004652
Eli Friedman24c01542008-08-22 00:06:13 +00004653bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004654 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4655 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004656
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004657 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004658 if (!EvaluateFloat(E->getLHS(), Result, Info))
4659 return false;
4660 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4661 return false;
4662
4663 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004664 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004665 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004666 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4667 return true;
John McCalle3027922010-08-25 11:45:40 +00004668 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004669 Result.add(RHS, APFloat::rmNearestTiesToEven);
4670 return true;
John McCalle3027922010-08-25 11:45:40 +00004671 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004672 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4673 return true;
John McCalle3027922010-08-25 11:45:40 +00004674 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004675 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4676 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004677 }
4678}
4679
4680bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4681 Result = E->getValue();
4682 return true;
4683}
4684
Peter Collingbournee9200682011-05-13 03:29:01 +00004685bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4686 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004687
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004688 switch (E->getCastKind()) {
4689 default:
Richard Smith11562c52011-10-28 17:51:58 +00004690 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004691
4692 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004693 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004694 return EvaluateInteger(SubExpr, IntResult, Info) &&
4695 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4696 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004697 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004698
4699 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004700 if (!Visit(SubExpr))
4701 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004702 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4703 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004704 }
John McCalld7646252010-11-14 08:17:51 +00004705
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004706 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004707 ComplexValue V;
4708 if (!EvaluateComplex(SubExpr, V, Info))
4709 return false;
4710 Result = V.getComplexFloatReal();
4711 return true;
4712 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004713 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004714
Richard Smithf57d8cb2011-12-09 22:58:01 +00004715 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004716}
4717
Eli Friedman24c01542008-08-22 00:06:13 +00004718//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004719// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004720//===----------------------------------------------------------------------===//
4721
4722namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004723class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004724 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004725 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004726
Anders Carlsson537969c2008-11-16 20:27:53 +00004727public:
John McCall93d91dc2010-05-07 17:22:02 +00004728 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004729 : ExprEvaluatorBaseTy(info), Result(Result) {}
4730
Richard Smith0b0a0b62011-10-29 20:57:55 +00004731 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004732 Result.setFrom(V);
4733 return true;
4734 }
Mike Stump11289f42009-09-09 15:08:12 +00004735
Anders Carlsson537969c2008-11-16 20:27:53 +00004736 //===--------------------------------------------------------------------===//
4737 // Visitor Methods
4738 //===--------------------------------------------------------------------===//
4739
Peter Collingbournee9200682011-05-13 03:29:01 +00004740 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004741
Peter Collingbournee9200682011-05-13 03:29:01 +00004742 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004743
John McCall93d91dc2010-05-07 17:22:02 +00004744 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004745 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004746 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004747};
4748} // end anonymous namespace
4749
John McCall93d91dc2010-05-07 17:22:02 +00004750static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4751 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004752 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004753 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004754}
4755
Peter Collingbournee9200682011-05-13 03:29:01 +00004756bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4757 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004758
4759 if (SubExpr->getType()->isRealFloatingType()) {
4760 Result.makeComplexFloat();
4761 APFloat &Imag = Result.FloatImag;
4762 if (!EvaluateFloat(SubExpr, Imag, Info))
4763 return false;
4764
4765 Result.FloatReal = APFloat(Imag.getSemantics());
4766 return true;
4767 } else {
4768 assert(SubExpr->getType()->isIntegerType() &&
4769 "Unexpected imaginary literal.");
4770
4771 Result.makeComplexInt();
4772 APSInt &Imag = Result.IntImag;
4773 if (!EvaluateInteger(SubExpr, Imag, Info))
4774 return false;
4775
4776 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4777 return true;
4778 }
4779}
4780
Peter Collingbournee9200682011-05-13 03:29:01 +00004781bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004782
John McCallfcef3cf2010-12-14 17:51:41 +00004783 switch (E->getCastKind()) {
4784 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004785 case CK_BaseToDerived:
4786 case CK_DerivedToBase:
4787 case CK_UncheckedDerivedToBase:
4788 case CK_Dynamic:
4789 case CK_ToUnion:
4790 case CK_ArrayToPointerDecay:
4791 case CK_FunctionToPointerDecay:
4792 case CK_NullToPointer:
4793 case CK_NullToMemberPointer:
4794 case CK_BaseToDerivedMemberPointer:
4795 case CK_DerivedToBaseMemberPointer:
4796 case CK_MemberPointerToBoolean:
4797 case CK_ConstructorConversion:
4798 case CK_IntegralToPointer:
4799 case CK_PointerToIntegral:
4800 case CK_PointerToBoolean:
4801 case CK_ToVoid:
4802 case CK_VectorSplat:
4803 case CK_IntegralCast:
4804 case CK_IntegralToBoolean:
4805 case CK_IntegralToFloating:
4806 case CK_FloatingToIntegral:
4807 case CK_FloatingToBoolean:
4808 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004809 case CK_CPointerToObjCPointerCast:
4810 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004811 case CK_AnyPointerToBlockPointerCast:
4812 case CK_ObjCObjectLValueCast:
4813 case CK_FloatingComplexToReal:
4814 case CK_FloatingComplexToBoolean:
4815 case CK_IntegralComplexToReal:
4816 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004817 case CK_ARCProduceObject:
4818 case CK_ARCConsumeObject:
4819 case CK_ARCReclaimReturnedObject:
4820 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004821 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004822
John McCallfcef3cf2010-12-14 17:51:41 +00004823 case CK_LValueToRValue:
4824 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004825 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004826
4827 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004828 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004829 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004830 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004831
4832 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004833 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004834 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004835 return false;
4836
John McCallfcef3cf2010-12-14 17:51:41 +00004837 Result.makeComplexFloat();
4838 Result.FloatImag = APFloat(Real.getSemantics());
4839 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004840 }
4841
John McCallfcef3cf2010-12-14 17:51:41 +00004842 case CK_FloatingComplexCast: {
4843 if (!Visit(E->getSubExpr()))
4844 return false;
4845
4846 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4847 QualType From
4848 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4849
Richard Smith357362d2011-12-13 06:39:58 +00004850 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4851 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004852 }
4853
4854 case CK_FloatingComplexToIntegralComplex: {
4855 if (!Visit(E->getSubExpr()))
4856 return false;
4857
4858 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4859 QualType From
4860 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4861 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004862 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4863 To, Result.IntReal) &&
4864 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4865 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004866 }
4867
4868 case CK_IntegralRealToComplex: {
4869 APSInt &Real = Result.IntReal;
4870 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4871 return false;
4872
4873 Result.makeComplexInt();
4874 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4875 return true;
4876 }
4877
4878 case CK_IntegralComplexCast: {
4879 if (!Visit(E->getSubExpr()))
4880 return false;
4881
4882 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4883 QualType From
4884 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4885
4886 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4887 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4888 return true;
4889 }
4890
4891 case CK_IntegralComplexToFloatingComplex: {
4892 if (!Visit(E->getSubExpr()))
4893 return false;
4894
4895 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4896 QualType From
4897 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4898 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00004899 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4900 To, Result.FloatReal) &&
4901 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4902 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004903 }
4904 }
4905
4906 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004907 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004908}
4909
John McCall93d91dc2010-05-07 17:22:02 +00004910bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004911 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004912 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4913
John McCall93d91dc2010-05-07 17:22:02 +00004914 if (!Visit(E->getLHS()))
4915 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004916
John McCall93d91dc2010-05-07 17:22:02 +00004917 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004918 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004919 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004920
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004921 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4922 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004923 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004924 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004925 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004926 if (Result.isComplexFloat()) {
4927 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4928 APFloat::rmNearestTiesToEven);
4929 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4930 APFloat::rmNearestTiesToEven);
4931 } else {
4932 Result.getComplexIntReal() += RHS.getComplexIntReal();
4933 Result.getComplexIntImag() += RHS.getComplexIntImag();
4934 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004935 break;
John McCalle3027922010-08-25 11:45:40 +00004936 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004937 if (Result.isComplexFloat()) {
4938 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4939 APFloat::rmNearestTiesToEven);
4940 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4941 APFloat::rmNearestTiesToEven);
4942 } else {
4943 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4944 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4945 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004946 break;
John McCalle3027922010-08-25 11:45:40 +00004947 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004948 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004949 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004950 APFloat &LHS_r = LHS.getComplexFloatReal();
4951 APFloat &LHS_i = LHS.getComplexFloatImag();
4952 APFloat &RHS_r = RHS.getComplexFloatReal();
4953 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004954
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004955 APFloat Tmp = LHS_r;
4956 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4957 Result.getComplexFloatReal() = Tmp;
4958 Tmp = LHS_i;
4959 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4960 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4961
4962 Tmp = LHS_r;
4963 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4964 Result.getComplexFloatImag() = Tmp;
4965 Tmp = LHS_i;
4966 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4967 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4968 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004969 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004970 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004971 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4972 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004973 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004974 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4975 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4976 }
4977 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004978 case BO_Div:
4979 if (Result.isComplexFloat()) {
4980 ComplexValue LHS = Result;
4981 APFloat &LHS_r = LHS.getComplexFloatReal();
4982 APFloat &LHS_i = LHS.getComplexFloatImag();
4983 APFloat &RHS_r = RHS.getComplexFloatReal();
4984 APFloat &RHS_i = RHS.getComplexFloatImag();
4985 APFloat &Res_r = Result.getComplexFloatReal();
4986 APFloat &Res_i = Result.getComplexFloatImag();
4987
4988 APFloat Den = RHS_r;
4989 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4990 APFloat Tmp = RHS_i;
4991 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4992 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4993
4994 Res_r = LHS_r;
4995 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4996 Tmp = LHS_i;
4997 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4998 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4999 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5000
5001 Res_i = LHS_i;
5002 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5003 Tmp = LHS_r;
5004 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5005 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5006 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5007 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005008 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5009 return Error(E, diag::note_expr_divide_by_zero);
5010
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005011 ComplexValue LHS = Result;
5012 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5013 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5014 Result.getComplexIntReal() =
5015 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5016 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5017 Result.getComplexIntImag() =
5018 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5019 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5020 }
5021 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005022 }
5023
John McCall93d91dc2010-05-07 17:22:02 +00005024 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005025}
5026
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005027bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5028 // Get the operand value into 'Result'.
5029 if (!Visit(E->getSubExpr()))
5030 return false;
5031
5032 switch (E->getOpcode()) {
5033 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005034 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005035 case UO_Extension:
5036 return true;
5037 case UO_Plus:
5038 // The result is always just the subexpr.
5039 return true;
5040 case UO_Minus:
5041 if (Result.isComplexFloat()) {
5042 Result.getComplexFloatReal().changeSign();
5043 Result.getComplexFloatImag().changeSign();
5044 }
5045 else {
5046 Result.getComplexIntReal() = -Result.getComplexIntReal();
5047 Result.getComplexIntImag() = -Result.getComplexIntImag();
5048 }
5049 return true;
5050 case UO_Not:
5051 if (Result.isComplexFloat())
5052 Result.getComplexFloatImag().changeSign();
5053 else
5054 Result.getComplexIntImag() = -Result.getComplexIntImag();
5055 return true;
5056 }
5057}
5058
Anders Carlsson537969c2008-11-16 20:27:53 +00005059//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00005060// Void expression evaluation, primarily for a cast to void on the LHS of a
5061// comma operator
5062//===----------------------------------------------------------------------===//
5063
5064namespace {
5065class VoidExprEvaluator
5066 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5067public:
5068 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5069
5070 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00005071
5072 bool VisitCastExpr(const CastExpr *E) {
5073 switch (E->getCastKind()) {
5074 default:
5075 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5076 case CK_ToVoid:
5077 VisitIgnoredValue(E->getSubExpr());
5078 return true;
5079 }
5080 }
5081};
5082} // end anonymous namespace
5083
5084static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5085 assert(E->isRValue() && E->getType()->isVoidType());
5086 return VoidExprEvaluator(Info).Visit(E);
5087}
5088
5089//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00005090// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00005091//===----------------------------------------------------------------------===//
5092
Richard Smith0b0a0b62011-10-29 20:57:55 +00005093static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005094 // In C, function designators are not lvalues, but we evaluate them as if they
5095 // are.
5096 if (E->isGLValue() || E->getType()->isFunctionType()) {
5097 LValue LV;
5098 if (!EvaluateLValue(E, LV, Info))
5099 return false;
5100 LV.moveInto(Result);
5101 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005102 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005103 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005104 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005105 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005106 return false;
John McCall45d55e42010-05-07 21:00:08 +00005107 } else if (E->getType()->hasPointerRepresentation()) {
5108 LValue LV;
5109 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005110 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005111 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00005112 } else if (E->getType()->isRealFloatingType()) {
5113 llvm::APFloat F(0.0);
5114 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005115 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005116 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00005117 } else if (E->getType()->isAnyComplexType()) {
5118 ComplexValue C;
5119 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005120 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005121 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00005122 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00005123 MemberPtr P;
5124 if (!EvaluateMemberPointer(E, P, Info))
5125 return false;
5126 P.moveInto(Result);
5127 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00005128 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005129 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005130 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005131 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00005132 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005133 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00005134 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005135 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005136 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005137 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5138 return false;
5139 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00005140 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00005141 if (Info.getLangOpts().CPlusPlus0x)
5142 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5143 << E->getType();
5144 else
5145 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00005146 if (!EvaluateVoid(E, Info))
5147 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005148 } else if (Info.getLangOpts().CPlusPlus0x) {
5149 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5150 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005151 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00005152 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00005153 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005154 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005155
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00005156 return true;
5157}
5158
Richard Smithed5165f2011-11-04 05:33:44 +00005159/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5160/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5161/// since later initializers for an object can indirectly refer to subobjects
5162/// which were initialized earlier.
5163static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00005164 const LValue &This, const Expr *E,
5165 CheckConstantExpressionKind CCEK) {
Richard Smithfddd3842011-12-30 21:15:51 +00005166 if (!CheckLiteralType(Info, E))
5167 return false;
5168
5169 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00005170 // Evaluate arrays and record types in-place, so that later initializers can
5171 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00005172 if (E->getType()->isArrayType())
5173 return EvaluateArray(E, This, Result, Info);
5174 else if (E->getType()->isRecordType())
5175 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00005176 }
5177
5178 // For any other type, in-place evaluation is unimportant.
5179 CCValue CoreConstResult;
5180 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00005181 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00005182}
5183
Richard Smithf57d8cb2011-12-09 22:58:01 +00005184/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5185/// lvalue-to-rvalue cast if it is an lvalue.
5186static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00005187 if (!CheckLiteralType(Info, E))
5188 return false;
5189
Richard Smithf57d8cb2011-12-09 22:58:01 +00005190 CCValue Value;
5191 if (!::Evaluate(Value, Info, E))
5192 return false;
5193
5194 if (E->isGLValue()) {
5195 LValue LV;
5196 LV.setFrom(Value);
5197 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5198 return false;
5199 }
5200
5201 // Check this core constant expression is a constant expression, and if so,
5202 // convert it to one.
5203 return CheckConstantExpression(Info, E, Value, Result);
5204}
Richard Smith11562c52011-10-28 17:51:58 +00005205
Richard Smith7b553f12011-10-29 00:50:52 +00005206/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00005207/// any crazy technique (that has nothing to do with language standards) that
5208/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00005209/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5210/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00005211bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00005212 // Fast-path evaluations of integer literals, since we sometimes see files
5213 // containing vast quantities of these.
5214 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5215 Result.Val = APValue(APSInt(L->getValue(),
5216 L->getType()->isUnsignedIntegerType()));
5217 return true;
5218 }
5219
Richard Smith5686e752011-11-10 03:30:42 +00005220 // FIXME: Evaluating initializers for large arrays can cause performance
5221 // problems, and we don't use such values yet. Once we have a more efficient
5222 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00005223 // The same problem affects large records.
5224 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5225 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00005226 return false;
5227
Richard Smithd62306a2011-11-10 06:34:14 +00005228 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005229 EvalInfo Info(Ctx, Result);
5230 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00005231}
5232
Jay Foad39c79802011-01-12 09:06:06 +00005233bool Expr::EvaluateAsBooleanCondition(bool &Result,
5234 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005235 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00005236 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00005237 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00005238 Result);
John McCall1be1c632010-01-05 23:42:56 +00005239}
5240
Richard Smith5fab0c92011-12-28 19:48:30 +00005241bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5242 SideEffectsKind AllowSideEffects) const {
5243 if (!getType()->isIntegralOrEnumerationType())
5244 return false;
5245
Richard Smith11562c52011-10-28 17:51:58 +00005246 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00005247 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5248 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00005249 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005250
Richard Smith11562c52011-10-28 17:51:58 +00005251 Result = ExprResult.Val.getInt();
5252 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00005253}
5254
Jay Foad39c79802011-01-12 09:06:06 +00005255bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00005256 EvalInfo Info(Ctx, Result);
5257
John McCall45d55e42010-05-07 21:00:08 +00005258 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005259 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005260 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5261 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005262}
5263
Richard Smithd0b4dd62011-12-19 06:19:21 +00005264bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5265 const VarDecl *VD,
5266 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5267 Expr::EvalStatus EStatus;
5268 EStatus.Diag = &Notes;
5269
5270 EvalInfo InitInfo(Ctx, EStatus);
5271 InitInfo.setEvaluatingDecl(VD, Value);
5272
Richard Smithfddd3842011-12-30 21:15:51 +00005273 if (!CheckLiteralType(InitInfo, this))
5274 return false;
5275
Richard Smithd0b4dd62011-12-19 06:19:21 +00005276 LValue LVal;
5277 LVal.set(VD);
5278
Richard Smithfddd3842011-12-30 21:15:51 +00005279 // C++11 [basic.start.init]p2:
5280 // Variables with static storage duration or thread storage duration shall be
5281 // zero-initialized before any other initialization takes place.
5282 // This behavior is not present in C.
5283 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5284 !VD->getType()->isReferenceType()) {
5285 ImplicitValueInitExpr VIE(VD->getType());
5286 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5287 return false;
5288 }
5289
Richard Smithd0b4dd62011-12-19 06:19:21 +00005290 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5291 !EStatus.HasSideEffects;
5292}
5293
Richard Smith7b553f12011-10-29 00:50:52 +00005294/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5295/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005296bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005297 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005298 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005299}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005300
Jay Foad39c79802011-01-12 09:06:06 +00005301bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005302 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005303}
5304
Richard Smithcaf33902011-10-10 18:28:20 +00005305APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005306 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005307 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005308 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005309 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005310 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005311
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005312 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005313}
John McCall864e3962010-05-07 05:32:02 +00005314
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005315 bool Expr::EvalResult::isGlobalLValue() const {
5316 assert(Val.isLValue());
5317 return IsGlobalLValue(Val.getLValueBase());
5318 }
5319
5320
John McCall864e3962010-05-07 05:32:02 +00005321/// isIntegerConstantExpr - this recursive routine will test if an expression is
5322/// an integer constant expression.
5323
5324/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5325/// comma, etc
5326///
5327/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5328/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5329/// cast+dereference.
5330
5331// CheckICE - This function does the fundamental ICE checking: the returned
5332// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5333// Note that to reduce code duplication, this helper does no evaluation
5334// itself; the caller checks whether the expression is evaluatable, and
5335// in the rare cases where CheckICE actually cares about the evaluated
5336// value, it calls into Evalute.
5337//
5338// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005339// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005340// 1: This expression is not an ICE, but if it isn't evaluated, it's
5341// a legal subexpression for an ICE. This return value is used to handle
5342// the comma operator in C99 mode.
5343// 2: This expression is not an ICE, and is not a legal subexpression for one.
5344
Dan Gohman28ade552010-07-26 21:25:24 +00005345namespace {
5346
John McCall864e3962010-05-07 05:32:02 +00005347struct ICEDiag {
5348 unsigned Val;
5349 SourceLocation Loc;
5350
5351 public:
5352 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5353 ICEDiag() : Val(0) {}
5354};
5355
Dan Gohman28ade552010-07-26 21:25:24 +00005356}
5357
5358static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005359
5360static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5361 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005362 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005363 !EVResult.Val.isInt()) {
5364 return ICEDiag(2, E->getLocStart());
5365 }
5366 return NoDiag();
5367}
5368
5369static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5370 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005371 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005372 return ICEDiag(2, E->getLocStart());
5373 }
5374
5375 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005376#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005377#define STMT(Node, Base) case Expr::Node##Class:
5378#define EXPR(Node, Base)
5379#include "clang/AST/StmtNodes.inc"
5380 case Expr::PredefinedExprClass:
5381 case Expr::FloatingLiteralClass:
5382 case Expr::ImaginaryLiteralClass:
5383 case Expr::StringLiteralClass:
5384 case Expr::ArraySubscriptExprClass:
5385 case Expr::MemberExprClass:
5386 case Expr::CompoundAssignOperatorClass:
5387 case Expr::CompoundLiteralExprClass:
5388 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005389 case Expr::DesignatedInitExprClass:
5390 case Expr::ImplicitValueInitExprClass:
5391 case Expr::ParenListExprClass:
5392 case Expr::VAArgExprClass:
5393 case Expr::AddrLabelExprClass:
5394 case Expr::StmtExprClass:
5395 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005396 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005397 case Expr::CXXDynamicCastExprClass:
5398 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005399 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005400 case Expr::CXXNullPtrLiteralExprClass:
5401 case Expr::CXXThisExprClass:
5402 case Expr::CXXThrowExprClass:
5403 case Expr::CXXNewExprClass:
5404 case Expr::CXXDeleteExprClass:
5405 case Expr::CXXPseudoDestructorExprClass:
5406 case Expr::UnresolvedLookupExprClass:
5407 case Expr::DependentScopeDeclRefExprClass:
5408 case Expr::CXXConstructExprClass:
5409 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005410 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005411 case Expr::CXXTemporaryObjectExprClass:
5412 case Expr::CXXUnresolvedConstructExprClass:
5413 case Expr::CXXDependentScopeMemberExprClass:
5414 case Expr::UnresolvedMemberExprClass:
5415 case Expr::ObjCStringLiteralClass:
5416 case Expr::ObjCEncodeExprClass:
5417 case Expr::ObjCMessageExprClass:
5418 case Expr::ObjCSelectorExprClass:
5419 case Expr::ObjCProtocolExprClass:
5420 case Expr::ObjCIvarRefExprClass:
5421 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005422 case Expr::ObjCIsaExprClass:
5423 case Expr::ShuffleVectorExprClass:
5424 case Expr::BlockExprClass:
5425 case Expr::BlockDeclRefExprClass:
5426 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005427 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005428 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005429 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005430 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005431 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005432 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005433 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005434 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005435 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005436 return ICEDiag(2, E->getLocStart());
5437
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005438 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005439 case Expr::GNUNullExprClass:
5440 // GCC considers the GNU __null value to be an integral constant expression.
5441 return NoDiag();
5442
John McCall7c454bb2011-07-15 05:09:51 +00005443 case Expr::SubstNonTypeTemplateParmExprClass:
5444 return
5445 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5446
John McCall864e3962010-05-07 05:32:02 +00005447 case Expr::ParenExprClass:
5448 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005449 case Expr::GenericSelectionExprClass:
5450 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005451 case Expr::IntegerLiteralClass:
5452 case Expr::CharacterLiteralClass:
5453 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005454 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005455 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005456 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005457 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005458 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005459 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005460 return NoDiag();
5461 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005462 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005463 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5464 // constant expressions, but they can never be ICEs because an ICE cannot
5465 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005466 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005467 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005468 return CheckEvalInICE(E, Ctx);
5469 return ICEDiag(2, E->getLocStart());
5470 }
5471 case Expr::DeclRefExprClass:
5472 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5473 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005474 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005475 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5476
5477 // Parameter variables are never constants. Without this check,
5478 // getAnyInitializer() can find a default argument, which leads
5479 // to chaos.
5480 if (isa<ParmVarDecl>(D))
5481 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5482
5483 // C++ 7.1.5.1p2
5484 // A variable of non-volatile const-qualified integral or enumeration
5485 // type initialized by an ICE can be used in ICEs.
5486 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005487 if (!Dcl->getType()->isIntegralOrEnumerationType())
5488 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5489
Richard Smithd0b4dd62011-12-19 06:19:21 +00005490 const VarDecl *VD;
5491 // Look for a declaration of this variable that has an initializer, and
5492 // check whether it is an ICE.
5493 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5494 return NoDiag();
5495 else
5496 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005497 }
5498 }
5499 return ICEDiag(2, E->getLocStart());
5500 case Expr::UnaryOperatorClass: {
5501 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5502 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005503 case UO_PostInc:
5504 case UO_PostDec:
5505 case UO_PreInc:
5506 case UO_PreDec:
5507 case UO_AddrOf:
5508 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005509 // C99 6.6/3 allows increment and decrement within unevaluated
5510 // subexpressions of constant expressions, but they can never be ICEs
5511 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005512 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005513 case UO_Extension:
5514 case UO_LNot:
5515 case UO_Plus:
5516 case UO_Minus:
5517 case UO_Not:
5518 case UO_Real:
5519 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005520 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005521 }
5522
5523 // OffsetOf falls through here.
5524 }
5525 case Expr::OffsetOfExprClass: {
5526 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005527 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005528 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005529 // compliance: we should warn earlier for offsetof expressions with
5530 // array subscripts that aren't ICEs, and if the array subscripts
5531 // are ICEs, the value of the offsetof must be an integer constant.
5532 return CheckEvalInICE(E, Ctx);
5533 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005534 case Expr::UnaryExprOrTypeTraitExprClass: {
5535 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5536 if ((Exp->getKind() == UETT_SizeOf) &&
5537 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005538 return ICEDiag(2, E->getLocStart());
5539 return NoDiag();
5540 }
5541 case Expr::BinaryOperatorClass: {
5542 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5543 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005544 case BO_PtrMemD:
5545 case BO_PtrMemI:
5546 case BO_Assign:
5547 case BO_MulAssign:
5548 case BO_DivAssign:
5549 case BO_RemAssign:
5550 case BO_AddAssign:
5551 case BO_SubAssign:
5552 case BO_ShlAssign:
5553 case BO_ShrAssign:
5554 case BO_AndAssign:
5555 case BO_XorAssign:
5556 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005557 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5558 // constant expressions, but they can never be ICEs because an ICE cannot
5559 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005560 return ICEDiag(2, E->getLocStart());
5561
John McCalle3027922010-08-25 11:45:40 +00005562 case BO_Mul:
5563 case BO_Div:
5564 case BO_Rem:
5565 case BO_Add:
5566 case BO_Sub:
5567 case BO_Shl:
5568 case BO_Shr:
5569 case BO_LT:
5570 case BO_GT:
5571 case BO_LE:
5572 case BO_GE:
5573 case BO_EQ:
5574 case BO_NE:
5575 case BO_And:
5576 case BO_Xor:
5577 case BO_Or:
5578 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005579 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5580 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005581 if (Exp->getOpcode() == BO_Div ||
5582 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005583 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005584 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005585 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005586 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005587 if (REval == 0)
5588 return ICEDiag(1, E->getLocStart());
5589 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005590 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005591 if (LEval.isMinSignedValue())
5592 return ICEDiag(1, E->getLocStart());
5593 }
5594 }
5595 }
John McCalle3027922010-08-25 11:45:40 +00005596 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005597 if (Ctx.getLangOptions().C99) {
5598 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5599 // if it isn't evaluated.
5600 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5601 return ICEDiag(1, E->getLocStart());
5602 } else {
5603 // In both C89 and C++, commas in ICEs are illegal.
5604 return ICEDiag(2, E->getLocStart());
5605 }
5606 }
5607 if (LHSResult.Val >= RHSResult.Val)
5608 return LHSResult;
5609 return RHSResult;
5610 }
John McCalle3027922010-08-25 11:45:40 +00005611 case BO_LAnd:
5612 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005613 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5614 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5615 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5616 // Rare case where the RHS has a comma "side-effect"; we need
5617 // to actually check the condition to see whether the side
5618 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005619 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005620 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005621 return RHSResult;
5622 return NoDiag();
5623 }
5624
5625 if (LHSResult.Val >= RHSResult.Val)
5626 return LHSResult;
5627 return RHSResult;
5628 }
5629 }
5630 }
5631 case Expr::ImplicitCastExprClass:
5632 case Expr::CStyleCastExprClass:
5633 case Expr::CXXFunctionalCastExprClass:
5634 case Expr::CXXStaticCastExprClass:
5635 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005636 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005637 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005638 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005639 if (isa<ExplicitCastExpr>(E)) {
5640 if (const FloatingLiteral *FL
5641 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5642 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5643 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5644 APSInt IgnoredVal(DestWidth, !DestSigned);
5645 bool Ignored;
5646 // If the value does not fit in the destination type, the behavior is
5647 // undefined, so we are not required to treat it as a constant
5648 // expression.
5649 if (FL->getValue().convertToInteger(IgnoredVal,
5650 llvm::APFloat::rmTowardZero,
5651 &Ignored) & APFloat::opInvalidOp)
5652 return ICEDiag(2, E->getLocStart());
5653 return NoDiag();
5654 }
5655 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005656 switch (cast<CastExpr>(E)->getCastKind()) {
5657 case CK_LValueToRValue:
5658 case CK_NoOp:
5659 case CK_IntegralToBoolean:
5660 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005661 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005662 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005663 return ICEDiag(2, E->getLocStart());
5664 }
John McCall864e3962010-05-07 05:32:02 +00005665 }
John McCallc07a0c72011-02-17 10:25:35 +00005666 case Expr::BinaryConditionalOperatorClass: {
5667 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5668 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5669 if (CommonResult.Val == 2) return CommonResult;
5670 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5671 if (FalseResult.Val == 2) return FalseResult;
5672 if (CommonResult.Val == 1) return CommonResult;
5673 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005674 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005675 return FalseResult;
5676 }
John McCall864e3962010-05-07 05:32:02 +00005677 case Expr::ConditionalOperatorClass: {
5678 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5679 // If the condition (ignoring parens) is a __builtin_constant_p call,
5680 // then only the true side is actually considered in an integer constant
5681 // expression, and it is fully evaluated. This is an important GNU
5682 // extension. See GCC PR38377 for discussion.
5683 if (const CallExpr *CallCE
5684 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00005685 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5686 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00005687 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005688 if (CondResult.Val == 2)
5689 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005690
Richard Smithf57d8cb2011-12-09 22:58:01 +00005691 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5692 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005693
John McCall864e3962010-05-07 05:32:02 +00005694 if (TrueResult.Val == 2)
5695 return TrueResult;
5696 if (FalseResult.Val == 2)
5697 return FalseResult;
5698 if (CondResult.Val == 1)
5699 return CondResult;
5700 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5701 return NoDiag();
5702 // Rare case where the diagnostics depend on which side is evaluated
5703 // Note that if we get here, CondResult is 0, and at least one of
5704 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005705 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005706 return FalseResult;
5707 }
5708 return TrueResult;
5709 }
5710 case Expr::CXXDefaultArgExprClass:
5711 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5712 case Expr::ChooseExprClass: {
5713 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5714 }
5715 }
5716
5717 // Silence a GCC warning
5718 return ICEDiag(2, E->getLocStart());
5719}
5720
Richard Smithf57d8cb2011-12-09 22:58:01 +00005721/// Evaluate an expression as a C++11 integral constant expression.
5722static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5723 const Expr *E,
5724 llvm::APSInt *Value,
5725 SourceLocation *Loc) {
5726 if (!E->getType()->isIntegralOrEnumerationType()) {
5727 if (Loc) *Loc = E->getExprLoc();
5728 return false;
5729 }
5730
5731 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005732 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5733 Result.Diag = &Diags;
5734 EvalInfo Info(Ctx, Result);
5735
5736 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5737 if (!Diags.empty()) {
5738 IsICE = false;
5739 if (Loc) *Loc = Diags[0].first;
5740 } else if (!IsICE && Loc) {
5741 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005742 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005743
5744 if (!IsICE)
5745 return false;
5746
5747 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5748 if (Value) *Value = Result.Val.getInt();
5749 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005750}
5751
Richard Smith92b1ce02011-12-12 09:28:41 +00005752bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005753 if (Ctx.getLangOptions().CPlusPlus0x)
5754 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5755
John McCall864e3962010-05-07 05:32:02 +00005756 ICEDiag d = CheckICE(this, Ctx);
5757 if (d.Val != 0) {
5758 if (Loc) *Loc = d.Loc;
5759 return false;
5760 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005761 return true;
5762}
5763
5764bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5765 SourceLocation *Loc, bool isEvaluated) const {
5766 if (Ctx.getLangOptions().CPlusPlus0x)
5767 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5768
5769 if (!isIntegerConstantExpr(Ctx, Loc))
5770 return false;
5771 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005772 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005773 return true;
5774}