blob: 4fc75a613eb44623b4329589a7a0ef04a3583df4 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Richard Smith180f4792011-11-10 06:34:14 +000046 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000049
Richard Smith1bf9a9e2011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smith180f4792011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smith9a17a682011-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 Smith180f4792011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith9a17a682011-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 Smith0a3bdb62011-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 Smith9a17a682011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith0a3bdb62011-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 Smith9a17a682011-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 Smith1bf9a9e2011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith9a17a682011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smithe24f5fc2011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith0a3bdb62011-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 Smith9a17a682011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith0a3bdb62011-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 Smith180f4792011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-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 Smithcc5d4f62011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith9a17a682011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith0a3bdb62011-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 Smith47a1eed2011-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 Smithe24f5fc2011-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 Smith47a1eed2011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-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 Smith0a3bdb62011-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 Smith47a1eed2011-10-29 20:57:55 +0000195 public:
Richard Smith177dce72011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith47a1eed2011-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 Smith177dce72011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smith177dce72011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith9a17a682011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000213
Richard Smith177dce72011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000217 }
Richard Smith0a3bdb62011-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 Smith47a1eed2011-10-29 20:57:55 +0000225 };
226
Richard Smithd0dccea2011-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 Smithbd552ef2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000233
Richard Smith08d6e032011-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 Smith180f4792011-11-10 06:34:14 +0000240 /// This - The binding for the this pointer in this call, if any.
241 const LValue *This;
242
Richard Smithd0dccea2011-10-28 22:34:42 +0000243 /// ParmBindings - Parameter bindings for this function call, indexed by
244 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000245 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000246
Richard Smithbd552ef2011-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 Smith08d6e032011-12-16 19:06:07 +0000252 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
253 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000254 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000255 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000256 };
257
Richard Smithdd1f29b2011-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 Smithbd552ef2011-10-31 05:52:43 +0000274 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000275 ASTContext &Ctx;
Richard Smithbd552ef2011-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 Smithbd552ef2011-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 Smith180f4792011-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 Smithc1c5f272011-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 Smithbd552ef2011-10-31 05:52:43 +0000307
308 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000309 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000310 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
311 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000312
Richard Smithbd552ef2011-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 Smith180f4792011-11-10 06:34:14 +0000319 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
320 EvaluatingDecl = VD;
321 EvaluatingDeclValue = &Value;
322 }
323
Richard Smithc18c4232011-11-21 19:36:32 +0000324 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
325
Richard Smithc1c5f272011-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 Smithc18c4232011-11-21 19:36:32 +0000332 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000333
Richard Smithc1c5f272011-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 Smith08d6e032011-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 Smithc1c5f272011-12-13 06:39:58 +0000345 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000346 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
348 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000349 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-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 Smithdd1f29b2011-12-12 09:28:41 +0000353 if (EvalStatus.Diag) {
Richard Smith08d6e032011-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 Smithc1c5f272011-12-13 06:39:58 +0000359 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000360 EvalStatus.Diag->clear();
Richard Smith08d6e032011-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 Smithdd1f29b2011-12-12 09:28:41 +0000365 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000366 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-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 Smith7098cbd2011-12-21 05:04:46 +0000372 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
373 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000374 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000375 // Don't override a previous diagnostic.
376 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
377 return OptionalDiagnostic();
Richard Smithc1c5f272011-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 Smithf48fdb02011-12-09 22:58:01 +0000386 }
Richard Smith099e7f62011-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 Smithbd552ef2011-10-31 05:52:43 +0000395 };
Richard Smith08d6e032011-12-16 19:06:07 +0000396}
Richard Smithbd552ef2011-10-31 05:52:43 +0000397
Richard Smith08d6e032011-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 Smithbd552ef2011-10-31 05:52:43 +0000441 }
442
Richard Smith08d6e032011-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 Smithbd552ef2011-10-31 05:52:43 +0000453 }
454
Richard Smith08d6e032011-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 McCallf4cf1a12010-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 Smith47a1eed2011-10-29 20:57:55 +0000497 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000498 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000499 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000500 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000501 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000502 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000503 void setFrom(const CCValue &v) {
John McCall56ca35d2011-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 McCallf4cf1a12010-05-07 17:22:02 +0000515 };
John McCallefdb83e2010-05-07 21:00:08 +0000516
517 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000518 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000519 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000520 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000521 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000522
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000523 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000524 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000525 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000526 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000527 SubobjectDesignator &getLValueDesignator() { return Designator; }
528 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000529
Richard Smith47a1eed2011-10-29 20:57:55 +0000530 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000531 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000532 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000533 void setFrom(const CCValue &V) {
534 assert(V.isLValue());
535 Base = V.getLValueBase();
536 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000537 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000538 Designator = V.getLValueDesignator();
539 }
540
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000541 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
542 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000543 Offset = CharUnits::Zero();
544 Frame = F;
545 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000546 }
John McCallefdb83e2010-05-07 21:00:08 +0000547 };
Richard Smithe24f5fc2011-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 Smithc1c5f272011-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 McCallf4cf1a12010-05-07 17:22:02 +0000644}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000645
Richard Smith47a1eed2011-10-29 20:57:55 +0000646static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000647static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000648 const LValue &This, const Expr *E,
649 CheckConstantExpressionKind CCEK
650 = CCEK_Constant);
John McCallefdb83e2010-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 Smithe24f5fc2011-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 Lattner87eae5e2008-07-11 22:52:41 +0000656static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000657static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000658 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000659static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000660static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000661
662//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000663// Misc utilities
664//===----------------------------------------------------------------------===//
665
Richard Smith180f4792011-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 Smith1bf9a9e2011-11-12 22:28:03 +0000673static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-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 Smith1bf9a9e2011-11-12 22:28:03 +0000679 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000680
Richard Smith1bf9a9e2011-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 Smith180f4792011-11-10 06:34:14 +0000690 switch (E->getStmtClass()) {
691 default:
692 return false;
Richard Smith180f4792011-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 McCall42c8f872010-05-10 23:27:23 +0000711}
712
Richard Smith9a17a682011-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 Smithf48fdb02011-12-09 22:58:01 +0000716static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-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 Smith7098cbd2011-12-21 05:04:46 +0000734 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000735 }
Richard Smith9a17a682011-11-07 05:07:52 +0000736 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000737 }
Richard Smith9a17a682011-11-07 05:07:52 +0000738
Richard Smith9a17a682011-11-07 05:07:52 +0000739 // A constant expression must refer to an object or be a null pointer.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000740 if (Designator.Invalid ||
Richard Smith9a17a682011-11-07 05:07:52 +0000741 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000742 // FIXME: This is not a core constant expression. We should have already
743 // produced a CCE diagnostic.
Richard Smith9a17a682011-11-07 05:07:52 +0000744 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
745 APValue::NoLValuePath());
746 return true;
747 }
748
Richard Smithc1c5f272011-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 Smith9a17a682011-11-07 05:07:52 +0000764 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smithe24f5fc2011-11-17 22:56:20 +0000765 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith9a17a682011-11-07 05:07:52 +0000766 return true;
767}
768
Richard Smitheba05b22011-12-25 20:00:17 +0000769/// Check that this core constant expression is of literal type, and if not,
770/// produce an appropriate diagnostic.
771static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
772 if (!E->isRValue() || E->getType()->isLiteralType())
773 return true;
774
775 // Prvalue constant expressions must be of literal types.
776 if (Info.getLangOpts().CPlusPlus0x)
777 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
778 << E->getType();
779 else
780 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
781 return false;
782}
783
Richard Smith47a1eed2011-10-29 20:57:55 +0000784/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000785/// constant expression, and if it is, produce the corresponding constant value.
Richard Smitheba05b22011-12-25 20:00:17 +0000786/// If not, report an appropriate diagnostic. Does not check that the expression
787/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000788static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000789 const CCValue &CCValue, APValue &Value,
790 CheckConstantExpressionKind CCEK
791 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000792 if (!CCValue.isLValue()) {
793 Value = CCValue;
794 return true;
795 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000796 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000797}
798
Richard Smith9e36b532011-10-31 05:11:32 +0000799const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000800 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000801}
802
803static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000804 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000805}
806
Richard Smith65ac5982011-11-01 21:06:14 +0000807static bool IsWeakLValue(const LValue &Value) {
808 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000809 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000810}
811
Richard Smithe24f5fc2011-11-17 22:56:20 +0000812static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000813 // A null base expression indicates a null pointer. These are always
814 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000815 if (!Value.getLValueBase()) {
816 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000817 return true;
818 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000819
John McCall42c8f872010-05-10 23:27:23 +0000820 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000821 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000822 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall42c8f872010-05-10 23:27:23 +0000823
Richard Smithe24f5fc2011-11-17 22:56:20 +0000824 // We have a non-null base. These are generally known to be true, but if it's
825 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000826 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000827 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +0000828 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +0000829}
830
Richard Smith47a1eed2011-10-29 20:57:55 +0000831static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000832 switch (Val.getKind()) {
833 case APValue::Uninitialized:
834 return false;
835 case APValue::Int:
836 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000837 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000838 case APValue::Float:
839 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000840 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000841 case APValue::ComplexInt:
842 Result = Val.getComplexIntReal().getBoolValue() ||
843 Val.getComplexIntImag().getBoolValue();
844 return true;
845 case APValue::ComplexFloat:
846 Result = !Val.getComplexFloatReal().isZero() ||
847 !Val.getComplexFloatImag().isZero();
848 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000849 case APValue::LValue:
850 return EvalPointerValueAsBool(Val, Result);
851 case APValue::MemberPointer:
852 Result = Val.getMemberPointerDecl();
853 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000854 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000855 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000856 case APValue::Struct:
857 case APValue::Union:
Richard Smithc49bd112011-10-28 17:51:58 +0000858 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000859 }
860
Richard Smithc49bd112011-10-28 17:51:58 +0000861 llvm_unreachable("unknown APValue kind");
862}
863
864static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
865 EvalInfo &Info) {
866 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000867 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000868 if (!Evaluate(Val, Info, E))
869 return false;
870 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000871}
872
Richard Smithc1c5f272011-12-13 06:39:58 +0000873template<typename T>
874static bool HandleOverflow(EvalInfo &Info, const Expr *E,
875 const T &SrcValue, QualType DestType) {
876 llvm::SmallVector<char, 32> Buffer;
877 SrcValue.toString(Buffer);
878 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
879 << StringRef(Buffer.data(), Buffer.size()) << DestType;
880 return false;
881}
882
883static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
884 QualType SrcType, const APFloat &Value,
885 QualType DestType, APSInt &Result) {
886 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000887 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000888 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Richard Smithc1c5f272011-12-13 06:39:58 +0000890 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000891 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000892 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
893 & APFloat::opInvalidOp)
894 return HandleOverflow(Info, E, Value, DestType);
895 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000896}
897
Richard Smithc1c5f272011-12-13 06:39:58 +0000898static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
899 QualType SrcType, QualType DestType,
900 APFloat &Result) {
901 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000902 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000903 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
904 APFloat::rmNearestTiesToEven, &ignored)
905 & APFloat::opOverflow)
906 return HandleOverflow(Info, E, Value, DestType);
907 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000908}
909
Mike Stump1eb44332009-09-09 15:08:12 +0000910static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000911 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000912 unsigned DestWidth = Ctx.getIntWidth(DestType);
913 APSInt Result = Value;
914 // Figure out if this is a truncate, extend or noop cast.
915 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000916 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000917 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000918 return Result;
919}
920
Richard Smithc1c5f272011-12-13 06:39:58 +0000921static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
922 QualType SrcType, const APSInt &Value,
923 QualType DestType, APFloat &Result) {
924 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
925 if (Result.convertFromAPInt(Value, Value.isSigned(),
926 APFloat::rmNearestTiesToEven)
927 & APFloat::opOverflow)
928 return HandleOverflow(Info, E, Value, DestType);
929 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000930}
931
Eli Friedmane6a24e82011-12-22 03:51:45 +0000932static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
933 llvm::APInt &Res) {
934 CCValue SVal;
935 if (!Evaluate(SVal, Info, E))
936 return false;
937 if (SVal.isInt()) {
938 Res = SVal.getInt();
939 return true;
940 }
941 if (SVal.isFloat()) {
942 Res = SVal.getFloat().bitcastToAPInt();
943 return true;
944 }
945 if (SVal.isVector()) {
946 QualType VecTy = E->getType();
947 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
948 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
949 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
950 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
951 Res = llvm::APInt::getNullValue(VecSize);
952 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
953 APValue &Elt = SVal.getVectorElt(i);
954 llvm::APInt EltAsInt;
955 if (Elt.isInt()) {
956 EltAsInt = Elt.getInt();
957 } else if (Elt.isFloat()) {
958 EltAsInt = Elt.getFloat().bitcastToAPInt();
959 } else {
960 // Don't try to handle vectors of anything other than int or float
961 // (not sure if it's possible to hit this case).
962 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
963 return false;
964 }
965 unsigned BaseEltSize = EltAsInt.getBitWidth();
966 if (BigEndian)
967 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
968 else
969 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
970 }
971 return true;
972 }
973 // Give up if the input isn't an int, float, or vector. For example, we
974 // reject "(v4i16)(intptr_t)&a".
975 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
976 return false;
977}
978
Richard Smithe24f5fc2011-11-17 22:56:20 +0000979static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
980 const CXXRecordDecl *&MostDerivedType,
981 unsigned &MostDerivedPathLength,
982 bool &MostDerivedIsArrayElement) {
983 const SubobjectDesignator &D = LVal.Designator;
984 if (D.Invalid || !LVal.Base)
Richard Smith180f4792011-11-10 06:34:14 +0000985 return false;
986
Richard Smithe24f5fc2011-11-17 22:56:20 +0000987 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smith180f4792011-11-10 06:34:14 +0000988
989 // Find path prefix which leads to the most-derived subobject.
Richard Smith180f4792011-11-10 06:34:14 +0000990 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +0000991 MostDerivedPathLength = 0;
992 MostDerivedIsArrayElement = false;
Richard Smith180f4792011-11-10 06:34:14 +0000993
994 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
995 bool IsArray = T && T->isArrayType();
996 if (IsArray)
997 T = T->getBaseElementTypeUnsafe();
998 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
999 T = FD->getType().getTypePtr();
1000 else
1001 T = 0;
1002
1003 if (T) {
1004 MostDerivedType = T->getAsCXXRecordDecl();
1005 MostDerivedPathLength = I + 1;
1006 MostDerivedIsArrayElement = IsArray;
1007 }
1008 }
1009
Richard Smith180f4792011-11-10 06:34:14 +00001010 // (B*)&d + 1 has no most-derived object.
1011 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
1012 return false;
1013
Richard Smithe24f5fc2011-11-17 22:56:20 +00001014 return MostDerivedType != 0;
1015}
1016
1017static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
1018 const RecordDecl *TruncatedType,
1019 unsigned TruncatedElements,
1020 bool IsArrayElement) {
1021 SubobjectDesignator &D = Result.Designator;
1022 const RecordDecl *RD = TruncatedType;
1023 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001024 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1025 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001026 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001027 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001028 else
Richard Smith180f4792011-11-10 06:34:14 +00001029 Result.Offset -= Layout.getBaseClassOffset(Base);
1030 RD = Base;
1031 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001032 D.Entries.resize(TruncatedElements);
1033 D.ArrayElement = IsArrayElement;
1034}
1035
1036/// If the given LValue refers to a base subobject of some object, find the most
1037/// derived object and the corresponding complete record type. This is necessary
1038/// in order to find the offset of a virtual base class.
1039static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
1040 const CXXRecordDecl *&MostDerivedType) {
1041 unsigned MostDerivedPathLength;
1042 bool MostDerivedIsArrayElement;
1043 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1044 MostDerivedPathLength, MostDerivedIsArrayElement))
1045 return false;
1046
1047 // Remove the trailing base class path entries and their offsets.
1048 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
1049 MostDerivedIsArrayElement);
Richard Smith180f4792011-11-10 06:34:14 +00001050 return true;
1051}
1052
1053static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
1054 const CXXRecordDecl *Derived,
1055 const CXXRecordDecl *Base,
1056 const ASTRecordLayout *RL = 0) {
1057 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1058 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1059 Obj.Designator.addDecl(Base, /*Virtual*/ false);
1060}
1061
1062static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1063 const CXXRecordDecl *DerivedDecl,
1064 const CXXBaseSpecifier *Base) {
1065 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1066
1067 if (!Base->isVirtual()) {
1068 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1069 return true;
1070 }
1071
1072 // Extract most-derived object and corresponding type.
1073 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1074 return false;
1075
1076 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1077 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1078 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1079 return true;
1080}
1081
1082/// Update LVal to refer to the given field, which must be a member of the type
1083/// currently described by LVal.
1084static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1085 const FieldDecl *FD,
1086 const ASTRecordLayout *RL = 0) {
1087 if (!RL)
1088 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1089
1090 unsigned I = FD->getFieldIndex();
1091 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1092 LVal.Designator.addDecl(FD);
1093}
1094
1095/// Get the size of the given type in char units.
1096static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1097 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1098 // extension.
1099 if (Type->isVoidType() || Type->isFunctionType()) {
1100 Size = CharUnits::One();
1101 return true;
1102 }
1103
1104 if (!Type->isConstantSizeType()) {
1105 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1106 return false;
1107 }
1108
1109 Size = Info.Ctx.getTypeSizeInChars(Type);
1110 return true;
1111}
1112
1113/// Update a pointer value to model pointer arithmetic.
1114/// \param Info - Information about the ongoing evaluation.
1115/// \param LVal - The pointer value to be updated.
1116/// \param EltTy - The pointee type represented by LVal.
1117/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1118static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1119 QualType EltTy, int64_t Adjustment) {
1120 CharUnits SizeOfPointee;
1121 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1122 return false;
1123
1124 // Compute the new offset in the appropriate width.
1125 LVal.Offset += Adjustment * SizeOfPointee;
1126 LVal.Designator.adjustIndex(Adjustment);
1127 return true;
1128}
1129
Richard Smith03f96112011-10-24 17:54:18 +00001130/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001131static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1132 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001133 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001134 // If this is a parameter to an active constexpr function call, perform
1135 // argument substitution.
1136 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001137 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001138 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001139 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001140 }
Richard Smith177dce72011-11-01 16:57:24 +00001141 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1142 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001143 }
Richard Smith03f96112011-10-24 17:54:18 +00001144
Richard Smith099e7f62011-12-19 06:19:21 +00001145 // Dig out the initializer, and use the declaration which it's attached to.
1146 const Expr *Init = VD->getAnyInitializer(VD);
1147 if (!Init || Init->isValueDependent()) {
1148 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1149 return false;
1150 }
1151
Richard Smith180f4792011-11-10 06:34:14 +00001152 // If we're currently evaluating the initializer of this declaration, use that
1153 // in-flight value.
1154 if (Info.EvaluatingDecl == VD) {
1155 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1156 return !Result.isUninit();
1157 }
1158
Richard Smith65ac5982011-11-01 21:06:14 +00001159 // Never evaluate the initializer of a weak variable. We can't be sure that
1160 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001161 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001162 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001163 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001164 }
Richard Smith65ac5982011-11-01 21:06:14 +00001165
Richard Smith099e7f62011-12-19 06:19:21 +00001166 // Check that we can fold the initializer. In C++, we will have already done
1167 // this in the cases where it matters for conformance.
1168 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1169 if (!VD->evaluateValue(Notes)) {
1170 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1171 Notes.size() + 1) << VD;
1172 Info.Note(VD->getLocation(), diag::note_declared_at);
1173 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001174 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001175 } else if (!VD->checkInitIsICE()) {
1176 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1177 Notes.size() + 1) << VD;
1178 Info.Note(VD->getLocation(), diag::note_declared_at);
1179 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001180 }
Richard Smith03f96112011-10-24 17:54:18 +00001181
Richard Smith099e7f62011-12-19 06:19:21 +00001182 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001183 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001184}
1185
Richard Smithc49bd112011-10-28 17:51:58 +00001186static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001187 Qualifiers Quals = T.getQualifiers();
1188 return Quals.hasConst() && !Quals.hasVolatile();
1189}
1190
Richard Smith59efe262011-11-11 04:05:33 +00001191/// Get the base index of the given base class within an APValue representing
1192/// the given derived class.
1193static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1194 const CXXRecordDecl *Base) {
1195 Base = Base->getCanonicalDecl();
1196 unsigned Index = 0;
1197 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1198 E = Derived->bases_end(); I != E; ++I, ++Index) {
1199 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1200 return Index;
1201 }
1202
1203 llvm_unreachable("base class missing from derived class's bases list");
1204}
1205
Richard Smithcc5d4f62011-11-07 09:22:26 +00001206/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001207static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1208 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001209 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001210 if (Sub.Invalid) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001211 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001212 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001213 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001214 if (Sub.OnePastTheEnd) {
1215 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001216 (unsigned)diag::note_constexpr_read_past_end :
1217 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001218 return false;
1219 }
Richard Smithf64699e2011-11-11 08:28:03 +00001220 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001221 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001222
1223 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1224 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001225 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001226 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001227 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001228 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001229 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001230 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001231 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001232 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001233 // Note, it should not be possible to form a pointer with a valid
1234 // designator which points more than one past the end of the array.
1235 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001236 (unsigned)diag::note_constexpr_read_past_end :
1237 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001238 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001239 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001240 if (O->getArrayInitializedElts() > Index)
1241 O = &O->getArrayInitializedElt(Index);
1242 else
1243 O = &O->getArrayFiller();
1244 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001245 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1246 // Next subobject is a class, struct or union field.
1247 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1248 if (RD->isUnion()) {
1249 const FieldDecl *UnionField = O->getUnionField();
1250 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001251 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001252 Info.Diag(E->getExprLoc(),
1253 diag::note_constexpr_read_inactive_union_member)
1254 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001255 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001256 }
Richard Smith180f4792011-11-10 06:34:14 +00001257 O = &O->getUnionValue();
1258 } else
1259 O = &O->getStructField(Field->getFieldIndex());
1260 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001261
1262 if (ObjType.isVolatileQualified()) {
1263 if (Info.getLangOpts().CPlusPlus) {
1264 // FIXME: Include a description of the path to the volatile subobject.
1265 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1266 << 2 << Field;
1267 Info.Note(Field->getLocation(), diag::note_declared_at);
1268 } else {
1269 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1270 }
1271 return false;
1272 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001273 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001274 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001275 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1276 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1277 O = &O->getStructBase(getBaseIndex(Derived, Base));
1278 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001279 }
Richard Smith180f4792011-11-10 06:34:14 +00001280
Richard Smithf48fdb02011-12-09 22:58:01 +00001281 if (O->isUninit()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001282 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001283 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001284 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001285 }
1286
Richard Smithcc5d4f62011-11-07 09:22:26 +00001287 Obj = CCValue(*O, CCValue::GlobalValue());
1288 return true;
1289}
1290
Richard Smith180f4792011-11-10 06:34:14 +00001291/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1292/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1293/// for looking up the glvalue referred to by an entity of reference type.
1294///
1295/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001296/// \param Conv - The expression for which we are performing the conversion.
1297/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001298/// \param Type - The type we expect this conversion to produce.
1299/// \param LVal - The glvalue on which we are attempting to perform this action.
1300/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001301static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1302 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001303 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001304 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1305 if (!Info.getLangOpts().CPlusPlus)
1306 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1307
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001308 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001309 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001310 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001311
Richard Smithf48fdb02011-12-09 22:58:01 +00001312 if (!LVal.Base) {
1313 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001314 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1315 return false;
1316 }
1317
1318 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1319 // is not a constant expression (even if the object is non-volatile). We also
1320 // apply this rule to C++98, in order to conform to the expected 'volatile'
1321 // semantics.
1322 if (Type.isVolatileQualified()) {
1323 if (Info.getLangOpts().CPlusPlus)
1324 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1325 else
1326 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001327 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001328 }
Richard Smithc49bd112011-10-28 17:51:58 +00001329
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001330 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001331 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1332 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001333 // expressions are constant expressions too. Inside constexpr functions,
1334 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001335 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001336 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001337 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001338 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001339 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001340 }
1341
Richard Smith7098cbd2011-12-21 05:04:46 +00001342 // DR1313: If the object is volatile-qualified but the glvalue was not,
1343 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001344 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001345 if (VT.isVolatileQualified()) {
1346 if (Info.getLangOpts().CPlusPlus) {
1347 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1348 Info.Note(VD->getLocation(), diag::note_declared_at);
1349 } else {
1350 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001351 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001352 return false;
1353 }
1354
1355 if (!isa<ParmVarDecl>(VD)) {
1356 if (VD->isConstexpr()) {
1357 // OK, we can read this variable.
1358 } else if (VT->isIntegralOrEnumerationType()) {
1359 if (!VT.isConstQualified()) {
1360 if (Info.getLangOpts().CPlusPlus) {
1361 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1362 Info.Note(VD->getLocation(), diag::note_declared_at);
1363 } else {
1364 Info.Diag(Loc);
1365 }
1366 return false;
1367 }
1368 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1369 // We support folding of const floating-point types, in order to make
1370 // static const data members of such types (supported as an extension)
1371 // more useful.
1372 if (Info.getLangOpts().CPlusPlus0x) {
1373 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1374 Info.Note(VD->getLocation(), diag::note_declared_at);
1375 } else {
1376 Info.CCEDiag(Loc);
1377 }
1378 } else {
1379 // FIXME: Allow folding of values of any literal type in all languages.
1380 if (Info.getLangOpts().CPlusPlus0x) {
1381 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1382 Info.Note(VD->getLocation(), diag::note_declared_at);
1383 } else {
1384 Info.Diag(Loc);
1385 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001386 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001387 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001388 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001389
Richard Smithf48fdb02011-12-09 22:58:01 +00001390 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001391 return false;
1392
Richard Smith47a1eed2011-10-29 20:57:55 +00001393 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001394 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001395
1396 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1397 // conversion. This happens when the declaration and the lvalue should be
1398 // considered synonymous, for instance when initializing an array of char
1399 // from a string literal. Continue as if the initializer lvalue was the
1400 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001401 assert(RVal.getLValueOffset().isZero() &&
1402 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001403 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001404 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001405 }
1406
Richard Smith7098cbd2011-12-21 05:04:46 +00001407 // Volatile temporary objects cannot be read in constant expressions.
1408 if (Base->getType().isVolatileQualified()) {
1409 if (Info.getLangOpts().CPlusPlus) {
1410 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1411 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1412 } else {
1413 Info.Diag(Loc);
1414 }
1415 return false;
1416 }
1417
Richard Smith0a3bdb62011-11-04 02:25:55 +00001418 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1419 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1420 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001421 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001422 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001423 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001424 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001425
1426 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001427 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001428 const ConstantArrayType *CAT =
1429 Info.Ctx.getAsConstantArrayType(S->getType());
1430 if (Index >= CAT->getSize().getZExtValue()) {
1431 // Note, it should not be possible to form a pointer which points more
1432 // than one past the end of the array without producing a prior const expr
1433 // diagnostic.
1434 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001435 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001436 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001437 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1438 Type->isUnsignedIntegerType());
1439 if (Index < S->getLength())
1440 Value = S->getCodeUnit(Index);
1441 RVal = CCValue(Value);
1442 return true;
1443 }
1444
Richard Smithcc5d4f62011-11-07 09:22:26 +00001445 if (Frame) {
1446 // If this is a temporary expression with a nontrivial initializer, grab the
1447 // value from the relevant stack frame.
1448 RVal = Frame->Temporaries[Base];
1449 } else if (const CompoundLiteralExpr *CLE
1450 = dyn_cast<CompoundLiteralExpr>(Base)) {
1451 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1452 // initializer until now for such expressions. Such an expression can't be
1453 // an ICE in C, so this only matters for fold.
1454 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1455 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1456 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001457 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001458 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001459 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001460 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001461
Richard Smithf48fdb02011-12-09 22:58:01 +00001462 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1463 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001464}
1465
Richard Smith59efe262011-11-11 04:05:33 +00001466/// Build an lvalue for the object argument of a member function call.
1467static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1468 LValue &This) {
1469 if (Object->getType()->isPointerType())
1470 return EvaluatePointer(Object, This, Info);
1471
1472 if (Object->isGLValue())
1473 return EvaluateLValue(Object, This, Info);
1474
Richard Smithe24f5fc2011-11-17 22:56:20 +00001475 if (Object->getType()->isLiteralType())
1476 return EvaluateTemporary(Object, This, Info);
1477
1478 return false;
1479}
1480
1481/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1482/// lvalue referring to the result.
1483///
1484/// \param Info - Information about the ongoing evaluation.
1485/// \param BO - The member pointer access operation.
1486/// \param LV - Filled in with a reference to the resulting object.
1487/// \param IncludeMember - Specifies whether the member itself is included in
1488/// the resulting LValue subobject designator. This is not possible when
1489/// creating a bound member function.
1490/// \return The field or method declaration to which the member pointer refers,
1491/// or 0 if evaluation fails.
1492static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1493 const BinaryOperator *BO,
1494 LValue &LV,
1495 bool IncludeMember = true) {
1496 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1497
1498 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1499 return 0;
1500
1501 MemberPtr MemPtr;
1502 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1503 return 0;
1504
1505 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1506 // member value, the behavior is undefined.
1507 if (!MemPtr.getDecl())
1508 return 0;
1509
1510 if (MemPtr.isDerivedMember()) {
1511 // This is a member of some derived class. Truncate LV appropriately.
1512 const CXXRecordDecl *MostDerivedType;
1513 unsigned MostDerivedPathLength;
1514 bool MostDerivedIsArrayElement;
1515 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1516 MostDerivedIsArrayElement))
1517 return 0;
1518
1519 // The end of the derived-to-base path for the base object must match the
1520 // derived-to-base path for the member pointer.
1521 if (MostDerivedPathLength + MemPtr.Path.size() >
1522 LV.Designator.Entries.size())
1523 return 0;
1524 unsigned PathLengthToMember =
1525 LV.Designator.Entries.size() - MemPtr.Path.size();
1526 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1527 const CXXRecordDecl *LVDecl = getAsBaseClass(
1528 LV.Designator.Entries[PathLengthToMember + I]);
1529 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1530 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1531 return 0;
1532 }
1533
1534 // Truncate the lvalue to the appropriate derived class.
1535 bool ResultIsArray = false;
1536 if (PathLengthToMember == MostDerivedPathLength)
1537 ResultIsArray = MostDerivedIsArrayElement;
1538 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1539 PathLengthToMember, ResultIsArray);
1540 } else if (!MemPtr.Path.empty()) {
1541 // Extend the LValue path with the member pointer's path.
1542 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1543 MemPtr.Path.size() + IncludeMember);
1544
1545 // Walk down to the appropriate base class.
1546 QualType LVType = BO->getLHS()->getType();
1547 if (const PointerType *PT = LVType->getAs<PointerType>())
1548 LVType = PT->getPointeeType();
1549 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1550 assert(RD && "member pointer access on non-class-type expression");
1551 // The first class in the path is that of the lvalue.
1552 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1553 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1554 HandleLValueDirectBase(Info, LV, RD, Base);
1555 RD = Base;
1556 }
1557 // Finally cast to the class containing the member.
1558 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1559 }
1560
1561 // Add the member. Note that we cannot build bound member functions here.
1562 if (IncludeMember) {
1563 // FIXME: Deal with IndirectFieldDecls.
1564 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1565 if (!FD) return 0;
1566 HandleLValueMember(Info, LV, FD);
1567 }
1568
1569 return MemPtr.getDecl();
1570}
1571
1572/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1573/// the provided lvalue, which currently refers to the base object.
1574static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1575 LValue &Result) {
1576 const CXXRecordDecl *MostDerivedType;
1577 unsigned MostDerivedPathLength;
1578 bool MostDerivedIsArrayElement;
1579
1580 // Check this cast doesn't take us outside the object.
1581 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1582 MostDerivedPathLength,
1583 MostDerivedIsArrayElement))
1584 return false;
1585 SubobjectDesignator &D = Result.Designator;
1586 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1587 return false;
1588
1589 // Check the type of the final cast. We don't need to check the path,
1590 // since a cast can only be formed if the path is unique.
1591 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1592 bool ResultIsArray = false;
1593 QualType TargetQT = E->getType();
1594 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1595 TargetQT = PT->getPointeeType();
1596 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1597 const CXXRecordDecl *FinalType;
1598 if (NewEntriesSize == MostDerivedPathLength) {
1599 ResultIsArray = MostDerivedIsArrayElement;
1600 FinalType = MostDerivedType;
1601 } else
1602 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1603 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1604 return false;
1605
1606 // Truncate the lvalue to the appropriate derived class.
1607 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1608 ResultIsArray);
1609 return true;
Richard Smith59efe262011-11-11 04:05:33 +00001610}
1611
Mike Stumpc4c90452009-10-27 22:09:17 +00001612namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001613enum EvalStmtResult {
1614 /// Evaluation failed.
1615 ESR_Failed,
1616 /// Hit a 'return' statement.
1617 ESR_Returned,
1618 /// Evaluation succeeded.
1619 ESR_Succeeded
1620};
1621}
1622
1623// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001624static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001625 const Stmt *S) {
1626 switch (S->getStmtClass()) {
1627 default:
1628 return ESR_Failed;
1629
1630 case Stmt::NullStmtClass:
1631 case Stmt::DeclStmtClass:
1632 return ESR_Succeeded;
1633
Richard Smithc1c5f272011-12-13 06:39:58 +00001634 case Stmt::ReturnStmtClass: {
1635 CCValue CCResult;
1636 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1637 if (!Evaluate(CCResult, Info, RetExpr) ||
1638 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1639 CCEK_ReturnValue))
1640 return ESR_Failed;
1641 return ESR_Returned;
1642 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001643
1644 case Stmt::CompoundStmtClass: {
1645 const CompoundStmt *CS = cast<CompoundStmt>(S);
1646 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1647 BE = CS->body_end(); BI != BE; ++BI) {
1648 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1649 if (ESR != ESR_Succeeded)
1650 return ESR;
1651 }
1652 return ESR_Succeeded;
1653 }
1654 }
1655}
1656
Richard Smith61802452011-12-22 02:22:31 +00001657/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1658/// default constructor. If so, we'll fold it whether or not it's marked as
1659/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1660/// so we need special handling.
1661static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smitheba05b22011-12-25 20:00:17 +00001662 const CXXConstructorDecl *CD,
1663 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001664 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1665 return false;
1666
1667 if (!CD->isConstexpr()) {
1668 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smitheba05b22011-12-25 20:00:17 +00001669 // Value-initialization does not call a trivial default constructor, so
1670 // such a call is a core constant expression whether or not the
1671 // constructor is constexpr.
1672 if (!IsValueInitialization) {
1673 // FIXME: If DiagDecl is an implicitly-declared special member function,
1674 // we should be much more explicit about why it's not constexpr.
1675 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1676 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1677 Info.Note(CD->getLocation(), diag::note_declared_at);
1678 }
Richard Smith61802452011-12-22 02:22:31 +00001679 } else {
1680 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1681 }
1682 }
1683 return true;
1684}
1685
Richard Smithc1c5f272011-12-13 06:39:58 +00001686/// CheckConstexprFunction - Check that a function can be called in a constant
1687/// expression.
1688static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1689 const FunctionDecl *Declaration,
1690 const FunctionDecl *Definition) {
1691 // Can we evaluate this function call?
1692 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1693 return true;
1694
1695 if (Info.getLangOpts().CPlusPlus0x) {
1696 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001697 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1698 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001699 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1700 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1701 << DiagDecl;
1702 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1703 } else {
1704 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1705 }
1706 return false;
1707}
1708
Richard Smith180f4792011-11-10 06:34:14 +00001709namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001710typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001711}
1712
1713/// EvaluateArgs - Evaluate the arguments to a function call.
1714static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1715 EvalInfo &Info) {
1716 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1717 I != E; ++I)
1718 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1719 return false;
1720 return true;
1721}
1722
Richard Smithd0dccea2011-10-28 22:34:42 +00001723/// Evaluate a function call.
Richard Smith08d6e032011-12-16 19:06:07 +00001724static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1725 const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001726 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001727 EvalInfo &Info, APValue &Result) {
1728 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd0dccea2011-10-28 22:34:42 +00001729 return false;
1730
Richard Smith180f4792011-11-10 06:34:14 +00001731 ArgVector ArgValues(Args.size());
1732 if (!EvaluateArgs(Args, ArgValues, Info))
1733 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001734
Richard Smith08d6e032011-12-16 19:06:07 +00001735 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1736 ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001737 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1738}
1739
Richard Smith180f4792011-11-10 06:34:14 +00001740/// Evaluate a constructor call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001741static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001742 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001743 const CXXConstructorDecl *Definition,
Richard Smitheba05b22011-12-25 20:00:17 +00001744 EvalInfo &Info, APValue &Result) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001745 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith180f4792011-11-10 06:34:14 +00001746 return false;
1747
1748 ArgVector ArgValues(Args.size());
1749 if (!EvaluateArgs(Args, ArgValues, Info))
1750 return false;
1751
Richard Smith08d6e032011-12-16 19:06:07 +00001752 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1753 &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001754
1755 // If it's a delegating constructor, just delegate.
1756 if (Definition->isDelegatingConstructor()) {
1757 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1758 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1759 }
1760
1761 // Reserve space for the struct members.
1762 const CXXRecordDecl *RD = Definition->getParent();
Richard Smitheba05b22011-12-25 20:00:17 +00001763 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001764 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1765 std::distance(RD->field_begin(), RD->field_end()));
1766
1767 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1768
1769 unsigned BasesSeen = 0;
1770#ifndef NDEBUG
1771 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1772#endif
1773 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1774 E = Definition->init_end(); I != E; ++I) {
1775 if ((*I)->isBaseInitializer()) {
1776 QualType BaseType((*I)->getBaseClass(), 0);
1777#ifndef NDEBUG
1778 // Non-virtual base classes are initialized in the order in the class
1779 // definition. We cannot have a virtual base class for a literal type.
1780 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1781 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1782 "base class initializers not in expected order");
1783 ++BaseIt;
1784#endif
1785 LValue Subobject = This;
1786 HandleLValueDirectBase(Info, Subobject, RD,
1787 BaseType->getAsCXXRecordDecl(), &Layout);
1788 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1789 Subobject, (*I)->getInit()))
1790 return false;
1791 } else if (FieldDecl *FD = (*I)->getMember()) {
1792 LValue Subobject = This;
1793 HandleLValueMember(Info, Subobject, FD, &Layout);
1794 if (RD->isUnion()) {
1795 Result = APValue(FD);
Richard Smithc1c5f272011-12-13 06:39:58 +00001796 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1797 (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001798 return false;
1799 } else if (!EvaluateConstantExpression(
1800 Result.getStructField(FD->getFieldIndex()),
Richard Smithc1c5f272011-12-13 06:39:58 +00001801 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001802 return false;
1803 } else {
1804 // FIXME: handle indirect field initializers
Richard Smithdd1f29b2011-12-12 09:28:41 +00001805 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf48fdb02011-12-09 22:58:01 +00001806 diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001807 return false;
1808 }
1809 }
1810
1811 return true;
1812}
1813
Richard Smithd0dccea2011-10-28 22:34:42 +00001814namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001815class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001816 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001817 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001818public:
1819
Richard Smith1e12c592011-10-16 21:26:27 +00001820 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001821
1822 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001823 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001824 return true;
1825 }
1826
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001827 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1828 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001829 return Visit(E->getResultExpr());
1830 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001831 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001832 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001833 return true;
1834 return false;
1835 }
John McCallf85e1932011-06-15 23:02:42 +00001836 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001837 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001838 return true;
1839 return false;
1840 }
1841 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001842 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001843 return true;
1844 return false;
1845 }
1846
Mike Stumpc4c90452009-10-27 22:09:17 +00001847 // We don't want to evaluate BlockExprs multiple times, as they generate
1848 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001849 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1850 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1851 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001852 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001853 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1854 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1855 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1856 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1857 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1858 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001859 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001860 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001861 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001862 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001863 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001864 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1865 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1866 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1867 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001868 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001869 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1870 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1871 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1872 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1873 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001874 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001875 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001876 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001877 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001878 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001879
1880 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001881 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001882 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1883 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001884 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001885 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001886 return false;
1887 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001888
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001889 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001890};
1891
John McCall56ca35d2011-02-17 10:25:35 +00001892class OpaqueValueEvaluation {
1893 EvalInfo &info;
1894 OpaqueValueExpr *opaqueValue;
1895
1896public:
1897 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1898 Expr *value)
1899 : info(info), opaqueValue(opaqueValue) {
1900
1901 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00001902 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00001903 this->opaqueValue = 0;
1904 return;
1905 }
John McCall56ca35d2011-02-17 10:25:35 +00001906 }
1907
1908 bool hasError() const { return opaqueValue == 0; }
1909
1910 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00001911 // FIXME: This will not work for recursive constexpr functions using opaque
1912 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00001913 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1914 }
1915};
1916
Mike Stumpc4c90452009-10-27 22:09:17 +00001917} // end anonymous namespace
1918
Eli Friedman4efaa272008-11-12 09:44:48 +00001919//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001920// Generic Evaluation
1921//===----------------------------------------------------------------------===//
1922namespace {
1923
Richard Smithf48fdb02011-12-09 22:58:01 +00001924// FIXME: RetTy is always bool. Remove it.
1925template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001926class ExprEvaluatorBase
1927 : public ConstStmtVisitor<Derived, RetTy> {
1928private:
Richard Smith47a1eed2011-10-29 20:57:55 +00001929 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001930 return static_cast<Derived*>(this)->Success(V, E);
1931 }
Richard Smitheba05b22011-12-25 20:00:17 +00001932 RetTy DerivedZeroInitialization(const Expr *E) {
1933 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00001934 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001935
1936protected:
1937 EvalInfo &Info;
1938 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1939 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1940
Richard Smithdd1f29b2011-12-12 09:28:41 +00001941 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00001942 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001943 }
1944
1945 /// Report an evaluation error. This should only be called when an error is
1946 /// first discovered. When propagating an error, just return false.
1947 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001948 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001949 return false;
1950 }
1951 bool Error(const Expr *E) {
1952 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1953 }
1954
Richard Smitheba05b22011-12-25 20:00:17 +00001955 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00001956
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001957public:
1958 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1959
1960 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001961 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001962 }
1963 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001964 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001965 }
1966
1967 RetTy VisitParenExpr(const ParenExpr *E)
1968 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1969 RetTy VisitUnaryExtension(const UnaryOperator *E)
1970 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1971 RetTy VisitUnaryPlus(const UnaryOperator *E)
1972 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1973 RetTy VisitChooseExpr(const ChooseExpr *E)
1974 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1975 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1976 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00001977 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1978 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00001979 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1980 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00001981 // We cannot create any objects for which cleanups are required, so there is
1982 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1983 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1984 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001985
Richard Smithc216a012011-12-12 12:46:16 +00001986 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1987 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1988 return static_cast<Derived*>(this)->VisitCastExpr(E);
1989 }
1990 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1991 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1992 return static_cast<Derived*>(this)->VisitCastExpr(E);
1993 }
1994
Richard Smithe24f5fc2011-11-17 22:56:20 +00001995 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1996 switch (E->getOpcode()) {
1997 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00001998 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001999
2000 case BO_Comma:
2001 VisitIgnoredValue(E->getLHS());
2002 return StmtVisitorTy::Visit(E->getRHS());
2003
2004 case BO_PtrMemD:
2005 case BO_PtrMemI: {
2006 LValue Obj;
2007 if (!HandleMemberPointerAccess(Info, E, Obj))
2008 return false;
2009 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002010 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002011 return false;
2012 return DerivedSuccess(Result, E);
2013 }
2014 }
2015 }
2016
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002017 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2018 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2019 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002020 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002021
2022 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002023 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002024 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002025
2026 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2027 }
2028
2029 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2030 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002031 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002032 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002033
Richard Smithc49bd112011-10-28 17:51:58 +00002034 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002035 return StmtVisitorTy::Visit(EvalExpr);
2036 }
2037
2038 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002039 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002040 if (!Value) {
2041 const Expr *Source = E->getSourceExpr();
2042 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002043 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002044 if (Source == E) { // sanity checking.
2045 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002046 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002047 }
2048 return StmtVisitorTy::Visit(Source);
2049 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002050 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002051 }
Richard Smithf10d9172011-10-11 21:43:33 +00002052
Richard Smithd0dccea2011-10-28 22:34:42 +00002053 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002054 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002055 QualType CalleeType = Callee->getType();
2056
Richard Smithd0dccea2011-10-28 22:34:42 +00002057 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002058 LValue *This = 0, ThisVal;
2059 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002060
Richard Smith59efe262011-11-11 04:05:33 +00002061 // Extract function decl and 'this' pointer from the callee.
2062 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002063 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002064 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2065 // Explicit bound member calls, such as x.f() or p->g();
2066 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002067 return false;
2068 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002069 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002070 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2071 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002072 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2073 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002074 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002075 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002076 return Error(Callee);
2077
2078 FD = dyn_cast<FunctionDecl>(Member);
2079 if (!FD)
2080 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002081 } else if (CalleeType->isFunctionPointerType()) {
2082 CCValue Call;
Richard Smithf48fdb02011-12-09 22:58:01 +00002083 if (!Evaluate(Call, Info, Callee))
2084 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002085
Richard Smithf48fdb02011-12-09 22:58:01 +00002086 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
2087 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002088 FD = dyn_cast_or_null<FunctionDecl>(
2089 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002090 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002091 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002092
2093 // Overloaded operator calls to member functions are represented as normal
2094 // calls with '*this' as the first argument.
2095 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2096 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002097 // FIXME: When selecting an implicit conversion for an overloaded
2098 // operator delete, we sometimes try to evaluate calls to conversion
2099 // operators without a 'this' parameter!
2100 if (Args.empty())
2101 return Error(E);
2102
Richard Smith59efe262011-11-11 04:05:33 +00002103 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2104 return false;
2105 This = &ThisVal;
2106 Args = Args.slice(1);
2107 }
2108
2109 // Don't call function pointers which have been cast to some other type.
2110 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002111 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002112 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002113 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002114
Richard Smithc1c5f272011-12-13 06:39:58 +00002115 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002116 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002117 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002118
Richard Smithc1c5f272011-12-13 06:39:58 +00002119 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith08d6e032011-12-16 19:06:07 +00002120 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002121 return false;
2122
2123 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002124 }
2125
Richard Smithc49bd112011-10-28 17:51:58 +00002126 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2127 return StmtVisitorTy::Visit(E->getInitializer());
2128 }
Richard Smithf10d9172011-10-11 21:43:33 +00002129 RetTy VisitInitListExpr(const InitListExpr *E) {
2130 if (Info.getLangOpts().CPlusPlus0x) {
2131 if (E->getNumInits() == 0)
Richard Smitheba05b22011-12-25 20:00:17 +00002132 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002133 if (E->getNumInits() == 1)
2134 return StmtVisitorTy::Visit(E->getInit(0));
2135 }
Richard Smithf48fdb02011-12-09 22:58:01 +00002136 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002137 }
2138 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smitheba05b22011-12-25 20:00:17 +00002139 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002140 }
2141 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smitheba05b22011-12-25 20:00:17 +00002142 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002143 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002144 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smitheba05b22011-12-25 20:00:17 +00002145 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002146 }
Richard Smithf10d9172011-10-11 21:43:33 +00002147
Richard Smith180f4792011-11-10 06:34:14 +00002148 /// A member expression where the object is a prvalue is itself a prvalue.
2149 RetTy VisitMemberExpr(const MemberExpr *E) {
2150 assert(!E->isArrow() && "missing call to bound member function?");
2151
2152 CCValue Val;
2153 if (!Evaluate(Val, Info, E->getBase()))
2154 return false;
2155
2156 QualType BaseTy = E->getBase()->getType();
2157
2158 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002159 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002160 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2161 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2162 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2163
2164 SubobjectDesignator Designator;
2165 Designator.addDecl(FD);
2166
Richard Smithf48fdb02011-12-09 22:58:01 +00002167 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002168 DerivedSuccess(Val, E);
2169 }
2170
Richard Smithc49bd112011-10-28 17:51:58 +00002171 RetTy VisitCastExpr(const CastExpr *E) {
2172 switch (E->getCastKind()) {
2173 default:
2174 break;
2175
2176 case CK_NoOp:
2177 return StmtVisitorTy::Visit(E->getSubExpr());
2178
2179 case CK_LValueToRValue: {
2180 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002181 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2182 return false;
2183 CCValue RVal;
2184 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2185 return false;
2186 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002187 }
2188 }
2189
Richard Smithf48fdb02011-12-09 22:58:01 +00002190 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002191 }
2192
Richard Smith8327fad2011-10-24 18:44:57 +00002193 /// Visit a value which is evaluated, but whose value is ignored.
2194 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002195 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002196 if (!Evaluate(Scratch, Info, E))
2197 Info.EvalStatus.HasSideEffects = true;
2198 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002199};
2200
2201}
2202
2203//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002204// Common base class for lvalue and temporary evaluation.
2205//===----------------------------------------------------------------------===//
2206namespace {
2207template<class Derived>
2208class LValueExprEvaluatorBase
2209 : public ExprEvaluatorBase<Derived, bool> {
2210protected:
2211 LValue &Result;
2212 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2213 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2214
2215 bool Success(APValue::LValueBase B) {
2216 Result.set(B);
2217 return true;
2218 }
2219
2220public:
2221 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2222 ExprEvaluatorBaseTy(Info), Result(Result) {}
2223
2224 bool Success(const CCValue &V, const Expr *E) {
2225 Result.setFrom(V);
2226 return true;
2227 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002228
2229 bool CheckValidLValue() {
2230 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2231 // there are no null references, nor once-past-the-end references.
2232 // FIXME: Check for one-past-the-end array indices
2233 return Result.Base && !Result.Designator.Invalid &&
2234 !Result.Designator.OnePastTheEnd;
2235 }
2236
2237 bool VisitMemberExpr(const MemberExpr *E) {
2238 // Handle non-static data members.
2239 QualType BaseTy;
2240 if (E->isArrow()) {
2241 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2242 return false;
2243 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002244 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002245 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002246 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2247 return false;
2248 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002249 } else {
2250 if (!this->Visit(E->getBase()))
2251 return false;
2252 BaseTy = E->getBase()->getType();
2253 }
2254 // FIXME: In C++11, require the result to be a valid lvalue.
2255
2256 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2257 // FIXME: Handle IndirectFieldDecls
Richard Smithf48fdb02011-12-09 22:58:01 +00002258 if (!FD) return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002259 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2260 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2261 (void)BaseTy;
2262
2263 HandleLValueMember(this->Info, Result, FD);
2264
2265 if (FD->getType()->isReferenceType()) {
2266 CCValue RefValue;
Richard Smithf48fdb02011-12-09 22:58:01 +00002267 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002268 RefValue))
2269 return false;
2270 return Success(RefValue, E);
2271 }
2272 return true;
2273 }
2274
2275 bool VisitBinaryOperator(const BinaryOperator *E) {
2276 switch (E->getOpcode()) {
2277 default:
2278 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2279
2280 case BO_PtrMemD:
2281 case BO_PtrMemI:
2282 return HandleMemberPointerAccess(this->Info, E, Result);
2283 }
2284 }
2285
2286 bool VisitCastExpr(const CastExpr *E) {
2287 switch (E->getCastKind()) {
2288 default:
2289 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2290
2291 case CK_DerivedToBase:
2292 case CK_UncheckedDerivedToBase: {
2293 if (!this->Visit(E->getSubExpr()))
2294 return false;
2295 if (!CheckValidLValue())
2296 return false;
2297
2298 // Now figure out the necessary offset to add to the base LV to get from
2299 // the derived class to the base class.
2300 QualType Type = E->getSubExpr()->getType();
2301
2302 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2303 PathE = E->path_end(); PathI != PathE; ++PathI) {
2304 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2305 *PathI))
2306 return false;
2307 Type = (*PathI)->getType();
2308 }
2309
2310 return true;
2311 }
2312 }
2313 }
2314};
2315}
2316
2317//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002318// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002319//
2320// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2321// function designators (in C), decl references to void objects (in C), and
2322// temporaries (if building with -Wno-address-of-temporary).
2323//
2324// LValue evaluation produces values comprising a base expression of one of the
2325// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002326// - Declarations
2327// * VarDecl
2328// * FunctionDecl
2329// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002330// * CompoundLiteralExpr in C
2331// * StringLiteral
2332// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002333// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002334// * ObjCEncodeExpr
2335// * AddrLabelExpr
2336// * BlockExpr
2337// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002338// - Locals and temporaries
2339// * Any Expr, with a Frame indicating the function in which the temporary was
2340// evaluated.
2341// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002342//===----------------------------------------------------------------------===//
2343namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002344class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002345 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002346public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002347 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2348 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Richard Smithc49bd112011-10-28 17:51:58 +00002350 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2351
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002352 bool VisitDeclRefExpr(const DeclRefExpr *E);
2353 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002354 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002355 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2356 bool VisitMemberExpr(const MemberExpr *E);
2357 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2358 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2359 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2360 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002361
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002362 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002363 switch (E->getCastKind()) {
2364 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002365 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002366
Eli Friedmandb924222011-10-11 00:13:24 +00002367 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002368 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002369 if (!Visit(E->getSubExpr()))
2370 return false;
2371 Result.Designator.setInvalid();
2372 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002373
Richard Smithe24f5fc2011-11-17 22:56:20 +00002374 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002375 if (!Visit(E->getSubExpr()))
2376 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002377 if (!CheckValidLValue())
2378 return false;
2379 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002380 }
2381 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002382
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002383 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002384
Eli Friedman4efaa272008-11-12 09:44:48 +00002385};
2386} // end anonymous namespace
2387
Richard Smithc49bd112011-10-28 17:51:58 +00002388/// Evaluate an expression as an lvalue. This can be legitimately called on
2389/// expressions which are not glvalues, in a few cases:
2390/// * function designators in C,
2391/// * "extern void" objects,
2392/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002393static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002394 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2395 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2396 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002397 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002398}
2399
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002400bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002401 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2402 return Success(FD);
2403 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002404 return VisitVarDecl(E, VD);
2405 return Error(E);
2406}
Richard Smith436c8892011-10-24 23:14:33 +00002407
Richard Smithc49bd112011-10-28 17:51:58 +00002408bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002409 if (!VD->getType()->isReferenceType()) {
2410 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002411 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002412 return true;
2413 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002414 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002415 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002416
Richard Smith47a1eed2011-10-29 20:57:55 +00002417 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002418 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2419 return false;
2420 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002421}
2422
Richard Smithbd552ef2011-10-31 05:52:43 +00002423bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2424 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002425 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002426 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002427 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2428
2429 Result.set(E, Info.CurrentCall);
2430 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2431 Result, E->GetTemporaryExpr());
2432 }
2433
2434 // Materialization of an lvalue temporary occurs when we need to force a copy
2435 // (for instance, if it's a bitfield).
2436 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2437 if (!Visit(E->GetTemporaryExpr()))
2438 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002439 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002440 Info.CurrentCall->Temporaries[E]))
2441 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002442 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002443 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002444}
2445
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002446bool
2447LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002448 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2449 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2450 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002451 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002452}
2453
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002454bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002455 // Handle static data members.
2456 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2457 VisitIgnoredValue(E->getBase());
2458 return VisitVarDecl(E, VD);
2459 }
2460
Richard Smithd0dccea2011-10-28 22:34:42 +00002461 // Handle static member functions.
2462 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2463 if (MD->isStatic()) {
2464 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002465 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002466 }
2467 }
2468
Richard Smith180f4792011-11-10 06:34:14 +00002469 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002470 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002471}
2472
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002473bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002474 // FIXME: Deal with vectors as array subscript bases.
2475 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002476 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002477
Anders Carlsson3068d112008-11-16 19:01:22 +00002478 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002479 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002480
Anders Carlsson3068d112008-11-16 19:01:22 +00002481 APSInt Index;
2482 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002483 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002484 int64_t IndexValue
2485 = Index.isSigned() ? Index.getSExtValue()
2486 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002487
Richard Smithe24f5fc2011-11-17 22:56:20 +00002488 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002489 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002490}
Eli Friedman4efaa272008-11-12 09:44:48 +00002491
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002492bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002493 // FIXME: In C++11, require the result to be a valid lvalue.
John McCallefdb83e2010-05-07 21:00:08 +00002494 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002495}
2496
Eli Friedman4efaa272008-11-12 09:44:48 +00002497//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002498// Pointer Evaluation
2499//===----------------------------------------------------------------------===//
2500
Anders Carlssonc754aa62008-07-08 05:13:58 +00002501namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002502class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002503 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002504 LValue &Result;
2505
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002506 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002507 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002508 return true;
2509 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002510public:
Mike Stump1eb44332009-09-09 15:08:12 +00002511
John McCallefdb83e2010-05-07 21:00:08 +00002512 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002513 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002514
Richard Smith47a1eed2011-10-29 20:57:55 +00002515 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002516 Result.setFrom(V);
2517 return true;
2518 }
Richard Smitheba05b22011-12-25 20:00:17 +00002519 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002520 return Success((Expr*)0);
2521 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002522
John McCallefdb83e2010-05-07 21:00:08 +00002523 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002524 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002525 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002526 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002527 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002528 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002529 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002530 bool VisitCallExpr(const CallExpr *E);
2531 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002532 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002533 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002534 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002535 }
Richard Smith180f4792011-11-10 06:34:14 +00002536 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2537 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002538 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002539 Result = *Info.CurrentCall->This;
2540 return true;
2541 }
John McCall56ca35d2011-02-17 10:25:35 +00002542
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002543 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002544};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002545} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002546
John McCallefdb83e2010-05-07 21:00:08 +00002547static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002548 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002549 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002550}
2551
John McCallefdb83e2010-05-07 21:00:08 +00002552bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002553 if (E->getOpcode() != BO_Add &&
2554 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002555 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002556
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002557 const Expr *PExp = E->getLHS();
2558 const Expr *IExp = E->getRHS();
2559 if (IExp->getType()->isPointerType())
2560 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002561
John McCallefdb83e2010-05-07 21:00:08 +00002562 if (!EvaluatePointer(PExp, Result, Info))
2563 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002564
John McCallefdb83e2010-05-07 21:00:08 +00002565 llvm::APSInt Offset;
2566 if (!EvaluateInteger(IExp, Offset, Info))
2567 return false;
2568 int64_t AdditionalOffset
2569 = Offset.isSigned() ? Offset.getSExtValue()
2570 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002571 if (E->getOpcode() == BO_Sub)
2572 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002573
Richard Smith180f4792011-11-10 06:34:14 +00002574 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002575 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002576 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002577}
Eli Friedman4efaa272008-11-12 09:44:48 +00002578
John McCallefdb83e2010-05-07 21:00:08 +00002579bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2580 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002581}
Mike Stump1eb44332009-09-09 15:08:12 +00002582
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002583bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2584 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002585
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002586 switch (E->getCastKind()) {
2587 default:
2588 break;
2589
John McCall2de56d12010-08-25 11:45:40 +00002590 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002591 case CK_CPointerToObjCPointerCast:
2592 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002593 case CK_AnyPointerToBlockPointerCast:
Richard Smithc216a012011-12-12 12:46:16 +00002594 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2595 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2596 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002597 if (!E->getType()->isVoidPointerType()) {
2598 if (SubExpr->getType()->isVoidPointerType())
2599 CCEDiag(E, diag::note_constexpr_invalid_cast)
2600 << 3 << SubExpr->getType();
2601 else
2602 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2603 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002604 if (!Visit(SubExpr))
2605 return false;
2606 Result.Designator.setInvalid();
2607 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002608
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002609 case CK_DerivedToBase:
2610 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002611 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002612 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002613 if (!Result.Base && Result.Offset.isZero())
2614 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002615
Richard Smith180f4792011-11-10 06:34:14 +00002616 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002617 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002618 QualType Type =
2619 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002620
Richard Smith180f4792011-11-10 06:34:14 +00002621 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002622 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smith180f4792011-11-10 06:34:14 +00002623 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002624 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002625 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002626 }
2627
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002628 return true;
2629 }
2630
Richard Smithe24f5fc2011-11-17 22:56:20 +00002631 case CK_BaseToDerived:
2632 if (!Visit(E->getSubExpr()))
2633 return false;
2634 if (!Result.Base && Result.Offset.isZero())
2635 return true;
2636 return HandleBaseToDerivedCast(Info, E, Result);
2637
Richard Smith47a1eed2011-10-29 20:57:55 +00002638 case CK_NullToPointer:
Richard Smitheba05b22011-12-25 20:00:17 +00002639 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002640
John McCall2de56d12010-08-25 11:45:40 +00002641 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002642 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2643
Richard Smith47a1eed2011-10-29 20:57:55 +00002644 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002645 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002646 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002647
John McCallefdb83e2010-05-07 21:00:08 +00002648 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002649 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2650 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002651 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002652 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002653 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002654 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002655 return true;
2656 } else {
2657 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002658 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002659 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002660 }
2661 }
John McCall2de56d12010-08-25 11:45:40 +00002662 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002663 if (SubExpr->isGLValue()) {
2664 if (!EvaluateLValue(SubExpr, Result, Info))
2665 return false;
2666 } else {
2667 Result.set(SubExpr, Info.CurrentCall);
2668 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2669 Info, Result, SubExpr))
2670 return false;
2671 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002672 // The result is a pointer to the first element of the array.
2673 Result.Designator.addIndex(0);
2674 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002675
John McCall2de56d12010-08-25 11:45:40 +00002676 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002677 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002678 }
2679
Richard Smithc49bd112011-10-28 17:51:58 +00002680 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002681}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002682
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002683bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002684 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002685 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002686
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002687 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002688}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002689
2690//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002691// Member Pointer Evaluation
2692//===----------------------------------------------------------------------===//
2693
2694namespace {
2695class MemberPointerExprEvaluator
2696 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2697 MemberPtr &Result;
2698
2699 bool Success(const ValueDecl *D) {
2700 Result = MemberPtr(D);
2701 return true;
2702 }
2703public:
2704
2705 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2706 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2707
2708 bool Success(const CCValue &V, const Expr *E) {
2709 Result.setFrom(V);
2710 return true;
2711 }
Richard Smitheba05b22011-12-25 20:00:17 +00002712 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002713 return Success((const ValueDecl*)0);
2714 }
2715
2716 bool VisitCastExpr(const CastExpr *E);
2717 bool VisitUnaryAddrOf(const UnaryOperator *E);
2718};
2719} // end anonymous namespace
2720
2721static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2722 EvalInfo &Info) {
2723 assert(E->isRValue() && E->getType()->isMemberPointerType());
2724 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2725}
2726
2727bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2728 switch (E->getCastKind()) {
2729 default:
2730 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2731
2732 case CK_NullToMemberPointer:
Richard Smitheba05b22011-12-25 20:00:17 +00002733 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002734
2735 case CK_BaseToDerivedMemberPointer: {
2736 if (!Visit(E->getSubExpr()))
2737 return false;
2738 if (E->path_empty())
2739 return true;
2740 // Base-to-derived member pointer casts store the path in derived-to-base
2741 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2742 // the wrong end of the derived->base arc, so stagger the path by one class.
2743 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2744 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2745 PathI != PathE; ++PathI) {
2746 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2747 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2748 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002749 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002750 }
2751 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2752 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002753 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002754 return true;
2755 }
2756
2757 case CK_DerivedToBaseMemberPointer:
2758 if (!Visit(E->getSubExpr()))
2759 return false;
2760 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2761 PathE = E->path_end(); PathI != PathE; ++PathI) {
2762 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2763 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2764 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002765 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002766 }
2767 return true;
2768 }
2769}
2770
2771bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2772 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2773 // member can be formed.
2774 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2775}
2776
2777//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002778// Record Evaluation
2779//===----------------------------------------------------------------------===//
2780
2781namespace {
2782 class RecordExprEvaluator
2783 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2784 const LValue &This;
2785 APValue &Result;
2786 public:
2787
2788 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2789 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2790
2791 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002792 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002793 }
Richard Smitheba05b22011-12-25 20:00:17 +00002794 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002795
Richard Smith59efe262011-11-11 04:05:33 +00002796 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002797 bool VisitInitListExpr(const InitListExpr *E);
2798 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2799 };
2800}
2801
Richard Smitheba05b22011-12-25 20:00:17 +00002802/// Perform zero-initialization on an object of non-union class type.
2803/// C++11 [dcl.init]p5:
2804/// To zero-initialize an object or reference of type T means:
2805/// [...]
2806/// -- if T is a (possibly cv-qualified) non-union class type,
2807/// each non-static data member and each base-class subobject is
2808/// zero-initialized
2809static bool HandleClassZeroInitialization(EvalInfo &Info, const RecordDecl *RD,
2810 const LValue &This, APValue &Result) {
2811 assert(!RD->isUnion() && "Expected non-union class type");
2812 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2813 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2814 std::distance(RD->field_begin(), RD->field_end()));
2815
2816 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2817
2818 if (CD) {
2819 unsigned Index = 0;
2820 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
2821 E = CD->bases_end(); I != E; ++I, ++Index) {
2822 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2823 LValue Subobject = This;
2824 HandleLValueDirectBase(Info, Subobject, CD, Base, &Layout);
2825 if (!HandleClassZeroInitialization(Info, Base, Subobject,
2826 Result.getStructBase(Index)))
2827 return false;
2828 }
2829 }
2830
2831 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2832 I != E; ++I) {
2833 // -- if T is a reference type, no initialization is performed.
2834 if ((*I)->getType()->isReferenceType())
2835 continue;
2836
2837 LValue Subobject = This;
2838 HandleLValueMember(Info, Subobject, *I, &Layout);
2839
2840 ImplicitValueInitExpr VIE((*I)->getType());
2841 if (!EvaluateConstantExpression(
2842 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2843 return false;
2844 }
2845
2846 return true;
2847}
2848
2849bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2850 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2851 if (RD->isUnion()) {
2852 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2853 // object's first non-static named data member is zero-initialized
2854 RecordDecl::field_iterator I = RD->field_begin();
2855 if (I == RD->field_end()) {
2856 Result = APValue((const FieldDecl*)0);
2857 return true;
2858 }
2859
2860 LValue Subobject = This;
2861 HandleLValueMember(Info, Subobject, *I);
2862 Result = APValue(*I);
2863 ImplicitValueInitExpr VIE((*I)->getType());
2864 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2865 Subobject, &VIE);
2866 }
2867
2868 return HandleClassZeroInitialization(Info, RD, This, Result);
2869}
2870
Richard Smith59efe262011-11-11 04:05:33 +00002871bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2872 switch (E->getCastKind()) {
2873 default:
2874 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2875
2876 case CK_ConstructorConversion:
2877 return Visit(E->getSubExpr());
2878
2879 case CK_DerivedToBase:
2880 case CK_UncheckedDerivedToBase: {
2881 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00002882 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00002883 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002884 if (!DerivedObject.isStruct())
2885 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00002886
2887 // Derived-to-base rvalue conversion: just slice off the derived part.
2888 APValue *Value = &DerivedObject;
2889 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2890 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2891 PathE = E->path_end(); PathI != PathE; ++PathI) {
2892 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2893 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2894 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2895 RD = Base;
2896 }
2897 Result = *Value;
2898 return true;
2899 }
2900 }
2901}
2902
Richard Smith180f4792011-11-10 06:34:14 +00002903bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2904 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2905 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2906
2907 if (RD->isUnion()) {
2908 Result = APValue(E->getInitializedFieldInUnion());
2909 if (!E->getNumInits())
2910 return true;
2911 LValue Subobject = This;
2912 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2913 &Layout);
2914 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2915 Subobject, E->getInit(0));
2916 }
2917
2918 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2919 "initializer list for class with base classes");
2920 Result = APValue(APValue::UninitStruct(), 0,
2921 std::distance(RD->field_begin(), RD->field_end()));
2922 unsigned ElementNo = 0;
2923 for (RecordDecl::field_iterator Field = RD->field_begin(),
2924 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2925 // Anonymous bit-fields are not considered members of the class for
2926 // purposes of aggregate initialization.
2927 if (Field->isUnnamedBitfield())
2928 continue;
2929
2930 LValue Subobject = This;
2931 HandleLValueMember(Info, Subobject, *Field, &Layout);
2932
2933 if (ElementNo < E->getNumInits()) {
2934 if (!EvaluateConstantExpression(
2935 Result.getStructField((*Field)->getFieldIndex()),
2936 Info, Subobject, E->getInit(ElementNo++)))
2937 return false;
2938 } else {
2939 // Perform an implicit value-initialization for members beyond the end of
2940 // the initializer list.
2941 ImplicitValueInitExpr VIE(Field->getType());
2942 if (!EvaluateConstantExpression(
2943 Result.getStructField((*Field)->getFieldIndex()),
2944 Info, Subobject, &VIE))
2945 return false;
2946 }
2947 }
2948
2949 return true;
2950}
2951
2952bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2953 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smitheba05b22011-12-25 20:00:17 +00002954 bool ZeroInit = E->requiresZeroInitialization();
2955 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
2956 if (ZeroInit)
2957 return ZeroInitialization(E);
2958
Richard Smith61802452011-12-22 02:22:31 +00002959 const CXXRecordDecl *RD = FD->getParent();
2960 if (RD->isUnion())
2961 Result = APValue((FieldDecl*)0);
2962 else
2963 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2964 std::distance(RD->field_begin(), RD->field_end()));
2965 return true;
2966 }
2967
Richard Smith180f4792011-11-10 06:34:14 +00002968 const FunctionDecl *Definition = 0;
2969 FD->getBody(Definition);
2970
Richard Smithc1c5f272011-12-13 06:39:58 +00002971 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2972 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002973
2974 // FIXME: Elide the copy/move construction wherever we can.
Richard Smitheba05b22011-12-25 20:00:17 +00002975 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00002976 if (const MaterializeTemporaryExpr *ME
2977 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2978 return Visit(ME->GetTemporaryExpr());
2979
Richard Smitheba05b22011-12-25 20:00:17 +00002980 if (ZeroInit && !ZeroInitialization(E))
2981 return false;
2982
Richard Smith180f4792011-11-10 06:34:14 +00002983 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00002984 return HandleConstructorCall(E, This, Args,
2985 cast<CXXConstructorDecl>(Definition), Info,
2986 Result);
Richard Smith180f4792011-11-10 06:34:14 +00002987}
2988
2989static bool EvaluateRecord(const Expr *E, const LValue &This,
2990 APValue &Result, EvalInfo &Info) {
2991 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00002992 "can't evaluate expression as a record rvalue");
2993 return RecordExprEvaluator(Info, This, Result).Visit(E);
2994}
2995
2996//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002997// Temporary Evaluation
2998//
2999// Temporaries are represented in the AST as rvalues, but generally behave like
3000// lvalues. The full-object of which the temporary is a subobject is implicitly
3001// materialized so that a reference can bind to it.
3002//===----------------------------------------------------------------------===//
3003namespace {
3004class TemporaryExprEvaluator
3005 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3006public:
3007 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3008 LValueExprEvaluatorBaseTy(Info, Result) {}
3009
3010 /// Visit an expression which constructs the value of this temporary.
3011 bool VisitConstructExpr(const Expr *E) {
3012 Result.set(E, Info.CurrentCall);
3013 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3014 Result, E);
3015 }
3016
3017 bool VisitCastExpr(const CastExpr *E) {
3018 switch (E->getCastKind()) {
3019 default:
3020 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3021
3022 case CK_ConstructorConversion:
3023 return VisitConstructExpr(E->getSubExpr());
3024 }
3025 }
3026 bool VisitInitListExpr(const InitListExpr *E) {
3027 return VisitConstructExpr(E);
3028 }
3029 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3030 return VisitConstructExpr(E);
3031 }
3032 bool VisitCallExpr(const CallExpr *E) {
3033 return VisitConstructExpr(E);
3034 }
3035};
3036} // end anonymous namespace
3037
3038/// Evaluate an expression of record type as a temporary.
3039static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003040 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003041 return TemporaryExprEvaluator(Info, Result).Visit(E);
3042}
3043
3044//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003045// Vector Evaluation
3046//===----------------------------------------------------------------------===//
3047
3048namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003049 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003050 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3051 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003052 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003053
Richard Smith07fc6572011-10-22 21:10:00 +00003054 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3055 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Richard Smith07fc6572011-10-22 21:10:00 +00003057 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3058 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3059 // FIXME: remove this APValue copy.
3060 Result = APValue(V.data(), V.size());
3061 return true;
3062 }
Richard Smith69c2c502011-11-04 05:33:44 +00003063 bool Success(const CCValue &V, const Expr *E) {
3064 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003065 Result = V;
3066 return true;
3067 }
Richard Smitheba05b22011-12-25 20:00:17 +00003068 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003069
Richard Smith07fc6572011-10-22 21:10:00 +00003070 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003071 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003072 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003073 bool VisitInitListExpr(const InitListExpr *E);
3074 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003075 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003076 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003077 // shufflevector, ExtVectorElementExpr
3078 // (Note that these require implementing conversions
3079 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00003080 };
3081} // end anonymous namespace
3082
3083static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003084 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003085 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003086}
3087
Richard Smith07fc6572011-10-22 21:10:00 +00003088bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3089 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003090 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003091
Richard Smithd62ca372011-12-06 22:44:34 +00003092 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003093 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003094
Eli Friedman46a52322011-03-25 00:43:55 +00003095 switch (E->getCastKind()) {
3096 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003097 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003098 if (SETy->isIntegerType()) {
3099 APSInt IntResult;
3100 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003101 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003102 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003103 } else if (SETy->isRealFloatingType()) {
3104 APFloat F(0.0);
3105 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003106 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003107 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003108 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003109 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003110 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003111
3112 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003113 SmallVector<APValue, 4> Elts(NElts, Val);
3114 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003115 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003116 case CK_BitCast: {
3117 // Evaluate the operand into an APInt we can extract from.
3118 llvm::APInt SValInt;
3119 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3120 return false;
3121 // Extract the elements
3122 QualType EltTy = VTy->getElementType();
3123 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3124 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3125 SmallVector<APValue, 4> Elts;
3126 if (EltTy->isRealFloatingType()) {
3127 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3128 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3129 unsigned FloatEltSize = EltSize;
3130 if (&Sem == &APFloat::x87DoubleExtended)
3131 FloatEltSize = 80;
3132 for (unsigned i = 0; i < NElts; i++) {
3133 llvm::APInt Elt;
3134 if (BigEndian)
3135 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3136 else
3137 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3138 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3139 }
3140 } else if (EltTy->isIntegerType()) {
3141 for (unsigned i = 0; i < NElts; i++) {
3142 llvm::APInt Elt;
3143 if (BigEndian)
3144 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3145 else
3146 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3147 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3148 }
3149 } else {
3150 return Error(E);
3151 }
3152 return Success(Elts, E);
3153 }
Eli Friedman46a52322011-03-25 00:43:55 +00003154 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003155 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003156 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003157}
3158
Richard Smith07fc6572011-10-22 21:10:00 +00003159bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003160VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003161 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003162 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003163 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003164
Nate Begeman59b5da62009-01-18 03:20:47 +00003165 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003166 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003167
John McCalla7d6c222010-06-11 17:54:15 +00003168 // If a vector is initialized with a single element, that value
3169 // becomes every element of the vector, not just the first.
3170 // This is the behavior described in the IBM AltiVec documentation.
3171 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00003172
3173 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00003174 // vector (OpenCL 6.1.6).
3175 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00003176 return Visit(E->getInit(0));
3177
John McCalla7d6c222010-06-11 17:54:15 +00003178 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00003179 if (EltTy->isIntegerType()) {
3180 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00003181 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003182 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003183 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00003184 } else {
3185 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00003186 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003187 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003188 InitValue = APValue(f);
3189 }
3190 for (unsigned i = 0; i < NumElements; i++) {
3191 Elements.push_back(InitValue);
3192 }
3193 } else {
3194 for (unsigned i = 0; i < NumElements; i++) {
3195 if (EltTy->isIntegerType()) {
3196 llvm::APSInt sInt(32);
3197 if (i < NumInits) {
3198 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003199 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003200 } else {
3201 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3202 }
3203 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00003204 } else {
John McCalla7d6c222010-06-11 17:54:15 +00003205 llvm::APFloat f(0.0);
3206 if (i < NumInits) {
3207 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003208 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003209 } else {
3210 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3211 }
3212 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00003213 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003214 }
3215 }
Richard Smith07fc6572011-10-22 21:10:00 +00003216 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003217}
3218
Richard Smith07fc6572011-10-22 21:10:00 +00003219bool
Richard Smitheba05b22011-12-25 20:00:17 +00003220VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003221 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003222 QualType EltTy = VT->getElementType();
3223 APValue ZeroElement;
3224 if (EltTy->isIntegerType())
3225 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3226 else
3227 ZeroElement =
3228 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3229
Chris Lattner5f9e2722011-07-23 10:55:15 +00003230 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003231 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003232}
3233
Richard Smith07fc6572011-10-22 21:10:00 +00003234bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003235 VisitIgnoredValue(E->getSubExpr());
Richard Smitheba05b22011-12-25 20:00:17 +00003236 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003237}
3238
Nate Begeman59b5da62009-01-18 03:20:47 +00003239//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003240// Array Evaluation
3241//===----------------------------------------------------------------------===//
3242
3243namespace {
3244 class ArrayExprEvaluator
3245 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003246 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003247 APValue &Result;
3248 public:
3249
Richard Smith180f4792011-11-10 06:34:14 +00003250 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3251 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003252
3253 bool Success(const APValue &V, const Expr *E) {
3254 assert(V.isArray() && "Expected array type");
3255 Result = V;
3256 return true;
3257 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003258
Richard Smitheba05b22011-12-25 20:00:17 +00003259 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003260 const ConstantArrayType *CAT =
3261 Info.Ctx.getAsConstantArrayType(E->getType());
3262 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003263 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003264
3265 Result = APValue(APValue::UninitArray(), 0,
3266 CAT->getSize().getZExtValue());
3267 if (!Result.hasArrayFiller()) return true;
3268
Richard Smitheba05b22011-12-25 20:00:17 +00003269 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003270 LValue Subobject = This;
3271 Subobject.Designator.addIndex(0);
3272 ImplicitValueInitExpr VIE(CAT->getElementType());
3273 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3274 Subobject, &VIE);
3275 }
3276
Richard Smithcc5d4f62011-11-07 09:22:26 +00003277 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003278 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003279 };
3280} // end anonymous namespace
3281
Richard Smith180f4792011-11-10 06:34:14 +00003282static bool EvaluateArray(const Expr *E, const LValue &This,
3283 APValue &Result, EvalInfo &Info) {
Richard Smitheba05b22011-12-25 20:00:17 +00003284 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003285 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003286}
3287
3288bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3289 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3290 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003291 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003292
Richard Smith974c5f92011-12-22 01:07:19 +00003293 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3294 // an appropriately-typed string literal enclosed in braces.
3295 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3296 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3297 LValue LV;
3298 if (!EvaluateLValue(E->getInit(0), LV, Info))
3299 return false;
3300 uint64_t NumElements = CAT->getSize().getZExtValue();
3301 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3302
3303 // Copy the string literal into the array. FIXME: Do this better.
3304 LV.Designator.addIndex(0);
3305 for (uint64_t I = 0; I < NumElements; ++I) {
3306 CCValue Char;
3307 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3308 CAT->getElementType(), LV, Char))
3309 return false;
3310 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3311 Result.getArrayInitializedElt(I)))
3312 return false;
3313 if (!HandleLValueArrayAdjustment(Info, LV, CAT->getElementType(), 1))
3314 return false;
3315 }
3316 return true;
3317 }
3318
Richard Smithcc5d4f62011-11-07 09:22:26 +00003319 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3320 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003321 LValue Subobject = This;
3322 Subobject.Designator.addIndex(0);
3323 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003324 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003325 I != End; ++I, ++Index) {
3326 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3327 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003328 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003329 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3330 return false;
3331 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003332
3333 if (!Result.hasArrayFiller()) return true;
3334 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003335 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3336 // but sometimes does:
3337 // struct S { constexpr S() : p(&p) {} void *p; };
3338 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003339 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00003340 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00003341}
3342
Richard Smithe24f5fc2011-11-17 22:56:20 +00003343bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3344 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3345 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003346 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003347
3348 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3349 if (!Result.hasArrayFiller())
3350 return true;
3351
3352 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003353
Richard Smitheba05b22011-12-25 20:00:17 +00003354 bool ZeroInit = E->requiresZeroInitialization();
3355 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3356 if (ZeroInit) {
3357 LValue Subobject = This;
3358 Subobject.Designator.addIndex(0);
3359 ImplicitValueInitExpr VIE(CAT->getElementType());
3360 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3361 Subobject, &VIE);
3362 }
3363
Richard Smith61802452011-12-22 02:22:31 +00003364 const CXXRecordDecl *RD = FD->getParent();
3365 if (RD->isUnion())
3366 Result.getArrayFiller() = APValue((FieldDecl*)0);
3367 else
3368 Result.getArrayFiller() =
3369 APValue(APValue::UninitStruct(), RD->getNumBases(),
3370 std::distance(RD->field_begin(), RD->field_end()));
3371 return true;
3372 }
3373
Richard Smithe24f5fc2011-11-17 22:56:20 +00003374 const FunctionDecl *Definition = 0;
3375 FD->getBody(Definition);
3376
Richard Smithc1c5f272011-12-13 06:39:58 +00003377 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3378 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003379
3380 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3381 // but sometimes does:
3382 // struct S { constexpr S() : p(&p) {} void *p; };
3383 // S s[10];
3384 LValue Subobject = This;
3385 Subobject.Designator.addIndex(0);
Richard Smitheba05b22011-12-25 20:00:17 +00003386
3387 if (ZeroInit) {
3388 ImplicitValueInitExpr VIE(CAT->getElementType());
3389 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3390 &VIE))
3391 return false;
3392 }
3393
Richard Smithe24f5fc2011-11-17 22:56:20 +00003394 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003395 return HandleConstructorCall(E, Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003396 cast<CXXConstructorDecl>(Definition),
3397 Info, Result.getArrayFiller());
3398}
3399
Richard Smithcc5d4f62011-11-07 09:22:26 +00003400//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003401// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003402//
3403// As a GNU extension, we support casting pointers to sufficiently-wide integer
3404// types and back in constant folding. Integer values are thus represented
3405// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003406//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003407
3408namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003409class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003410 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003411 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003412public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003413 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003414 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003415
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003416 bool Success(const llvm::APSInt &SI, const Expr *E) {
3417 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003418 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003419 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003420 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003421 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003422 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003423 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003424 return true;
3425 }
3426
Daniel Dunbar131eb432009-02-19 09:06:44 +00003427 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003428 assert(E->getType()->isIntegralOrEnumerationType() &&
3429 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003430 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003431 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003432 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003433 Result.getInt().setIsUnsigned(
3434 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003435 return true;
3436 }
3437
3438 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003439 assert(E->getType()->isIntegralOrEnumerationType() &&
3440 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003441 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003442 return true;
3443 }
3444
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003445 bool Success(CharUnits Size, const Expr *E) {
3446 return Success(Size.getQuantity(), E);
3447 }
3448
Richard Smith47a1eed2011-10-29 20:57:55 +00003449 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00003450 if (V.isLValue()) {
3451 Result = V;
3452 return true;
3453 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003454 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003455 }
Mike Stump1eb44332009-09-09 15:08:12 +00003456
Richard Smitheba05b22011-12-25 20:00:17 +00003457 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003458
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003459 //===--------------------------------------------------------------------===//
3460 // Visitor Methods
3461 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003462
Chris Lattner4c4867e2008-07-12 00:38:25 +00003463 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003464 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003465 }
3466 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003467 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003468 }
Eli Friedman04309752009-11-24 05:28:59 +00003469
3470 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3471 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003472 if (CheckReferencedDecl(E, E->getDecl()))
3473 return true;
3474
3475 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003476 }
3477 bool VisitMemberExpr(const MemberExpr *E) {
3478 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003479 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003480 return true;
3481 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003482
3483 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003484 }
3485
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003486 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003487 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003488 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003489 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003490
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003491 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003492 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003493
Anders Carlsson3068d112008-11-16 19:01:22 +00003494 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003495 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003496 }
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Richard Smithf10d9172011-10-11 21:43:33 +00003498 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003499 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smitheba05b22011-12-25 20:00:17 +00003500 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003501 }
3502
Sebastian Redl64b45f72009-01-05 20:52:13 +00003503 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003504 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003505 }
3506
Francois Pichet6ad6f282010-12-07 00:08:36 +00003507 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3508 return Success(E->getValue(), E);
3509 }
3510
John Wiegley21ff2e52011-04-28 00:16:57 +00003511 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3512 return Success(E->getValue(), E);
3513 }
3514
John Wiegley55262202011-04-25 06:54:41 +00003515 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3516 return Success(E->getValue(), E);
3517 }
3518
Eli Friedman722c7172009-02-28 03:59:05 +00003519 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003520 bool VisitUnaryImag(const UnaryOperator *E);
3521
Sebastian Redl295995c2010-09-10 20:55:47 +00003522 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003523 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003524
Chris Lattnerfcee0012008-07-11 21:24:13 +00003525private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003526 CharUnits GetAlignOfExpr(const Expr *E);
3527 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003528 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003529 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003530 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003531};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003532} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003533
Richard Smithc49bd112011-10-28 17:51:58 +00003534/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3535/// produce either the integer value or a pointer.
3536///
3537/// GCC has a heinous extension which folds casts between pointer types and
3538/// pointer-sized integral types. We support this by allowing the evaluation of
3539/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3540/// Some simple arithmetic on such values is supported (they are treated much
3541/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003542static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003543 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003544 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003545 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003546}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003547
Richard Smithf48fdb02011-12-09 22:58:01 +00003548static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003549 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003550 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003551 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003552 if (!Val.isInt()) {
3553 // FIXME: It would be better to produce the diagnostic for casting
3554 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003555 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003556 return false;
3557 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003558 Result = Val.getInt();
3559 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003560}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003561
Richard Smithf48fdb02011-12-09 22:58:01 +00003562/// Check whether the given declaration can be directly converted to an integral
3563/// rvalue. If not, no diagnostic is produced; there are other things we can
3564/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003565bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003566 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003567 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003568 // Check for signedness/width mismatches between E type and ECD value.
3569 bool SameSign = (ECD->getInitVal().isSigned()
3570 == E->getType()->isSignedIntegerOrEnumerationType());
3571 bool SameWidth = (ECD->getInitVal().getBitWidth()
3572 == Info.Ctx.getIntWidth(E->getType()));
3573 if (SameSign && SameWidth)
3574 return Success(ECD->getInitVal(), E);
3575 else {
3576 // Get rid of mismatch (otherwise Success assertions will fail)
3577 // by computing a new value matching the type of E.
3578 llvm::APSInt Val = ECD->getInitVal();
3579 if (!SameSign)
3580 Val.setIsSigned(!ECD->getInitVal().isSigned());
3581 if (!SameWidth)
3582 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3583 return Success(Val, E);
3584 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003585 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003586 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003587}
3588
Chris Lattnera4d55d82008-10-06 06:40:35 +00003589/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3590/// as GCC.
3591static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3592 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003593 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003594 enum gcc_type_class {
3595 no_type_class = -1,
3596 void_type_class, integer_type_class, char_type_class,
3597 enumeral_type_class, boolean_type_class,
3598 pointer_type_class, reference_type_class, offset_type_class,
3599 real_type_class, complex_type_class,
3600 function_type_class, method_type_class,
3601 record_type_class, union_type_class,
3602 array_type_class, string_type_class,
3603 lang_type_class
3604 };
Mike Stump1eb44332009-09-09 15:08:12 +00003605
3606 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003607 // ideal, however it is what gcc does.
3608 if (E->getNumArgs() == 0)
3609 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Chris Lattnera4d55d82008-10-06 06:40:35 +00003611 QualType ArgTy = E->getArg(0)->getType();
3612 if (ArgTy->isVoidType())
3613 return void_type_class;
3614 else if (ArgTy->isEnumeralType())
3615 return enumeral_type_class;
3616 else if (ArgTy->isBooleanType())
3617 return boolean_type_class;
3618 else if (ArgTy->isCharType())
3619 return string_type_class; // gcc doesn't appear to use char_type_class
3620 else if (ArgTy->isIntegerType())
3621 return integer_type_class;
3622 else if (ArgTy->isPointerType())
3623 return pointer_type_class;
3624 else if (ArgTy->isReferenceType())
3625 return reference_type_class;
3626 else if (ArgTy->isRealType())
3627 return real_type_class;
3628 else if (ArgTy->isComplexType())
3629 return complex_type_class;
3630 else if (ArgTy->isFunctionType())
3631 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003632 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003633 return record_type_class;
3634 else if (ArgTy->isUnionType())
3635 return union_type_class;
3636 else if (ArgTy->isArrayType())
3637 return array_type_class;
3638 else if (ArgTy->isUnionType())
3639 return union_type_class;
3640 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003641 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003642 return -1;
3643}
3644
John McCall42c8f872010-05-10 23:27:23 +00003645/// Retrieves the "underlying object type" of the given expression,
3646/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003647QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3648 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3649 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003650 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003651 } else if (const Expr *E = B.get<const Expr*>()) {
3652 if (isa<CompoundLiteralExpr>(E))
3653 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003654 }
3655
3656 return QualType();
3657}
3658
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003659bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003660 // TODO: Perhaps we should let LLVM lower this?
3661 LValue Base;
3662 if (!EvaluatePointer(E->getArg(0), Base, Info))
3663 return false;
3664
3665 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003666 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003667
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003668 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003669 if (T.isNull() ||
3670 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003671 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003672 T->isVariablyModifiedType() ||
3673 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003674 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003675
3676 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3677 CharUnits Offset = Base.getLValueOffset();
3678
3679 if (!Offset.isNegative() && Offset <= Size)
3680 Size -= Offset;
3681 else
3682 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003683 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003684}
3685
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003686bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003687 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003688 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003689 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003690
3691 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003692 if (TryEvaluateBuiltinObjectSize(E))
3693 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003694
Eric Christopherb2aaf512010-01-19 22:58:35 +00003695 // If evaluating the argument has side-effects we can't determine
3696 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003697 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003698 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003699 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003700 return Success(0, E);
3701 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003702
Richard Smithf48fdb02011-12-09 22:58:01 +00003703 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003704 }
3705
Chris Lattner019f4e82008-10-06 05:28:25 +00003706 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003707 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Richard Smithe052d462011-12-09 02:04:48 +00003709 case Builtin::BI__builtin_constant_p: {
3710 const Expr *Arg = E->getArg(0);
3711 QualType ArgType = Arg->getType();
3712 // __builtin_constant_p always has one operand. The rules which gcc follows
3713 // are not precisely documented, but are as follows:
3714 //
3715 // - If the operand is of integral, floating, complex or enumeration type,
3716 // and can be folded to a known value of that type, it returns 1.
3717 // - If the operand and can be folded to a pointer to the first character
3718 // of a string literal (or such a pointer cast to an integral type), it
3719 // returns 1.
3720 //
3721 // Otherwise, it returns 0.
3722 //
3723 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3724 // its support for this does not currently work.
3725 int IsConstant = 0;
3726 if (ArgType->isIntegralOrEnumerationType()) {
3727 // Note, a pointer cast to an integral type is only a constant if it is
3728 // a pointer to the first character of a string literal.
3729 Expr::EvalResult Result;
3730 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3731 APValue &V = Result.Val;
3732 if (V.getKind() == APValue::LValue) {
3733 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3734 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3735 } else {
3736 IsConstant = 1;
3737 }
3738 }
3739 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3740 IsConstant = Arg->isEvaluatable(Info.Ctx);
3741 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3742 LValue LV;
3743 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3744 // during the check.
3745 Expr::EvalStatus Status;
3746 EvalInfo SubInfo(Info.Ctx, Status);
3747 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3748 : EvaluatePointer(Arg, LV, SubInfo)) &&
3749 !Status.HasSideEffects)
3750 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3751 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3752 }
3753
3754 return Success(IsConstant, E);
3755 }
Chris Lattner21fb98e2009-09-23 06:06:36 +00003756 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003757 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003758 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003759 return Success(Operand, E);
3760 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003761
3762 case Builtin::BI__builtin_expect:
3763 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00003764
3765 case Builtin::BIstrlen:
3766 case Builtin::BI__builtin_strlen:
3767 // As an extension, we support strlen() and __builtin_strlen() as constant
3768 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003769 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003770 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3771 // The string literal may have embedded null characters. Find the first
3772 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003773 StringRef Str = S->getString();
3774 StringRef::size_type Pos = Str.find(0);
3775 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003776 Str = Str.substr(0, Pos);
3777
3778 return Success(Str.size(), E);
3779 }
3780
Richard Smithf48fdb02011-12-09 22:58:01 +00003781 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003782
3783 case Builtin::BI__atomic_is_lock_free: {
3784 APSInt SizeVal;
3785 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3786 return false;
3787
3788 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3789 // of two less than the maximum inline atomic width, we know it is
3790 // lock-free. If the size isn't a power of two, or greater than the
3791 // maximum alignment where we promote atomics, we know it is not lock-free
3792 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3793 // the answer can only be determined at runtime; for example, 16-byte
3794 // atomics have lock-free implementations on some, but not all,
3795 // x86-64 processors.
3796
3797 // Check power-of-two.
3798 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3799 if (!Size.isPowerOfTwo())
3800#if 0
3801 // FIXME: Suppress this folding until the ABI for the promotion width
3802 // settles.
3803 return Success(0, E);
3804#else
Richard Smithf48fdb02011-12-09 22:58:01 +00003805 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003806#endif
3807
3808#if 0
3809 // Check against promotion width.
3810 // FIXME: Suppress this folding until the ABI for the promotion width
3811 // settles.
3812 unsigned PromoteWidthBits =
3813 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3814 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3815 return Success(0, E);
3816#endif
3817
3818 // Check against inlining width.
3819 unsigned InlineWidthBits =
3820 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3821 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3822 return Success(1, E);
3823
Richard Smithf48fdb02011-12-09 22:58:01 +00003824 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003825 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003826 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00003827}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003828
Richard Smith625b8072011-10-31 01:37:14 +00003829static bool HasSameBase(const LValue &A, const LValue &B) {
3830 if (!A.getLValueBase())
3831 return !B.getLValueBase();
3832 if (!B.getLValueBase())
3833 return false;
3834
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003835 if (A.getLValueBase().getOpaqueValue() !=
3836 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00003837 const Decl *ADecl = GetLValueBaseDecl(A);
3838 if (!ADecl)
3839 return false;
3840 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00003841 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00003842 return false;
3843 }
3844
3845 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00003846 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00003847}
3848
Chris Lattnerb542afe2008-07-11 19:10:17 +00003849bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003850 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003851 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003852
John McCall2de56d12010-08-25 11:45:40 +00003853 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003854 VisitIgnoredValue(E->getLHS());
3855 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00003856 }
3857
3858 if (E->isLogicalOp()) {
3859 // These need to be handled specially because the operands aren't
3860 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003861 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Richard Smithc49bd112011-10-28 17:51:58 +00003863 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00003864 // We were able to evaluate the LHS, see if we can get away with not
3865 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00003866 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003867 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003868
Richard Smithc49bd112011-10-28 17:51:58 +00003869 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00003870 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003871 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003872 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00003873 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003874 }
3875 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00003876 // FIXME: If both evaluations fail, we should produce the diagnostic from
3877 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3878 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00003879 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003880 // We can't evaluate the LHS; however, sometimes the result
3881 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00003882 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003883 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003884 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00003885 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003886
3887 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003888 }
3889 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00003890 }
Eli Friedmana6afa762008-11-13 06:09:17 +00003891
Eli Friedmana6afa762008-11-13 06:09:17 +00003892 return false;
3893 }
3894
Anders Carlsson286f85e2008-11-16 07:17:21 +00003895 QualType LHSTy = E->getLHS()->getType();
3896 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00003897
3898 if (LHSTy->isAnyComplexType()) {
3899 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00003900 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00003901
3902 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3903 return false;
3904
3905 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3906 return false;
3907
3908 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003909 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003910 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00003911 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003912 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3913
John McCall2de56d12010-08-25 11:45:40 +00003914 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003915 return Success((CR_r == APFloat::cmpEqual &&
3916 CR_i == APFloat::cmpEqual), E);
3917 else {
John McCall2de56d12010-08-25 11:45:40 +00003918 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003919 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00003920 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003921 CR_r == APFloat::cmpLessThan ||
3922 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003923 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003924 CR_i == APFloat::cmpLessThan ||
3925 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00003926 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003927 } else {
John McCall2de56d12010-08-25 11:45:40 +00003928 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003929 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3930 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3931 else {
John McCall2de56d12010-08-25 11:45:40 +00003932 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003933 "Invalid compex comparison.");
3934 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3935 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3936 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003937 }
3938 }
Mike Stump1eb44332009-09-09 15:08:12 +00003939
Anders Carlsson286f85e2008-11-16 07:17:21 +00003940 if (LHSTy->isRealFloatingType() &&
3941 RHSTy->isRealFloatingType()) {
3942 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00003943
Anders Carlsson286f85e2008-11-16 07:17:21 +00003944 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3945 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003946
Anders Carlsson286f85e2008-11-16 07:17:21 +00003947 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3948 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Anders Carlsson286f85e2008-11-16 07:17:21 +00003950 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00003951
Anders Carlsson286f85e2008-11-16 07:17:21 +00003952 switch (E->getOpcode()) {
3953 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003954 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00003955 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003956 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003957 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003958 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003959 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003960 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003961 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00003962 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00003963 E);
John McCall2de56d12010-08-25 11:45:40 +00003964 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003965 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003966 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00003967 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00003968 || CR == APFloat::cmpLessThan
3969 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00003970 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00003971 }
Mike Stump1eb44332009-09-09 15:08:12 +00003972
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003973 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00003974 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00003975 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003976 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3977 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003978
John McCallefdb83e2010-05-07 21:00:08 +00003979 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003980 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3981 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003982
Richard Smith625b8072011-10-31 01:37:14 +00003983 // Reject differing bases from the normal codepath; we special-case
3984 // comparisons to null.
3985 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00003986 // Inequalities and subtractions between unrelated pointers have
3987 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00003988 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003989 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00003990 // A constant address may compare equal to the address of a symbol.
3991 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00003992 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00003993 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3994 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003995 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003996 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00003997 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00003998 // distinct. However, we do know that the address of a literal will be
3999 // non-null.
4000 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4001 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004002 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004003 // We can't tell whether weak symbols will end up pointing to the same
4004 // object.
4005 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004006 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004007 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004008 // (Note that clang defaults to -fmerge-all-constants, which can
4009 // lead to inconsistent results for comparisons involving the address
4010 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004011 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004012 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004013
Richard Smithcc5d4f62011-11-07 09:22:26 +00004014 // FIXME: Implement the C++11 restrictions:
4015 // - Pointer subtractions must be on elements of the same array.
4016 // - Pointer comparisons must be between members with the same access.
4017
John McCall2de56d12010-08-25 11:45:40 +00004018 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004019 QualType Type = E->getLHS()->getType();
4020 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004021
Richard Smith180f4792011-11-10 06:34:14 +00004022 CharUnits ElementSize;
4023 if (!HandleSizeof(Info, ElementType, ElementSize))
4024 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004025
Richard Smith180f4792011-11-10 06:34:14 +00004026 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004027 RHSValue.getLValueOffset();
4028 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004029 }
Richard Smith625b8072011-10-31 01:37:14 +00004030
4031 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4032 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4033 switch (E->getOpcode()) {
4034 default: llvm_unreachable("missing comparison operator");
4035 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4036 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4037 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4038 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4039 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4040 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004041 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004042 }
4043 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004044 if (!LHSTy->isIntegralOrEnumerationType() ||
4045 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004046 // We can't continue from here for non-integral types.
4047 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004048 }
4049
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004050 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004051 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00004052 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00004053 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004054
Richard Smithc49bd112011-10-28 17:51:58 +00004055 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004056 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004057 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004058
4059 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004060 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004061 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4062 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004063 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004064 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004065 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004066 LHSVal.getLValueOffset() -= AdditionalOffset;
4067 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004068 return true;
4069 }
4070
4071 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004072 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004073 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004074 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4075 LHSVal.getInt().getZExtValue());
4076 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004077 return true;
4078 }
4079
4080 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004081 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004082 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004083
Richard Smithc49bd112011-10-28 17:51:58 +00004084 APSInt &LHS = LHSVal.getInt();
4085 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004086
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004087 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004088 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004089 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004090 case BO_Mul: return Success(LHS * RHS, E);
4091 case BO_Add: return Success(LHS + RHS, E);
4092 case BO_Sub: return Success(LHS - RHS, E);
4093 case BO_And: return Success(LHS & RHS, E);
4094 case BO_Xor: return Success(LHS ^ RHS, E);
4095 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004096 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00004097 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004098 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004099 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004100 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004101 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004102 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004103 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004104 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00004105 // During constant-folding, a negative shift is an opposite shift.
4106 if (RHS.isSigned() && RHS.isNegative()) {
4107 RHS = -RHS;
4108 goto shift_right;
4109 }
4110
4111 shift_left:
4112 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00004113 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4114 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004115 }
John McCall2de56d12010-08-25 11:45:40 +00004116 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00004117 // During constant-folding, a negative shift is an opposite shift.
4118 if (RHS.isSigned() && RHS.isNegative()) {
4119 RHS = -RHS;
4120 goto shift_left;
4121 }
4122
4123 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00004124 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00004125 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4126 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004127 }
Mike Stump1eb44332009-09-09 15:08:12 +00004128
Richard Smithc49bd112011-10-28 17:51:58 +00004129 case BO_LT: return Success(LHS < RHS, E);
4130 case BO_GT: return Success(LHS > RHS, E);
4131 case BO_LE: return Success(LHS <= RHS, E);
4132 case BO_GE: return Success(LHS >= RHS, E);
4133 case BO_EQ: return Success(LHS == RHS, E);
4134 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004135 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004136}
4137
Ken Dyck8b752f12010-01-27 17:10:57 +00004138CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004139 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4140 // the result is the size of the referenced type."
4141 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4142 // result shall be the alignment of the referenced type."
4143 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4144 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004145
4146 // __alignof is defined to return the preferred alignment.
4147 return Info.Ctx.toCharUnitsFromBits(
4148 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004149}
4150
Ken Dyck8b752f12010-01-27 17:10:57 +00004151CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004152 E = E->IgnoreParens();
4153
4154 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004155 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004156 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004157 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4158 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004159
Chris Lattneraf707ab2009-01-24 21:53:27 +00004160 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004161 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4162 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004163
Chris Lattnere9feb472009-01-24 21:09:06 +00004164 return GetAlignOfType(E->getType());
4165}
4166
4167
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004168/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4169/// a result as the expression's type.
4170bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4171 const UnaryExprOrTypeTraitExpr *E) {
4172 switch(E->getKind()) {
4173 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004174 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004175 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004176 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004177 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004178 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004179
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004180 case UETT_VecStep: {
4181 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004182
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004183 if (Ty->isVectorType()) {
4184 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004185
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004186 // The vec_step built-in functions that take a 3-component
4187 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4188 if (n == 3)
4189 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004190
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004191 return Success(n, E);
4192 } else
4193 return Success(1, E);
4194 }
4195
4196 case UETT_SizeOf: {
4197 QualType SrcTy = E->getTypeOfArgument();
4198 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4199 // the result is the size of the referenced type."
4200 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4201 // result shall be the alignment of the referenced type."
4202 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4203 SrcTy = Ref->getPointeeType();
4204
Richard Smith180f4792011-11-10 06:34:14 +00004205 CharUnits Sizeof;
4206 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004207 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004208 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004209 }
4210 }
4211
4212 llvm_unreachable("unknown expr/type trait");
Richard Smithf48fdb02011-12-09 22:58:01 +00004213 return Error(E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00004214}
4215
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004216bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004217 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004218 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004219 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004220 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004221 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004222 for (unsigned i = 0; i != n; ++i) {
4223 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4224 switch (ON.getKind()) {
4225 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004226 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004227 APSInt IdxResult;
4228 if (!EvaluateInteger(Idx, IdxResult, Info))
4229 return false;
4230 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4231 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004232 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004233 CurrentType = AT->getElementType();
4234 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4235 Result += IdxResult.getSExtValue() * ElementSize;
4236 break;
4237 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004238
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004239 case OffsetOfExpr::OffsetOfNode::Field: {
4240 FieldDecl *MemberDecl = ON.getField();
4241 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004242 if (!RT)
4243 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004244 RecordDecl *RD = RT->getDecl();
4245 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004246 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004247 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004248 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004249 CurrentType = MemberDecl->getType().getNonReferenceType();
4250 break;
4251 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004252
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004253 case OffsetOfExpr::OffsetOfNode::Identifier:
4254 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004255 return Error(OOE);
4256
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004257 case OffsetOfExpr::OffsetOfNode::Base: {
4258 CXXBaseSpecifier *BaseSpec = ON.getBase();
4259 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004260 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004261
4262 // Find the layout of the class whose base we are looking into.
4263 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004264 if (!RT)
4265 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004266 RecordDecl *RD = RT->getDecl();
4267 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4268
4269 // Find the base class itself.
4270 CurrentType = BaseSpec->getType();
4271 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4272 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004273 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004274
4275 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004276 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004277 break;
4278 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004279 }
4280 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004281 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004282}
4283
Chris Lattnerb542afe2008-07-11 19:10:17 +00004284bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004285 switch (E->getOpcode()) {
4286 default:
4287 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4288 // See C99 6.6p3.
4289 return Error(E);
4290 case UO_Extension:
4291 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4292 // If so, we could clear the diagnostic ID.
4293 return Visit(E->getSubExpr());
4294 case UO_Plus:
4295 // The result is just the value.
4296 return Visit(E->getSubExpr());
4297 case UO_Minus: {
4298 if (!Visit(E->getSubExpr()))
4299 return false;
4300 if (!Result.isInt()) return Error(E);
4301 return Success(-Result.getInt(), E);
4302 }
4303 case UO_Not: {
4304 if (!Visit(E->getSubExpr()))
4305 return false;
4306 if (!Result.isInt()) return Error(E);
4307 return Success(~Result.getInt(), E);
4308 }
4309 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004310 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004311 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004312 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004313 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004314 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004315 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004316}
Mike Stump1eb44332009-09-09 15:08:12 +00004317
Chris Lattner732b2232008-07-12 01:15:53 +00004318/// HandleCast - This is used to evaluate implicit or explicit casts where the
4319/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004320bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4321 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004322 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004323 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004324
Eli Friedman46a52322011-03-25 00:43:55 +00004325 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004326 case CK_BaseToDerived:
4327 case CK_DerivedToBase:
4328 case CK_UncheckedDerivedToBase:
4329 case CK_Dynamic:
4330 case CK_ToUnion:
4331 case CK_ArrayToPointerDecay:
4332 case CK_FunctionToPointerDecay:
4333 case CK_NullToPointer:
4334 case CK_NullToMemberPointer:
4335 case CK_BaseToDerivedMemberPointer:
4336 case CK_DerivedToBaseMemberPointer:
4337 case CK_ConstructorConversion:
4338 case CK_IntegralToPointer:
4339 case CK_ToVoid:
4340 case CK_VectorSplat:
4341 case CK_IntegralToFloating:
4342 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004343 case CK_CPointerToObjCPointerCast:
4344 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004345 case CK_AnyPointerToBlockPointerCast:
4346 case CK_ObjCObjectLValueCast:
4347 case CK_FloatingRealToComplex:
4348 case CK_FloatingComplexToReal:
4349 case CK_FloatingComplexCast:
4350 case CK_FloatingComplexToIntegralComplex:
4351 case CK_IntegralRealToComplex:
4352 case CK_IntegralComplexCast:
4353 case CK_IntegralComplexToFloatingComplex:
4354 llvm_unreachable("invalid cast kind for integral value");
4355
Eli Friedmane50c2972011-03-25 19:07:11 +00004356 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004357 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004358 case CK_LValueBitCast:
4359 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00004360 case CK_ARCProduceObject:
4361 case CK_ARCConsumeObject:
4362 case CK_ARCReclaimReturnedObject:
4363 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004364 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004365
4366 case CK_LValueToRValue:
4367 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004368 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004369
4370 case CK_MemberPointerToBoolean:
4371 case CK_PointerToBoolean:
4372 case CK_IntegralToBoolean:
4373 case CK_FloatingToBoolean:
4374 case CK_FloatingComplexToBoolean:
4375 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004376 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004377 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004378 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004379 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004380 }
4381
Eli Friedman46a52322011-03-25 00:43:55 +00004382 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004383 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004384 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004385
Eli Friedmanbe265702009-02-20 01:15:07 +00004386 if (!Result.isInt()) {
4387 // Only allow casts of lvalues if they are lossless.
4388 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4389 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004390
Daniel Dunbardd211642009-02-19 22:24:01 +00004391 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004392 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004393 }
Mike Stump1eb44332009-09-09 15:08:12 +00004394
Eli Friedman46a52322011-03-25 00:43:55 +00004395 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004396 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4397
John McCallefdb83e2010-05-07 21:00:08 +00004398 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004399 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004400 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004401
Daniel Dunbardd211642009-02-19 22:24:01 +00004402 if (LV.getLValueBase()) {
4403 // Only allow based lvalue casts if they are lossless.
4404 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004405 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004406
Richard Smithb755a9d2011-11-16 07:18:12 +00004407 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004408 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004409 return true;
4410 }
4411
Ken Dycka7305832010-01-15 12:37:54 +00004412 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4413 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00004414 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004415 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004416
Eli Friedman46a52322011-03-25 00:43:55 +00004417 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004418 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004419 if (!EvaluateComplex(SubExpr, C, Info))
4420 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004421 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004422 }
Eli Friedman2217c872009-02-22 11:46:18 +00004423
Eli Friedman46a52322011-03-25 00:43:55 +00004424 case CK_FloatingToIntegral: {
4425 APFloat F(0.0);
4426 if (!EvaluateFloat(SubExpr, F, Info))
4427 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004428
Richard Smithc1c5f272011-12-13 06:39:58 +00004429 APSInt Value;
4430 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4431 return false;
4432 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004433 }
4434 }
Mike Stump1eb44332009-09-09 15:08:12 +00004435
Eli Friedman46a52322011-03-25 00:43:55 +00004436 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004437 return Error(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004438}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004439
Eli Friedman722c7172009-02-28 03:59:05 +00004440bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4441 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004442 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004443 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4444 return false;
4445 if (!LV.isComplexInt())
4446 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004447 return Success(LV.getComplexIntReal(), E);
4448 }
4449
4450 return Visit(E->getSubExpr());
4451}
4452
Eli Friedman664a1042009-02-27 04:45:43 +00004453bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004454 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004455 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004456 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4457 return false;
4458 if (!LV.isComplexInt())
4459 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004460 return Success(LV.getComplexIntImag(), E);
4461 }
4462
Richard Smith8327fad2011-10-24 18:44:57 +00004463 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004464 return Success(0, E);
4465}
4466
Douglas Gregoree8aff02011-01-04 17:33:58 +00004467bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4468 return Success(E->getPackLength(), E);
4469}
4470
Sebastian Redl295995c2010-09-10 20:55:47 +00004471bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4472 return Success(E->getValue(), E);
4473}
4474
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004475//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004476// Float Evaluation
4477//===----------------------------------------------------------------------===//
4478
4479namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004480class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004481 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004482 APFloat &Result;
4483public:
4484 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004485 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004486
Richard Smith47a1eed2011-10-29 20:57:55 +00004487 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004488 Result = V.getFloat();
4489 return true;
4490 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004491
Richard Smitheba05b22011-12-25 20:00:17 +00004492 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004493 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4494 return true;
4495 }
4496
Chris Lattner019f4e82008-10-06 05:28:25 +00004497 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004498
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004499 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004500 bool VisitBinaryOperator(const BinaryOperator *E);
4501 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004502 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004503
John McCallabd3a852010-05-07 22:08:54 +00004504 bool VisitUnaryReal(const UnaryOperator *E);
4505 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004506
Richard Smitheba05b22011-12-25 20:00:17 +00004507 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004508};
4509} // end anonymous namespace
4510
4511static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004512 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004513 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004514}
4515
Jay Foad4ba2a172011-01-12 09:06:06 +00004516static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004517 QualType ResultTy,
4518 const Expr *Arg,
4519 bool SNaN,
4520 llvm::APFloat &Result) {
4521 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4522 if (!S) return false;
4523
4524 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4525
4526 llvm::APInt fill;
4527
4528 // Treat empty strings as if they were zero.
4529 if (S->getString().empty())
4530 fill = llvm::APInt(32, 0);
4531 else if (S->getString().getAsInteger(0, fill))
4532 return false;
4533
4534 if (SNaN)
4535 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4536 else
4537 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4538 return true;
4539}
4540
Chris Lattner019f4e82008-10-06 05:28:25 +00004541bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004542 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004543 default:
4544 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4545
Chris Lattner019f4e82008-10-06 05:28:25 +00004546 case Builtin::BI__builtin_huge_val:
4547 case Builtin::BI__builtin_huge_valf:
4548 case Builtin::BI__builtin_huge_vall:
4549 case Builtin::BI__builtin_inf:
4550 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004551 case Builtin::BI__builtin_infl: {
4552 const llvm::fltSemantics &Sem =
4553 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004554 Result = llvm::APFloat::getInf(Sem);
4555 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004556 }
Mike Stump1eb44332009-09-09 15:08:12 +00004557
John McCalldb7b72a2010-02-28 13:00:19 +00004558 case Builtin::BI__builtin_nans:
4559 case Builtin::BI__builtin_nansf:
4560 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004561 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4562 true, Result))
4563 return Error(E);
4564 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004565
Chris Lattner9e621712008-10-06 06:31:58 +00004566 case Builtin::BI__builtin_nan:
4567 case Builtin::BI__builtin_nanf:
4568 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004569 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004570 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004571 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4572 false, Result))
4573 return Error(E);
4574 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004575
4576 case Builtin::BI__builtin_fabs:
4577 case Builtin::BI__builtin_fabsf:
4578 case Builtin::BI__builtin_fabsl:
4579 if (!EvaluateFloat(E->getArg(0), Result, Info))
4580 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004581
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004582 if (Result.isNegative())
4583 Result.changeSign();
4584 return true;
4585
Mike Stump1eb44332009-09-09 15:08:12 +00004586 case Builtin::BI__builtin_copysign:
4587 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004588 case Builtin::BI__builtin_copysignl: {
4589 APFloat RHS(0.);
4590 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4591 !EvaluateFloat(E->getArg(1), RHS, Info))
4592 return false;
4593 Result.copySign(RHS);
4594 return true;
4595 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004596 }
4597}
4598
John McCallabd3a852010-05-07 22:08:54 +00004599bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004600 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4601 ComplexValue CV;
4602 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4603 return false;
4604 Result = CV.FloatReal;
4605 return true;
4606 }
4607
4608 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004609}
4610
4611bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004612 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4613 ComplexValue CV;
4614 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4615 return false;
4616 Result = CV.FloatImag;
4617 return true;
4618 }
4619
Richard Smith8327fad2011-10-24 18:44:57 +00004620 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004621 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4622 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004623 return true;
4624}
4625
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004626bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004627 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004628 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004629 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004630 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004631 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004632 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4633 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004634 Result.changeSign();
4635 return true;
4636 }
4637}
Chris Lattner019f4e82008-10-06 05:28:25 +00004638
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004639bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004640 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4641 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004642
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004643 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004644 if (!EvaluateFloat(E->getLHS(), Result, Info))
4645 return false;
4646 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4647 return false;
4648
4649 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004650 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004651 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004652 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4653 return true;
John McCall2de56d12010-08-25 11:45:40 +00004654 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004655 Result.add(RHS, APFloat::rmNearestTiesToEven);
4656 return true;
John McCall2de56d12010-08-25 11:45:40 +00004657 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004658 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4659 return true;
John McCall2de56d12010-08-25 11:45:40 +00004660 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004661 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4662 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004663 }
4664}
4665
4666bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4667 Result = E->getValue();
4668 return true;
4669}
4670
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004671bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4672 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004673
Eli Friedman2a523ee2011-03-25 00:54:52 +00004674 switch (E->getCastKind()) {
4675 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004676 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004677
4678 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004679 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004680 return EvaluateInteger(SubExpr, IntResult, Info) &&
4681 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4682 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004683 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004684
4685 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004686 if (!Visit(SubExpr))
4687 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004688 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4689 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004690 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004691
Eli Friedman2a523ee2011-03-25 00:54:52 +00004692 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004693 ComplexValue V;
4694 if (!EvaluateComplex(SubExpr, V, Info))
4695 return false;
4696 Result = V.getComplexFloatReal();
4697 return true;
4698 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004699 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004700
Richard Smithf48fdb02011-12-09 22:58:01 +00004701 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004702}
4703
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004704//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004705// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004706//===----------------------------------------------------------------------===//
4707
4708namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004709class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004710 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004711 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004712
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004713public:
John McCallf4cf1a12010-05-07 17:22:02 +00004714 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004715 : ExprEvaluatorBaseTy(info), Result(Result) {}
4716
Richard Smith47a1eed2011-10-29 20:57:55 +00004717 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004718 Result.setFrom(V);
4719 return true;
4720 }
Mike Stump1eb44332009-09-09 15:08:12 +00004721
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004722 //===--------------------------------------------------------------------===//
4723 // Visitor Methods
4724 //===--------------------------------------------------------------------===//
4725
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004726 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004728 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004729
John McCallf4cf1a12010-05-07 17:22:02 +00004730 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004731 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004732 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004733};
4734} // end anonymous namespace
4735
John McCallf4cf1a12010-05-07 17:22:02 +00004736static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4737 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004738 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004739 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004740}
4741
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004742bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4743 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004744
4745 if (SubExpr->getType()->isRealFloatingType()) {
4746 Result.makeComplexFloat();
4747 APFloat &Imag = Result.FloatImag;
4748 if (!EvaluateFloat(SubExpr, Imag, Info))
4749 return false;
4750
4751 Result.FloatReal = APFloat(Imag.getSemantics());
4752 return true;
4753 } else {
4754 assert(SubExpr->getType()->isIntegerType() &&
4755 "Unexpected imaginary literal.");
4756
4757 Result.makeComplexInt();
4758 APSInt &Imag = Result.IntImag;
4759 if (!EvaluateInteger(SubExpr, Imag, Info))
4760 return false;
4761
4762 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4763 return true;
4764 }
4765}
4766
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004767bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004768
John McCall8786da72010-12-14 17:51:41 +00004769 switch (E->getCastKind()) {
4770 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00004771 case CK_BaseToDerived:
4772 case CK_DerivedToBase:
4773 case CK_UncheckedDerivedToBase:
4774 case CK_Dynamic:
4775 case CK_ToUnion:
4776 case CK_ArrayToPointerDecay:
4777 case CK_FunctionToPointerDecay:
4778 case CK_NullToPointer:
4779 case CK_NullToMemberPointer:
4780 case CK_BaseToDerivedMemberPointer:
4781 case CK_DerivedToBaseMemberPointer:
4782 case CK_MemberPointerToBoolean:
4783 case CK_ConstructorConversion:
4784 case CK_IntegralToPointer:
4785 case CK_PointerToIntegral:
4786 case CK_PointerToBoolean:
4787 case CK_ToVoid:
4788 case CK_VectorSplat:
4789 case CK_IntegralCast:
4790 case CK_IntegralToBoolean:
4791 case CK_IntegralToFloating:
4792 case CK_FloatingToIntegral:
4793 case CK_FloatingToBoolean:
4794 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004795 case CK_CPointerToObjCPointerCast:
4796 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00004797 case CK_AnyPointerToBlockPointerCast:
4798 case CK_ObjCObjectLValueCast:
4799 case CK_FloatingComplexToReal:
4800 case CK_FloatingComplexToBoolean:
4801 case CK_IntegralComplexToReal:
4802 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00004803 case CK_ARCProduceObject:
4804 case CK_ARCConsumeObject:
4805 case CK_ARCReclaimReturnedObject:
4806 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00004807 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00004808
John McCall8786da72010-12-14 17:51:41 +00004809 case CK_LValueToRValue:
4810 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004811 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00004812
4813 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004814 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00004815 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00004816 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00004817
4818 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004819 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00004820 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004821 return false;
4822
John McCall8786da72010-12-14 17:51:41 +00004823 Result.makeComplexFloat();
4824 Result.FloatImag = APFloat(Real.getSemantics());
4825 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004826 }
4827
John McCall8786da72010-12-14 17:51:41 +00004828 case CK_FloatingComplexCast: {
4829 if (!Visit(E->getSubExpr()))
4830 return false;
4831
4832 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4833 QualType From
4834 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4835
Richard Smithc1c5f272011-12-13 06:39:58 +00004836 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4837 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004838 }
4839
4840 case CK_FloatingComplexToIntegralComplex: {
4841 if (!Visit(E->getSubExpr()))
4842 return false;
4843
4844 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4845 QualType From
4846 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4847 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00004848 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4849 To, Result.IntReal) &&
4850 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4851 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00004852 }
4853
4854 case CK_IntegralRealToComplex: {
4855 APSInt &Real = Result.IntReal;
4856 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4857 return false;
4858
4859 Result.makeComplexInt();
4860 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4861 return true;
4862 }
4863
4864 case CK_IntegralComplexCast: {
4865 if (!Visit(E->getSubExpr()))
4866 return false;
4867
4868 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4869 QualType From
4870 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4871
4872 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4873 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4874 return true;
4875 }
4876
4877 case CK_IntegralComplexToFloatingComplex: {
4878 if (!Visit(E->getSubExpr()))
4879 return false;
4880
4881 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4882 QualType From
4883 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4884 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00004885 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4886 To, Result.FloatReal) &&
4887 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4888 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004889 }
4890 }
4891
4892 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004893 return Error(E);
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004894}
4895
John McCallf4cf1a12010-05-07 17:22:02 +00004896bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004897 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00004898 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4899
John McCallf4cf1a12010-05-07 17:22:02 +00004900 if (!Visit(E->getLHS()))
4901 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004902
John McCallf4cf1a12010-05-07 17:22:02 +00004903 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004904 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00004905 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004906
Daniel Dunbar3f279872009-01-29 01:32:56 +00004907 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4908 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004909 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004910 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004911 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004912 if (Result.isComplexFloat()) {
4913 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4914 APFloat::rmNearestTiesToEven);
4915 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4916 APFloat::rmNearestTiesToEven);
4917 } else {
4918 Result.getComplexIntReal() += RHS.getComplexIntReal();
4919 Result.getComplexIntImag() += RHS.getComplexIntImag();
4920 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004921 break;
John McCall2de56d12010-08-25 11:45:40 +00004922 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004923 if (Result.isComplexFloat()) {
4924 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4925 APFloat::rmNearestTiesToEven);
4926 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4927 APFloat::rmNearestTiesToEven);
4928 } else {
4929 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4930 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4931 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004932 break;
John McCall2de56d12010-08-25 11:45:40 +00004933 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00004934 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004935 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00004936 APFloat &LHS_r = LHS.getComplexFloatReal();
4937 APFloat &LHS_i = LHS.getComplexFloatImag();
4938 APFloat &RHS_r = RHS.getComplexFloatReal();
4939 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00004940
Daniel Dunbar3f279872009-01-29 01:32:56 +00004941 APFloat Tmp = LHS_r;
4942 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4943 Result.getComplexFloatReal() = Tmp;
4944 Tmp = LHS_i;
4945 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4946 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4947
4948 Tmp = LHS_r;
4949 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4950 Result.getComplexFloatImag() = Tmp;
4951 Tmp = LHS_i;
4952 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4953 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4954 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00004955 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004956 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004957 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4958 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00004959 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004960 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4961 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4962 }
4963 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004964 case BO_Div:
4965 if (Result.isComplexFloat()) {
4966 ComplexValue LHS = Result;
4967 APFloat &LHS_r = LHS.getComplexFloatReal();
4968 APFloat &LHS_i = LHS.getComplexFloatImag();
4969 APFloat &RHS_r = RHS.getComplexFloatReal();
4970 APFloat &RHS_i = RHS.getComplexFloatImag();
4971 APFloat &Res_r = Result.getComplexFloatReal();
4972 APFloat &Res_i = Result.getComplexFloatImag();
4973
4974 APFloat Den = RHS_r;
4975 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4976 APFloat Tmp = RHS_i;
4977 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4978 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4979
4980 Res_r = LHS_r;
4981 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4982 Tmp = LHS_i;
4983 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4984 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4985 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4986
4987 Res_i = LHS_i;
4988 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4989 Tmp = LHS_r;
4990 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4991 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4992 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4993 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004994 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4995 return Error(E, diag::note_expr_divide_by_zero);
4996
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004997 ComplexValue LHS = Result;
4998 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4999 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5000 Result.getComplexIntReal() =
5001 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5002 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5003 Result.getComplexIntImag() =
5004 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5005 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5006 }
5007 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005008 }
5009
John McCallf4cf1a12010-05-07 17:22:02 +00005010 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005011}
5012
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005013bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5014 // Get the operand value into 'Result'.
5015 if (!Visit(E->getSubExpr()))
5016 return false;
5017
5018 switch (E->getOpcode()) {
5019 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005020 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005021 case UO_Extension:
5022 return true;
5023 case UO_Plus:
5024 // The result is always just the subexpr.
5025 return true;
5026 case UO_Minus:
5027 if (Result.isComplexFloat()) {
5028 Result.getComplexFloatReal().changeSign();
5029 Result.getComplexFloatImag().changeSign();
5030 }
5031 else {
5032 Result.getComplexIntReal() = -Result.getComplexIntReal();
5033 Result.getComplexIntImag() = -Result.getComplexIntImag();
5034 }
5035 return true;
5036 case UO_Not:
5037 if (Result.isComplexFloat())
5038 Result.getComplexFloatImag().changeSign();
5039 else
5040 Result.getComplexIntImag() = -Result.getComplexIntImag();
5041 return true;
5042 }
5043}
5044
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005045//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005046// Void expression evaluation, primarily for a cast to void on the LHS of a
5047// comma operator
5048//===----------------------------------------------------------------------===//
5049
5050namespace {
5051class VoidExprEvaluator
5052 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5053public:
5054 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5055
5056 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005057
5058 bool VisitCastExpr(const CastExpr *E) {
5059 switch (E->getCastKind()) {
5060 default:
5061 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5062 case CK_ToVoid:
5063 VisitIgnoredValue(E->getSubExpr());
5064 return true;
5065 }
5066 }
5067};
5068} // end anonymous namespace
5069
5070static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5071 assert(E->isRValue() && E->getType()->isVoidType());
5072 return VoidExprEvaluator(Info).Visit(E);
5073}
5074
5075//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005076// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005077//===----------------------------------------------------------------------===//
5078
Richard Smith47a1eed2011-10-29 20:57:55 +00005079static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005080 // In C, function designators are not lvalues, but we evaluate them as if they
5081 // are.
5082 if (E->isGLValue() || E->getType()->isFunctionType()) {
5083 LValue LV;
5084 if (!EvaluateLValue(E, LV, Info))
5085 return false;
5086 LV.moveInto(Result);
5087 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005088 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005089 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005090 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005091 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005092 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005093 } else if (E->getType()->hasPointerRepresentation()) {
5094 LValue LV;
5095 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005096 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005097 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005098 } else if (E->getType()->isRealFloatingType()) {
5099 llvm::APFloat F(0.0);
5100 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005101 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005102 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005103 } else if (E->getType()->isAnyComplexType()) {
5104 ComplexValue C;
5105 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005106 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005107 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005108 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005109 MemberPtr P;
5110 if (!EvaluateMemberPointer(E, P, Info))
5111 return false;
5112 P.moveInto(Result);
5113 return true;
Richard Smitheba05b22011-12-25 20:00:17 +00005114 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005115 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005116 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005117 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005118 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005119 Result = Info.CurrentCall->Temporaries[E];
Richard Smitheba05b22011-12-25 20:00:17 +00005120 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005121 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005122 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005123 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5124 return false;
5125 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005126 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005127 if (Info.getLangOpts().CPlusPlus0x)
5128 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5129 << E->getType();
5130 else
5131 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005132 if (!EvaluateVoid(E, Info))
5133 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005134 } else if (Info.getLangOpts().CPlusPlus0x) {
5135 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5136 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005137 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005138 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005139 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005140 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005141
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005142 return true;
5143}
5144
Richard Smith69c2c502011-11-04 05:33:44 +00005145/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5146/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5147/// since later initializers for an object can indirectly refer to subobjects
5148/// which were initialized earlier.
5149static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005150 const LValue &This, const Expr *E,
5151 CheckConstantExpressionKind CCEK) {
Richard Smitheba05b22011-12-25 20:00:17 +00005152 if (!CheckLiteralType(Info, E))
5153 return false;
5154
5155 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005156 // Evaluate arrays and record types in-place, so that later initializers can
5157 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005158 if (E->getType()->isArrayType())
5159 return EvaluateArray(E, This, Result, Info);
5160 else if (E->getType()->isRecordType())
5161 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005162 }
5163
5164 // For any other type, in-place evaluation is unimportant.
5165 CCValue CoreConstResult;
5166 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005167 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005168}
5169
Richard Smithf48fdb02011-12-09 22:58:01 +00005170/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5171/// lvalue-to-rvalue cast if it is an lvalue.
5172static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smitheba05b22011-12-25 20:00:17 +00005173 if (!CheckLiteralType(Info, E))
5174 return false;
5175
Richard Smithf48fdb02011-12-09 22:58:01 +00005176 CCValue Value;
5177 if (!::Evaluate(Value, Info, E))
5178 return false;
5179
5180 if (E->isGLValue()) {
5181 LValue LV;
5182 LV.setFrom(Value);
5183 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5184 return false;
5185 }
5186
5187 // Check this core constant expression is a constant expression, and if so,
5188 // convert it to one.
5189 return CheckConstantExpression(Info, E, Value, Result);
5190}
Richard Smithc49bd112011-10-28 17:51:58 +00005191
Richard Smith51f47082011-10-29 00:50:52 +00005192/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005193/// any crazy technique (that has nothing to do with language standards) that
5194/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005195/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5196/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005197bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005198 // Fast-path evaluations of integer literals, since we sometimes see files
5199 // containing vast quantities of these.
5200 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5201 Result.Val = APValue(APSInt(L->getValue(),
5202 L->getType()->isUnsignedIntegerType()));
5203 return true;
5204 }
5205
Richard Smith1445bba2011-11-10 03:30:42 +00005206 // FIXME: Evaluating initializers for large arrays can cause performance
5207 // problems, and we don't use such values yet. Once we have a more efficient
5208 // array representation, this should be reinstated, and used by CodeGen.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005209 // The same problem affects large records.
5210 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5211 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005212 return false;
5213
Richard Smith180f4792011-11-10 06:34:14 +00005214 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf48fdb02011-12-09 22:58:01 +00005215 EvalInfo Info(Ctx, Result);
5216 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005217}
5218
Jay Foad4ba2a172011-01-12 09:06:06 +00005219bool Expr::EvaluateAsBooleanCondition(bool &Result,
5220 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005221 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005222 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00005223 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005224 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005225}
5226
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005227bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005228 EvalResult ExprResult;
Richard Smith51f47082011-10-29 00:50:52 +00005229 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf48fdb02011-12-09 22:58:01 +00005230 !ExprResult.Val.isInt())
Richard Smithc49bd112011-10-28 17:51:58 +00005231 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005232
Richard Smithc49bd112011-10-28 17:51:58 +00005233 Result = ExprResult.Val.getInt();
5234 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005235}
5236
Jay Foad4ba2a172011-01-12 09:06:06 +00005237bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005238 EvalInfo Info(Ctx, Result);
5239
John McCallefdb83e2010-05-07 21:00:08 +00005240 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005241 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005242 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5243 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005244}
5245
Richard Smith099e7f62011-12-19 06:19:21 +00005246bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5247 const VarDecl *VD,
5248 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5249 Expr::EvalStatus EStatus;
5250 EStatus.Diag = &Notes;
5251
5252 EvalInfo InitInfo(Ctx, EStatus);
5253 InitInfo.setEvaluatingDecl(VD, Value);
5254
Richard Smitheba05b22011-12-25 20:00:17 +00005255 if (!CheckLiteralType(InitInfo, this))
5256 return false;
5257
Richard Smith099e7f62011-12-19 06:19:21 +00005258 LValue LVal;
5259 LVal.set(VD);
5260
Richard Smitheba05b22011-12-25 20:00:17 +00005261 // C++11 [basic.start.init]p2:
5262 // Variables with static storage duration or thread storage duration shall be
5263 // zero-initialized before any other initialization takes place.
5264 // This behavior is not present in C.
5265 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5266 !VD->getType()->isReferenceType()) {
5267 ImplicitValueInitExpr VIE(VD->getType());
5268 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5269 return false;
5270 }
5271
Richard Smith099e7f62011-12-19 06:19:21 +00005272 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5273 !EStatus.HasSideEffects;
5274}
5275
Richard Smith51f47082011-10-29 00:50:52 +00005276/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5277/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005278bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005279 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005280 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005281}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005282
Jay Foad4ba2a172011-01-12 09:06:06 +00005283bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005284 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005285}
5286
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005287APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005288 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005289 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005290 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005291 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005292 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005293
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005294 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005295}
John McCalld905f5a2010-05-07 05:32:02 +00005296
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005297 bool Expr::EvalResult::isGlobalLValue() const {
5298 assert(Val.isLValue());
5299 return IsGlobalLValue(Val.getLValueBase());
5300 }
5301
5302
John McCalld905f5a2010-05-07 05:32:02 +00005303/// isIntegerConstantExpr - this recursive routine will test if an expression is
5304/// an integer constant expression.
5305
5306/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5307/// comma, etc
5308///
5309/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5310/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5311/// cast+dereference.
5312
5313// CheckICE - This function does the fundamental ICE checking: the returned
5314// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5315// Note that to reduce code duplication, this helper does no evaluation
5316// itself; the caller checks whether the expression is evaluatable, and
5317// in the rare cases where CheckICE actually cares about the evaluated
5318// value, it calls into Evalute.
5319//
5320// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005321// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005322// 1: This expression is not an ICE, but if it isn't evaluated, it's
5323// a legal subexpression for an ICE. This return value is used to handle
5324// the comma operator in C99 mode.
5325// 2: This expression is not an ICE, and is not a legal subexpression for one.
5326
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005327namespace {
5328
John McCalld905f5a2010-05-07 05:32:02 +00005329struct ICEDiag {
5330 unsigned Val;
5331 SourceLocation Loc;
5332
5333 public:
5334 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5335 ICEDiag() : Val(0) {}
5336};
5337
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005338}
5339
5340static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005341
5342static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5343 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005344 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005345 !EVResult.Val.isInt()) {
5346 return ICEDiag(2, E->getLocStart());
5347 }
5348 return NoDiag();
5349}
5350
5351static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5352 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005353 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005354 return ICEDiag(2, E->getLocStart());
5355 }
5356
5357 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005358#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005359#define STMT(Node, Base) case Expr::Node##Class:
5360#define EXPR(Node, Base)
5361#include "clang/AST/StmtNodes.inc"
5362 case Expr::PredefinedExprClass:
5363 case Expr::FloatingLiteralClass:
5364 case Expr::ImaginaryLiteralClass:
5365 case Expr::StringLiteralClass:
5366 case Expr::ArraySubscriptExprClass:
5367 case Expr::MemberExprClass:
5368 case Expr::CompoundAssignOperatorClass:
5369 case Expr::CompoundLiteralExprClass:
5370 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005371 case Expr::DesignatedInitExprClass:
5372 case Expr::ImplicitValueInitExprClass:
5373 case Expr::ParenListExprClass:
5374 case Expr::VAArgExprClass:
5375 case Expr::AddrLabelExprClass:
5376 case Expr::StmtExprClass:
5377 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005378 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005379 case Expr::CXXDynamicCastExprClass:
5380 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005381 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005382 case Expr::CXXNullPtrLiteralExprClass:
5383 case Expr::CXXThisExprClass:
5384 case Expr::CXXThrowExprClass:
5385 case Expr::CXXNewExprClass:
5386 case Expr::CXXDeleteExprClass:
5387 case Expr::CXXPseudoDestructorExprClass:
5388 case Expr::UnresolvedLookupExprClass:
5389 case Expr::DependentScopeDeclRefExprClass:
5390 case Expr::CXXConstructExprClass:
5391 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005392 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005393 case Expr::CXXTemporaryObjectExprClass:
5394 case Expr::CXXUnresolvedConstructExprClass:
5395 case Expr::CXXDependentScopeMemberExprClass:
5396 case Expr::UnresolvedMemberExprClass:
5397 case Expr::ObjCStringLiteralClass:
5398 case Expr::ObjCEncodeExprClass:
5399 case Expr::ObjCMessageExprClass:
5400 case Expr::ObjCSelectorExprClass:
5401 case Expr::ObjCProtocolExprClass:
5402 case Expr::ObjCIvarRefExprClass:
5403 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005404 case Expr::ObjCIsaExprClass:
5405 case Expr::ShuffleVectorExprClass:
5406 case Expr::BlockExprClass:
5407 case Expr::BlockDeclRefExprClass:
5408 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005409 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005410 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005411 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005412 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005413 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005414 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005415 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005416 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005417 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005418 return ICEDiag(2, E->getLocStart());
5419
Douglas Gregoree8aff02011-01-04 17:33:58 +00005420 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005421 case Expr::GNUNullExprClass:
5422 // GCC considers the GNU __null value to be an integral constant expression.
5423 return NoDiag();
5424
John McCall91a57552011-07-15 05:09:51 +00005425 case Expr::SubstNonTypeTemplateParmExprClass:
5426 return
5427 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5428
John McCalld905f5a2010-05-07 05:32:02 +00005429 case Expr::ParenExprClass:
5430 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005431 case Expr::GenericSelectionExprClass:
5432 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005433 case Expr::IntegerLiteralClass:
5434 case Expr::CharacterLiteralClass:
5435 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005436 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005437 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005438 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005439 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005440 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005441 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005442 return NoDiag();
5443 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005444 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005445 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5446 // constant expressions, but they can never be ICEs because an ICE cannot
5447 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005448 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005449 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005450 return CheckEvalInICE(E, Ctx);
5451 return ICEDiag(2, E->getLocStart());
5452 }
5453 case Expr::DeclRefExprClass:
5454 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5455 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005456 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005457 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5458
5459 // Parameter variables are never constants. Without this check,
5460 // getAnyInitializer() can find a default argument, which leads
5461 // to chaos.
5462 if (isa<ParmVarDecl>(D))
5463 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5464
5465 // C++ 7.1.5.1p2
5466 // A variable of non-volatile const-qualified integral or enumeration
5467 // type initialized by an ICE can be used in ICEs.
5468 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005469 if (!Dcl->getType()->isIntegralOrEnumerationType())
5470 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5471
Richard Smith099e7f62011-12-19 06:19:21 +00005472 const VarDecl *VD;
5473 // Look for a declaration of this variable that has an initializer, and
5474 // check whether it is an ICE.
5475 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5476 return NoDiag();
5477 else
5478 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005479 }
5480 }
5481 return ICEDiag(2, E->getLocStart());
5482 case Expr::UnaryOperatorClass: {
5483 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5484 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005485 case UO_PostInc:
5486 case UO_PostDec:
5487 case UO_PreInc:
5488 case UO_PreDec:
5489 case UO_AddrOf:
5490 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005491 // C99 6.6/3 allows increment and decrement within unevaluated
5492 // subexpressions of constant expressions, but they can never be ICEs
5493 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005494 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005495 case UO_Extension:
5496 case UO_LNot:
5497 case UO_Plus:
5498 case UO_Minus:
5499 case UO_Not:
5500 case UO_Real:
5501 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005502 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005503 }
5504
5505 // OffsetOf falls through here.
5506 }
5507 case Expr::OffsetOfExprClass: {
5508 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005509 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005510 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005511 // compliance: we should warn earlier for offsetof expressions with
5512 // array subscripts that aren't ICEs, and if the array subscripts
5513 // are ICEs, the value of the offsetof must be an integer constant.
5514 return CheckEvalInICE(E, Ctx);
5515 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005516 case Expr::UnaryExprOrTypeTraitExprClass: {
5517 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5518 if ((Exp->getKind() == UETT_SizeOf) &&
5519 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005520 return ICEDiag(2, E->getLocStart());
5521 return NoDiag();
5522 }
5523 case Expr::BinaryOperatorClass: {
5524 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5525 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005526 case BO_PtrMemD:
5527 case BO_PtrMemI:
5528 case BO_Assign:
5529 case BO_MulAssign:
5530 case BO_DivAssign:
5531 case BO_RemAssign:
5532 case BO_AddAssign:
5533 case BO_SubAssign:
5534 case BO_ShlAssign:
5535 case BO_ShrAssign:
5536 case BO_AndAssign:
5537 case BO_XorAssign:
5538 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005539 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5540 // constant expressions, but they can never be ICEs because an ICE cannot
5541 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005542 return ICEDiag(2, E->getLocStart());
5543
John McCall2de56d12010-08-25 11:45:40 +00005544 case BO_Mul:
5545 case BO_Div:
5546 case BO_Rem:
5547 case BO_Add:
5548 case BO_Sub:
5549 case BO_Shl:
5550 case BO_Shr:
5551 case BO_LT:
5552 case BO_GT:
5553 case BO_LE:
5554 case BO_GE:
5555 case BO_EQ:
5556 case BO_NE:
5557 case BO_And:
5558 case BO_Xor:
5559 case BO_Or:
5560 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005561 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5562 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005563 if (Exp->getOpcode() == BO_Div ||
5564 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005565 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005566 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005567 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005568 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005569 if (REval == 0)
5570 return ICEDiag(1, E->getLocStart());
5571 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005572 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005573 if (LEval.isMinSignedValue())
5574 return ICEDiag(1, E->getLocStart());
5575 }
5576 }
5577 }
John McCall2de56d12010-08-25 11:45:40 +00005578 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005579 if (Ctx.getLangOptions().C99) {
5580 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5581 // if it isn't evaluated.
5582 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5583 return ICEDiag(1, E->getLocStart());
5584 } else {
5585 // In both C89 and C++, commas in ICEs are illegal.
5586 return ICEDiag(2, E->getLocStart());
5587 }
5588 }
5589 if (LHSResult.Val >= RHSResult.Val)
5590 return LHSResult;
5591 return RHSResult;
5592 }
John McCall2de56d12010-08-25 11:45:40 +00005593 case BO_LAnd:
5594 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005595 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5596 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5597 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5598 // Rare case where the RHS has a comma "side-effect"; we need
5599 // to actually check the condition to see whether the side
5600 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005601 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005602 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005603 return RHSResult;
5604 return NoDiag();
5605 }
5606
5607 if (LHSResult.Val >= RHSResult.Val)
5608 return LHSResult;
5609 return RHSResult;
5610 }
5611 }
5612 }
5613 case Expr::ImplicitCastExprClass:
5614 case Expr::CStyleCastExprClass:
5615 case Expr::CXXFunctionalCastExprClass:
5616 case Expr::CXXStaticCastExprClass:
5617 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005618 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005619 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005620 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00005621 if (isa<ExplicitCastExpr>(E)) {
5622 if (const FloatingLiteral *FL
5623 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5624 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5625 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5626 APSInt IgnoredVal(DestWidth, !DestSigned);
5627 bool Ignored;
5628 // If the value does not fit in the destination type, the behavior is
5629 // undefined, so we are not required to treat it as a constant
5630 // expression.
5631 if (FL->getValue().convertToInteger(IgnoredVal,
5632 llvm::APFloat::rmTowardZero,
5633 &Ignored) & APFloat::opInvalidOp)
5634 return ICEDiag(2, E->getLocStart());
5635 return NoDiag();
5636 }
5637 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00005638 switch (cast<CastExpr>(E)->getCastKind()) {
5639 case CK_LValueToRValue:
5640 case CK_NoOp:
5641 case CK_IntegralToBoolean:
5642 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00005643 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00005644 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005645 return ICEDiag(2, E->getLocStart());
5646 }
John McCalld905f5a2010-05-07 05:32:02 +00005647 }
John McCall56ca35d2011-02-17 10:25:35 +00005648 case Expr::BinaryConditionalOperatorClass: {
5649 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5650 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5651 if (CommonResult.Val == 2) return CommonResult;
5652 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5653 if (FalseResult.Val == 2) return FalseResult;
5654 if (CommonResult.Val == 1) return CommonResult;
5655 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005656 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00005657 return FalseResult;
5658 }
John McCalld905f5a2010-05-07 05:32:02 +00005659 case Expr::ConditionalOperatorClass: {
5660 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5661 // If the condition (ignoring parens) is a __builtin_constant_p call,
5662 // then only the true side is actually considered in an integer constant
5663 // expression, and it is fully evaluated. This is an important GNU
5664 // extension. See GCC PR38377 for discussion.
5665 if (const CallExpr *CallCE
5666 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith180f4792011-11-10 06:34:14 +00005667 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCalld905f5a2010-05-07 05:32:02 +00005668 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005669 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005670 !EVResult.Val.isInt()) {
5671 return ICEDiag(2, E->getLocStart());
5672 }
5673 return NoDiag();
5674 }
5675 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005676 if (CondResult.Val == 2)
5677 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00005678
Richard Smithf48fdb02011-12-09 22:58:01 +00005679 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5680 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00005681
John McCalld905f5a2010-05-07 05:32:02 +00005682 if (TrueResult.Val == 2)
5683 return TrueResult;
5684 if (FalseResult.Val == 2)
5685 return FalseResult;
5686 if (CondResult.Val == 1)
5687 return CondResult;
5688 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5689 return NoDiag();
5690 // Rare case where the diagnostics depend on which side is evaluated
5691 // Note that if we get here, CondResult is 0, and at least one of
5692 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005693 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00005694 return FalseResult;
5695 }
5696 return TrueResult;
5697 }
5698 case Expr::CXXDefaultArgExprClass:
5699 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5700 case Expr::ChooseExprClass: {
5701 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5702 }
5703 }
5704
5705 // Silence a GCC warning
5706 return ICEDiag(2, E->getLocStart());
5707}
5708
Richard Smithf48fdb02011-12-09 22:58:01 +00005709/// Evaluate an expression as a C++11 integral constant expression.
5710static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5711 const Expr *E,
5712 llvm::APSInt *Value,
5713 SourceLocation *Loc) {
5714 if (!E->getType()->isIntegralOrEnumerationType()) {
5715 if (Loc) *Loc = E->getExprLoc();
5716 return false;
5717 }
5718
5719 Expr::EvalResult Result;
Richard Smithdd1f29b2011-12-12 09:28:41 +00005720 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5721 Result.Diag = &Diags;
5722 EvalInfo Info(Ctx, Result);
5723
5724 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5725 if (!Diags.empty()) {
5726 IsICE = false;
5727 if (Loc) *Loc = Diags[0].first;
5728 } else if (!IsICE && Loc) {
5729 *Loc = E->getExprLoc();
Richard Smithf48fdb02011-12-09 22:58:01 +00005730 }
Richard Smithdd1f29b2011-12-12 09:28:41 +00005731
5732 if (!IsICE)
5733 return false;
5734
5735 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5736 if (Value) *Value = Result.Val.getInt();
5737 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00005738}
5739
Richard Smithdd1f29b2011-12-12 09:28:41 +00005740bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00005741 if (Ctx.getLangOptions().CPlusPlus0x)
5742 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5743
John McCalld905f5a2010-05-07 05:32:02 +00005744 ICEDiag d = CheckICE(this, Ctx);
5745 if (d.Val != 0) {
5746 if (Loc) *Loc = d.Loc;
5747 return false;
5748 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005749 return true;
5750}
5751
5752bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5753 SourceLocation *Loc, bool isEvaluated) const {
5754 if (Ctx.getLangOptions().CPlusPlus0x)
5755 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5756
5757 if (!isIntegerConstantExpr(Ctx, Loc))
5758 return false;
5759 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00005760 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00005761 return true;
5762}