blob: c58a5688760dcc08c1e2792e728ca53de5fac8f9 [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:
700 return true;
701 case Expr::CallExprClass:
702 return IsStringLiteralCall(cast<CallExpr>(E));
703 // For GCC compatibility, &&label has static storage duration.
704 case Expr::AddrLabelExprClass:
705 return true;
706 // A Block literal expression may be used as the initialization value for
707 // Block variables at global or local static scope.
708 case Expr::BlockExprClass:
709 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
710 }
John McCall95007602010-05-10 23:27:23 +0000711}
712
Richard Smith80815602011-11-07 05:07:52 +0000713/// Check that this reference or pointer core constant expression is a valid
714/// value for a constant expression. Type T should be either LValue or CCValue.
715template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000716static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000717 const T &LVal, APValue &Value,
718 CheckConstantExpressionKind CCEK) {
719 APValue::LValueBase Base = LVal.getLValueBase();
720 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
721
722 if (!IsGlobalLValue(Base)) {
723 if (Info.getLangOpts().CPlusPlus0x) {
724 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
725 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
726 << E->isGLValue() << !Designator.Entries.empty()
727 << !!VD << CCEK << VD;
728 if (VD)
729 Info.Note(VD->getLocation(), diag::note_declared_at);
730 else
731 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
732 diag::note_constexpr_temporary_here);
733 } else {
Richard Smithf2b681b2011-12-21 05:04:46 +0000734 Info.Diag(E->getExprLoc());
Richard Smith357362d2011-12-13 06:39:58 +0000735 }
Richard Smith80815602011-11-07 05:07:52 +0000736 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000737 }
Richard Smith80815602011-11-07 05:07:52 +0000738
Richard Smith80815602011-11-07 05:07:52 +0000739 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000740 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000741 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith357362d2011-12-13 06:39:58 +0000742 // FIXME: This is not a core constant expression. We should have already
743 // produced a CCE diagnostic.
Richard Smith80815602011-11-07 05:07:52 +0000744 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
745 APValue::NoLValuePath());
746 return true;
747 }
748
Richard Smith357362d2011-12-13 06:39:58 +0000749 // Does this refer one past the end of some object?
750 // This is technically not an address constant expression nor a reference
751 // constant expression, but we allow it for address constant expressions.
752 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
753 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
754 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
755 << !Designator.Entries.empty() << !!VD << VD;
756 if (VD)
757 Info.Note(VD->getLocation(), diag::note_declared_at);
758 else
759 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
760 diag::note_constexpr_temporary_here);
761 return false;
762 }
763
Richard Smith80815602011-11-07 05:07:52 +0000764 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000765 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000766 return true;
767}
768
Richard Smith0b0a0b62011-10-29 20:57:55 +0000769/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000770/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000771/// If not, report an appropriate diagnostic.
772static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000773 const CCValue &CCValue, APValue &Value,
774 CheckConstantExpressionKind CCEK
775 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000776 if (!CCValue.isLValue()) {
777 Value = CCValue;
778 return true;
779 }
Richard Smith357362d2011-12-13 06:39:58 +0000780 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000781}
782
Richard Smith83c68212011-10-31 05:11:32 +0000783const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000784 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000785}
786
787static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000788 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000789}
790
Richard Smithcecf1842011-11-01 21:06:14 +0000791static bool IsWeakLValue(const LValue &Value) {
792 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000793 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000794}
795
Richard Smith027bf112011-11-17 22:56:20 +0000796static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000797 // A null base expression indicates a null pointer. These are always
798 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000799 if (!Value.getLValueBase()) {
800 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000801 return true;
802 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000803
John McCall95007602010-05-10 23:27:23 +0000804 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000805 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000806 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000807
Richard Smith027bf112011-11-17 22:56:20 +0000808 // We have a non-null base. These are generally known to be true, but if it's
809 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000810 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000811 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000812 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000813}
814
Richard Smith0b0a0b62011-10-29 20:57:55 +0000815static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000816 switch (Val.getKind()) {
817 case APValue::Uninitialized:
818 return false;
819 case APValue::Int:
820 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000821 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000822 case APValue::Float:
823 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000824 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000825 case APValue::ComplexInt:
826 Result = Val.getComplexIntReal().getBoolValue() ||
827 Val.getComplexIntImag().getBoolValue();
828 return true;
829 case APValue::ComplexFloat:
830 Result = !Val.getComplexFloatReal().isZero() ||
831 !Val.getComplexFloatImag().isZero();
832 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000833 case APValue::LValue:
834 return EvalPointerValueAsBool(Val, Result);
835 case APValue::MemberPointer:
836 Result = Val.getMemberPointerDecl();
837 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000838 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000839 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000840 case APValue::Struct:
841 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000842 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000843 }
844
Richard Smith11562c52011-10-28 17:51:58 +0000845 llvm_unreachable("unknown APValue kind");
846}
847
848static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
849 EvalInfo &Info) {
850 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000851 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000852 if (!Evaluate(Val, Info, E))
853 return false;
854 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000855}
856
Richard Smith357362d2011-12-13 06:39:58 +0000857template<typename T>
858static bool HandleOverflow(EvalInfo &Info, const Expr *E,
859 const T &SrcValue, QualType DestType) {
860 llvm::SmallVector<char, 32> Buffer;
861 SrcValue.toString(Buffer);
862 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
863 << StringRef(Buffer.data(), Buffer.size()) << DestType;
864 return false;
865}
866
867static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
868 QualType SrcType, const APFloat &Value,
869 QualType DestType, APSInt &Result) {
870 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000871 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000872 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000873
Richard Smith357362d2011-12-13 06:39:58 +0000874 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000875 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000876 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
877 & APFloat::opInvalidOp)
878 return HandleOverflow(Info, E, Value, DestType);
879 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000880}
881
Richard Smith357362d2011-12-13 06:39:58 +0000882static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
883 QualType SrcType, QualType DestType,
884 APFloat &Result) {
885 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000886 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000887 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
888 APFloat::rmNearestTiesToEven, &ignored)
889 & APFloat::opOverflow)
890 return HandleOverflow(Info, E, Value, DestType);
891 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000892}
893
Mike Stump11289f42009-09-09 15:08:12 +0000894static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000895 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000896 unsigned DestWidth = Ctx.getIntWidth(DestType);
897 APSInt Result = Value;
898 // Figure out if this is a truncate, extend or noop cast.
899 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000900 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000901 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000902 return Result;
903}
904
Richard Smith357362d2011-12-13 06:39:58 +0000905static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
906 QualType SrcType, const APSInt &Value,
907 QualType DestType, APFloat &Result) {
908 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
909 if (Result.convertFromAPInt(Value, Value.isSigned(),
910 APFloat::rmNearestTiesToEven)
911 & APFloat::opOverflow)
912 return HandleOverflow(Info, E, Value, DestType);
913 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000914}
915
Richard Smith027bf112011-11-17 22:56:20 +0000916static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
917 const CXXRecordDecl *&MostDerivedType,
918 unsigned &MostDerivedPathLength,
919 bool &MostDerivedIsArrayElement) {
920 const SubobjectDesignator &D = LVal.Designator;
921 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000922 return false;
923
Richard Smith027bf112011-11-17 22:56:20 +0000924 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000925
926 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000927 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000928 MostDerivedPathLength = 0;
929 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000930
931 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
932 bool IsArray = T && T->isArrayType();
933 if (IsArray)
934 T = T->getBaseElementTypeUnsafe();
935 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
936 T = FD->getType().getTypePtr();
937 else
938 T = 0;
939
940 if (T) {
941 MostDerivedType = T->getAsCXXRecordDecl();
942 MostDerivedPathLength = I + 1;
943 MostDerivedIsArrayElement = IsArray;
944 }
945 }
946
Richard Smithd62306a2011-11-10 06:34:14 +0000947 // (B*)&d + 1 has no most-derived object.
948 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
949 return false;
950
Richard Smith027bf112011-11-17 22:56:20 +0000951 return MostDerivedType != 0;
952}
953
954static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
955 const RecordDecl *TruncatedType,
956 unsigned TruncatedElements,
957 bool IsArrayElement) {
958 SubobjectDesignator &D = Result.Designator;
959 const RecordDecl *RD = TruncatedType;
960 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +0000961 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
962 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +0000963 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +0000964 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +0000965 else
Richard Smithd62306a2011-11-10 06:34:14 +0000966 Result.Offset -= Layout.getBaseClassOffset(Base);
967 RD = Base;
968 }
Richard Smith027bf112011-11-17 22:56:20 +0000969 D.Entries.resize(TruncatedElements);
970 D.ArrayElement = IsArrayElement;
971}
972
973/// If the given LValue refers to a base subobject of some object, find the most
974/// derived object and the corresponding complete record type. This is necessary
975/// in order to find the offset of a virtual base class.
976static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
977 const CXXRecordDecl *&MostDerivedType) {
978 unsigned MostDerivedPathLength;
979 bool MostDerivedIsArrayElement;
980 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
981 MostDerivedPathLength, MostDerivedIsArrayElement))
982 return false;
983
984 // Remove the trailing base class path entries and their offsets.
985 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
986 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +0000987 return true;
988}
989
990static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
991 const CXXRecordDecl *Derived,
992 const CXXRecordDecl *Base,
993 const ASTRecordLayout *RL = 0) {
994 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
995 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
996 Obj.Designator.addDecl(Base, /*Virtual*/ false);
997}
998
999static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1000 const CXXRecordDecl *DerivedDecl,
1001 const CXXBaseSpecifier *Base) {
1002 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1003
1004 if (!Base->isVirtual()) {
1005 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1006 return true;
1007 }
1008
1009 // Extract most-derived object and corresponding type.
1010 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1011 return false;
1012
1013 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1014 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1015 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1016 return true;
1017}
1018
1019/// Update LVal to refer to the given field, which must be a member of the type
1020/// currently described by LVal.
1021static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1022 const FieldDecl *FD,
1023 const ASTRecordLayout *RL = 0) {
1024 if (!RL)
1025 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1026
1027 unsigned I = FD->getFieldIndex();
1028 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1029 LVal.Designator.addDecl(FD);
1030}
1031
1032/// Get the size of the given type in char units.
1033static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1034 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1035 // extension.
1036 if (Type->isVoidType() || Type->isFunctionType()) {
1037 Size = CharUnits::One();
1038 return true;
1039 }
1040
1041 if (!Type->isConstantSizeType()) {
1042 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1043 return false;
1044 }
1045
1046 Size = Info.Ctx.getTypeSizeInChars(Type);
1047 return true;
1048}
1049
1050/// Update a pointer value to model pointer arithmetic.
1051/// \param Info - Information about the ongoing evaluation.
1052/// \param LVal - The pointer value to be updated.
1053/// \param EltTy - The pointee type represented by LVal.
1054/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1055static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1056 QualType EltTy, int64_t Adjustment) {
1057 CharUnits SizeOfPointee;
1058 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1059 return false;
1060
1061 // Compute the new offset in the appropriate width.
1062 LVal.Offset += Adjustment * SizeOfPointee;
1063 LVal.Designator.adjustIndex(Adjustment);
1064 return true;
1065}
1066
Richard Smith27908702011-10-24 17:54:18 +00001067/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001068static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1069 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001070 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001071 // If this is a parameter to an active constexpr function call, perform
1072 // argument substitution.
1073 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001074 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001075 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001076 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001077 }
Richard Smithfec09922011-11-01 16:57:24 +00001078 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1079 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001080 }
Richard Smith27908702011-10-24 17:54:18 +00001081
Richard Smithd0b4dd62011-12-19 06:19:21 +00001082 // Dig out the initializer, and use the declaration which it's attached to.
1083 const Expr *Init = VD->getAnyInitializer(VD);
1084 if (!Init || Init->isValueDependent()) {
1085 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1086 return false;
1087 }
1088
Richard Smithd62306a2011-11-10 06:34:14 +00001089 // If we're currently evaluating the initializer of this declaration, use that
1090 // in-flight value.
1091 if (Info.EvaluatingDecl == VD) {
1092 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1093 return !Result.isUninit();
1094 }
1095
Richard Smithcecf1842011-11-01 21:06:14 +00001096 // Never evaluate the initializer of a weak variable. We can't be sure that
1097 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001098 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001099 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001100 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001101 }
Richard Smithcecf1842011-11-01 21:06:14 +00001102
Richard Smithd0b4dd62011-12-19 06:19:21 +00001103 // Check that we can fold the initializer. In C++, we will have already done
1104 // this in the cases where it matters for conformance.
1105 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1106 if (!VD->evaluateValue(Notes)) {
1107 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1108 Notes.size() + 1) << VD;
1109 Info.Note(VD->getLocation(), diag::note_declared_at);
1110 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001111 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001112 } else if (!VD->checkInitIsICE()) {
1113 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1114 Notes.size() + 1) << VD;
1115 Info.Note(VD->getLocation(), diag::note_declared_at);
1116 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001117 }
Richard Smith27908702011-10-24 17:54:18 +00001118
Richard Smithd0b4dd62011-12-19 06:19:21 +00001119 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001120 return true;
Richard Smith27908702011-10-24 17:54:18 +00001121}
1122
Richard Smith11562c52011-10-28 17:51:58 +00001123static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001124 Qualifiers Quals = T.getQualifiers();
1125 return Quals.hasConst() && !Quals.hasVolatile();
1126}
1127
Richard Smithe97cbd72011-11-11 04:05:33 +00001128/// Get the base index of the given base class within an APValue representing
1129/// the given derived class.
1130static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1131 const CXXRecordDecl *Base) {
1132 Base = Base->getCanonicalDecl();
1133 unsigned Index = 0;
1134 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1135 E = Derived->bases_end(); I != E; ++I, ++Index) {
1136 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1137 return Index;
1138 }
1139
1140 llvm_unreachable("base class missing from derived class's bases list");
1141}
1142
Richard Smithf3e9e432011-11-07 09:22:26 +00001143/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001144static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1145 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001146 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001147 if (Sub.Invalid) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001148 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001149 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001150 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001151 if (Sub.OnePastTheEnd) {
1152 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001153 (unsigned)diag::note_constexpr_read_past_end :
1154 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001155 return false;
1156 }
Richard Smith6804be52011-11-11 08:28:03 +00001157 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001158 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001159
1160 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1161 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001162 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001163 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001164 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001165 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001166 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001167 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001168 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001169 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001170 // Note, it should not be possible to form a pointer with a valid
1171 // designator which points more than one past the end of the array.
1172 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001173 (unsigned)diag::note_constexpr_read_past_end :
1174 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001175 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001176 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001177 if (O->getArrayInitializedElts() > Index)
1178 O = &O->getArrayInitializedElt(Index);
1179 else
1180 O = &O->getArrayFiller();
1181 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001182 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1183 // Next subobject is a class, struct or union field.
1184 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1185 if (RD->isUnion()) {
1186 const FieldDecl *UnionField = O->getUnionField();
1187 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001188 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001189 Info.Diag(E->getExprLoc(),
1190 diag::note_constexpr_read_inactive_union_member)
1191 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001192 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001193 }
Richard Smithd62306a2011-11-10 06:34:14 +00001194 O = &O->getUnionValue();
1195 } else
1196 O = &O->getStructField(Field->getFieldIndex());
1197 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001198
1199 if (ObjType.isVolatileQualified()) {
1200 if (Info.getLangOpts().CPlusPlus) {
1201 // FIXME: Include a description of the path to the volatile subobject.
1202 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1203 << 2 << Field;
1204 Info.Note(Field->getLocation(), diag::note_declared_at);
1205 } else {
1206 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1207 }
1208 return false;
1209 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001210 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001211 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001212 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1213 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1214 O = &O->getStructBase(getBaseIndex(Derived, Base));
1215 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001216 }
Richard Smithd62306a2011-11-10 06:34:14 +00001217
Richard Smithf57d8cb2011-12-09 22:58:01 +00001218 if (O->isUninit()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001219 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001220 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001221 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001222 }
1223
Richard Smithf3e9e432011-11-07 09:22:26 +00001224 Obj = CCValue(*O, CCValue::GlobalValue());
1225 return true;
1226}
1227
Richard Smithd62306a2011-11-10 06:34:14 +00001228/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1229/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1230/// for looking up the glvalue referred to by an entity of reference type.
1231///
1232/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001233/// \param Conv - The expression for which we are performing the conversion.
1234/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001235/// \param Type - The type we expect this conversion to produce.
1236/// \param LVal - The glvalue on which we are attempting to perform this action.
1237/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001238static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1239 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001240 const LValue &LVal, CCValue &RVal) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001241 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1242 if (!Info.getLangOpts().CPlusPlus)
1243 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1244
Richard Smithce40ad62011-11-12 22:28:03 +00001245 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001246 CallStackFrame *Frame = LVal.Frame;
Richard Smithf2b681b2011-12-21 05:04:46 +00001247 SourceLocation Loc = Conv->getExprLoc();
Richard Smith11562c52011-10-28 17:51:58 +00001248
Richard Smithf57d8cb2011-12-09 22:58:01 +00001249 if (!LVal.Base) {
1250 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithf2b681b2011-12-21 05:04:46 +00001251 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1252 return false;
1253 }
1254
1255 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1256 // is not a constant expression (even if the object is non-volatile). We also
1257 // apply this rule to C++98, in order to conform to the expected 'volatile'
1258 // semantics.
1259 if (Type.isVolatileQualified()) {
1260 if (Info.getLangOpts().CPlusPlus)
1261 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1262 else
1263 Info.Diag(Loc);
Richard Smith11562c52011-10-28 17:51:58 +00001264 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001265 }
Richard Smith11562c52011-10-28 17:51:58 +00001266
Richard Smithce40ad62011-11-12 22:28:03 +00001267 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001268 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1269 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001270 // expressions are constant expressions too. Inside constexpr functions,
1271 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001272 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001273 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001274 if (!VD || VD->isInvalidDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001275 Info.Diag(Loc);
Richard Smith96e0c102011-11-04 02:25:55 +00001276 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001277 }
1278
Richard Smithf2b681b2011-12-21 05:04:46 +00001279 // DR1313: If the object is volatile-qualified but the glvalue was not,
1280 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001281 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001282 if (VT.isVolatileQualified()) {
1283 if (Info.getLangOpts().CPlusPlus) {
1284 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1285 Info.Note(VD->getLocation(), diag::note_declared_at);
1286 } else {
1287 Info.Diag(Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001288 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001289 return false;
1290 }
1291
1292 if (!isa<ParmVarDecl>(VD)) {
1293 if (VD->isConstexpr()) {
1294 // OK, we can read this variable.
1295 } else if (VT->isIntegralOrEnumerationType()) {
1296 if (!VT.isConstQualified()) {
1297 if (Info.getLangOpts().CPlusPlus) {
1298 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1299 Info.Note(VD->getLocation(), diag::note_declared_at);
1300 } else {
1301 Info.Diag(Loc);
1302 }
1303 return false;
1304 }
1305 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1306 // We support folding of const floating-point types, in order to make
1307 // static const data members of such types (supported as an extension)
1308 // more useful.
1309 if (Info.getLangOpts().CPlusPlus0x) {
1310 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1311 Info.Note(VD->getLocation(), diag::note_declared_at);
1312 } else {
1313 Info.CCEDiag(Loc);
1314 }
1315 } else {
1316 // FIXME: Allow folding of values of any literal type in all languages.
1317 if (Info.getLangOpts().CPlusPlus0x) {
1318 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1319 Info.Note(VD->getLocation(), diag::note_declared_at);
1320 } else {
1321 Info.Diag(Loc);
1322 }
Richard Smith96e0c102011-11-04 02:25:55 +00001323 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001324 }
Richard Smith96e0c102011-11-04 02:25:55 +00001325 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001326
Richard Smithf57d8cb2011-12-09 22:58:01 +00001327 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001328 return false;
1329
Richard Smith0b0a0b62011-10-29 20:57:55 +00001330 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001331 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001332
1333 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1334 // conversion. This happens when the declaration and the lvalue should be
1335 // considered synonymous, for instance when initializing an array of char
1336 // from a string literal. Continue as if the initializer lvalue was the
1337 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001338 assert(RVal.getLValueOffset().isZero() &&
1339 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001340 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001341 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001342 }
1343
Richard Smithf2b681b2011-12-21 05:04:46 +00001344 // Volatile temporary objects cannot be read in constant expressions.
1345 if (Base->getType().isVolatileQualified()) {
1346 if (Info.getLangOpts().CPlusPlus) {
1347 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1348 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1349 } else {
1350 Info.Diag(Loc);
1351 }
1352 return false;
1353 }
1354
Richard Smith96e0c102011-11-04 02:25:55 +00001355 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1356 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1357 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001358 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001359 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001360 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001361 }
Richard Smith96e0c102011-11-04 02:25:55 +00001362
1363 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001364 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf2b681b2011-12-21 05:04:46 +00001365 const ConstantArrayType *CAT =
1366 Info.Ctx.getAsConstantArrayType(S->getType());
1367 if (Index >= CAT->getSize().getZExtValue()) {
1368 // Note, it should not be possible to form a pointer which points more
1369 // than one past the end of the array without producing a prior const expr
1370 // diagnostic.
1371 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith96e0c102011-11-04 02:25:55 +00001372 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001373 }
Richard Smith96e0c102011-11-04 02:25:55 +00001374 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1375 Type->isUnsignedIntegerType());
1376 if (Index < S->getLength())
1377 Value = S->getCodeUnit(Index);
1378 RVal = CCValue(Value);
1379 return true;
1380 }
1381
Richard Smithf3e9e432011-11-07 09:22:26 +00001382 if (Frame) {
1383 // If this is a temporary expression with a nontrivial initializer, grab the
1384 // value from the relevant stack frame.
1385 RVal = Frame->Temporaries[Base];
1386 } else if (const CompoundLiteralExpr *CLE
1387 = dyn_cast<CompoundLiteralExpr>(Base)) {
1388 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1389 // initializer until now for such expressions. Such an expression can't be
1390 // an ICE in C, so this only matters for fold.
1391 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1392 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1393 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001394 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001395 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001396 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001397 }
Richard Smith96e0c102011-11-04 02:25:55 +00001398
Richard Smithf57d8cb2011-12-09 22:58:01 +00001399 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1400 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001401}
1402
Richard Smithe97cbd72011-11-11 04:05:33 +00001403/// Build an lvalue for the object argument of a member function call.
1404static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1405 LValue &This) {
1406 if (Object->getType()->isPointerType())
1407 return EvaluatePointer(Object, This, Info);
1408
1409 if (Object->isGLValue())
1410 return EvaluateLValue(Object, This, Info);
1411
Richard Smith027bf112011-11-17 22:56:20 +00001412 if (Object->getType()->isLiteralType())
1413 return EvaluateTemporary(Object, This, Info);
1414
1415 return false;
1416}
1417
1418/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1419/// lvalue referring to the result.
1420///
1421/// \param Info - Information about the ongoing evaluation.
1422/// \param BO - The member pointer access operation.
1423/// \param LV - Filled in with a reference to the resulting object.
1424/// \param IncludeMember - Specifies whether the member itself is included in
1425/// the resulting LValue subobject designator. This is not possible when
1426/// creating a bound member function.
1427/// \return The field or method declaration to which the member pointer refers,
1428/// or 0 if evaluation fails.
1429static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1430 const BinaryOperator *BO,
1431 LValue &LV,
1432 bool IncludeMember = true) {
1433 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1434
1435 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1436 return 0;
1437
1438 MemberPtr MemPtr;
1439 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1440 return 0;
1441
1442 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1443 // member value, the behavior is undefined.
1444 if (!MemPtr.getDecl())
1445 return 0;
1446
1447 if (MemPtr.isDerivedMember()) {
1448 // This is a member of some derived class. Truncate LV appropriately.
1449 const CXXRecordDecl *MostDerivedType;
1450 unsigned MostDerivedPathLength;
1451 bool MostDerivedIsArrayElement;
1452 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1453 MostDerivedIsArrayElement))
1454 return 0;
1455
1456 // The end of the derived-to-base path for the base object must match the
1457 // derived-to-base path for the member pointer.
1458 if (MostDerivedPathLength + MemPtr.Path.size() >
1459 LV.Designator.Entries.size())
1460 return 0;
1461 unsigned PathLengthToMember =
1462 LV.Designator.Entries.size() - MemPtr.Path.size();
1463 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1464 const CXXRecordDecl *LVDecl = getAsBaseClass(
1465 LV.Designator.Entries[PathLengthToMember + I]);
1466 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1467 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1468 return 0;
1469 }
1470
1471 // Truncate the lvalue to the appropriate derived class.
1472 bool ResultIsArray = false;
1473 if (PathLengthToMember == MostDerivedPathLength)
1474 ResultIsArray = MostDerivedIsArrayElement;
1475 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1476 PathLengthToMember, ResultIsArray);
1477 } else if (!MemPtr.Path.empty()) {
1478 // Extend the LValue path with the member pointer's path.
1479 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1480 MemPtr.Path.size() + IncludeMember);
1481
1482 // Walk down to the appropriate base class.
1483 QualType LVType = BO->getLHS()->getType();
1484 if (const PointerType *PT = LVType->getAs<PointerType>())
1485 LVType = PT->getPointeeType();
1486 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1487 assert(RD && "member pointer access on non-class-type expression");
1488 // The first class in the path is that of the lvalue.
1489 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1490 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1491 HandleLValueDirectBase(Info, LV, RD, Base);
1492 RD = Base;
1493 }
1494 // Finally cast to the class containing the member.
1495 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1496 }
1497
1498 // Add the member. Note that we cannot build bound member functions here.
1499 if (IncludeMember) {
1500 // FIXME: Deal with IndirectFieldDecls.
1501 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1502 if (!FD) return 0;
1503 HandleLValueMember(Info, LV, FD);
1504 }
1505
1506 return MemPtr.getDecl();
1507}
1508
1509/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1510/// the provided lvalue, which currently refers to the base object.
1511static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1512 LValue &Result) {
1513 const CXXRecordDecl *MostDerivedType;
1514 unsigned MostDerivedPathLength;
1515 bool MostDerivedIsArrayElement;
1516
1517 // Check this cast doesn't take us outside the object.
1518 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1519 MostDerivedPathLength,
1520 MostDerivedIsArrayElement))
1521 return false;
1522 SubobjectDesignator &D = Result.Designator;
1523 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1524 return false;
1525
1526 // Check the type of the final cast. We don't need to check the path,
1527 // since a cast can only be formed if the path is unique.
1528 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1529 bool ResultIsArray = false;
1530 QualType TargetQT = E->getType();
1531 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1532 TargetQT = PT->getPointeeType();
1533 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1534 const CXXRecordDecl *FinalType;
1535 if (NewEntriesSize == MostDerivedPathLength) {
1536 ResultIsArray = MostDerivedIsArrayElement;
1537 FinalType = MostDerivedType;
1538 } else
1539 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1540 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1541 return false;
1542
1543 // Truncate the lvalue to the appropriate derived class.
1544 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1545 ResultIsArray);
1546 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001547}
1548
Mike Stump876387b2009-10-27 22:09:17 +00001549namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001550enum EvalStmtResult {
1551 /// Evaluation failed.
1552 ESR_Failed,
1553 /// Hit a 'return' statement.
1554 ESR_Returned,
1555 /// Evaluation succeeded.
1556 ESR_Succeeded
1557};
1558}
1559
1560// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001561static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001562 const Stmt *S) {
1563 switch (S->getStmtClass()) {
1564 default:
1565 return ESR_Failed;
1566
1567 case Stmt::NullStmtClass:
1568 case Stmt::DeclStmtClass:
1569 return ESR_Succeeded;
1570
Richard Smith357362d2011-12-13 06:39:58 +00001571 case Stmt::ReturnStmtClass: {
1572 CCValue CCResult;
1573 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1574 if (!Evaluate(CCResult, Info, RetExpr) ||
1575 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1576 CCEK_ReturnValue))
1577 return ESR_Failed;
1578 return ESR_Returned;
1579 }
Richard Smith254a73d2011-10-28 22:34:42 +00001580
1581 case Stmt::CompoundStmtClass: {
1582 const CompoundStmt *CS = cast<CompoundStmt>(S);
1583 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1584 BE = CS->body_end(); BI != BE; ++BI) {
1585 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1586 if (ESR != ESR_Succeeded)
1587 return ESR;
1588 }
1589 return ESR_Succeeded;
1590 }
1591 }
1592}
1593
Richard Smithcc36f692011-12-22 02:22:31 +00001594/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1595/// default constructor. If so, we'll fold it whether or not it's marked as
1596/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1597/// so we need special handling.
1598static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
1599 const CXXConstructorDecl *CD) {
1600 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1601 return false;
1602
1603 if (!CD->isConstexpr()) {
1604 if (Info.getLangOpts().CPlusPlus0x) {
1605 // FIXME: If DiagDecl is an implicitly-declared special member function,
1606 // we should be much more explicit about why it's not constexpr.
1607 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1608 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1609 Info.Note(CD->getLocation(), diag::note_declared_at);
1610 } else {
1611 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1612 }
1613 }
1614 return true;
1615}
1616
Richard Smith357362d2011-12-13 06:39:58 +00001617/// CheckConstexprFunction - Check that a function can be called in a constant
1618/// expression.
1619static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1620 const FunctionDecl *Declaration,
1621 const FunctionDecl *Definition) {
1622 // Can we evaluate this function call?
1623 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1624 return true;
1625
1626 if (Info.getLangOpts().CPlusPlus0x) {
1627 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001628 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1629 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001630 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1631 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1632 << DiagDecl;
1633 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1634 } else {
1635 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1636 }
1637 return false;
1638}
1639
Richard Smithd62306a2011-11-10 06:34:14 +00001640namespace {
Richard Smith60494462011-11-11 05:48:57 +00001641typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001642}
1643
1644/// EvaluateArgs - Evaluate the arguments to a function call.
1645static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1646 EvalInfo &Info) {
1647 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1648 I != E; ++I)
1649 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1650 return false;
1651 return true;
1652}
1653
Richard Smith254a73d2011-10-28 22:34:42 +00001654/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001655static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1656 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001657 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001658 EvalInfo &Info, APValue &Result) {
1659 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001660 return false;
1661
Richard Smithd62306a2011-11-10 06:34:14 +00001662 ArgVector ArgValues(Args.size());
1663 if (!EvaluateArgs(Args, ArgValues, Info))
1664 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001665
Richard Smithf6f003a2011-12-16 19:06:07 +00001666 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1667 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001668 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1669}
1670
Richard Smithd62306a2011-11-10 06:34:14 +00001671/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001672static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001673 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001674 const CXXConstructorDecl *Definition,
Richard Smithe97cbd72011-11-11 04:05:33 +00001675 EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00001676 APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001677 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001678 return false;
1679
1680 ArgVector ArgValues(Args.size());
1681 if (!EvaluateArgs(Args, ArgValues, Info))
1682 return false;
1683
Richard Smithf6f003a2011-12-16 19:06:07 +00001684 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1685 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001686
1687 // If it's a delegating constructor, just delegate.
1688 if (Definition->isDelegatingConstructor()) {
1689 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1690 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1691 }
1692
1693 // Reserve space for the struct members.
1694 const CXXRecordDecl *RD = Definition->getParent();
1695 if (!RD->isUnion())
1696 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1697 std::distance(RD->field_begin(), RD->field_end()));
1698
1699 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1700
1701 unsigned BasesSeen = 0;
1702#ifndef NDEBUG
1703 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1704#endif
1705 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1706 E = Definition->init_end(); I != E; ++I) {
1707 if ((*I)->isBaseInitializer()) {
1708 QualType BaseType((*I)->getBaseClass(), 0);
1709#ifndef NDEBUG
1710 // Non-virtual base classes are initialized in the order in the class
1711 // definition. We cannot have a virtual base class for a literal type.
1712 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1713 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1714 "base class initializers not in expected order");
1715 ++BaseIt;
1716#endif
1717 LValue Subobject = This;
1718 HandleLValueDirectBase(Info, Subobject, RD,
1719 BaseType->getAsCXXRecordDecl(), &Layout);
1720 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1721 Subobject, (*I)->getInit()))
1722 return false;
1723 } else if (FieldDecl *FD = (*I)->getMember()) {
1724 LValue Subobject = This;
1725 HandleLValueMember(Info, Subobject, FD, &Layout);
1726 if (RD->isUnion()) {
1727 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001728 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1729 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001730 return false;
1731 } else if (!EvaluateConstantExpression(
1732 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001733 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001734 return false;
1735 } else {
1736 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001737 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001738 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001739 return false;
1740 }
1741 }
1742
1743 return true;
1744}
1745
Richard Smith254a73d2011-10-28 22:34:42 +00001746namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001747class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001748 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001749 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001750public:
1751
Richard Smith725810a2011-10-16 21:26:27 +00001752 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001753
1754 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001755 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001756 return true;
1757 }
1758
Peter Collingbournee9200682011-05-13 03:29:01 +00001759 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1760 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001761 return Visit(E->getResultExpr());
1762 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001763 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001764 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001765 return true;
1766 return false;
1767 }
John McCall31168b02011-06-15 23:02:42 +00001768 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001769 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001770 return true;
1771 return false;
1772 }
1773 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001774 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001775 return true;
1776 return false;
1777 }
1778
Mike Stump876387b2009-10-27 22:09:17 +00001779 // We don't want to evaluate BlockExprs multiple times, as they generate
1780 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001781 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1782 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1783 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001784 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001785 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1786 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1787 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1788 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1789 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1790 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001791 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001792 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001793 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001794 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001795 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001796 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1797 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1798 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1799 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001800 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001801 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1802 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1803 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1804 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1805 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001806 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001807 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001808 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001809 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001810 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001811
1812 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001813 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001814 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1815 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001816 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001817 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001818 return false;
1819 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001820
Peter Collingbournee9200682011-05-13 03:29:01 +00001821 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001822};
1823
John McCallc07a0c72011-02-17 10:25:35 +00001824class OpaqueValueEvaluation {
1825 EvalInfo &info;
1826 OpaqueValueExpr *opaqueValue;
1827
1828public:
1829 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1830 Expr *value)
1831 : info(info), opaqueValue(opaqueValue) {
1832
1833 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001834 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001835 this->opaqueValue = 0;
1836 return;
1837 }
John McCallc07a0c72011-02-17 10:25:35 +00001838 }
1839
1840 bool hasError() const { return opaqueValue == 0; }
1841
1842 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001843 // FIXME: This will not work for recursive constexpr functions using opaque
1844 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001845 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1846 }
1847};
1848
Mike Stump876387b2009-10-27 22:09:17 +00001849} // end anonymous namespace
1850
Eli Friedman9a156e52008-11-12 09:44:48 +00001851//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001852// Generic Evaluation
1853//===----------------------------------------------------------------------===//
1854namespace {
1855
Richard Smithf57d8cb2011-12-09 22:58:01 +00001856// FIXME: RetTy is always bool. Remove it.
1857template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001858class ExprEvaluatorBase
1859 : public ConstStmtVisitor<Derived, RetTy> {
1860private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001861 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001862 return static_cast<Derived*>(this)->Success(V, E);
1863 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001864 RetTy DerivedValueInitialization(const Expr *E) {
1865 return static_cast<Derived*>(this)->ValueInitialization(E);
1866 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001867
1868protected:
1869 EvalInfo &Info;
1870 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1871 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1872
Richard Smith92b1ce02011-12-12 09:28:41 +00001873 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001874 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001875 }
1876
1877 /// Report an evaluation error. This should only be called when an error is
1878 /// first discovered. When propagating an error, just return false.
1879 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001880 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001881 return false;
1882 }
1883 bool Error(const Expr *E) {
1884 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1885 }
1886
1887 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001888
Peter Collingbournee9200682011-05-13 03:29:01 +00001889public:
1890 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1891
1892 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001893 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001894 }
1895 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001896 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001897 }
1898
1899 RetTy VisitParenExpr(const ParenExpr *E)
1900 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1901 RetTy VisitUnaryExtension(const UnaryOperator *E)
1902 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1903 RetTy VisitUnaryPlus(const UnaryOperator *E)
1904 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1905 RetTy VisitChooseExpr(const ChooseExpr *E)
1906 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1907 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1908 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001909 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1910 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001911 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1912 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00001913 // We cannot create any objects for which cleanups are required, so there is
1914 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1915 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1916 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001917
Richard Smith6d6ecc32011-12-12 12:46:16 +00001918 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1919 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1920 return static_cast<Derived*>(this)->VisitCastExpr(E);
1921 }
1922 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1923 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1924 return static_cast<Derived*>(this)->VisitCastExpr(E);
1925 }
1926
Richard Smith027bf112011-11-17 22:56:20 +00001927 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1928 switch (E->getOpcode()) {
1929 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001930 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001931
1932 case BO_Comma:
1933 VisitIgnoredValue(E->getLHS());
1934 return StmtVisitorTy::Visit(E->getRHS());
1935
1936 case BO_PtrMemD:
1937 case BO_PtrMemI: {
1938 LValue Obj;
1939 if (!HandleMemberPointerAccess(Info, E, Obj))
1940 return false;
1941 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001942 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00001943 return false;
1944 return DerivedSuccess(Result, E);
1945 }
1946 }
1947 }
1948
Peter Collingbournee9200682011-05-13 03:29:01 +00001949 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1950 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1951 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001952 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001953
1954 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00001955 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001956 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001957
1958 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1959 }
1960
1961 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1962 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00001963 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001964 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001965
Richard Smith11562c52011-10-28 17:51:58 +00001966 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00001967 return StmtVisitorTy::Visit(EvalExpr);
1968 }
1969
1970 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001971 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001972 if (!Value) {
1973 const Expr *Source = E->getSourceExpr();
1974 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001975 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001976 if (Source == E) { // sanity checking.
1977 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00001978 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001979 }
1980 return StmtVisitorTy::Visit(Source);
1981 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001982 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001983 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001984
Richard Smith254a73d2011-10-28 22:34:42 +00001985 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00001986 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00001987 QualType CalleeType = Callee->getType();
1988
Richard Smith254a73d2011-10-28 22:34:42 +00001989 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00001990 LValue *This = 0, ThisVal;
1991 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00001992
Richard Smithe97cbd72011-11-11 04:05:33 +00001993 // Extract function decl and 'this' pointer from the callee.
1994 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001995 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00001996 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1997 // Explicit bound member calls, such as x.f() or p->g();
1998 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001999 return false;
2000 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002001 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002002 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2003 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002004 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2005 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002006 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002007 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002008 return Error(Callee);
2009
2010 FD = dyn_cast<FunctionDecl>(Member);
2011 if (!FD)
2012 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002013 } else if (CalleeType->isFunctionPointerType()) {
2014 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002015 if (!Evaluate(Call, Info, Callee))
2016 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002017
Richard Smithf57d8cb2011-12-09 22:58:01 +00002018 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
2019 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002020 FD = dyn_cast_or_null<FunctionDecl>(
2021 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002022 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002023 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002024
2025 // Overloaded operator calls to member functions are represented as normal
2026 // calls with '*this' as the first argument.
2027 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2028 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002029 // FIXME: When selecting an implicit conversion for an overloaded
2030 // operator delete, we sometimes try to evaluate calls to conversion
2031 // operators without a 'this' parameter!
2032 if (Args.empty())
2033 return Error(E);
2034
Richard Smithe97cbd72011-11-11 04:05:33 +00002035 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2036 return false;
2037 This = &ThisVal;
2038 Args = Args.slice(1);
2039 }
2040
2041 // Don't call function pointers which have been cast to some other type.
2042 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002043 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002044 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002045 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002046
Richard Smith357362d2011-12-13 06:39:58 +00002047 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002048 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002049 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002050
Richard Smith357362d2011-12-13 06:39:58 +00002051 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002052 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002053 return false;
2054
2055 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002056 }
2057
Richard Smith11562c52011-10-28 17:51:58 +00002058 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2059 return StmtVisitorTy::Visit(E->getInitializer());
2060 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002061 RetTy VisitInitListExpr(const InitListExpr *E) {
2062 if (Info.getLangOpts().CPlusPlus0x) {
2063 if (E->getNumInits() == 0)
2064 return DerivedValueInitialization(E);
2065 if (E->getNumInits() == 1)
2066 return StmtVisitorTy::Visit(E->getInit(0));
2067 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00002068 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002069 }
2070 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
2071 return DerivedValueInitialization(E);
2072 }
2073 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
2074 return DerivedValueInitialization(E);
2075 }
Richard Smith027bf112011-11-17 22:56:20 +00002076 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2077 return DerivedValueInitialization(E);
2078 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002079
Richard Smithd62306a2011-11-10 06:34:14 +00002080 /// A member expression where the object is a prvalue is itself a prvalue.
2081 RetTy VisitMemberExpr(const MemberExpr *E) {
2082 assert(!E->isArrow() && "missing call to bound member function?");
2083
2084 CCValue Val;
2085 if (!Evaluate(Val, Info, E->getBase()))
2086 return false;
2087
2088 QualType BaseTy = E->getBase()->getType();
2089
2090 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002091 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002092 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2093 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2094 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2095
2096 SubobjectDesignator Designator;
2097 Designator.addDecl(FD);
2098
Richard Smithf57d8cb2011-12-09 22:58:01 +00002099 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002100 DerivedSuccess(Val, E);
2101 }
2102
Richard Smith11562c52011-10-28 17:51:58 +00002103 RetTy VisitCastExpr(const CastExpr *E) {
2104 switch (E->getCastKind()) {
2105 default:
2106 break;
2107
2108 case CK_NoOp:
2109 return StmtVisitorTy::Visit(E->getSubExpr());
2110
2111 case CK_LValueToRValue: {
2112 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002113 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2114 return false;
2115 CCValue RVal;
2116 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2117 return false;
2118 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002119 }
2120 }
2121
Richard Smithf57d8cb2011-12-09 22:58:01 +00002122 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002123 }
2124
Richard Smith4a678122011-10-24 18:44:57 +00002125 /// Visit a value which is evaluated, but whose value is ignored.
2126 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002127 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002128 if (!Evaluate(Scratch, Info, E))
2129 Info.EvalStatus.HasSideEffects = true;
2130 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002131};
2132
2133}
2134
2135//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002136// Common base class for lvalue and temporary evaluation.
2137//===----------------------------------------------------------------------===//
2138namespace {
2139template<class Derived>
2140class LValueExprEvaluatorBase
2141 : public ExprEvaluatorBase<Derived, bool> {
2142protected:
2143 LValue &Result;
2144 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2145 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2146
2147 bool Success(APValue::LValueBase B) {
2148 Result.set(B);
2149 return true;
2150 }
2151
2152public:
2153 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2154 ExprEvaluatorBaseTy(Info), Result(Result) {}
2155
2156 bool Success(const CCValue &V, const Expr *E) {
2157 Result.setFrom(V);
2158 return true;
2159 }
Richard Smith027bf112011-11-17 22:56:20 +00002160
2161 bool CheckValidLValue() {
2162 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2163 // there are no null references, nor once-past-the-end references.
2164 // FIXME: Check for one-past-the-end array indices
2165 return Result.Base && !Result.Designator.Invalid &&
2166 !Result.Designator.OnePastTheEnd;
2167 }
2168
2169 bool VisitMemberExpr(const MemberExpr *E) {
2170 // Handle non-static data members.
2171 QualType BaseTy;
2172 if (E->isArrow()) {
2173 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2174 return false;
2175 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002176 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002177 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002178 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2179 return false;
2180 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002181 } else {
2182 if (!this->Visit(E->getBase()))
2183 return false;
2184 BaseTy = E->getBase()->getType();
2185 }
2186 // FIXME: In C++11, require the result to be a valid lvalue.
2187
2188 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2189 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002190 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002191 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2192 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2193 (void)BaseTy;
2194
2195 HandleLValueMember(this->Info, Result, FD);
2196
2197 if (FD->getType()->isReferenceType()) {
2198 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002199 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002200 RefValue))
2201 return false;
2202 return Success(RefValue, E);
2203 }
2204 return true;
2205 }
2206
2207 bool VisitBinaryOperator(const BinaryOperator *E) {
2208 switch (E->getOpcode()) {
2209 default:
2210 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2211
2212 case BO_PtrMemD:
2213 case BO_PtrMemI:
2214 return HandleMemberPointerAccess(this->Info, E, Result);
2215 }
2216 }
2217
2218 bool VisitCastExpr(const CastExpr *E) {
2219 switch (E->getCastKind()) {
2220 default:
2221 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2222
2223 case CK_DerivedToBase:
2224 case CK_UncheckedDerivedToBase: {
2225 if (!this->Visit(E->getSubExpr()))
2226 return false;
2227 if (!CheckValidLValue())
2228 return false;
2229
2230 // Now figure out the necessary offset to add to the base LV to get from
2231 // the derived class to the base class.
2232 QualType Type = E->getSubExpr()->getType();
2233
2234 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2235 PathE = E->path_end(); PathI != PathE; ++PathI) {
2236 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2237 *PathI))
2238 return false;
2239 Type = (*PathI)->getType();
2240 }
2241
2242 return true;
2243 }
2244 }
2245 }
2246};
2247}
2248
2249//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002250// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002251//
2252// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2253// function designators (in C), decl references to void objects (in C), and
2254// temporaries (if building with -Wno-address-of-temporary).
2255//
2256// LValue evaluation produces values comprising a base expression of one of the
2257// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002258// - Declarations
2259// * VarDecl
2260// * FunctionDecl
2261// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002262// * CompoundLiteralExpr in C
2263// * StringLiteral
2264// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002265// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002266// * ObjCEncodeExpr
2267// * AddrLabelExpr
2268// * BlockExpr
2269// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002270// - Locals and temporaries
2271// * Any Expr, with a Frame indicating the function in which the temporary was
2272// evaluated.
2273// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002274//===----------------------------------------------------------------------===//
2275namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002276class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002277 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002278public:
Richard Smith027bf112011-11-17 22:56:20 +00002279 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2280 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002281
Richard Smith11562c52011-10-28 17:51:58 +00002282 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2283
Peter Collingbournee9200682011-05-13 03:29:01 +00002284 bool VisitDeclRefExpr(const DeclRefExpr *E);
2285 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002286 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002287 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2288 bool VisitMemberExpr(const MemberExpr *E);
2289 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2290 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2291 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2292 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002293
Peter Collingbournee9200682011-05-13 03:29:01 +00002294 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002295 switch (E->getCastKind()) {
2296 default:
Richard Smith027bf112011-11-17 22:56:20 +00002297 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002298
Eli Friedmance3e02a2011-10-11 00:13:24 +00002299 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002300 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002301 if (!Visit(E->getSubExpr()))
2302 return false;
2303 Result.Designator.setInvalid();
2304 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002305
Richard Smith027bf112011-11-17 22:56:20 +00002306 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002307 if (!Visit(E->getSubExpr()))
2308 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002309 if (!CheckValidLValue())
2310 return false;
2311 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002312 }
2313 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002314
Eli Friedman449fe542009-03-23 04:56:01 +00002315 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002316
Eli Friedman9a156e52008-11-12 09:44:48 +00002317};
2318} // end anonymous namespace
2319
Richard Smith11562c52011-10-28 17:51:58 +00002320/// Evaluate an expression as an lvalue. This can be legitimately called on
2321/// expressions which are not glvalues, in a few cases:
2322/// * function designators in C,
2323/// * "extern void" objects,
2324/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002325static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002326 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2327 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2328 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002329 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002330}
2331
Peter Collingbournee9200682011-05-13 03:29:01 +00002332bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002333 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2334 return Success(FD);
2335 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002336 return VisitVarDecl(E, VD);
2337 return Error(E);
2338}
Richard Smith733237d2011-10-24 23:14:33 +00002339
Richard Smith11562c52011-10-28 17:51:58 +00002340bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002341 if (!VD->getType()->isReferenceType()) {
2342 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002343 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002344 return true;
2345 }
Richard Smithce40ad62011-11-12 22:28:03 +00002346 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002347 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002348
Richard Smith0b0a0b62011-10-29 20:57:55 +00002349 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002350 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2351 return false;
2352 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002353}
2354
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002355bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2356 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002357 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002358 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002359 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2360
2361 Result.set(E, Info.CurrentCall);
2362 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2363 Result, E->GetTemporaryExpr());
2364 }
2365
2366 // Materialization of an lvalue temporary occurs when we need to force a copy
2367 // (for instance, if it's a bitfield).
2368 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2369 if (!Visit(E->GetTemporaryExpr()))
2370 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002371 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002372 Info.CurrentCall->Temporaries[E]))
2373 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002374 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002375 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002376}
2377
Peter Collingbournee9200682011-05-13 03:29:01 +00002378bool
2379LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002380 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2381 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2382 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002383 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002384}
2385
Peter Collingbournee9200682011-05-13 03:29:01 +00002386bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002387 // Handle static data members.
2388 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2389 VisitIgnoredValue(E->getBase());
2390 return VisitVarDecl(E, VD);
2391 }
2392
Richard Smith254a73d2011-10-28 22:34:42 +00002393 // Handle static member functions.
2394 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2395 if (MD->isStatic()) {
2396 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002397 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002398 }
2399 }
2400
Richard Smithd62306a2011-11-10 06:34:14 +00002401 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002402 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002403}
2404
Peter Collingbournee9200682011-05-13 03:29:01 +00002405bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002406 // FIXME: Deal with vectors as array subscript bases.
2407 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002408 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002409
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002410 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002411 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002412
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002413 APSInt Index;
2414 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002415 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002416 int64_t IndexValue
2417 = Index.isSigned() ? Index.getSExtValue()
2418 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002419
Richard Smith027bf112011-11-17 22:56:20 +00002420 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002421 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002422}
Eli Friedman9a156e52008-11-12 09:44:48 +00002423
Peter Collingbournee9200682011-05-13 03:29:01 +00002424bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002425 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002426 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002427}
2428
Eli Friedman9a156e52008-11-12 09:44:48 +00002429//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002430// Pointer Evaluation
2431//===----------------------------------------------------------------------===//
2432
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002433namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002434class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002435 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002436 LValue &Result;
2437
Peter Collingbournee9200682011-05-13 03:29:01 +00002438 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002439 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002440 return true;
2441 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002442public:
Mike Stump11289f42009-09-09 15:08:12 +00002443
John McCall45d55e42010-05-07 21:00:08 +00002444 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002445 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002446
Richard Smith0b0a0b62011-10-29 20:57:55 +00002447 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002448 Result.setFrom(V);
2449 return true;
2450 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002451 bool ValueInitialization(const Expr *E) {
2452 return Success((Expr*)0);
2453 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002454
John McCall45d55e42010-05-07 21:00:08 +00002455 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002456 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002457 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002458 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002459 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002460 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002461 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002462 bool VisitCallExpr(const CallExpr *E);
2463 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002464 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002465 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002466 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002467 }
Richard Smithd62306a2011-11-10 06:34:14 +00002468 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2469 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002470 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002471 Result = *Info.CurrentCall->This;
2472 return true;
2473 }
John McCallc07a0c72011-02-17 10:25:35 +00002474
Eli Friedman449fe542009-03-23 04:56:01 +00002475 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002476};
Chris Lattner05706e882008-07-11 18:11:29 +00002477} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002478
John McCall45d55e42010-05-07 21:00:08 +00002479static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002480 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002481 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002482}
2483
John McCall45d55e42010-05-07 21:00:08 +00002484bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002485 if (E->getOpcode() != BO_Add &&
2486 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002487 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002488
Chris Lattner05706e882008-07-11 18:11:29 +00002489 const Expr *PExp = E->getLHS();
2490 const Expr *IExp = E->getRHS();
2491 if (IExp->getType()->isPointerType())
2492 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002493
John McCall45d55e42010-05-07 21:00:08 +00002494 if (!EvaluatePointer(PExp, Result, Info))
2495 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002496
John McCall45d55e42010-05-07 21:00:08 +00002497 llvm::APSInt Offset;
2498 if (!EvaluateInteger(IExp, Offset, Info))
2499 return false;
2500 int64_t AdditionalOffset
2501 = Offset.isSigned() ? Offset.getSExtValue()
2502 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002503 if (E->getOpcode() == BO_Sub)
2504 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002505
Richard Smithd62306a2011-11-10 06:34:14 +00002506 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002507 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002508 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002509}
Eli Friedman9a156e52008-11-12 09:44:48 +00002510
John McCall45d55e42010-05-07 21:00:08 +00002511bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2512 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002513}
Mike Stump11289f42009-09-09 15:08:12 +00002514
Peter Collingbournee9200682011-05-13 03:29:01 +00002515bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2516 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002517
Eli Friedman847a2bc2009-12-27 05:43:15 +00002518 switch (E->getCastKind()) {
2519 default:
2520 break;
2521
John McCalle3027922010-08-25 11:45:40 +00002522 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002523 case CK_CPointerToObjCPointerCast:
2524 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002525 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002526 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2527 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2528 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002529 if (!E->getType()->isVoidPointerType()) {
2530 if (SubExpr->getType()->isVoidPointerType())
2531 CCEDiag(E, diag::note_constexpr_invalid_cast)
2532 << 3 << SubExpr->getType();
2533 else
2534 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2535 }
Richard Smith96e0c102011-11-04 02:25:55 +00002536 if (!Visit(SubExpr))
2537 return false;
2538 Result.Designator.setInvalid();
2539 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002540
Anders Carlsson18275092010-10-31 20:41:46 +00002541 case CK_DerivedToBase:
2542 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002543 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002544 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002545 if (!Result.Base && Result.Offset.isZero())
2546 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002547
Richard Smithd62306a2011-11-10 06:34:14 +00002548 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002549 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002550 QualType Type =
2551 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002552
Richard Smithd62306a2011-11-10 06:34:14 +00002553 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002554 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002555 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002556 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002557 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002558 }
2559
Anders Carlsson18275092010-10-31 20:41:46 +00002560 return true;
2561 }
2562
Richard Smith027bf112011-11-17 22:56:20 +00002563 case CK_BaseToDerived:
2564 if (!Visit(E->getSubExpr()))
2565 return false;
2566 if (!Result.Base && Result.Offset.isZero())
2567 return true;
2568 return HandleBaseToDerivedCast(Info, E, Result);
2569
Richard Smith0b0a0b62011-10-29 20:57:55 +00002570 case CK_NullToPointer:
2571 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002572
John McCalle3027922010-08-25 11:45:40 +00002573 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002574 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2575
Richard Smith0b0a0b62011-10-29 20:57:55 +00002576 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002577 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002578 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002579
John McCall45d55e42010-05-07 21:00:08 +00002580 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002581 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2582 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002583 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002584 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002585 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002586 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002587 return true;
2588 } else {
2589 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002590 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002591 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002592 }
2593 }
John McCalle3027922010-08-25 11:45:40 +00002594 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002595 if (SubExpr->isGLValue()) {
2596 if (!EvaluateLValue(SubExpr, Result, Info))
2597 return false;
2598 } else {
2599 Result.set(SubExpr, Info.CurrentCall);
2600 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2601 Info, Result, SubExpr))
2602 return false;
2603 }
Richard Smith96e0c102011-11-04 02:25:55 +00002604 // The result is a pointer to the first element of the array.
2605 Result.Designator.addIndex(0);
2606 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002607
John McCalle3027922010-08-25 11:45:40 +00002608 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002609 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002610 }
2611
Richard Smith11562c52011-10-28 17:51:58 +00002612 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002613}
Chris Lattner05706e882008-07-11 18:11:29 +00002614
Peter Collingbournee9200682011-05-13 03:29:01 +00002615bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002616 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002617 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002618
Peter Collingbournee9200682011-05-13 03:29:01 +00002619 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002620}
Chris Lattner05706e882008-07-11 18:11:29 +00002621
2622//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002623// Member Pointer Evaluation
2624//===----------------------------------------------------------------------===//
2625
2626namespace {
2627class MemberPointerExprEvaluator
2628 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2629 MemberPtr &Result;
2630
2631 bool Success(const ValueDecl *D) {
2632 Result = MemberPtr(D);
2633 return true;
2634 }
2635public:
2636
2637 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2638 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2639
2640 bool Success(const CCValue &V, const Expr *E) {
2641 Result.setFrom(V);
2642 return true;
2643 }
Richard Smith027bf112011-11-17 22:56:20 +00002644 bool ValueInitialization(const Expr *E) {
2645 return Success((const ValueDecl*)0);
2646 }
2647
2648 bool VisitCastExpr(const CastExpr *E);
2649 bool VisitUnaryAddrOf(const UnaryOperator *E);
2650};
2651} // end anonymous namespace
2652
2653static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2654 EvalInfo &Info) {
2655 assert(E->isRValue() && E->getType()->isMemberPointerType());
2656 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2657}
2658
2659bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2660 switch (E->getCastKind()) {
2661 default:
2662 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2663
2664 case CK_NullToMemberPointer:
2665 return ValueInitialization(E);
2666
2667 case CK_BaseToDerivedMemberPointer: {
2668 if (!Visit(E->getSubExpr()))
2669 return false;
2670 if (E->path_empty())
2671 return true;
2672 // Base-to-derived member pointer casts store the path in derived-to-base
2673 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2674 // the wrong end of the derived->base arc, so stagger the path by one class.
2675 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2676 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2677 PathI != PathE; ++PathI) {
2678 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2679 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2680 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002681 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002682 }
2683 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2684 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002685 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002686 return true;
2687 }
2688
2689 case CK_DerivedToBaseMemberPointer:
2690 if (!Visit(E->getSubExpr()))
2691 return false;
2692 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2693 PathE = E->path_end(); PathI != PathE; ++PathI) {
2694 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2695 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2696 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002697 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002698 }
2699 return true;
2700 }
2701}
2702
2703bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2704 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2705 // member can be formed.
2706 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2707}
2708
2709//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002710// Record Evaluation
2711//===----------------------------------------------------------------------===//
2712
2713namespace {
2714 class RecordExprEvaluator
2715 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2716 const LValue &This;
2717 APValue &Result;
2718 public:
2719
2720 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2721 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2722
2723 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002724 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002725 }
Richard Smithd62306a2011-11-10 06:34:14 +00002726
Richard Smithe97cbd72011-11-11 04:05:33 +00002727 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002728 bool VisitInitListExpr(const InitListExpr *E);
2729 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2730 };
2731}
2732
Richard Smithe97cbd72011-11-11 04:05:33 +00002733bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2734 switch (E->getCastKind()) {
2735 default:
2736 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2737
2738 case CK_ConstructorConversion:
2739 return Visit(E->getSubExpr());
2740
2741 case CK_DerivedToBase:
2742 case CK_UncheckedDerivedToBase: {
2743 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002744 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002745 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002746 if (!DerivedObject.isStruct())
2747 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002748
2749 // Derived-to-base rvalue conversion: just slice off the derived part.
2750 APValue *Value = &DerivedObject;
2751 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2752 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2753 PathE = E->path_end(); PathI != PathE; ++PathI) {
2754 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2755 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2756 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2757 RD = Base;
2758 }
2759 Result = *Value;
2760 return true;
2761 }
2762 }
2763}
2764
Richard Smithd62306a2011-11-10 06:34:14 +00002765bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2766 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2767 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2768
2769 if (RD->isUnion()) {
2770 Result = APValue(E->getInitializedFieldInUnion());
2771 if (!E->getNumInits())
2772 return true;
2773 LValue Subobject = This;
2774 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2775 &Layout);
2776 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2777 Subobject, E->getInit(0));
2778 }
2779
2780 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2781 "initializer list for class with base classes");
2782 Result = APValue(APValue::UninitStruct(), 0,
2783 std::distance(RD->field_begin(), RD->field_end()));
2784 unsigned ElementNo = 0;
2785 for (RecordDecl::field_iterator Field = RD->field_begin(),
2786 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2787 // Anonymous bit-fields are not considered members of the class for
2788 // purposes of aggregate initialization.
2789 if (Field->isUnnamedBitfield())
2790 continue;
2791
2792 LValue Subobject = This;
2793 HandleLValueMember(Info, Subobject, *Field, &Layout);
2794
2795 if (ElementNo < E->getNumInits()) {
2796 if (!EvaluateConstantExpression(
2797 Result.getStructField((*Field)->getFieldIndex()),
2798 Info, Subobject, E->getInit(ElementNo++)))
2799 return false;
2800 } else {
2801 // Perform an implicit value-initialization for members beyond the end of
2802 // the initializer list.
2803 ImplicitValueInitExpr VIE(Field->getType());
2804 if (!EvaluateConstantExpression(
2805 Result.getStructField((*Field)->getFieldIndex()),
2806 Info, Subobject, &VIE))
2807 return false;
2808 }
2809 }
2810
2811 return true;
2812}
2813
2814bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2815 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00002816 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD)) {
2817 const CXXRecordDecl *RD = FD->getParent();
2818 if (RD->isUnion())
2819 Result = APValue((FieldDecl*)0);
2820 else
2821 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2822 std::distance(RD->field_begin(), RD->field_end()));
2823 return true;
2824 }
2825
Richard Smithd62306a2011-11-10 06:34:14 +00002826 const FunctionDecl *Definition = 0;
2827 FD->getBody(Definition);
2828
Richard Smith357362d2011-12-13 06:39:58 +00002829 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2830 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002831
2832 // FIXME: Elide the copy/move construction wherever we can.
2833 if (E->isElidable())
2834 if (const MaterializeTemporaryExpr *ME
2835 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2836 return Visit(ME->GetTemporaryExpr());
2837
2838 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002839 return HandleConstructorCall(E, This, Args,
2840 cast<CXXConstructorDecl>(Definition), Info,
2841 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002842}
2843
2844static bool EvaluateRecord(const Expr *E, const LValue &This,
2845 APValue &Result, EvalInfo &Info) {
2846 assert(E->isRValue() && E->getType()->isRecordType() &&
2847 E->getType()->isLiteralType() &&
2848 "can't evaluate expression as a record rvalue");
2849 return RecordExprEvaluator(Info, This, Result).Visit(E);
2850}
2851
2852//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002853// Temporary Evaluation
2854//
2855// Temporaries are represented in the AST as rvalues, but generally behave like
2856// lvalues. The full-object of which the temporary is a subobject is implicitly
2857// materialized so that a reference can bind to it.
2858//===----------------------------------------------------------------------===//
2859namespace {
2860class TemporaryExprEvaluator
2861 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2862public:
2863 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2864 LValueExprEvaluatorBaseTy(Info, Result) {}
2865
2866 /// Visit an expression which constructs the value of this temporary.
2867 bool VisitConstructExpr(const Expr *E) {
2868 Result.set(E, Info.CurrentCall);
2869 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2870 Result, E);
2871 }
2872
2873 bool VisitCastExpr(const CastExpr *E) {
2874 switch (E->getCastKind()) {
2875 default:
2876 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2877
2878 case CK_ConstructorConversion:
2879 return VisitConstructExpr(E->getSubExpr());
2880 }
2881 }
2882 bool VisitInitListExpr(const InitListExpr *E) {
2883 return VisitConstructExpr(E);
2884 }
2885 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2886 return VisitConstructExpr(E);
2887 }
2888 bool VisitCallExpr(const CallExpr *E) {
2889 return VisitConstructExpr(E);
2890 }
2891};
2892} // end anonymous namespace
2893
2894/// Evaluate an expression of record type as a temporary.
2895static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002896 assert(E->isRValue() && E->getType()->isRecordType());
2897 if (!E->getType()->isLiteralType()) {
2898 if (Info.getLangOpts().CPlusPlus0x)
2899 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
2900 << E->getType();
2901 else
2902 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
2903 return false;
2904 }
Richard Smith027bf112011-11-17 22:56:20 +00002905 return TemporaryExprEvaluator(Info, Result).Visit(E);
2906}
2907
2908//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002909// Vector Evaluation
2910//===----------------------------------------------------------------------===//
2911
2912namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002913 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00002914 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2915 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002916 public:
Mike Stump11289f42009-09-09 15:08:12 +00002917
Richard Smith2d406342011-10-22 21:10:00 +00002918 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2919 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002920
Richard Smith2d406342011-10-22 21:10:00 +00002921 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2922 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2923 // FIXME: remove this APValue copy.
2924 Result = APValue(V.data(), V.size());
2925 return true;
2926 }
Richard Smithed5165f2011-11-04 05:33:44 +00002927 bool Success(const CCValue &V, const Expr *E) {
2928 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00002929 Result = V;
2930 return true;
2931 }
Richard Smith2d406342011-10-22 21:10:00 +00002932 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002933
Richard Smith2d406342011-10-22 21:10:00 +00002934 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00002935 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00002936 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00002937 bool VisitInitListExpr(const InitListExpr *E);
2938 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002939 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00002940 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00002941 // shufflevector, ExtVectorElementExpr
2942 // (Note that these require implementing conversions
2943 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002944 };
2945} // end anonymous namespace
2946
2947static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002948 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00002949 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002950}
2951
Richard Smith2d406342011-10-22 21:10:00 +00002952bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2953 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002954 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002955
Richard Smith161f09a2011-12-06 22:44:34 +00002956 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00002957 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002958
Eli Friedmanc757de22011-03-25 00:43:55 +00002959 switch (E->getCastKind()) {
2960 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00002961 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00002962 if (SETy->isIntegerType()) {
2963 APSInt IntResult;
2964 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002965 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002966 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00002967 } else if (SETy->isRealFloatingType()) {
2968 APFloat F(0.0);
2969 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002970 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002971 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00002972 } else {
Richard Smith2d406342011-10-22 21:10:00 +00002973 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002974 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002975
2976 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00002977 SmallVector<APValue, 4> Elts(NElts, Val);
2978 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00002979 }
Eli Friedmanc757de22011-03-25 00:43:55 +00002980 default:
Richard Smith11562c52011-10-28 17:51:58 +00002981 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002982 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002983}
2984
Richard Smith2d406342011-10-22 21:10:00 +00002985bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002986VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00002987 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002988 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00002989 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002990
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002991 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002992 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002993
John McCall875679e2010-06-11 17:54:15 +00002994 // If a vector is initialized with a single element, that value
2995 // becomes every element of the vector, not just the first.
2996 // This is the behavior described in the IBM AltiVec documentation.
2997 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00002998
2999 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00003000 // vector (OpenCL 6.1.6).
3001 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00003002 return Visit(E->getInit(0));
3003
John McCall875679e2010-06-11 17:54:15 +00003004 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003005 if (EltTy->isIntegerType()) {
3006 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00003007 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003008 return false;
John McCall875679e2010-06-11 17:54:15 +00003009 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003010 } else {
3011 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00003012 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003013 return false;
John McCall875679e2010-06-11 17:54:15 +00003014 InitValue = APValue(f);
3015 }
3016 for (unsigned i = 0; i < NumElements; i++) {
3017 Elements.push_back(InitValue);
3018 }
3019 } else {
3020 for (unsigned i = 0; i < NumElements; i++) {
3021 if (EltTy->isIntegerType()) {
3022 llvm::APSInt sInt(32);
3023 if (i < NumInits) {
3024 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003025 return false;
John McCall875679e2010-06-11 17:54:15 +00003026 } else {
3027 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3028 }
3029 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00003030 } else {
John McCall875679e2010-06-11 17:54:15 +00003031 llvm::APFloat f(0.0);
3032 if (i < NumInits) {
3033 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003034 return false;
John McCall875679e2010-06-11 17:54:15 +00003035 } else {
3036 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3037 }
3038 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00003039 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003040 }
3041 }
Richard Smith2d406342011-10-22 21:10:00 +00003042 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003043}
3044
Richard Smith2d406342011-10-22 21:10:00 +00003045bool
3046VectorExprEvaluator::ValueInitialization(const Expr *E) {
3047 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003048 QualType EltTy = VT->getElementType();
3049 APValue ZeroElement;
3050 if (EltTy->isIntegerType())
3051 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3052 else
3053 ZeroElement =
3054 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3055
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003056 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003057 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003058}
3059
Richard Smith2d406342011-10-22 21:10:00 +00003060bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003061 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00003062 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003063}
3064
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003065//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003066// Array Evaluation
3067//===----------------------------------------------------------------------===//
3068
3069namespace {
3070 class ArrayExprEvaluator
3071 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003072 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003073 APValue &Result;
3074 public:
3075
Richard Smithd62306a2011-11-10 06:34:14 +00003076 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3077 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003078
3079 bool Success(const APValue &V, const Expr *E) {
3080 assert(V.isArray() && "Expected array type");
3081 Result = V;
3082 return true;
3083 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003084
Richard Smithd62306a2011-11-10 06:34:14 +00003085 bool ValueInitialization(const Expr *E) {
3086 const ConstantArrayType *CAT =
3087 Info.Ctx.getAsConstantArrayType(E->getType());
3088 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003089 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003090
3091 Result = APValue(APValue::UninitArray(), 0,
3092 CAT->getSize().getZExtValue());
3093 if (!Result.hasArrayFiller()) return true;
3094
3095 // Value-initialize all elements.
3096 LValue Subobject = This;
3097 Subobject.Designator.addIndex(0);
3098 ImplicitValueInitExpr VIE(CAT->getElementType());
3099 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3100 Subobject, &VIE);
3101 }
3102
Richard Smithf3e9e432011-11-07 09:22:26 +00003103 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003104 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003105 };
3106} // end anonymous namespace
3107
Richard Smithd62306a2011-11-10 06:34:14 +00003108static bool EvaluateArray(const Expr *E, const LValue &This,
3109 APValue &Result, EvalInfo &Info) {
Richard Smithf3e9e432011-11-07 09:22:26 +00003110 assert(E->isRValue() && E->getType()->isArrayType() &&
3111 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003112 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003113}
3114
3115bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3116 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3117 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003118 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003119
Richard Smithca2cfbf2011-12-22 01:07:19 +00003120 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3121 // an appropriately-typed string literal enclosed in braces.
3122 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3123 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3124 LValue LV;
3125 if (!EvaluateLValue(E->getInit(0), LV, Info))
3126 return false;
3127 uint64_t NumElements = CAT->getSize().getZExtValue();
3128 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3129
3130 // Copy the string literal into the array. FIXME: Do this better.
3131 LV.Designator.addIndex(0);
3132 for (uint64_t I = 0; I < NumElements; ++I) {
3133 CCValue Char;
3134 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3135 CAT->getElementType(), LV, Char))
3136 return false;
3137 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3138 Result.getArrayInitializedElt(I)))
3139 return false;
3140 if (!HandleLValueArrayAdjustment(Info, LV, CAT->getElementType(), 1))
3141 return false;
3142 }
3143 return true;
3144 }
3145
Richard Smithf3e9e432011-11-07 09:22:26 +00003146 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3147 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003148 LValue Subobject = This;
3149 Subobject.Designator.addIndex(0);
3150 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003151 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003152 I != End; ++I, ++Index) {
3153 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3154 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003155 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003156 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3157 return false;
3158 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003159
3160 if (!Result.hasArrayFiller()) return true;
3161 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003162 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3163 // but sometimes does:
3164 // struct S { constexpr S() : p(&p) {} void *p; };
3165 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003166 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003167 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003168}
3169
Richard Smith027bf112011-11-17 22:56:20 +00003170bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3171 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3172 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003173 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003174
3175 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3176 if (!Result.hasArrayFiller())
3177 return true;
3178
3179 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003180
3181 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD)) {
3182 const CXXRecordDecl *RD = FD->getParent();
3183 if (RD->isUnion())
3184 Result.getArrayFiller() = APValue((FieldDecl*)0);
3185 else
3186 Result.getArrayFiller() =
3187 APValue(APValue::UninitStruct(), RD->getNumBases(),
3188 std::distance(RD->field_begin(), RD->field_end()));
3189 return true;
3190 }
3191
Richard Smith027bf112011-11-17 22:56:20 +00003192 const FunctionDecl *Definition = 0;
3193 FD->getBody(Definition);
3194
Richard Smith357362d2011-12-13 06:39:58 +00003195 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3196 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003197
3198 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3199 // but sometimes does:
3200 // struct S { constexpr S() : p(&p) {} void *p; };
3201 // S s[10];
3202 LValue Subobject = This;
3203 Subobject.Designator.addIndex(0);
3204 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003205 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003206 cast<CXXConstructorDecl>(Definition),
3207 Info, Result.getArrayFiller());
3208}
3209
Richard Smithf3e9e432011-11-07 09:22:26 +00003210//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003211// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003212//
3213// As a GNU extension, we support casting pointers to sufficiently-wide integer
3214// types and back in constant folding. Integer values are thus represented
3215// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003216//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003217
3218namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003219class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003220 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003221 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003222public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003223 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003224 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003225
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003226 bool Success(const llvm::APSInt &SI, const Expr *E) {
3227 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003228 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003229 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003230 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003231 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003232 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003233 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003234 return true;
3235 }
3236
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003237 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003238 assert(E->getType()->isIntegralOrEnumerationType() &&
3239 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003240 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003241 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003242 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003243 Result.getInt().setIsUnsigned(
3244 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003245 return true;
3246 }
3247
3248 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003249 assert(E->getType()->isIntegralOrEnumerationType() &&
3250 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003251 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003252 return true;
3253 }
3254
Ken Dyckdbc01912011-03-11 02:13:43 +00003255 bool Success(CharUnits Size, const Expr *E) {
3256 return Success(Size.getQuantity(), E);
3257 }
3258
Richard Smith0b0a0b62011-10-29 20:57:55 +00003259 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003260 if (V.isLValue()) {
3261 Result = V;
3262 return true;
3263 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003264 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003265 }
Mike Stump11289f42009-09-09 15:08:12 +00003266
Richard Smith4ce706a2011-10-11 21:43:33 +00003267 bool ValueInitialization(const Expr *E) { return Success(0, E); }
3268
Peter Collingbournee9200682011-05-13 03:29:01 +00003269 //===--------------------------------------------------------------------===//
3270 // Visitor Methods
3271 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003272
Chris Lattner7174bf32008-07-12 00:38:25 +00003273 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003274 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003275 }
3276 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003277 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003278 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003279
3280 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3281 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003282 if (CheckReferencedDecl(E, E->getDecl()))
3283 return true;
3284
3285 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003286 }
3287 bool VisitMemberExpr(const MemberExpr *E) {
3288 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003289 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003290 return true;
3291 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003292
3293 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003294 }
3295
Peter Collingbournee9200682011-05-13 03:29:01 +00003296 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003297 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003298 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003299 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003300
Peter Collingbournee9200682011-05-13 03:29:01 +00003301 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003302 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003303
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003304 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003305 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003306 }
Mike Stump11289f42009-09-09 15:08:12 +00003307
Richard Smith4ce706a2011-10-11 21:43:33 +00003308 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003309 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003310 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003311 }
3312
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003313 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003314 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003315 }
3316
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003317 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3318 return Success(E->getValue(), E);
3319 }
3320
John Wiegley6242b6a2011-04-28 00:16:57 +00003321 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3322 return Success(E->getValue(), E);
3323 }
3324
John Wiegleyf9f65842011-04-25 06:54:41 +00003325 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3326 return Success(E->getValue(), E);
3327 }
3328
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003329 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003330 bool VisitUnaryImag(const UnaryOperator *E);
3331
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003332 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003333 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003334
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003335private:
Ken Dyck160146e2010-01-27 17:10:57 +00003336 CharUnits GetAlignOfExpr(const Expr *E);
3337 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003338 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003339 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003340 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003341};
Chris Lattner05706e882008-07-11 18:11:29 +00003342} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003343
Richard Smith11562c52011-10-28 17:51:58 +00003344/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3345/// produce either the integer value or a pointer.
3346///
3347/// GCC has a heinous extension which folds casts between pointer types and
3348/// pointer-sized integral types. We support this by allowing the evaluation of
3349/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3350/// Some simple arithmetic on such values is supported (they are treated much
3351/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003352static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003353 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003354 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003355 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003356}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003357
Richard Smithf57d8cb2011-12-09 22:58:01 +00003358static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003359 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003360 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003361 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003362 if (!Val.isInt()) {
3363 // FIXME: It would be better to produce the diagnostic for casting
3364 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003365 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003366 return false;
3367 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003368 Result = Val.getInt();
3369 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003370}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003371
Richard Smithf57d8cb2011-12-09 22:58:01 +00003372/// Check whether the given declaration can be directly converted to an integral
3373/// rvalue. If not, no diagnostic is produced; there are other things we can
3374/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003375bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003376 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003377 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003378 // Check for signedness/width mismatches between E type and ECD value.
3379 bool SameSign = (ECD->getInitVal().isSigned()
3380 == E->getType()->isSignedIntegerOrEnumerationType());
3381 bool SameWidth = (ECD->getInitVal().getBitWidth()
3382 == Info.Ctx.getIntWidth(E->getType()));
3383 if (SameSign && SameWidth)
3384 return Success(ECD->getInitVal(), E);
3385 else {
3386 // Get rid of mismatch (otherwise Success assertions will fail)
3387 // by computing a new value matching the type of E.
3388 llvm::APSInt Val = ECD->getInitVal();
3389 if (!SameSign)
3390 Val.setIsSigned(!ECD->getInitVal().isSigned());
3391 if (!SameWidth)
3392 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3393 return Success(Val, E);
3394 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003395 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003396 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003397}
3398
Chris Lattner86ee2862008-10-06 06:40:35 +00003399/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3400/// as GCC.
3401static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3402 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003403 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003404 enum gcc_type_class {
3405 no_type_class = -1,
3406 void_type_class, integer_type_class, char_type_class,
3407 enumeral_type_class, boolean_type_class,
3408 pointer_type_class, reference_type_class, offset_type_class,
3409 real_type_class, complex_type_class,
3410 function_type_class, method_type_class,
3411 record_type_class, union_type_class,
3412 array_type_class, string_type_class,
3413 lang_type_class
3414 };
Mike Stump11289f42009-09-09 15:08:12 +00003415
3416 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003417 // ideal, however it is what gcc does.
3418 if (E->getNumArgs() == 0)
3419 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003420
Chris Lattner86ee2862008-10-06 06:40:35 +00003421 QualType ArgTy = E->getArg(0)->getType();
3422 if (ArgTy->isVoidType())
3423 return void_type_class;
3424 else if (ArgTy->isEnumeralType())
3425 return enumeral_type_class;
3426 else if (ArgTy->isBooleanType())
3427 return boolean_type_class;
3428 else if (ArgTy->isCharType())
3429 return string_type_class; // gcc doesn't appear to use char_type_class
3430 else if (ArgTy->isIntegerType())
3431 return integer_type_class;
3432 else if (ArgTy->isPointerType())
3433 return pointer_type_class;
3434 else if (ArgTy->isReferenceType())
3435 return reference_type_class;
3436 else if (ArgTy->isRealType())
3437 return real_type_class;
3438 else if (ArgTy->isComplexType())
3439 return complex_type_class;
3440 else if (ArgTy->isFunctionType())
3441 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003442 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003443 return record_type_class;
3444 else if (ArgTy->isUnionType())
3445 return union_type_class;
3446 else if (ArgTy->isArrayType())
3447 return array_type_class;
3448 else if (ArgTy->isUnionType())
3449 return union_type_class;
3450 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003451 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003452 return -1;
3453}
3454
John McCall95007602010-05-10 23:27:23 +00003455/// Retrieves the "underlying object type" of the given expression,
3456/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003457QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3458 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3459 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003460 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003461 } else if (const Expr *E = B.get<const Expr*>()) {
3462 if (isa<CompoundLiteralExpr>(E))
3463 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003464 }
3465
3466 return QualType();
3467}
3468
Peter Collingbournee9200682011-05-13 03:29:01 +00003469bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003470 // TODO: Perhaps we should let LLVM lower this?
3471 LValue Base;
3472 if (!EvaluatePointer(E->getArg(0), Base, Info))
3473 return false;
3474
3475 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003476 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003477
Richard Smithce40ad62011-11-12 22:28:03 +00003478 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003479 if (T.isNull() ||
3480 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003481 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003482 T->isVariablyModifiedType() ||
3483 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003484 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003485
3486 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3487 CharUnits Offset = Base.getLValueOffset();
3488
3489 if (!Offset.isNegative() && Offset <= Size)
3490 Size -= Offset;
3491 else
3492 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003493 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003494}
3495
Peter Collingbournee9200682011-05-13 03:29:01 +00003496bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003497 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003498 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003499 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003500
3501 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003502 if (TryEvaluateBuiltinObjectSize(E))
3503 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003504
Eric Christopher99469702010-01-19 22:58:35 +00003505 // If evaluating the argument has side-effects we can't determine
3506 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003507 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003508 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003509 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003510 return Success(0, E);
3511 }
Mike Stump876387b2009-10-27 22:09:17 +00003512
Richard Smithf57d8cb2011-12-09 22:58:01 +00003513 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003514 }
3515
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003516 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003517 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003518
Richard Smith10c7c902011-12-09 02:04:48 +00003519 case Builtin::BI__builtin_constant_p: {
3520 const Expr *Arg = E->getArg(0);
3521 QualType ArgType = Arg->getType();
3522 // __builtin_constant_p always has one operand. The rules which gcc follows
3523 // are not precisely documented, but are as follows:
3524 //
3525 // - If the operand is of integral, floating, complex or enumeration type,
3526 // and can be folded to a known value of that type, it returns 1.
3527 // - If the operand and can be folded to a pointer to the first character
3528 // of a string literal (or such a pointer cast to an integral type), it
3529 // returns 1.
3530 //
3531 // Otherwise, it returns 0.
3532 //
3533 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3534 // its support for this does not currently work.
3535 int IsConstant = 0;
3536 if (ArgType->isIntegralOrEnumerationType()) {
3537 // Note, a pointer cast to an integral type is only a constant if it is
3538 // a pointer to the first character of a string literal.
3539 Expr::EvalResult Result;
3540 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3541 APValue &V = Result.Val;
3542 if (V.getKind() == APValue::LValue) {
3543 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3544 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3545 } else {
3546 IsConstant = 1;
3547 }
3548 }
3549 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3550 IsConstant = Arg->isEvaluatable(Info.Ctx);
3551 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3552 LValue LV;
3553 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3554 // during the check.
3555 Expr::EvalStatus Status;
3556 EvalInfo SubInfo(Info.Ctx, Status);
3557 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3558 : EvaluatePointer(Arg, LV, SubInfo)) &&
3559 !Status.HasSideEffects)
3560 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3561 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3562 }
3563
3564 return Success(IsConstant, E);
3565 }
Chris Lattnerd545ad12009-09-23 06:06:36 +00003566 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003567 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003568 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003569 return Success(Operand, E);
3570 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003571
3572 case Builtin::BI__builtin_expect:
3573 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003574
3575 case Builtin::BIstrlen:
3576 case Builtin::BI__builtin_strlen:
3577 // As an extension, we support strlen() and __builtin_strlen() as constant
3578 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003579 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003580 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3581 // The string literal may have embedded null characters. Find the first
3582 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003583 StringRef Str = S->getString();
3584 StringRef::size_type Pos = Str.find(0);
3585 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003586 Str = Str.substr(0, Pos);
3587
3588 return Success(Str.size(), E);
3589 }
3590
Richard Smithf57d8cb2011-12-09 22:58:01 +00003591 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003592
3593 case Builtin::BI__atomic_is_lock_free: {
3594 APSInt SizeVal;
3595 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3596 return false;
3597
3598 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3599 // of two less than the maximum inline atomic width, we know it is
3600 // lock-free. If the size isn't a power of two, or greater than the
3601 // maximum alignment where we promote atomics, we know it is not lock-free
3602 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3603 // the answer can only be determined at runtime; for example, 16-byte
3604 // atomics have lock-free implementations on some, but not all,
3605 // x86-64 processors.
3606
3607 // Check power-of-two.
3608 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3609 if (!Size.isPowerOfTwo())
3610#if 0
3611 // FIXME: Suppress this folding until the ABI for the promotion width
3612 // settles.
3613 return Success(0, E);
3614#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003615 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003616#endif
3617
3618#if 0
3619 // Check against promotion width.
3620 // FIXME: Suppress this folding until the ABI for the promotion width
3621 // settles.
3622 unsigned PromoteWidthBits =
3623 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3624 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3625 return Success(0, E);
3626#endif
3627
3628 // Check against inlining width.
3629 unsigned InlineWidthBits =
3630 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3631 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3632 return Success(1, E);
3633
Richard Smithf57d8cb2011-12-09 22:58:01 +00003634 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003635 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003636 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003637}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003638
Richard Smith8b3497e2011-10-31 01:37:14 +00003639static bool HasSameBase(const LValue &A, const LValue &B) {
3640 if (!A.getLValueBase())
3641 return !B.getLValueBase();
3642 if (!B.getLValueBase())
3643 return false;
3644
Richard Smithce40ad62011-11-12 22:28:03 +00003645 if (A.getLValueBase().getOpaqueValue() !=
3646 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003647 const Decl *ADecl = GetLValueBaseDecl(A);
3648 if (!ADecl)
3649 return false;
3650 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003651 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003652 return false;
3653 }
3654
3655 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003656 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003657}
3658
Chris Lattnere13042c2008-07-11 19:10:17 +00003659bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003660 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003661 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003662
John McCalle3027922010-08-25 11:45:40 +00003663 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003664 VisitIgnoredValue(E->getLHS());
3665 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003666 }
3667
3668 if (E->isLogicalOp()) {
3669 // These need to be handled specially because the operands aren't
3670 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003671 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003672
Richard Smith11562c52011-10-28 17:51:58 +00003673 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003674 // We were able to evaluate the LHS, see if we can get away with not
3675 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003676 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003677 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003678
Richard Smith11562c52011-10-28 17:51:58 +00003679 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003680 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003681 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003682 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003683 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003684 }
3685 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003686 // FIXME: If both evaluations fail, we should produce the diagnostic from
3687 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3688 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003689 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003690 // We can't evaluate the LHS; however, sometimes the result
3691 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003692 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003693 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003694 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003695 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003696
3697 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003698 }
3699 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003700 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003701
Eli Friedman5a332ea2008-11-13 06:09:17 +00003702 return false;
3703 }
3704
Anders Carlssonacc79812008-11-16 07:17:21 +00003705 QualType LHSTy = E->getLHS()->getType();
3706 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003707
3708 if (LHSTy->isAnyComplexType()) {
3709 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003710 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003711
3712 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3713 return false;
3714
3715 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3716 return false;
3717
3718 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003719 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003720 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003721 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003722 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3723
John McCalle3027922010-08-25 11:45:40 +00003724 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003725 return Success((CR_r == APFloat::cmpEqual &&
3726 CR_i == APFloat::cmpEqual), E);
3727 else {
John McCalle3027922010-08-25 11:45:40 +00003728 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003729 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003730 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003731 CR_r == APFloat::cmpLessThan ||
3732 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003733 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003734 CR_i == APFloat::cmpLessThan ||
3735 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003736 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003737 } else {
John McCalle3027922010-08-25 11:45:40 +00003738 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003739 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3740 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3741 else {
John McCalle3027922010-08-25 11:45:40 +00003742 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003743 "Invalid compex comparison.");
3744 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3745 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3746 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003747 }
3748 }
Mike Stump11289f42009-09-09 15:08:12 +00003749
Anders Carlssonacc79812008-11-16 07:17:21 +00003750 if (LHSTy->isRealFloatingType() &&
3751 RHSTy->isRealFloatingType()) {
3752 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003753
Anders Carlssonacc79812008-11-16 07:17:21 +00003754 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3755 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003756
Anders Carlssonacc79812008-11-16 07:17:21 +00003757 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3758 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003759
Anders Carlssonacc79812008-11-16 07:17:21 +00003760 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003761
Anders Carlssonacc79812008-11-16 07:17:21 +00003762 switch (E->getOpcode()) {
3763 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003764 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003765 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003766 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003767 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003768 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003769 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003770 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003771 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003772 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003773 E);
John McCalle3027922010-08-25 11:45:40 +00003774 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003775 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003776 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003777 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003778 || CR == APFloat::cmpLessThan
3779 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003780 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003781 }
Mike Stump11289f42009-09-09 15:08:12 +00003782
Eli Friedmana38da572009-04-28 19:17:36 +00003783 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003784 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003785 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003786 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3787 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003788
John McCall45d55e42010-05-07 21:00:08 +00003789 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003790 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3791 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003792
Richard Smith8b3497e2011-10-31 01:37:14 +00003793 // Reject differing bases from the normal codepath; we special-case
3794 // comparisons to null.
3795 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00003796 // Inequalities and subtractions between unrelated pointers have
3797 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00003798 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003799 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003800 // A constant address may compare equal to the address of a symbol.
3801 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00003802 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003803 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3804 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003805 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003806 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00003807 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00003808 // distinct. However, we do know that the address of a literal will be
3809 // non-null.
3810 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3811 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003812 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003813 // We can't tell whether weak symbols will end up pointing to the same
3814 // object.
3815 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003816 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003817 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00003818 // (Note that clang defaults to -fmerge-all-constants, which can
3819 // lead to inconsistent results for comparisons involving the address
3820 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00003821 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00003822 }
Eli Friedman64004332009-03-23 04:38:34 +00003823
Richard Smithf3e9e432011-11-07 09:22:26 +00003824 // FIXME: Implement the C++11 restrictions:
3825 // - Pointer subtractions must be on elements of the same array.
3826 // - Pointer comparisons must be between members with the same access.
3827
John McCalle3027922010-08-25 11:45:40 +00003828 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00003829 QualType Type = E->getLHS()->getType();
3830 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003831
Richard Smithd62306a2011-11-10 06:34:14 +00003832 CharUnits ElementSize;
3833 if (!HandleSizeof(Info, ElementType, ElementSize))
3834 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003835
Richard Smithd62306a2011-11-10 06:34:14 +00003836 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00003837 RHSValue.getLValueOffset();
3838 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003839 }
Richard Smith8b3497e2011-10-31 01:37:14 +00003840
3841 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3842 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3843 switch (E->getOpcode()) {
3844 default: llvm_unreachable("missing comparison operator");
3845 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3846 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3847 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3848 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3849 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3850 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003851 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003852 }
3853 }
Douglas Gregorb90df602010-06-16 00:17:44 +00003854 if (!LHSTy->isIntegralOrEnumerationType() ||
3855 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00003856 // We can't continue from here for non-integral types.
3857 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003858 }
3859
Anders Carlsson9c181652008-07-08 14:35:21 +00003860 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003861 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00003862 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003863 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00003864
Richard Smith11562c52011-10-28 17:51:58 +00003865 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003866 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003867 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00003868
3869 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00003870 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00003871 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3872 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00003873 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00003874 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00003875 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00003876 LHSVal.getLValueOffset() -= AdditionalOffset;
3877 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00003878 return true;
3879 }
3880
3881 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00003882 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00003883 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003884 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3885 LHSVal.getInt().getZExtValue());
3886 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00003887 return true;
3888 }
3889
3890 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00003891 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003892 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003893
Richard Smith11562c52011-10-28 17:51:58 +00003894 APSInt &LHS = LHSVal.getInt();
3895 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00003896
Anders Carlsson9c181652008-07-08 14:35:21 +00003897 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003898 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003899 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003900 case BO_Mul: return Success(LHS * RHS, E);
3901 case BO_Add: return Success(LHS + RHS, E);
3902 case BO_Sub: return Success(LHS - RHS, E);
3903 case BO_And: return Success(LHS & RHS, E);
3904 case BO_Xor: return Success(LHS ^ RHS, E);
3905 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003906 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00003907 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003908 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003909 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003910 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00003911 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003912 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003913 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003914 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00003915 // During constant-folding, a negative shift is an opposite shift.
3916 if (RHS.isSigned() && RHS.isNegative()) {
3917 RHS = -RHS;
3918 goto shift_right;
3919 }
3920
3921 shift_left:
3922 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00003923 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3924 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003925 }
John McCalle3027922010-08-25 11:45:40 +00003926 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00003927 // During constant-folding, a negative shift is an opposite shift.
3928 if (RHS.isSigned() && RHS.isNegative()) {
3929 RHS = -RHS;
3930 goto shift_left;
3931 }
3932
3933 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00003934 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00003935 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3936 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003937 }
Mike Stump11289f42009-09-09 15:08:12 +00003938
Richard Smith11562c52011-10-28 17:51:58 +00003939 case BO_LT: return Success(LHS < RHS, E);
3940 case BO_GT: return Success(LHS > RHS, E);
3941 case BO_LE: return Success(LHS <= RHS, E);
3942 case BO_GE: return Success(LHS >= RHS, E);
3943 case BO_EQ: return Success(LHS == RHS, E);
3944 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00003945 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003946}
3947
Ken Dyck160146e2010-01-27 17:10:57 +00003948CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003949 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3950 // the result is the size of the referenced type."
3951 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3952 // result shall be the alignment of the referenced type."
3953 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3954 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00003955
3956 // __alignof is defined to return the preferred alignment.
3957 return Info.Ctx.toCharUnitsFromBits(
3958 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00003959}
3960
Ken Dyck160146e2010-01-27 17:10:57 +00003961CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00003962 E = E->IgnoreParens();
3963
3964 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00003965 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00003966 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003967 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3968 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00003969
Chris Lattner68061312009-01-24 21:53:27 +00003970 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003971 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3972 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00003973
Chris Lattner24aeeab2009-01-24 21:09:06 +00003974 return GetAlignOfType(E->getType());
3975}
3976
3977
Peter Collingbournee190dee2011-03-11 19:24:49 +00003978/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3979/// a result as the expression's type.
3980bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3981 const UnaryExprOrTypeTraitExpr *E) {
3982 switch(E->getKind()) {
3983 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00003984 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00003985 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003986 else
Ken Dyckdbc01912011-03-11 02:13:43 +00003987 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003988 }
Eli Friedman64004332009-03-23 04:38:34 +00003989
Peter Collingbournee190dee2011-03-11 19:24:49 +00003990 case UETT_VecStep: {
3991 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00003992
Peter Collingbournee190dee2011-03-11 19:24:49 +00003993 if (Ty->isVectorType()) {
3994 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00003995
Peter Collingbournee190dee2011-03-11 19:24:49 +00003996 // The vec_step built-in functions that take a 3-component
3997 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3998 if (n == 3)
3999 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00004000
Peter Collingbournee190dee2011-03-11 19:24:49 +00004001 return Success(n, E);
4002 } else
4003 return Success(1, E);
4004 }
4005
4006 case UETT_SizeOf: {
4007 QualType SrcTy = E->getTypeOfArgument();
4008 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4009 // the result is the size of the referenced type."
4010 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4011 // result shall be the alignment of the referenced type."
4012 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4013 SrcTy = Ref->getPointeeType();
4014
Richard Smithd62306a2011-11-10 06:34:14 +00004015 CharUnits Sizeof;
4016 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00004017 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004018 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004019 }
4020 }
4021
4022 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004023 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004024}
4025
Peter Collingbournee9200682011-05-13 03:29:01 +00004026bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00004027 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00004028 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00004029 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004030 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00004031 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00004032 for (unsigned i = 0; i != n; ++i) {
4033 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4034 switch (ON.getKind()) {
4035 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00004036 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00004037 APSInt IdxResult;
4038 if (!EvaluateInteger(Idx, IdxResult, Info))
4039 return false;
4040 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4041 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004042 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004043 CurrentType = AT->getElementType();
4044 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4045 Result += IdxResult.getSExtValue() * ElementSize;
4046 break;
4047 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004048
Douglas Gregor882211c2010-04-28 22:16:22 +00004049 case OffsetOfExpr::OffsetOfNode::Field: {
4050 FieldDecl *MemberDecl = ON.getField();
4051 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004052 if (!RT)
4053 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004054 RecordDecl *RD = RT->getDecl();
4055 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004056 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004057 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004058 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004059 CurrentType = MemberDecl->getType().getNonReferenceType();
4060 break;
4061 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004062
Douglas Gregor882211c2010-04-28 22:16:22 +00004063 case OffsetOfExpr::OffsetOfNode::Identifier:
4064 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004065 return Error(OOE);
4066
Douglas Gregord1702062010-04-29 00:18:15 +00004067 case OffsetOfExpr::OffsetOfNode::Base: {
4068 CXXBaseSpecifier *BaseSpec = ON.getBase();
4069 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004070 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004071
4072 // Find the layout of the class whose base we are looking into.
4073 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004074 if (!RT)
4075 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004076 RecordDecl *RD = RT->getDecl();
4077 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4078
4079 // Find the base class itself.
4080 CurrentType = BaseSpec->getType();
4081 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4082 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004083 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004084
4085 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004086 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004087 break;
4088 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004089 }
4090 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004091 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004092}
4093
Chris Lattnere13042c2008-07-11 19:10:17 +00004094bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004095 switch (E->getOpcode()) {
4096 default:
4097 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4098 // See C99 6.6p3.
4099 return Error(E);
4100 case UO_Extension:
4101 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4102 // If so, we could clear the diagnostic ID.
4103 return Visit(E->getSubExpr());
4104 case UO_Plus:
4105 // The result is just the value.
4106 return Visit(E->getSubExpr());
4107 case UO_Minus: {
4108 if (!Visit(E->getSubExpr()))
4109 return false;
4110 if (!Result.isInt()) return Error(E);
4111 return Success(-Result.getInt(), E);
4112 }
4113 case UO_Not: {
4114 if (!Visit(E->getSubExpr()))
4115 return false;
4116 if (!Result.isInt()) return Error(E);
4117 return Success(~Result.getInt(), E);
4118 }
4119 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004120 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004121 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004122 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004123 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004124 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004125 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004126}
Mike Stump11289f42009-09-09 15:08:12 +00004127
Chris Lattner477c4be2008-07-12 01:15:53 +00004128/// HandleCast - This is used to evaluate implicit or explicit casts where the
4129/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004130bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4131 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004132 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004133 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004134
Eli Friedmanc757de22011-03-25 00:43:55 +00004135 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004136 case CK_BaseToDerived:
4137 case CK_DerivedToBase:
4138 case CK_UncheckedDerivedToBase:
4139 case CK_Dynamic:
4140 case CK_ToUnion:
4141 case CK_ArrayToPointerDecay:
4142 case CK_FunctionToPointerDecay:
4143 case CK_NullToPointer:
4144 case CK_NullToMemberPointer:
4145 case CK_BaseToDerivedMemberPointer:
4146 case CK_DerivedToBaseMemberPointer:
4147 case CK_ConstructorConversion:
4148 case CK_IntegralToPointer:
4149 case CK_ToVoid:
4150 case CK_VectorSplat:
4151 case CK_IntegralToFloating:
4152 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004153 case CK_CPointerToObjCPointerCast:
4154 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004155 case CK_AnyPointerToBlockPointerCast:
4156 case CK_ObjCObjectLValueCast:
4157 case CK_FloatingRealToComplex:
4158 case CK_FloatingComplexToReal:
4159 case CK_FloatingComplexCast:
4160 case CK_FloatingComplexToIntegralComplex:
4161 case CK_IntegralRealToComplex:
4162 case CK_IntegralComplexCast:
4163 case CK_IntegralComplexToFloatingComplex:
4164 llvm_unreachable("invalid cast kind for integral value");
4165
Eli Friedman9faf2f92011-03-25 19:07:11 +00004166 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004167 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004168 case CK_LValueBitCast:
4169 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004170 case CK_ARCProduceObject:
4171 case CK_ARCConsumeObject:
4172 case CK_ARCReclaimReturnedObject:
4173 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004174 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004175
4176 case CK_LValueToRValue:
4177 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004178 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004179
4180 case CK_MemberPointerToBoolean:
4181 case CK_PointerToBoolean:
4182 case CK_IntegralToBoolean:
4183 case CK_FloatingToBoolean:
4184 case CK_FloatingComplexToBoolean:
4185 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004186 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004187 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004188 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004189 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004190 }
4191
Eli Friedmanc757de22011-03-25 00:43:55 +00004192 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004193 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004194 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004195
Eli Friedman742421e2009-02-20 01:15:07 +00004196 if (!Result.isInt()) {
4197 // Only allow casts of lvalues if they are lossless.
4198 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4199 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004200
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004201 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004202 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004203 }
Mike Stump11289f42009-09-09 15:08:12 +00004204
Eli Friedmanc757de22011-03-25 00:43:55 +00004205 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004206 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4207
John McCall45d55e42010-05-07 21:00:08 +00004208 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004209 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004210 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004211
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004212 if (LV.getLValueBase()) {
4213 // Only allow based lvalue casts if they are lossless.
4214 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004215 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004216
Richard Smithcf74da72011-11-16 07:18:12 +00004217 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004218 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004219 return true;
4220 }
4221
Ken Dyck02990832010-01-15 12:37:54 +00004222 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4223 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004224 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004225 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004226
Eli Friedmanc757de22011-03-25 00:43:55 +00004227 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004228 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004229 if (!EvaluateComplex(SubExpr, C, Info))
4230 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004231 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004232 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004233
Eli Friedmanc757de22011-03-25 00:43:55 +00004234 case CK_FloatingToIntegral: {
4235 APFloat F(0.0);
4236 if (!EvaluateFloat(SubExpr, F, Info))
4237 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004238
Richard Smith357362d2011-12-13 06:39:58 +00004239 APSInt Value;
4240 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4241 return false;
4242 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004243 }
4244 }
Mike Stump11289f42009-09-09 15:08:12 +00004245
Eli Friedmanc757de22011-03-25 00:43:55 +00004246 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004247 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004248}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004249
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004250bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4251 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004252 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004253 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4254 return false;
4255 if (!LV.isComplexInt())
4256 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004257 return Success(LV.getComplexIntReal(), E);
4258 }
4259
4260 return Visit(E->getSubExpr());
4261}
4262
Eli Friedman4e7a2412009-02-27 04:45:43 +00004263bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004264 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004265 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004266 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4267 return false;
4268 if (!LV.isComplexInt())
4269 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004270 return Success(LV.getComplexIntImag(), E);
4271 }
4272
Richard Smith4a678122011-10-24 18:44:57 +00004273 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004274 return Success(0, E);
4275}
4276
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004277bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4278 return Success(E->getPackLength(), E);
4279}
4280
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004281bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4282 return Success(E->getValue(), E);
4283}
4284
Chris Lattner05706e882008-07-11 18:11:29 +00004285//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004286// Float Evaluation
4287//===----------------------------------------------------------------------===//
4288
4289namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004290class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004291 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004292 APFloat &Result;
4293public:
4294 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004295 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004296
Richard Smith0b0a0b62011-10-29 20:57:55 +00004297 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004298 Result = V.getFloat();
4299 return true;
4300 }
Eli Friedman24c01542008-08-22 00:06:13 +00004301
Richard Smith4ce706a2011-10-11 21:43:33 +00004302 bool ValueInitialization(const Expr *E) {
4303 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4304 return true;
4305 }
4306
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004307 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004308
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004309 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004310 bool VisitBinaryOperator(const BinaryOperator *E);
4311 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004312 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004313
John McCallb1fb0d32010-05-07 22:08:54 +00004314 bool VisitUnaryReal(const UnaryOperator *E);
4315 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004316
John McCallb1fb0d32010-05-07 22:08:54 +00004317 // FIXME: Missing: array subscript of vector, member of vector,
4318 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00004319};
4320} // end anonymous namespace
4321
4322static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004323 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004324 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004325}
4326
Jay Foad39c79802011-01-12 09:06:06 +00004327static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004328 QualType ResultTy,
4329 const Expr *Arg,
4330 bool SNaN,
4331 llvm::APFloat &Result) {
4332 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4333 if (!S) return false;
4334
4335 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4336
4337 llvm::APInt fill;
4338
4339 // Treat empty strings as if they were zero.
4340 if (S->getString().empty())
4341 fill = llvm::APInt(32, 0);
4342 else if (S->getString().getAsInteger(0, fill))
4343 return false;
4344
4345 if (SNaN)
4346 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4347 else
4348 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4349 return true;
4350}
4351
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004352bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004353 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004354 default:
4355 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4356
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004357 case Builtin::BI__builtin_huge_val:
4358 case Builtin::BI__builtin_huge_valf:
4359 case Builtin::BI__builtin_huge_vall:
4360 case Builtin::BI__builtin_inf:
4361 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004362 case Builtin::BI__builtin_infl: {
4363 const llvm::fltSemantics &Sem =
4364 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004365 Result = llvm::APFloat::getInf(Sem);
4366 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004367 }
Mike Stump11289f42009-09-09 15:08:12 +00004368
John McCall16291492010-02-28 13:00:19 +00004369 case Builtin::BI__builtin_nans:
4370 case Builtin::BI__builtin_nansf:
4371 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004372 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4373 true, Result))
4374 return Error(E);
4375 return true;
John McCall16291492010-02-28 13:00:19 +00004376
Chris Lattner0b7282e2008-10-06 06:31:58 +00004377 case Builtin::BI__builtin_nan:
4378 case Builtin::BI__builtin_nanf:
4379 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004380 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004381 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004382 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4383 false, Result))
4384 return Error(E);
4385 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004386
4387 case Builtin::BI__builtin_fabs:
4388 case Builtin::BI__builtin_fabsf:
4389 case Builtin::BI__builtin_fabsl:
4390 if (!EvaluateFloat(E->getArg(0), Result, Info))
4391 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004392
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004393 if (Result.isNegative())
4394 Result.changeSign();
4395 return true;
4396
Mike Stump11289f42009-09-09 15:08:12 +00004397 case Builtin::BI__builtin_copysign:
4398 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004399 case Builtin::BI__builtin_copysignl: {
4400 APFloat RHS(0.);
4401 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4402 !EvaluateFloat(E->getArg(1), RHS, Info))
4403 return false;
4404 Result.copySign(RHS);
4405 return true;
4406 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004407 }
4408}
4409
John McCallb1fb0d32010-05-07 22:08:54 +00004410bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004411 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4412 ComplexValue CV;
4413 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4414 return false;
4415 Result = CV.FloatReal;
4416 return true;
4417 }
4418
4419 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004420}
4421
4422bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004423 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4424 ComplexValue CV;
4425 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4426 return false;
4427 Result = CV.FloatImag;
4428 return true;
4429 }
4430
Richard Smith4a678122011-10-24 18:44:57 +00004431 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004432 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4433 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004434 return true;
4435}
4436
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004437bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004438 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004439 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004440 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004441 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004442 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004443 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4444 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004445 Result.changeSign();
4446 return true;
4447 }
4448}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004449
Eli Friedman24c01542008-08-22 00:06:13 +00004450bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004451 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4452 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004453
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004454 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004455 if (!EvaluateFloat(E->getLHS(), Result, Info))
4456 return false;
4457 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4458 return false;
4459
4460 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004461 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004462 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004463 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4464 return true;
John McCalle3027922010-08-25 11:45:40 +00004465 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004466 Result.add(RHS, APFloat::rmNearestTiesToEven);
4467 return true;
John McCalle3027922010-08-25 11:45:40 +00004468 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004469 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4470 return true;
John McCalle3027922010-08-25 11:45:40 +00004471 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004472 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4473 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004474 }
4475}
4476
4477bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4478 Result = E->getValue();
4479 return true;
4480}
4481
Peter Collingbournee9200682011-05-13 03:29:01 +00004482bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4483 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004484
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004485 switch (E->getCastKind()) {
4486 default:
Richard Smith11562c52011-10-28 17:51:58 +00004487 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004488
4489 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004490 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004491 return EvaluateInteger(SubExpr, IntResult, Info) &&
4492 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4493 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004494 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004495
4496 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004497 if (!Visit(SubExpr))
4498 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004499 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4500 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004501 }
John McCalld7646252010-11-14 08:17:51 +00004502
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004503 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004504 ComplexValue V;
4505 if (!EvaluateComplex(SubExpr, V, Info))
4506 return false;
4507 Result = V.getComplexFloatReal();
4508 return true;
4509 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004510 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004511
Richard Smithf57d8cb2011-12-09 22:58:01 +00004512 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004513}
4514
Eli Friedman24c01542008-08-22 00:06:13 +00004515//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004516// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004517//===----------------------------------------------------------------------===//
4518
4519namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004520class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004521 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004522 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004523
Anders Carlsson537969c2008-11-16 20:27:53 +00004524public:
John McCall93d91dc2010-05-07 17:22:02 +00004525 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004526 : ExprEvaluatorBaseTy(info), Result(Result) {}
4527
Richard Smith0b0a0b62011-10-29 20:57:55 +00004528 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004529 Result.setFrom(V);
4530 return true;
4531 }
Mike Stump11289f42009-09-09 15:08:12 +00004532
Anders Carlsson537969c2008-11-16 20:27:53 +00004533 //===--------------------------------------------------------------------===//
4534 // Visitor Methods
4535 //===--------------------------------------------------------------------===//
4536
Peter Collingbournee9200682011-05-13 03:29:01 +00004537 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004538
Peter Collingbournee9200682011-05-13 03:29:01 +00004539 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004540
John McCall93d91dc2010-05-07 17:22:02 +00004541 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004542 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004543 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004544};
4545} // end anonymous namespace
4546
John McCall93d91dc2010-05-07 17:22:02 +00004547static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4548 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004549 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004550 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004551}
4552
Peter Collingbournee9200682011-05-13 03:29:01 +00004553bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4554 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004555
4556 if (SubExpr->getType()->isRealFloatingType()) {
4557 Result.makeComplexFloat();
4558 APFloat &Imag = Result.FloatImag;
4559 if (!EvaluateFloat(SubExpr, Imag, Info))
4560 return false;
4561
4562 Result.FloatReal = APFloat(Imag.getSemantics());
4563 return true;
4564 } else {
4565 assert(SubExpr->getType()->isIntegerType() &&
4566 "Unexpected imaginary literal.");
4567
4568 Result.makeComplexInt();
4569 APSInt &Imag = Result.IntImag;
4570 if (!EvaluateInteger(SubExpr, Imag, Info))
4571 return false;
4572
4573 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4574 return true;
4575 }
4576}
4577
Peter Collingbournee9200682011-05-13 03:29:01 +00004578bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004579
John McCallfcef3cf2010-12-14 17:51:41 +00004580 switch (E->getCastKind()) {
4581 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004582 case CK_BaseToDerived:
4583 case CK_DerivedToBase:
4584 case CK_UncheckedDerivedToBase:
4585 case CK_Dynamic:
4586 case CK_ToUnion:
4587 case CK_ArrayToPointerDecay:
4588 case CK_FunctionToPointerDecay:
4589 case CK_NullToPointer:
4590 case CK_NullToMemberPointer:
4591 case CK_BaseToDerivedMemberPointer:
4592 case CK_DerivedToBaseMemberPointer:
4593 case CK_MemberPointerToBoolean:
4594 case CK_ConstructorConversion:
4595 case CK_IntegralToPointer:
4596 case CK_PointerToIntegral:
4597 case CK_PointerToBoolean:
4598 case CK_ToVoid:
4599 case CK_VectorSplat:
4600 case CK_IntegralCast:
4601 case CK_IntegralToBoolean:
4602 case CK_IntegralToFloating:
4603 case CK_FloatingToIntegral:
4604 case CK_FloatingToBoolean:
4605 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004606 case CK_CPointerToObjCPointerCast:
4607 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004608 case CK_AnyPointerToBlockPointerCast:
4609 case CK_ObjCObjectLValueCast:
4610 case CK_FloatingComplexToReal:
4611 case CK_FloatingComplexToBoolean:
4612 case CK_IntegralComplexToReal:
4613 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004614 case CK_ARCProduceObject:
4615 case CK_ARCConsumeObject:
4616 case CK_ARCReclaimReturnedObject:
4617 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004618 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004619
John McCallfcef3cf2010-12-14 17:51:41 +00004620 case CK_LValueToRValue:
4621 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004622 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004623
4624 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004625 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004626 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004627 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004628
4629 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004630 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004631 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004632 return false;
4633
John McCallfcef3cf2010-12-14 17:51:41 +00004634 Result.makeComplexFloat();
4635 Result.FloatImag = APFloat(Real.getSemantics());
4636 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004637 }
4638
John McCallfcef3cf2010-12-14 17:51:41 +00004639 case CK_FloatingComplexCast: {
4640 if (!Visit(E->getSubExpr()))
4641 return false;
4642
4643 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4644 QualType From
4645 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4646
Richard Smith357362d2011-12-13 06:39:58 +00004647 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4648 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004649 }
4650
4651 case CK_FloatingComplexToIntegralComplex: {
4652 if (!Visit(E->getSubExpr()))
4653 return false;
4654
4655 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4656 QualType From
4657 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4658 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004659 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4660 To, Result.IntReal) &&
4661 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4662 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004663 }
4664
4665 case CK_IntegralRealToComplex: {
4666 APSInt &Real = Result.IntReal;
4667 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4668 return false;
4669
4670 Result.makeComplexInt();
4671 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4672 return true;
4673 }
4674
4675 case CK_IntegralComplexCast: {
4676 if (!Visit(E->getSubExpr()))
4677 return false;
4678
4679 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4680 QualType From
4681 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4682
4683 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4684 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4685 return true;
4686 }
4687
4688 case CK_IntegralComplexToFloatingComplex: {
4689 if (!Visit(E->getSubExpr()))
4690 return false;
4691
4692 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4693 QualType From
4694 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4695 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00004696 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4697 To, Result.FloatReal) &&
4698 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4699 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004700 }
4701 }
4702
4703 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004704 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004705}
4706
John McCall93d91dc2010-05-07 17:22:02 +00004707bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004708 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004709 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4710
John McCall93d91dc2010-05-07 17:22:02 +00004711 if (!Visit(E->getLHS()))
4712 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004713
John McCall93d91dc2010-05-07 17:22:02 +00004714 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004715 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004716 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004717
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004718 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4719 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004720 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004721 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004722 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004723 if (Result.isComplexFloat()) {
4724 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4725 APFloat::rmNearestTiesToEven);
4726 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4727 APFloat::rmNearestTiesToEven);
4728 } else {
4729 Result.getComplexIntReal() += RHS.getComplexIntReal();
4730 Result.getComplexIntImag() += RHS.getComplexIntImag();
4731 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004732 break;
John McCalle3027922010-08-25 11:45:40 +00004733 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004734 if (Result.isComplexFloat()) {
4735 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4736 APFloat::rmNearestTiesToEven);
4737 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4738 APFloat::rmNearestTiesToEven);
4739 } else {
4740 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4741 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4742 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004743 break;
John McCalle3027922010-08-25 11:45:40 +00004744 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004745 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004746 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004747 APFloat &LHS_r = LHS.getComplexFloatReal();
4748 APFloat &LHS_i = LHS.getComplexFloatImag();
4749 APFloat &RHS_r = RHS.getComplexFloatReal();
4750 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004751
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004752 APFloat Tmp = LHS_r;
4753 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4754 Result.getComplexFloatReal() = Tmp;
4755 Tmp = LHS_i;
4756 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4757 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4758
4759 Tmp = LHS_r;
4760 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4761 Result.getComplexFloatImag() = Tmp;
4762 Tmp = LHS_i;
4763 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4764 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4765 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004766 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004767 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004768 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4769 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004770 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004771 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4772 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4773 }
4774 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004775 case BO_Div:
4776 if (Result.isComplexFloat()) {
4777 ComplexValue LHS = Result;
4778 APFloat &LHS_r = LHS.getComplexFloatReal();
4779 APFloat &LHS_i = LHS.getComplexFloatImag();
4780 APFloat &RHS_r = RHS.getComplexFloatReal();
4781 APFloat &RHS_i = RHS.getComplexFloatImag();
4782 APFloat &Res_r = Result.getComplexFloatReal();
4783 APFloat &Res_i = Result.getComplexFloatImag();
4784
4785 APFloat Den = RHS_r;
4786 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4787 APFloat Tmp = RHS_i;
4788 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4789 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4790
4791 Res_r = LHS_r;
4792 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4793 Tmp = LHS_i;
4794 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4795 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4796 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4797
4798 Res_i = LHS_i;
4799 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4800 Tmp = LHS_r;
4801 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4802 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4803 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4804 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004805 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4806 return Error(E, diag::note_expr_divide_by_zero);
4807
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004808 ComplexValue LHS = Result;
4809 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4810 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4811 Result.getComplexIntReal() =
4812 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4813 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4814 Result.getComplexIntImag() =
4815 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4816 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4817 }
4818 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004819 }
4820
John McCall93d91dc2010-05-07 17:22:02 +00004821 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004822}
4823
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004824bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4825 // Get the operand value into 'Result'.
4826 if (!Visit(E->getSubExpr()))
4827 return false;
4828
4829 switch (E->getOpcode()) {
4830 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004831 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004832 case UO_Extension:
4833 return true;
4834 case UO_Plus:
4835 // The result is always just the subexpr.
4836 return true;
4837 case UO_Minus:
4838 if (Result.isComplexFloat()) {
4839 Result.getComplexFloatReal().changeSign();
4840 Result.getComplexFloatImag().changeSign();
4841 }
4842 else {
4843 Result.getComplexIntReal() = -Result.getComplexIntReal();
4844 Result.getComplexIntImag() = -Result.getComplexIntImag();
4845 }
4846 return true;
4847 case UO_Not:
4848 if (Result.isComplexFloat())
4849 Result.getComplexFloatImag().changeSign();
4850 else
4851 Result.getComplexIntImag() = -Result.getComplexIntImag();
4852 return true;
4853 }
4854}
4855
Anders Carlsson537969c2008-11-16 20:27:53 +00004856//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00004857// Void expression evaluation, primarily for a cast to void on the LHS of a
4858// comma operator
4859//===----------------------------------------------------------------------===//
4860
4861namespace {
4862class VoidExprEvaluator
4863 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4864public:
4865 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4866
4867 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00004868
4869 bool VisitCastExpr(const CastExpr *E) {
4870 switch (E->getCastKind()) {
4871 default:
4872 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4873 case CK_ToVoid:
4874 VisitIgnoredValue(E->getSubExpr());
4875 return true;
4876 }
4877 }
4878};
4879} // end anonymous namespace
4880
4881static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4882 assert(E->isRValue() && E->getType()->isVoidType());
4883 return VoidExprEvaluator(Info).Visit(E);
4884}
4885
4886//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00004887// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00004888//===----------------------------------------------------------------------===//
4889
Richard Smith0b0a0b62011-10-29 20:57:55 +00004890static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004891 // In C, function designators are not lvalues, but we evaluate them as if they
4892 // are.
4893 if (E->isGLValue() || E->getType()->isFunctionType()) {
4894 LValue LV;
4895 if (!EvaluateLValue(E, LV, Info))
4896 return false;
4897 LV.moveInto(Result);
4898 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004899 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004900 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004901 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004902 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004903 return false;
John McCall45d55e42010-05-07 21:00:08 +00004904 } else if (E->getType()->hasPointerRepresentation()) {
4905 LValue LV;
4906 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004907 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004908 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00004909 } else if (E->getType()->isRealFloatingType()) {
4910 llvm::APFloat F(0.0);
4911 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004912 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004913 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00004914 } else if (E->getType()->isAnyComplexType()) {
4915 ComplexValue C;
4916 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004917 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004918 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004919 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004920 MemberPtr P;
4921 if (!EvaluateMemberPointer(E, P, Info))
4922 return false;
4923 P.moveInto(Result);
4924 return true;
Richard Smithed5165f2011-11-04 05:33:44 +00004925 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004926 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004927 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004928 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00004929 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004930 Result = Info.CurrentCall->Temporaries[E];
Richard Smithed5165f2011-11-04 05:33:44 +00004931 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004932 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004933 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004934 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4935 return false;
4936 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00004937 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00004938 if (Info.getLangOpts().CPlusPlus0x)
4939 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
4940 << E->getType();
4941 else
4942 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00004943 if (!EvaluateVoid(E, Info))
4944 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004945 } else if (Info.getLangOpts().CPlusPlus0x) {
4946 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
4947 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004948 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00004949 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00004950 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004951 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004952
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00004953 return true;
4954}
4955
Richard Smithed5165f2011-11-04 05:33:44 +00004956/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4957/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4958/// since later initializers for an object can indirectly refer to subobjects
4959/// which were initialized earlier.
4960static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00004961 const LValue &This, const Expr *E,
4962 CheckConstantExpressionKind CCEK) {
Richard Smithed5165f2011-11-04 05:33:44 +00004963 if (E->isRValue() && E->getType()->isLiteralType()) {
4964 // Evaluate arrays and record types in-place, so that later initializers can
4965 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00004966 if (E->getType()->isArrayType())
4967 return EvaluateArray(E, This, Result, Info);
4968 else if (E->getType()->isRecordType())
4969 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00004970 }
4971
4972 // For any other type, in-place evaluation is unimportant.
4973 CCValue CoreConstResult;
4974 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00004975 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00004976}
4977
Richard Smithf57d8cb2011-12-09 22:58:01 +00004978/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4979/// lvalue-to-rvalue cast if it is an lvalue.
4980static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4981 CCValue Value;
4982 if (!::Evaluate(Value, Info, E))
4983 return false;
4984
4985 if (E->isGLValue()) {
4986 LValue LV;
4987 LV.setFrom(Value);
4988 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4989 return false;
4990 }
4991
4992 // Check this core constant expression is a constant expression, and if so,
4993 // convert it to one.
4994 return CheckConstantExpression(Info, E, Value, Result);
4995}
Richard Smith11562c52011-10-28 17:51:58 +00004996
Richard Smith7b553f12011-10-29 00:50:52 +00004997/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00004998/// any crazy technique (that has nothing to do with language standards) that
4999/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00005000/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5001/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00005002bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00005003 // Fast-path evaluations of integer literals, since we sometimes see files
5004 // containing vast quantities of these.
5005 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5006 Result.Val = APValue(APSInt(L->getValue(),
5007 L->getType()->isUnsignedIntegerType()));
5008 return true;
5009 }
5010
Richard Smith5686e752011-11-10 03:30:42 +00005011 // FIXME: Evaluating initializers for large arrays can cause performance
5012 // problems, and we don't use such values yet. Once we have a more efficient
5013 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00005014 // The same problem affects large records.
5015 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5016 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00005017 return false;
5018
Richard Smithd62306a2011-11-10 06:34:14 +00005019 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005020 EvalInfo Info(Ctx, Result);
5021 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00005022}
5023
Jay Foad39c79802011-01-12 09:06:06 +00005024bool Expr::EvaluateAsBooleanCondition(bool &Result,
5025 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005026 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00005027 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00005028 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00005029 Result);
John McCall1be1c632010-01-05 23:42:56 +00005030}
5031
Richard Smithcaf33902011-10-10 18:28:20 +00005032bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005033 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005034 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00005035 !ExprResult.Val.isInt())
Richard Smith11562c52011-10-28 17:51:58 +00005036 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005037
Richard Smith11562c52011-10-28 17:51:58 +00005038 Result = ExprResult.Val.getInt();
5039 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00005040}
5041
Jay Foad39c79802011-01-12 09:06:06 +00005042bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00005043 EvalInfo Info(Ctx, Result);
5044
John McCall45d55e42010-05-07 21:00:08 +00005045 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005046 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005047 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5048 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005049}
5050
Richard Smithd0b4dd62011-12-19 06:19:21 +00005051bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5052 const VarDecl *VD,
5053 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5054 Expr::EvalStatus EStatus;
5055 EStatus.Diag = &Notes;
5056
5057 EvalInfo InitInfo(Ctx, EStatus);
5058 InitInfo.setEvaluatingDecl(VD, Value);
5059
5060 LValue LVal;
5061 LVal.set(VD);
5062
5063 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5064 !EStatus.HasSideEffects;
5065}
5066
Richard Smith7b553f12011-10-29 00:50:52 +00005067/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5068/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005069bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005070 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005071 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005072}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005073
Jay Foad39c79802011-01-12 09:06:06 +00005074bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005075 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005076}
5077
Richard Smithcaf33902011-10-10 18:28:20 +00005078APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005079 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005080 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005081 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005082 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005083 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005084
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005085 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005086}
John McCall864e3962010-05-07 05:32:02 +00005087
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005088 bool Expr::EvalResult::isGlobalLValue() const {
5089 assert(Val.isLValue());
5090 return IsGlobalLValue(Val.getLValueBase());
5091 }
5092
5093
John McCall864e3962010-05-07 05:32:02 +00005094/// isIntegerConstantExpr - this recursive routine will test if an expression is
5095/// an integer constant expression.
5096
5097/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5098/// comma, etc
5099///
5100/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5101/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5102/// cast+dereference.
5103
5104// CheckICE - This function does the fundamental ICE checking: the returned
5105// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5106// Note that to reduce code duplication, this helper does no evaluation
5107// itself; the caller checks whether the expression is evaluatable, and
5108// in the rare cases where CheckICE actually cares about the evaluated
5109// value, it calls into Evalute.
5110//
5111// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005112// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005113// 1: This expression is not an ICE, but if it isn't evaluated, it's
5114// a legal subexpression for an ICE. This return value is used to handle
5115// the comma operator in C99 mode.
5116// 2: This expression is not an ICE, and is not a legal subexpression for one.
5117
Dan Gohman28ade552010-07-26 21:25:24 +00005118namespace {
5119
John McCall864e3962010-05-07 05:32:02 +00005120struct ICEDiag {
5121 unsigned Val;
5122 SourceLocation Loc;
5123
5124 public:
5125 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5126 ICEDiag() : Val(0) {}
5127};
5128
Dan Gohman28ade552010-07-26 21:25:24 +00005129}
5130
5131static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005132
5133static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5134 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005135 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005136 !EVResult.Val.isInt()) {
5137 return ICEDiag(2, E->getLocStart());
5138 }
5139 return NoDiag();
5140}
5141
5142static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5143 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005144 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005145 return ICEDiag(2, E->getLocStart());
5146 }
5147
5148 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005149#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005150#define STMT(Node, Base) case Expr::Node##Class:
5151#define EXPR(Node, Base)
5152#include "clang/AST/StmtNodes.inc"
5153 case Expr::PredefinedExprClass:
5154 case Expr::FloatingLiteralClass:
5155 case Expr::ImaginaryLiteralClass:
5156 case Expr::StringLiteralClass:
5157 case Expr::ArraySubscriptExprClass:
5158 case Expr::MemberExprClass:
5159 case Expr::CompoundAssignOperatorClass:
5160 case Expr::CompoundLiteralExprClass:
5161 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005162 case Expr::DesignatedInitExprClass:
5163 case Expr::ImplicitValueInitExprClass:
5164 case Expr::ParenListExprClass:
5165 case Expr::VAArgExprClass:
5166 case Expr::AddrLabelExprClass:
5167 case Expr::StmtExprClass:
5168 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005169 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005170 case Expr::CXXDynamicCastExprClass:
5171 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005172 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005173 case Expr::CXXNullPtrLiteralExprClass:
5174 case Expr::CXXThisExprClass:
5175 case Expr::CXXThrowExprClass:
5176 case Expr::CXXNewExprClass:
5177 case Expr::CXXDeleteExprClass:
5178 case Expr::CXXPseudoDestructorExprClass:
5179 case Expr::UnresolvedLookupExprClass:
5180 case Expr::DependentScopeDeclRefExprClass:
5181 case Expr::CXXConstructExprClass:
5182 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005183 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005184 case Expr::CXXTemporaryObjectExprClass:
5185 case Expr::CXXUnresolvedConstructExprClass:
5186 case Expr::CXXDependentScopeMemberExprClass:
5187 case Expr::UnresolvedMemberExprClass:
5188 case Expr::ObjCStringLiteralClass:
5189 case Expr::ObjCEncodeExprClass:
5190 case Expr::ObjCMessageExprClass:
5191 case Expr::ObjCSelectorExprClass:
5192 case Expr::ObjCProtocolExprClass:
5193 case Expr::ObjCIvarRefExprClass:
5194 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005195 case Expr::ObjCIsaExprClass:
5196 case Expr::ShuffleVectorExprClass:
5197 case Expr::BlockExprClass:
5198 case Expr::BlockDeclRefExprClass:
5199 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005200 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005201 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005202 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005203 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005204 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005205 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005206 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005207 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005208 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005209 return ICEDiag(2, E->getLocStart());
5210
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005211 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005212 case Expr::GNUNullExprClass:
5213 // GCC considers the GNU __null value to be an integral constant expression.
5214 return NoDiag();
5215
John McCall7c454bb2011-07-15 05:09:51 +00005216 case Expr::SubstNonTypeTemplateParmExprClass:
5217 return
5218 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5219
John McCall864e3962010-05-07 05:32:02 +00005220 case Expr::ParenExprClass:
5221 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005222 case Expr::GenericSelectionExprClass:
5223 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005224 case Expr::IntegerLiteralClass:
5225 case Expr::CharacterLiteralClass:
5226 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005227 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005228 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005229 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005230 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005231 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005232 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005233 return NoDiag();
5234 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005235 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005236 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5237 // constant expressions, but they can never be ICEs because an ICE cannot
5238 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005239 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005240 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005241 return CheckEvalInICE(E, Ctx);
5242 return ICEDiag(2, E->getLocStart());
5243 }
5244 case Expr::DeclRefExprClass:
5245 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5246 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005247 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005248 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5249
5250 // Parameter variables are never constants. Without this check,
5251 // getAnyInitializer() can find a default argument, which leads
5252 // to chaos.
5253 if (isa<ParmVarDecl>(D))
5254 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5255
5256 // C++ 7.1.5.1p2
5257 // A variable of non-volatile const-qualified integral or enumeration
5258 // type initialized by an ICE can be used in ICEs.
5259 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005260 if (!Dcl->getType()->isIntegralOrEnumerationType())
5261 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5262
Richard Smithd0b4dd62011-12-19 06:19:21 +00005263 const VarDecl *VD;
5264 // Look for a declaration of this variable that has an initializer, and
5265 // check whether it is an ICE.
5266 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5267 return NoDiag();
5268 else
5269 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005270 }
5271 }
5272 return ICEDiag(2, E->getLocStart());
5273 case Expr::UnaryOperatorClass: {
5274 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5275 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005276 case UO_PostInc:
5277 case UO_PostDec:
5278 case UO_PreInc:
5279 case UO_PreDec:
5280 case UO_AddrOf:
5281 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005282 // C99 6.6/3 allows increment and decrement within unevaluated
5283 // subexpressions of constant expressions, but they can never be ICEs
5284 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005285 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005286 case UO_Extension:
5287 case UO_LNot:
5288 case UO_Plus:
5289 case UO_Minus:
5290 case UO_Not:
5291 case UO_Real:
5292 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005293 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005294 }
5295
5296 // OffsetOf falls through here.
5297 }
5298 case Expr::OffsetOfExprClass: {
5299 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005300 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005301 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005302 // compliance: we should warn earlier for offsetof expressions with
5303 // array subscripts that aren't ICEs, and if the array subscripts
5304 // are ICEs, the value of the offsetof must be an integer constant.
5305 return CheckEvalInICE(E, Ctx);
5306 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005307 case Expr::UnaryExprOrTypeTraitExprClass: {
5308 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5309 if ((Exp->getKind() == UETT_SizeOf) &&
5310 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005311 return ICEDiag(2, E->getLocStart());
5312 return NoDiag();
5313 }
5314 case Expr::BinaryOperatorClass: {
5315 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5316 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005317 case BO_PtrMemD:
5318 case BO_PtrMemI:
5319 case BO_Assign:
5320 case BO_MulAssign:
5321 case BO_DivAssign:
5322 case BO_RemAssign:
5323 case BO_AddAssign:
5324 case BO_SubAssign:
5325 case BO_ShlAssign:
5326 case BO_ShrAssign:
5327 case BO_AndAssign:
5328 case BO_XorAssign:
5329 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005330 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5331 // constant expressions, but they can never be ICEs because an ICE cannot
5332 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005333 return ICEDiag(2, E->getLocStart());
5334
John McCalle3027922010-08-25 11:45:40 +00005335 case BO_Mul:
5336 case BO_Div:
5337 case BO_Rem:
5338 case BO_Add:
5339 case BO_Sub:
5340 case BO_Shl:
5341 case BO_Shr:
5342 case BO_LT:
5343 case BO_GT:
5344 case BO_LE:
5345 case BO_GE:
5346 case BO_EQ:
5347 case BO_NE:
5348 case BO_And:
5349 case BO_Xor:
5350 case BO_Or:
5351 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005352 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5353 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005354 if (Exp->getOpcode() == BO_Div ||
5355 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005356 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005357 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005358 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005359 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005360 if (REval == 0)
5361 return ICEDiag(1, E->getLocStart());
5362 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005363 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005364 if (LEval.isMinSignedValue())
5365 return ICEDiag(1, E->getLocStart());
5366 }
5367 }
5368 }
John McCalle3027922010-08-25 11:45:40 +00005369 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005370 if (Ctx.getLangOptions().C99) {
5371 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5372 // if it isn't evaluated.
5373 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5374 return ICEDiag(1, E->getLocStart());
5375 } else {
5376 // In both C89 and C++, commas in ICEs are illegal.
5377 return ICEDiag(2, E->getLocStart());
5378 }
5379 }
5380 if (LHSResult.Val >= RHSResult.Val)
5381 return LHSResult;
5382 return RHSResult;
5383 }
John McCalle3027922010-08-25 11:45:40 +00005384 case BO_LAnd:
5385 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005386 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5387 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5388 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5389 // Rare case where the RHS has a comma "side-effect"; we need
5390 // to actually check the condition to see whether the side
5391 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005392 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005393 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005394 return RHSResult;
5395 return NoDiag();
5396 }
5397
5398 if (LHSResult.Val >= RHSResult.Val)
5399 return LHSResult;
5400 return RHSResult;
5401 }
5402 }
5403 }
5404 case Expr::ImplicitCastExprClass:
5405 case Expr::CStyleCastExprClass:
5406 case Expr::CXXFunctionalCastExprClass:
5407 case Expr::CXXStaticCastExprClass:
5408 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005409 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005410 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005411 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005412 if (isa<ExplicitCastExpr>(E)) {
5413 if (const FloatingLiteral *FL
5414 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5415 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5416 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5417 APSInt IgnoredVal(DestWidth, !DestSigned);
5418 bool Ignored;
5419 // If the value does not fit in the destination type, the behavior is
5420 // undefined, so we are not required to treat it as a constant
5421 // expression.
5422 if (FL->getValue().convertToInteger(IgnoredVal,
5423 llvm::APFloat::rmTowardZero,
5424 &Ignored) & APFloat::opInvalidOp)
5425 return ICEDiag(2, E->getLocStart());
5426 return NoDiag();
5427 }
5428 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005429 switch (cast<CastExpr>(E)->getCastKind()) {
5430 case CK_LValueToRValue:
5431 case CK_NoOp:
5432 case CK_IntegralToBoolean:
5433 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005434 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005435 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005436 return ICEDiag(2, E->getLocStart());
5437 }
John McCall864e3962010-05-07 05:32:02 +00005438 }
John McCallc07a0c72011-02-17 10:25:35 +00005439 case Expr::BinaryConditionalOperatorClass: {
5440 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5441 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5442 if (CommonResult.Val == 2) return CommonResult;
5443 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5444 if (FalseResult.Val == 2) return FalseResult;
5445 if (CommonResult.Val == 1) return CommonResult;
5446 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005447 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005448 return FalseResult;
5449 }
John McCall864e3962010-05-07 05:32:02 +00005450 case Expr::ConditionalOperatorClass: {
5451 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5452 // If the condition (ignoring parens) is a __builtin_constant_p call,
5453 // then only the true side is actually considered in an integer constant
5454 // expression, and it is fully evaluated. This is an important GNU
5455 // extension. See GCC PR38377 for discussion.
5456 if (const CallExpr *CallCE
5457 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00005458 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00005459 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005460 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005461 !EVResult.Val.isInt()) {
5462 return ICEDiag(2, E->getLocStart());
5463 }
5464 return NoDiag();
5465 }
5466 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005467 if (CondResult.Val == 2)
5468 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005469
Richard Smithf57d8cb2011-12-09 22:58:01 +00005470 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5471 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005472
John McCall864e3962010-05-07 05:32:02 +00005473 if (TrueResult.Val == 2)
5474 return TrueResult;
5475 if (FalseResult.Val == 2)
5476 return FalseResult;
5477 if (CondResult.Val == 1)
5478 return CondResult;
5479 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5480 return NoDiag();
5481 // Rare case where the diagnostics depend on which side is evaluated
5482 // Note that if we get here, CondResult is 0, and at least one of
5483 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005484 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005485 return FalseResult;
5486 }
5487 return TrueResult;
5488 }
5489 case Expr::CXXDefaultArgExprClass:
5490 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5491 case Expr::ChooseExprClass: {
5492 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5493 }
5494 }
5495
5496 // Silence a GCC warning
5497 return ICEDiag(2, E->getLocStart());
5498}
5499
Richard Smithf57d8cb2011-12-09 22:58:01 +00005500/// Evaluate an expression as a C++11 integral constant expression.
5501static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5502 const Expr *E,
5503 llvm::APSInt *Value,
5504 SourceLocation *Loc) {
5505 if (!E->getType()->isIntegralOrEnumerationType()) {
5506 if (Loc) *Loc = E->getExprLoc();
5507 return false;
5508 }
5509
5510 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005511 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5512 Result.Diag = &Diags;
5513 EvalInfo Info(Ctx, Result);
5514
5515 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5516 if (!Diags.empty()) {
5517 IsICE = false;
5518 if (Loc) *Loc = Diags[0].first;
5519 } else if (!IsICE && Loc) {
5520 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005521 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005522
5523 if (!IsICE)
5524 return false;
5525
5526 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5527 if (Value) *Value = Result.Val.getInt();
5528 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005529}
5530
Richard Smith92b1ce02011-12-12 09:28:41 +00005531bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005532 if (Ctx.getLangOptions().CPlusPlus0x)
5533 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5534
John McCall864e3962010-05-07 05:32:02 +00005535 ICEDiag d = CheckICE(this, Ctx);
5536 if (d.Val != 0) {
5537 if (Loc) *Loc = d.Loc;
5538 return false;
5539 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005540 return true;
5541}
5542
5543bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5544 SourceLocation *Loc, bool isEvaluated) const {
5545 if (Ctx.getLangOptions().CPlusPlus0x)
5546 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5547
5548 if (!isIntegerConstantExpr(Ctx, Loc))
5549 return false;
5550 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005551 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005552 return true;
5553}