blob: 0d32ebf1c67718074652676500b5d19f45e54c71 [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 Smithc1c5f272011-12-13 06:39:58 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
348 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000349 // If we have a prior diagnostic, it will be noting that the expression
350 // isn't a constant expression. This diagnostic is more important.
351 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000352 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000353 unsigned CallStackNotes = CallStackDepth - 1;
354 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
355 if (Limit)
356 CallStackNotes = std::min(CallStackNotes, Limit + 1);
357
Richard Smithc1c5f272011-12-13 06:39:58 +0000358 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000359 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000360 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
361 addDiag(Loc, DiagId);
362 addCallStack(Limit);
363 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000364 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000365 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000366 return OptionalDiagnostic();
367 }
368
369 /// Diagnose that the evaluation does not produce a C++11 core constant
370 /// expression.
Richard Smithc1c5f272011-12-13 06:39:58 +0000371 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId,
372 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000373 // Don't override a previous diagnostic.
374 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
375 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000376 return Diag(Loc, DiagId, ExtraNotes);
377 }
378
379 /// Add a note to a prior diagnostic.
380 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
381 if (!HasActiveDiagnostic)
382 return OptionalDiagnostic();
383 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000384 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000385 };
Richard Smith08d6e032011-12-16 19:06:07 +0000386}
Richard Smithbd552ef2011-10-31 05:52:43 +0000387
Richard Smith08d6e032011-12-16 19:06:07 +0000388CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
389 const FunctionDecl *Callee, const LValue *This,
390 const CCValue *Arguments)
391 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
392 This(This), Arguments(Arguments) {
393 Info.CurrentCall = this;
394 ++Info.CallStackDepth;
395}
396
397CallStackFrame::~CallStackFrame() {
398 assert(Info.CurrentCall == this && "calls retired out of order");
399 --Info.CallStackDepth;
400 Info.CurrentCall = Caller;
401}
402
403/// Produce a string describing the given constexpr call.
404static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
405 unsigned ArgIndex = 0;
406 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
407 !isa<CXXConstructorDecl>(Frame->Callee);
408
409 if (!IsMemberCall)
410 Out << *Frame->Callee << '(';
411
412 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
413 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
414 if (ArgIndex > IsMemberCall)
415 Out << ", ";
416
417 const ParmVarDecl *Param = *I;
418 const CCValue &Arg = Frame->Arguments[ArgIndex];
419 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
420 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
421 else {
422 // Deliberately slice off the frame to form an APValue we can print.
423 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
424 Arg.getLValueDesignator().Entries,
425 Arg.getLValueDesignator().OnePastTheEnd);
426 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
427 }
428
429 if (ArgIndex == 0 && IsMemberCall)
430 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000431 }
432
Richard Smith08d6e032011-12-16 19:06:07 +0000433 Out << ')';
434}
435
436void EvalInfo::addCallStack(unsigned Limit) {
437 // Determine which calls to skip, if any.
438 unsigned ActiveCalls = CallStackDepth - 1;
439 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
440 if (Limit && Limit < ActiveCalls) {
441 SkipStart = Limit / 2 + Limit % 2;
442 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000443 }
444
Richard Smith08d6e032011-12-16 19:06:07 +0000445 // Walk the call stack and add the diagnostics.
446 unsigned CallIdx = 0;
447 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
448 Frame = Frame->Caller, ++CallIdx) {
449 // Skip this call?
450 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
451 if (CallIdx == SkipStart) {
452 // Note that we're skipping calls.
453 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
454 << unsigned(ActiveCalls - Limit);
455 }
456 continue;
457 }
458
459 llvm::SmallVector<char, 128> Buffer;
460 llvm::raw_svector_ostream Out(Buffer);
461 describeCall(Frame, Out);
462 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
463 }
464}
465
466namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000467 struct ComplexValue {
468 private:
469 bool IsInt;
470
471 public:
472 APSInt IntReal, IntImag;
473 APFloat FloatReal, FloatImag;
474
475 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
476
477 void makeComplexFloat() { IsInt = false; }
478 bool isComplexFloat() const { return !IsInt; }
479 APFloat &getComplexFloatReal() { return FloatReal; }
480 APFloat &getComplexFloatImag() { return FloatImag; }
481
482 void makeComplexInt() { IsInt = true; }
483 bool isComplexInt() const { return IsInt; }
484 APSInt &getComplexIntReal() { return IntReal; }
485 APSInt &getComplexIntImag() { return IntImag; }
486
Richard Smith47a1eed2011-10-29 20:57:55 +0000487 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000488 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000489 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000490 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000491 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000492 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000493 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000494 assert(v.isComplexFloat() || v.isComplexInt());
495 if (v.isComplexFloat()) {
496 makeComplexFloat();
497 FloatReal = v.getComplexFloatReal();
498 FloatImag = v.getComplexFloatImag();
499 } else {
500 makeComplexInt();
501 IntReal = v.getComplexIntReal();
502 IntImag = v.getComplexIntImag();
503 }
504 }
John McCallf4cf1a12010-05-07 17:22:02 +0000505 };
John McCallefdb83e2010-05-07 21:00:08 +0000506
507 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000508 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000509 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000510 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000511 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000512
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000513 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000514 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000515 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000516 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000517 SubobjectDesignator &getLValueDesignator() { return Designator; }
518 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000519
Richard Smith47a1eed2011-10-29 20:57:55 +0000520 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000521 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000522 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000523 void setFrom(const CCValue &V) {
524 assert(V.isLValue());
525 Base = V.getLValueBase();
526 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000527 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000528 Designator = V.getLValueDesignator();
529 }
530
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000531 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
532 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000533 Offset = CharUnits::Zero();
534 Frame = F;
535 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000536 }
John McCallefdb83e2010-05-07 21:00:08 +0000537 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000538
539 struct MemberPtr {
540 MemberPtr() {}
541 explicit MemberPtr(const ValueDecl *Decl) :
542 DeclAndIsDerivedMember(Decl, false), Path() {}
543
544 /// The member or (direct or indirect) field referred to by this member
545 /// pointer, or 0 if this is a null member pointer.
546 const ValueDecl *getDecl() const {
547 return DeclAndIsDerivedMember.getPointer();
548 }
549 /// Is this actually a member of some type derived from the relevant class?
550 bool isDerivedMember() const {
551 return DeclAndIsDerivedMember.getInt();
552 }
553 /// Get the class which the declaration actually lives in.
554 const CXXRecordDecl *getContainingRecord() const {
555 return cast<CXXRecordDecl>(
556 DeclAndIsDerivedMember.getPointer()->getDeclContext());
557 }
558
559 void moveInto(CCValue &V) const {
560 V = CCValue(getDecl(), isDerivedMember(), Path);
561 }
562 void setFrom(const CCValue &V) {
563 assert(V.isMemberPointer());
564 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
565 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
566 Path.clear();
567 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
568 Path.insert(Path.end(), P.begin(), P.end());
569 }
570
571 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
572 /// whether the member is a member of some class derived from the class type
573 /// of the member pointer.
574 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
575 /// Path - The path of base/derived classes from the member declaration's
576 /// class (exclusive) to the class type of the member pointer (inclusive).
577 SmallVector<const CXXRecordDecl*, 4> Path;
578
579 /// Perform a cast towards the class of the Decl (either up or down the
580 /// hierarchy).
581 bool castBack(const CXXRecordDecl *Class) {
582 assert(!Path.empty());
583 const CXXRecordDecl *Expected;
584 if (Path.size() >= 2)
585 Expected = Path[Path.size() - 2];
586 else
587 Expected = getContainingRecord();
588 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
589 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
590 // if B does not contain the original member and is not a base or
591 // derived class of the class containing the original member, the result
592 // of the cast is undefined.
593 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
594 // (D::*). We consider that to be a language defect.
595 return false;
596 }
597 Path.pop_back();
598 return true;
599 }
600 /// Perform a base-to-derived member pointer cast.
601 bool castToDerived(const CXXRecordDecl *Derived) {
602 if (!getDecl())
603 return true;
604 if (!isDerivedMember()) {
605 Path.push_back(Derived);
606 return true;
607 }
608 if (!castBack(Derived))
609 return false;
610 if (Path.empty())
611 DeclAndIsDerivedMember.setInt(false);
612 return true;
613 }
614 /// Perform a derived-to-base member pointer cast.
615 bool castToBase(const CXXRecordDecl *Base) {
616 if (!getDecl())
617 return true;
618 if (Path.empty())
619 DeclAndIsDerivedMember.setInt(true);
620 if (isDerivedMember()) {
621 Path.push_back(Base);
622 return true;
623 }
624 return castBack(Base);
625 }
626 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000627
628 /// Kinds of constant expression checking, for diagnostics.
629 enum CheckConstantExpressionKind {
630 CCEK_Constant, ///< A normal constant.
631 CCEK_ReturnValue, ///< A constexpr function return value.
632 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
633 };
John McCallf4cf1a12010-05-07 17:22:02 +0000634}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000635
Richard Smith47a1eed2011-10-29 20:57:55 +0000636static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000637static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000638 const LValue &This, const Expr *E,
639 CheckConstantExpressionKind CCEK
640 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000641static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
642static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000643static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
644 EvalInfo &Info);
645static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000646static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000647static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000648 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000649static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000650static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000651
652//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000653// Misc utilities
654//===----------------------------------------------------------------------===//
655
Richard Smith180f4792011-11-10 06:34:14 +0000656/// Should this call expression be treated as a string literal?
657static bool IsStringLiteralCall(const CallExpr *E) {
658 unsigned Builtin = E->isBuiltinCall();
659 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
660 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
661}
662
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000663static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000664 // C++11 [expr.const]p3 An address constant expression is a prvalue core
665 // constant expression of pointer type that evaluates to...
666
667 // ... a null pointer value, or a prvalue core constant expression of type
668 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000669 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000670
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000671 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
672 // ... the address of an object with static storage duration,
673 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
674 return VD->hasGlobalStorage();
675 // ... the address of a function,
676 return isa<FunctionDecl>(D);
677 }
678
679 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000680 switch (E->getStmtClass()) {
681 default:
682 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000683 case Expr::CompoundLiteralExprClass:
684 return cast<CompoundLiteralExpr>(E)->isFileScope();
685 // A string literal has static storage duration.
686 case Expr::StringLiteralClass:
687 case Expr::PredefinedExprClass:
688 case Expr::ObjCStringLiteralClass:
689 case Expr::ObjCEncodeExprClass:
690 return true;
691 case Expr::CallExprClass:
692 return IsStringLiteralCall(cast<CallExpr>(E));
693 // For GCC compatibility, &&label has static storage duration.
694 case Expr::AddrLabelExprClass:
695 return true;
696 // A Block literal expression may be used as the initialization value for
697 // Block variables at global or local static scope.
698 case Expr::BlockExprClass:
699 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
700 }
John McCall42c8f872010-05-10 23:27:23 +0000701}
702
Richard Smith9a17a682011-11-07 05:07:52 +0000703/// Check that this reference or pointer core constant expression is a valid
704/// value for a constant expression. Type T should be either LValue or CCValue.
705template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000706static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000707 const T &LVal, APValue &Value,
708 CheckConstantExpressionKind CCEK) {
709 APValue::LValueBase Base = LVal.getLValueBase();
710 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
711
712 if (!IsGlobalLValue(Base)) {
713 if (Info.getLangOpts().CPlusPlus0x) {
714 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
715 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
716 << E->isGLValue() << !Designator.Entries.empty()
717 << !!VD << CCEK << VD;
718 if (VD)
719 Info.Note(VD->getLocation(), diag::note_declared_at);
720 else
721 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
722 diag::note_constexpr_temporary_here);
723 } else {
724 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
725 }
Richard Smith9a17a682011-11-07 05:07:52 +0000726 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000727 }
Richard Smith9a17a682011-11-07 05:07:52 +0000728
Richard Smith9a17a682011-11-07 05:07:52 +0000729 // A constant expression must refer to an object or be a null pointer.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000730 if (Designator.Invalid ||
Richard Smith9a17a682011-11-07 05:07:52 +0000731 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000732 // FIXME: This is not a core constant expression. We should have already
733 // produced a CCE diagnostic.
Richard Smith9a17a682011-11-07 05:07:52 +0000734 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
735 APValue::NoLValuePath());
736 return true;
737 }
738
Richard Smithc1c5f272011-12-13 06:39:58 +0000739 // Does this refer one past the end of some object?
740 // This is technically not an address constant expression nor a reference
741 // constant expression, but we allow it for address constant expressions.
742 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
743 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
744 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
745 << !Designator.Entries.empty() << !!VD << VD;
746 if (VD)
747 Info.Note(VD->getLocation(), diag::note_declared_at);
748 else
749 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
750 diag::note_constexpr_temporary_here);
751 return false;
752 }
753
Richard Smith9a17a682011-11-07 05:07:52 +0000754 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smithe24f5fc2011-11-17 22:56:20 +0000755 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith9a17a682011-11-07 05:07:52 +0000756 return true;
757}
758
Richard Smith47a1eed2011-10-29 20:57:55 +0000759/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000760/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf48fdb02011-12-09 22:58:01 +0000761/// If not, report an appropriate diagnostic.
762static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000763 const CCValue &CCValue, APValue &Value,
764 CheckConstantExpressionKind CCEK
765 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000766 if (!CCValue.isLValue()) {
767 Value = CCValue;
768 return true;
769 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000770 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000771}
772
Richard Smith9e36b532011-10-31 05:11:32 +0000773const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000774 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000775}
776
777static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000778 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000779}
780
Richard Smith65ac5982011-11-01 21:06:14 +0000781static bool IsWeakLValue(const LValue &Value) {
782 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000783 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000784}
785
Richard Smithe24f5fc2011-11-17 22:56:20 +0000786static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000787 // A null base expression indicates a null pointer. These are always
788 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000789 if (!Value.getLValueBase()) {
790 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000791 return true;
792 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000793
John McCall42c8f872010-05-10 23:27:23 +0000794 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000795 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000796 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall42c8f872010-05-10 23:27:23 +0000797
Richard Smithe24f5fc2011-11-17 22:56:20 +0000798 // We have a non-null base. These are generally known to be true, but if it's
799 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000800 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000801 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +0000802 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +0000803}
804
Richard Smith47a1eed2011-10-29 20:57:55 +0000805static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000806 switch (Val.getKind()) {
807 case APValue::Uninitialized:
808 return false;
809 case APValue::Int:
810 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000811 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000812 case APValue::Float:
813 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000814 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000815 case APValue::ComplexInt:
816 Result = Val.getComplexIntReal().getBoolValue() ||
817 Val.getComplexIntImag().getBoolValue();
818 return true;
819 case APValue::ComplexFloat:
820 Result = !Val.getComplexFloatReal().isZero() ||
821 !Val.getComplexFloatImag().isZero();
822 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000823 case APValue::LValue:
824 return EvalPointerValueAsBool(Val, Result);
825 case APValue::MemberPointer:
826 Result = Val.getMemberPointerDecl();
827 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000828 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000829 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000830 case APValue::Struct:
831 case APValue::Union:
Richard Smithc49bd112011-10-28 17:51:58 +0000832 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000833 }
834
Richard Smithc49bd112011-10-28 17:51:58 +0000835 llvm_unreachable("unknown APValue kind");
836}
837
838static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
839 EvalInfo &Info) {
840 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000841 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000842 if (!Evaluate(Val, Info, E))
843 return false;
844 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000845}
846
Richard Smithc1c5f272011-12-13 06:39:58 +0000847template<typename T>
848static bool HandleOverflow(EvalInfo &Info, const Expr *E,
849 const T &SrcValue, QualType DestType) {
850 llvm::SmallVector<char, 32> Buffer;
851 SrcValue.toString(Buffer);
852 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
853 << StringRef(Buffer.data(), Buffer.size()) << DestType;
854 return false;
855}
856
857static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
858 QualType SrcType, const APFloat &Value,
859 QualType DestType, APSInt &Result) {
860 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000861 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000862 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Richard Smithc1c5f272011-12-13 06:39:58 +0000864 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000865 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000866 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
867 & APFloat::opInvalidOp)
868 return HandleOverflow(Info, E, Value, DestType);
869 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000870}
871
Richard Smithc1c5f272011-12-13 06:39:58 +0000872static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
873 QualType SrcType, QualType DestType,
874 APFloat &Result) {
875 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000876 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000877 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
878 APFloat::rmNearestTiesToEven, &ignored)
879 & APFloat::opOverflow)
880 return HandleOverflow(Info, E, Value, DestType);
881 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000882}
883
Mike Stump1eb44332009-09-09 15:08:12 +0000884static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000885 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000886 unsigned DestWidth = Ctx.getIntWidth(DestType);
887 APSInt Result = Value;
888 // Figure out if this is a truncate, extend or noop cast.
889 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000890 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000891 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000892 return Result;
893}
894
Richard Smithc1c5f272011-12-13 06:39:58 +0000895static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
896 QualType SrcType, const APSInt &Value,
897 QualType DestType, APFloat &Result) {
898 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
899 if (Result.convertFromAPInt(Value, Value.isSigned(),
900 APFloat::rmNearestTiesToEven)
901 & APFloat::opOverflow)
902 return HandleOverflow(Info, E, Value, DestType);
903 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000904}
905
Richard Smithe24f5fc2011-11-17 22:56:20 +0000906static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
907 const CXXRecordDecl *&MostDerivedType,
908 unsigned &MostDerivedPathLength,
909 bool &MostDerivedIsArrayElement) {
910 const SubobjectDesignator &D = LVal.Designator;
911 if (D.Invalid || !LVal.Base)
Richard Smith180f4792011-11-10 06:34:14 +0000912 return false;
913
Richard Smithe24f5fc2011-11-17 22:56:20 +0000914 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smith180f4792011-11-10 06:34:14 +0000915
916 // Find path prefix which leads to the most-derived subobject.
Richard Smith180f4792011-11-10 06:34:14 +0000917 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +0000918 MostDerivedPathLength = 0;
919 MostDerivedIsArrayElement = false;
Richard Smith180f4792011-11-10 06:34:14 +0000920
921 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
922 bool IsArray = T && T->isArrayType();
923 if (IsArray)
924 T = T->getBaseElementTypeUnsafe();
925 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
926 T = FD->getType().getTypePtr();
927 else
928 T = 0;
929
930 if (T) {
931 MostDerivedType = T->getAsCXXRecordDecl();
932 MostDerivedPathLength = I + 1;
933 MostDerivedIsArrayElement = IsArray;
934 }
935 }
936
Richard Smith180f4792011-11-10 06:34:14 +0000937 // (B*)&d + 1 has no most-derived object.
938 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
939 return false;
940
Richard Smithe24f5fc2011-11-17 22:56:20 +0000941 return MostDerivedType != 0;
942}
943
944static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
945 const RecordDecl *TruncatedType,
946 unsigned TruncatedElements,
947 bool IsArrayElement) {
948 SubobjectDesignator &D = Result.Designator;
949 const RecordDecl *RD = TruncatedType;
950 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +0000951 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
952 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000953 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +0000954 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000955 else
Richard Smith180f4792011-11-10 06:34:14 +0000956 Result.Offset -= Layout.getBaseClassOffset(Base);
957 RD = Base;
958 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000959 D.Entries.resize(TruncatedElements);
960 D.ArrayElement = IsArrayElement;
961}
962
963/// If the given LValue refers to a base subobject of some object, find the most
964/// derived object and the corresponding complete record type. This is necessary
965/// in order to find the offset of a virtual base class.
966static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
967 const CXXRecordDecl *&MostDerivedType) {
968 unsigned MostDerivedPathLength;
969 bool MostDerivedIsArrayElement;
970 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
971 MostDerivedPathLength, MostDerivedIsArrayElement))
972 return false;
973
974 // Remove the trailing base class path entries and their offsets.
975 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
976 MostDerivedIsArrayElement);
Richard Smith180f4792011-11-10 06:34:14 +0000977 return true;
978}
979
980static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
981 const CXXRecordDecl *Derived,
982 const CXXRecordDecl *Base,
983 const ASTRecordLayout *RL = 0) {
984 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
985 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
986 Obj.Designator.addDecl(Base, /*Virtual*/ false);
987}
988
989static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
990 const CXXRecordDecl *DerivedDecl,
991 const CXXBaseSpecifier *Base) {
992 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
993
994 if (!Base->isVirtual()) {
995 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
996 return true;
997 }
998
999 // Extract most-derived object and corresponding type.
1000 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1001 return false;
1002
1003 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1004 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1005 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1006 return true;
1007}
1008
1009/// Update LVal to refer to the given field, which must be a member of the type
1010/// currently described by LVal.
1011static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1012 const FieldDecl *FD,
1013 const ASTRecordLayout *RL = 0) {
1014 if (!RL)
1015 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1016
1017 unsigned I = FD->getFieldIndex();
1018 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1019 LVal.Designator.addDecl(FD);
1020}
1021
1022/// Get the size of the given type in char units.
1023static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1024 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1025 // extension.
1026 if (Type->isVoidType() || Type->isFunctionType()) {
1027 Size = CharUnits::One();
1028 return true;
1029 }
1030
1031 if (!Type->isConstantSizeType()) {
1032 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1033 return false;
1034 }
1035
1036 Size = Info.Ctx.getTypeSizeInChars(Type);
1037 return true;
1038}
1039
1040/// Update a pointer value to model pointer arithmetic.
1041/// \param Info - Information about the ongoing evaluation.
1042/// \param LVal - The pointer value to be updated.
1043/// \param EltTy - The pointee type represented by LVal.
1044/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1045static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1046 QualType EltTy, int64_t Adjustment) {
1047 CharUnits SizeOfPointee;
1048 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1049 return false;
1050
1051 // Compute the new offset in the appropriate width.
1052 LVal.Offset += Adjustment * SizeOfPointee;
1053 LVal.Designator.adjustIndex(Adjustment);
1054 return true;
1055}
1056
Richard Smith03f96112011-10-24 17:54:18 +00001057/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001058static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1059 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001060 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001061 // If this is a parameter to an active constexpr function call, perform
1062 // argument substitution.
1063 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001064 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001065 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001066 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001067 }
Richard Smith177dce72011-11-01 16:57:24 +00001068 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1069 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001070 }
Richard Smith03f96112011-10-24 17:54:18 +00001071
Richard Smith180f4792011-11-10 06:34:14 +00001072 // If we're currently evaluating the initializer of this declaration, use that
1073 // in-flight value.
1074 if (Info.EvaluatingDecl == VD) {
1075 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1076 return !Result.isUninit();
1077 }
1078
Richard Smith65ac5982011-11-01 21:06:14 +00001079 // Never evaluate the initializer of a weak variable. We can't be sure that
1080 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001081 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001082 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001083 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001084 }
Richard Smith65ac5982011-11-01 21:06:14 +00001085
Richard Smith03f96112011-10-24 17:54:18 +00001086 const Expr *Init = VD->getAnyInitializer();
Richard Smithf48fdb02011-12-09 22:58:01 +00001087 if (!Init || Init->isValueDependent()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001088 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith47a1eed2011-10-29 20:57:55 +00001089 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001090 }
Richard Smith03f96112011-10-24 17:54:18 +00001091
Richard Smith47a1eed2011-10-29 20:57:55 +00001092 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smith177dce72011-11-01 16:57:24 +00001093 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001094 return !Result.isUninit();
1095 }
Richard Smith03f96112011-10-24 17:54:18 +00001096
Richard Smithf48fdb02011-12-09 22:58:01 +00001097 if (VD->isEvaluatingValue()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001098 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith47a1eed2011-10-29 20:57:55 +00001099 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001100 }
Richard Smith03f96112011-10-24 17:54:18 +00001101
1102 VD->setEvaluatingValue();
1103
Richard Smith47a1eed2011-10-29 20:57:55 +00001104 Expr::EvalStatus EStatus;
1105 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith180f4792011-11-10 06:34:14 +00001106 APValue EvalResult;
1107 InitInfo.setEvaluatingDecl(VD, EvalResult);
1108 LValue LVal;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001109 LVal.set(VD);
Richard Smithc49bd112011-10-28 17:51:58 +00001110 // FIXME: The caller will need to know whether the value was a constant
1111 // expression. If not, we should propagate up a diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001112 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001113 // FIXME: If the evaluation failure was not permanent (for instance, if we
1114 // hit a variable with no declaration yet, or a constexpr function with no
1115 // definition yet), the standard is unclear as to how we should behave.
1116 //
1117 // Either the initializer should be evaluated when the variable is defined,
1118 // or a failed evaluation of the initializer should be reattempted each time
1119 // it is used.
Richard Smith03f96112011-10-24 17:54:18 +00001120 VD->setEvaluatedValue(APValue());
Richard Smithdd1f29b2011-12-12 09:28:41 +00001121 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith47a1eed2011-10-29 20:57:55 +00001122 return false;
1123 }
Richard Smith03f96112011-10-24 17:54:18 +00001124
Richard Smith69c2c502011-11-04 05:33:44 +00001125 VD->setEvaluatedValue(EvalResult);
1126 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001127 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001128}
1129
Richard Smithc49bd112011-10-28 17:51:58 +00001130static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001131 Qualifiers Quals = T.getQualifiers();
1132 return Quals.hasConst() && !Quals.hasVolatile();
1133}
1134
Richard Smith59efe262011-11-11 04:05:33 +00001135/// Get the base index of the given base class within an APValue representing
1136/// the given derived class.
1137static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1138 const CXXRecordDecl *Base) {
1139 Base = Base->getCanonicalDecl();
1140 unsigned Index = 0;
1141 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1142 E = Derived->bases_end(); I != E; ++I, ++Index) {
1143 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1144 return Index;
1145 }
1146
1147 llvm_unreachable("base class missing from derived class's bases list");
1148}
1149
Richard Smithcc5d4f62011-11-07 09:22:26 +00001150/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001151static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1152 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001153 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001154 if (Sub.Invalid || Sub.OnePastTheEnd) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001155 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001156 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001157 }
Richard Smithf64699e2011-11-11 08:28:03 +00001158 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001159 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001160
1161 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1162 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001163 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001164 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001165 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001166 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001167 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001168 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001169 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001170 if (CAT->getSize().ule(Index)) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001171 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001172 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001173 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001174 if (O->getArrayInitializedElts() > Index)
1175 O = &O->getArrayInitializedElt(Index);
1176 else
1177 O = &O->getArrayFiller();
1178 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001179 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1180 // Next subobject is a class, struct or union field.
1181 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1182 if (RD->isUnion()) {
1183 const FieldDecl *UnionField = O->getUnionField();
1184 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001185 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001186 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001187 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001188 }
Richard Smith180f4792011-11-10 06:34:14 +00001189 O = &O->getUnionValue();
1190 } else
1191 O = &O->getStructField(Field->getFieldIndex());
1192 ObjType = Field->getType();
Richard Smithcc5d4f62011-11-07 09:22:26 +00001193 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001194 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001195 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1196 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1197 O = &O->getStructBase(getBaseIndex(Derived, Base));
1198 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001199 }
Richard Smith180f4792011-11-10 06:34:14 +00001200
Richard Smithf48fdb02011-12-09 22:58:01 +00001201 if (O->isUninit()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001202 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001203 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001204 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001205 }
1206
Richard Smithcc5d4f62011-11-07 09:22:26 +00001207 Obj = CCValue(*O, CCValue::GlobalValue());
1208 return true;
1209}
1210
Richard Smith180f4792011-11-10 06:34:14 +00001211/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1212/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1213/// for looking up the glvalue referred to by an entity of reference type.
1214///
1215/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001216/// \param Conv - The expression for which we are performing the conversion.
1217/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001218/// \param Type - The type we expect this conversion to produce.
1219/// \param LVal - The glvalue on which we are attempting to perform this action.
1220/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001221static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1222 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001223 const LValue &LVal, CCValue &RVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001224 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001225 CallStackFrame *Frame = LVal.Frame;
Richard Smithc49bd112011-10-28 17:51:58 +00001226
Richard Smithf48fdb02011-12-09 22:58:01 +00001227 if (!LVal.Base) {
1228 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithdd1f29b2011-12-12 09:28:41 +00001229 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithc49bd112011-10-28 17:51:58 +00001230 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001231 }
Richard Smithc49bd112011-10-28 17:51:58 +00001232
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001233 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001234 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1235 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001236 // expressions are constant expressions too. Inside constexpr functions,
1237 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001238 // In C, such things can also be folded, although they are not ICEs.
1239 //
Richard Smithd0dccea2011-10-28 22:34:42 +00001240 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1241 // interpretation of C++11 suggests that volatile parameters are OK if
1242 // they're never read (there's no prohibition against constructing volatile
1243 // objects in constant expressions), but lvalue-to-rvalue conversions on
1244 // them are not permitted.
Richard Smithc49bd112011-10-28 17:51:58 +00001245 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001246 if (!VD || VD->isInvalidDecl()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001247 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001248 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001249 }
1250
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001251 QualType VT = VD->getType();
Richard Smith0a3bdb62011-11-04 02:25:55 +00001252 if (!isa<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001253 if (!IsConstNonVolatile(VT)) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001254 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001255 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001256 }
Richard Smithcd689922011-11-07 03:22:51 +00001257 // FIXME: Allow folding of values of any literal type in all languages.
1258 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
Richard Smithf48fdb02011-12-09 22:58:01 +00001259 !VD->isConstexpr()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001260 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001261 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001262 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001263 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001264 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001265 return false;
1266
Richard Smith47a1eed2011-10-29 20:57:55 +00001267 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001268 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001269
1270 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1271 // conversion. This happens when the declaration and the lvalue should be
1272 // considered synonymous, for instance when initializing an array of char
1273 // from a string literal. Continue as if the initializer lvalue was the
1274 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001275 assert(RVal.getLValueOffset().isZero() &&
1276 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001277 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001278 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001279 }
1280
Richard Smith0a3bdb62011-11-04 02:25:55 +00001281 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1282 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1283 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001284 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001285 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001286 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001287 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001288
1289 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001290 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001291 if (Index > S->getLength()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001292 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001293 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001294 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001295 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1296 Type->isUnsignedIntegerType());
1297 if (Index < S->getLength())
1298 Value = S->getCodeUnit(Index);
1299 RVal = CCValue(Value);
1300 return true;
1301 }
1302
Richard Smithcc5d4f62011-11-07 09:22:26 +00001303 if (Frame) {
1304 // If this is a temporary expression with a nontrivial initializer, grab the
1305 // value from the relevant stack frame.
1306 RVal = Frame->Temporaries[Base];
1307 } else if (const CompoundLiteralExpr *CLE
1308 = dyn_cast<CompoundLiteralExpr>(Base)) {
1309 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1310 // initializer until now for such expressions. Such an expression can't be
1311 // an ICE in C, so this only matters for fold.
1312 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1313 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1314 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001315 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001316 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001317 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001318 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001319
Richard Smithf48fdb02011-12-09 22:58:01 +00001320 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1321 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001322}
1323
Richard Smith59efe262011-11-11 04:05:33 +00001324/// Build an lvalue for the object argument of a member function call.
1325static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1326 LValue &This) {
1327 if (Object->getType()->isPointerType())
1328 return EvaluatePointer(Object, This, Info);
1329
1330 if (Object->isGLValue())
1331 return EvaluateLValue(Object, This, Info);
1332
Richard Smithe24f5fc2011-11-17 22:56:20 +00001333 if (Object->getType()->isLiteralType())
1334 return EvaluateTemporary(Object, This, Info);
1335
1336 return false;
1337}
1338
1339/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1340/// lvalue referring to the result.
1341///
1342/// \param Info - Information about the ongoing evaluation.
1343/// \param BO - The member pointer access operation.
1344/// \param LV - Filled in with a reference to the resulting object.
1345/// \param IncludeMember - Specifies whether the member itself is included in
1346/// the resulting LValue subobject designator. This is not possible when
1347/// creating a bound member function.
1348/// \return The field or method declaration to which the member pointer refers,
1349/// or 0 if evaluation fails.
1350static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1351 const BinaryOperator *BO,
1352 LValue &LV,
1353 bool IncludeMember = true) {
1354 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1355
1356 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1357 return 0;
1358
1359 MemberPtr MemPtr;
1360 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1361 return 0;
1362
1363 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1364 // member value, the behavior is undefined.
1365 if (!MemPtr.getDecl())
1366 return 0;
1367
1368 if (MemPtr.isDerivedMember()) {
1369 // This is a member of some derived class. Truncate LV appropriately.
1370 const CXXRecordDecl *MostDerivedType;
1371 unsigned MostDerivedPathLength;
1372 bool MostDerivedIsArrayElement;
1373 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1374 MostDerivedIsArrayElement))
1375 return 0;
1376
1377 // The end of the derived-to-base path for the base object must match the
1378 // derived-to-base path for the member pointer.
1379 if (MostDerivedPathLength + MemPtr.Path.size() >
1380 LV.Designator.Entries.size())
1381 return 0;
1382 unsigned PathLengthToMember =
1383 LV.Designator.Entries.size() - MemPtr.Path.size();
1384 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1385 const CXXRecordDecl *LVDecl = getAsBaseClass(
1386 LV.Designator.Entries[PathLengthToMember + I]);
1387 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1388 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1389 return 0;
1390 }
1391
1392 // Truncate the lvalue to the appropriate derived class.
1393 bool ResultIsArray = false;
1394 if (PathLengthToMember == MostDerivedPathLength)
1395 ResultIsArray = MostDerivedIsArrayElement;
1396 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1397 PathLengthToMember, ResultIsArray);
1398 } else if (!MemPtr.Path.empty()) {
1399 // Extend the LValue path with the member pointer's path.
1400 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1401 MemPtr.Path.size() + IncludeMember);
1402
1403 // Walk down to the appropriate base class.
1404 QualType LVType = BO->getLHS()->getType();
1405 if (const PointerType *PT = LVType->getAs<PointerType>())
1406 LVType = PT->getPointeeType();
1407 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1408 assert(RD && "member pointer access on non-class-type expression");
1409 // The first class in the path is that of the lvalue.
1410 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1411 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1412 HandleLValueDirectBase(Info, LV, RD, Base);
1413 RD = Base;
1414 }
1415 // Finally cast to the class containing the member.
1416 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1417 }
1418
1419 // Add the member. Note that we cannot build bound member functions here.
1420 if (IncludeMember) {
1421 // FIXME: Deal with IndirectFieldDecls.
1422 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1423 if (!FD) return 0;
1424 HandleLValueMember(Info, LV, FD);
1425 }
1426
1427 return MemPtr.getDecl();
1428}
1429
1430/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1431/// the provided lvalue, which currently refers to the base object.
1432static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1433 LValue &Result) {
1434 const CXXRecordDecl *MostDerivedType;
1435 unsigned MostDerivedPathLength;
1436 bool MostDerivedIsArrayElement;
1437
1438 // Check this cast doesn't take us outside the object.
1439 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1440 MostDerivedPathLength,
1441 MostDerivedIsArrayElement))
1442 return false;
1443 SubobjectDesignator &D = Result.Designator;
1444 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1445 return false;
1446
1447 // Check the type of the final cast. We don't need to check the path,
1448 // since a cast can only be formed if the path is unique.
1449 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1450 bool ResultIsArray = false;
1451 QualType TargetQT = E->getType();
1452 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1453 TargetQT = PT->getPointeeType();
1454 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1455 const CXXRecordDecl *FinalType;
1456 if (NewEntriesSize == MostDerivedPathLength) {
1457 ResultIsArray = MostDerivedIsArrayElement;
1458 FinalType = MostDerivedType;
1459 } else
1460 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1461 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1462 return false;
1463
1464 // Truncate the lvalue to the appropriate derived class.
1465 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1466 ResultIsArray);
1467 return true;
Richard Smith59efe262011-11-11 04:05:33 +00001468}
1469
Mike Stumpc4c90452009-10-27 22:09:17 +00001470namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001471enum EvalStmtResult {
1472 /// Evaluation failed.
1473 ESR_Failed,
1474 /// Hit a 'return' statement.
1475 ESR_Returned,
1476 /// Evaluation succeeded.
1477 ESR_Succeeded
1478};
1479}
1480
1481// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001482static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001483 const Stmt *S) {
1484 switch (S->getStmtClass()) {
1485 default:
1486 return ESR_Failed;
1487
1488 case Stmt::NullStmtClass:
1489 case Stmt::DeclStmtClass:
1490 return ESR_Succeeded;
1491
Richard Smithc1c5f272011-12-13 06:39:58 +00001492 case Stmt::ReturnStmtClass: {
1493 CCValue CCResult;
1494 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1495 if (!Evaluate(CCResult, Info, RetExpr) ||
1496 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1497 CCEK_ReturnValue))
1498 return ESR_Failed;
1499 return ESR_Returned;
1500 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001501
1502 case Stmt::CompoundStmtClass: {
1503 const CompoundStmt *CS = cast<CompoundStmt>(S);
1504 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1505 BE = CS->body_end(); BI != BE; ++BI) {
1506 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1507 if (ESR != ESR_Succeeded)
1508 return ESR;
1509 }
1510 return ESR_Succeeded;
1511 }
1512 }
1513}
1514
Richard Smithc1c5f272011-12-13 06:39:58 +00001515/// CheckConstexprFunction - Check that a function can be called in a constant
1516/// expression.
1517static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1518 const FunctionDecl *Declaration,
1519 const FunctionDecl *Definition) {
1520 // Can we evaluate this function call?
1521 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1522 return true;
1523
1524 if (Info.getLangOpts().CPlusPlus0x) {
1525 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
1526 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1527 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1528 << DiagDecl;
1529 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1530 } else {
1531 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1532 }
1533 return false;
1534}
1535
Richard Smith180f4792011-11-10 06:34:14 +00001536namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001537typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001538}
1539
1540/// EvaluateArgs - Evaluate the arguments to a function call.
1541static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1542 EvalInfo &Info) {
1543 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1544 I != E; ++I)
1545 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1546 return false;
1547 return true;
1548}
1549
Richard Smithd0dccea2011-10-28 22:34:42 +00001550/// Evaluate a function call.
Richard Smith08d6e032011-12-16 19:06:07 +00001551static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1552 const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001553 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001554 EvalInfo &Info, APValue &Result) {
1555 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd0dccea2011-10-28 22:34:42 +00001556 return false;
1557
Richard Smith180f4792011-11-10 06:34:14 +00001558 ArgVector ArgValues(Args.size());
1559 if (!EvaluateArgs(Args, ArgValues, Info))
1560 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001561
Richard Smith08d6e032011-12-16 19:06:07 +00001562 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1563 ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001564 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1565}
1566
Richard Smith180f4792011-11-10 06:34:14 +00001567/// Evaluate a constructor call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001568static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001569 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001570 const CXXConstructorDecl *Definition,
Richard Smith59efe262011-11-11 04:05:33 +00001571 EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00001572 APValue &Result) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001573 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith180f4792011-11-10 06:34:14 +00001574 return false;
1575
1576 ArgVector ArgValues(Args.size());
1577 if (!EvaluateArgs(Args, ArgValues, Info))
1578 return false;
1579
Richard Smith08d6e032011-12-16 19:06:07 +00001580 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1581 &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001582
1583 // If it's a delegating constructor, just delegate.
1584 if (Definition->isDelegatingConstructor()) {
1585 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1586 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1587 }
1588
1589 // Reserve space for the struct members.
1590 const CXXRecordDecl *RD = Definition->getParent();
1591 if (!RD->isUnion())
1592 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1593 std::distance(RD->field_begin(), RD->field_end()));
1594
1595 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1596
1597 unsigned BasesSeen = 0;
1598#ifndef NDEBUG
1599 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1600#endif
1601 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1602 E = Definition->init_end(); I != E; ++I) {
1603 if ((*I)->isBaseInitializer()) {
1604 QualType BaseType((*I)->getBaseClass(), 0);
1605#ifndef NDEBUG
1606 // Non-virtual base classes are initialized in the order in the class
1607 // definition. We cannot have a virtual base class for a literal type.
1608 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1609 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1610 "base class initializers not in expected order");
1611 ++BaseIt;
1612#endif
1613 LValue Subobject = This;
1614 HandleLValueDirectBase(Info, Subobject, RD,
1615 BaseType->getAsCXXRecordDecl(), &Layout);
1616 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1617 Subobject, (*I)->getInit()))
1618 return false;
1619 } else if (FieldDecl *FD = (*I)->getMember()) {
1620 LValue Subobject = This;
1621 HandleLValueMember(Info, Subobject, FD, &Layout);
1622 if (RD->isUnion()) {
1623 Result = APValue(FD);
Richard Smithc1c5f272011-12-13 06:39:58 +00001624 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1625 (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001626 return false;
1627 } else if (!EvaluateConstantExpression(
1628 Result.getStructField(FD->getFieldIndex()),
Richard Smithc1c5f272011-12-13 06:39:58 +00001629 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001630 return false;
1631 } else {
1632 // FIXME: handle indirect field initializers
Richard Smithdd1f29b2011-12-12 09:28:41 +00001633 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf48fdb02011-12-09 22:58:01 +00001634 diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001635 return false;
1636 }
1637 }
1638
1639 return true;
1640}
1641
Richard Smithd0dccea2011-10-28 22:34:42 +00001642namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001643class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001644 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001645 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001646public:
1647
Richard Smith1e12c592011-10-16 21:26:27 +00001648 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001649
1650 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001651 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001652 return true;
1653 }
1654
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001655 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1656 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001657 return Visit(E->getResultExpr());
1658 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001659 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001660 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001661 return true;
1662 return false;
1663 }
John McCallf85e1932011-06-15 23:02:42 +00001664 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001665 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001666 return true;
1667 return false;
1668 }
1669 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001670 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001671 return true;
1672 return false;
1673 }
1674
Mike Stumpc4c90452009-10-27 22:09:17 +00001675 // We don't want to evaluate BlockExprs multiple times, as they generate
1676 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001677 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1678 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1679 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001680 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001681 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1682 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1683 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1684 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1685 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1686 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001687 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001688 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001689 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001690 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001691 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001692 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1693 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1694 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1695 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001696 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001697 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1698 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1699 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1700 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1701 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001702 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001703 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001704 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001705 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001706 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001707
1708 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001709 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001710 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1711 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001712 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001713 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001714 return false;
1715 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001716
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001717 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001718};
1719
John McCall56ca35d2011-02-17 10:25:35 +00001720class OpaqueValueEvaluation {
1721 EvalInfo &info;
1722 OpaqueValueExpr *opaqueValue;
1723
1724public:
1725 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1726 Expr *value)
1727 : info(info), opaqueValue(opaqueValue) {
1728
1729 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00001730 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00001731 this->opaqueValue = 0;
1732 return;
1733 }
John McCall56ca35d2011-02-17 10:25:35 +00001734 }
1735
1736 bool hasError() const { return opaqueValue == 0; }
1737
1738 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00001739 // FIXME: This will not work for recursive constexpr functions using opaque
1740 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00001741 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1742 }
1743};
1744
Mike Stumpc4c90452009-10-27 22:09:17 +00001745} // end anonymous namespace
1746
Eli Friedman4efaa272008-11-12 09:44:48 +00001747//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001748// Generic Evaluation
1749//===----------------------------------------------------------------------===//
1750namespace {
1751
Richard Smithf48fdb02011-12-09 22:58:01 +00001752// FIXME: RetTy is always bool. Remove it.
1753template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001754class ExprEvaluatorBase
1755 : public ConstStmtVisitor<Derived, RetTy> {
1756private:
Richard Smith47a1eed2011-10-29 20:57:55 +00001757 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001758 return static_cast<Derived*>(this)->Success(V, E);
1759 }
Richard Smithf10d9172011-10-11 21:43:33 +00001760 RetTy DerivedValueInitialization(const Expr *E) {
1761 return static_cast<Derived*>(this)->ValueInitialization(E);
1762 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001763
1764protected:
1765 EvalInfo &Info;
1766 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1767 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1768
Richard Smithdd1f29b2011-12-12 09:28:41 +00001769 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00001770 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001771 }
1772
1773 /// Report an evaluation error. This should only be called when an error is
1774 /// first discovered. When propagating an error, just return false.
1775 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001776 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001777 return false;
1778 }
1779 bool Error(const Expr *E) {
1780 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1781 }
1782
1783 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00001784
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001785public:
1786 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1787
1788 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001789 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001790 }
1791 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001792 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001793 }
1794
1795 RetTy VisitParenExpr(const ParenExpr *E)
1796 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1797 RetTy VisitUnaryExtension(const UnaryOperator *E)
1798 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1799 RetTy VisitUnaryPlus(const UnaryOperator *E)
1800 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1801 RetTy VisitChooseExpr(const ChooseExpr *E)
1802 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1803 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1804 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00001805 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1806 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00001807 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1808 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001809
Richard Smithc216a012011-12-12 12:46:16 +00001810 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1811 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1812 return static_cast<Derived*>(this)->VisitCastExpr(E);
1813 }
1814 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1815 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1816 return static_cast<Derived*>(this)->VisitCastExpr(E);
1817 }
1818
Richard Smithe24f5fc2011-11-17 22:56:20 +00001819 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1820 switch (E->getOpcode()) {
1821 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00001822 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001823
1824 case BO_Comma:
1825 VisitIgnoredValue(E->getLHS());
1826 return StmtVisitorTy::Visit(E->getRHS());
1827
1828 case BO_PtrMemD:
1829 case BO_PtrMemI: {
1830 LValue Obj;
1831 if (!HandleMemberPointerAccess(Info, E, Obj))
1832 return false;
1833 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00001834 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001835 return false;
1836 return DerivedSuccess(Result, E);
1837 }
1838 }
1839 }
1840
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001841 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1842 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1843 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00001844 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001845
1846 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00001847 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00001848 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001849
1850 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1851 }
1852
1853 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1854 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00001855 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00001856 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001857
Richard Smithc49bd112011-10-28 17:51:58 +00001858 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001859 return StmtVisitorTy::Visit(EvalExpr);
1860 }
1861
1862 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001863 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001864 if (!Value) {
1865 const Expr *Source = E->getSourceExpr();
1866 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00001867 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001868 if (Source == E) { // sanity checking.
1869 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00001870 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001871 }
1872 return StmtVisitorTy::Visit(Source);
1873 }
Richard Smith47a1eed2011-10-29 20:57:55 +00001874 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001875 }
Richard Smithf10d9172011-10-11 21:43:33 +00001876
Richard Smithd0dccea2011-10-28 22:34:42 +00001877 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001878 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00001879 QualType CalleeType = Callee->getType();
1880
Richard Smithd0dccea2011-10-28 22:34:42 +00001881 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00001882 LValue *This = 0, ThisVal;
1883 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00001884
Richard Smith59efe262011-11-11 04:05:33 +00001885 // Extract function decl and 'this' pointer from the callee.
1886 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001887 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001888 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1889 // Explicit bound member calls, such as x.f() or p->g();
1890 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00001891 return false;
1892 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001893 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001894 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1895 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00001896 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1897 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001898 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001899 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00001900 return Error(Callee);
1901
1902 FD = dyn_cast<FunctionDecl>(Member);
1903 if (!FD)
1904 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00001905 } else if (CalleeType->isFunctionPointerType()) {
1906 CCValue Call;
Richard Smithf48fdb02011-12-09 22:58:01 +00001907 if (!Evaluate(Call, Info, Callee))
1908 return false;
Richard Smith59efe262011-11-11 04:05:33 +00001909
Richard Smithf48fdb02011-12-09 22:58:01 +00001910 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1911 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001912 FD = dyn_cast_or_null<FunctionDecl>(
1913 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00001914 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00001915 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00001916
1917 // Overloaded operator calls to member functions are represented as normal
1918 // calls with '*this' as the first argument.
1919 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1920 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001921 // FIXME: When selecting an implicit conversion for an overloaded
1922 // operator delete, we sometimes try to evaluate calls to conversion
1923 // operators without a 'this' parameter!
1924 if (Args.empty())
1925 return Error(E);
1926
Richard Smith59efe262011-11-11 04:05:33 +00001927 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1928 return false;
1929 This = &ThisVal;
1930 Args = Args.slice(1);
1931 }
1932
1933 // Don't call function pointers which have been cast to some other type.
1934 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00001935 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00001936 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00001937 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001938
Richard Smithc1c5f272011-12-13 06:39:58 +00001939 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00001940 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00001941 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00001942
Richard Smithc1c5f272011-12-13 06:39:58 +00001943 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith08d6e032011-12-16 19:06:07 +00001944 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00001945 return false;
1946
1947 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001948 }
1949
Richard Smithc49bd112011-10-28 17:51:58 +00001950 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1951 return StmtVisitorTy::Visit(E->getInitializer());
1952 }
Richard Smithf10d9172011-10-11 21:43:33 +00001953 RetTy VisitInitListExpr(const InitListExpr *E) {
1954 if (Info.getLangOpts().CPlusPlus0x) {
1955 if (E->getNumInits() == 0)
1956 return DerivedValueInitialization(E);
1957 if (E->getNumInits() == 1)
1958 return StmtVisitorTy::Visit(E->getInit(0));
1959 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001960 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00001961 }
1962 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1963 return DerivedValueInitialization(E);
1964 }
1965 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1966 return DerivedValueInitialization(E);
1967 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001968 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1969 return DerivedValueInitialization(E);
1970 }
Richard Smithf10d9172011-10-11 21:43:33 +00001971
Richard Smith180f4792011-11-10 06:34:14 +00001972 /// A member expression where the object is a prvalue is itself a prvalue.
1973 RetTy VisitMemberExpr(const MemberExpr *E) {
1974 assert(!E->isArrow() && "missing call to bound member function?");
1975
1976 CCValue Val;
1977 if (!Evaluate(Val, Info, E->getBase()))
1978 return false;
1979
1980 QualType BaseTy = E->getBase()->getType();
1981
1982 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00001983 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00001984 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1985 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1986 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1987
1988 SubobjectDesignator Designator;
1989 Designator.addDecl(FD);
1990
Richard Smithf48fdb02011-12-09 22:58:01 +00001991 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00001992 DerivedSuccess(Val, E);
1993 }
1994
Richard Smithc49bd112011-10-28 17:51:58 +00001995 RetTy VisitCastExpr(const CastExpr *E) {
1996 switch (E->getCastKind()) {
1997 default:
1998 break;
1999
2000 case CK_NoOp:
2001 return StmtVisitorTy::Visit(E->getSubExpr());
2002
2003 case CK_LValueToRValue: {
2004 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002005 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2006 return false;
2007 CCValue RVal;
2008 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2009 return false;
2010 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002011 }
2012 }
2013
Richard Smithf48fdb02011-12-09 22:58:01 +00002014 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002015 }
2016
Richard Smith8327fad2011-10-24 18:44:57 +00002017 /// Visit a value which is evaluated, but whose value is ignored.
2018 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002019 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002020 if (!Evaluate(Scratch, Info, E))
2021 Info.EvalStatus.HasSideEffects = true;
2022 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002023};
2024
2025}
2026
2027//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002028// Common base class for lvalue and temporary evaluation.
2029//===----------------------------------------------------------------------===//
2030namespace {
2031template<class Derived>
2032class LValueExprEvaluatorBase
2033 : public ExprEvaluatorBase<Derived, bool> {
2034protected:
2035 LValue &Result;
2036 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2037 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2038
2039 bool Success(APValue::LValueBase B) {
2040 Result.set(B);
2041 return true;
2042 }
2043
2044public:
2045 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2046 ExprEvaluatorBaseTy(Info), Result(Result) {}
2047
2048 bool Success(const CCValue &V, const Expr *E) {
2049 Result.setFrom(V);
2050 return true;
2051 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002052
2053 bool CheckValidLValue() {
2054 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2055 // there are no null references, nor once-past-the-end references.
2056 // FIXME: Check for one-past-the-end array indices
2057 return Result.Base && !Result.Designator.Invalid &&
2058 !Result.Designator.OnePastTheEnd;
2059 }
2060
2061 bool VisitMemberExpr(const MemberExpr *E) {
2062 // Handle non-static data members.
2063 QualType BaseTy;
2064 if (E->isArrow()) {
2065 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2066 return false;
2067 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002068 } else if (E->getBase()->isRValue()) {
Eli Friedmanf59ff8c2011-12-17 02:24:21 +00002069 if (!E->getBase()->getType()->isRecordType() ||
2070 !E->getBase()->getType()->isLiteralType())
2071 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00002072 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2073 return false;
2074 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002075 } else {
2076 if (!this->Visit(E->getBase()))
2077 return false;
2078 BaseTy = E->getBase()->getType();
2079 }
2080 // FIXME: In C++11, require the result to be a valid lvalue.
2081
2082 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2083 // FIXME: Handle IndirectFieldDecls
Richard Smithf48fdb02011-12-09 22:58:01 +00002084 if (!FD) return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002085 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2086 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2087 (void)BaseTy;
2088
2089 HandleLValueMember(this->Info, Result, FD);
2090
2091 if (FD->getType()->isReferenceType()) {
2092 CCValue RefValue;
Richard Smithf48fdb02011-12-09 22:58:01 +00002093 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002094 RefValue))
2095 return false;
2096 return Success(RefValue, E);
2097 }
2098 return true;
2099 }
2100
2101 bool VisitBinaryOperator(const BinaryOperator *E) {
2102 switch (E->getOpcode()) {
2103 default:
2104 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2105
2106 case BO_PtrMemD:
2107 case BO_PtrMemI:
2108 return HandleMemberPointerAccess(this->Info, E, Result);
2109 }
2110 }
2111
2112 bool VisitCastExpr(const CastExpr *E) {
2113 switch (E->getCastKind()) {
2114 default:
2115 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2116
2117 case CK_DerivedToBase:
2118 case CK_UncheckedDerivedToBase: {
2119 if (!this->Visit(E->getSubExpr()))
2120 return false;
2121 if (!CheckValidLValue())
2122 return false;
2123
2124 // Now figure out the necessary offset to add to the base LV to get from
2125 // the derived class to the base class.
2126 QualType Type = E->getSubExpr()->getType();
2127
2128 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2129 PathE = E->path_end(); PathI != PathE; ++PathI) {
2130 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2131 *PathI))
2132 return false;
2133 Type = (*PathI)->getType();
2134 }
2135
2136 return true;
2137 }
2138 }
2139 }
2140};
2141}
2142
2143//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002144// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002145//
2146// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2147// function designators (in C), decl references to void objects (in C), and
2148// temporaries (if building with -Wno-address-of-temporary).
2149//
2150// LValue evaluation produces values comprising a base expression of one of the
2151// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002152// - Declarations
2153// * VarDecl
2154// * FunctionDecl
2155// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002156// * CompoundLiteralExpr in C
2157// * StringLiteral
2158// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002159// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002160// * ObjCEncodeExpr
2161// * AddrLabelExpr
2162// * BlockExpr
2163// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002164// - Locals and temporaries
2165// * Any Expr, with a Frame indicating the function in which the temporary was
2166// evaluated.
2167// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002168//===----------------------------------------------------------------------===//
2169namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002170class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002171 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002172public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002173 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2174 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Richard Smithc49bd112011-10-28 17:51:58 +00002176 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2177
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002178 bool VisitDeclRefExpr(const DeclRefExpr *E);
2179 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002180 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002181 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2182 bool VisitMemberExpr(const MemberExpr *E);
2183 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2184 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2185 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2186 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002187
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002188 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002189 switch (E->getCastKind()) {
2190 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002191 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002192
Eli Friedmandb924222011-10-11 00:13:24 +00002193 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002194 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002195 if (!Visit(E->getSubExpr()))
2196 return false;
2197 Result.Designator.setInvalid();
2198 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002199
Richard Smithe24f5fc2011-11-17 22:56:20 +00002200 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002201 if (!Visit(E->getSubExpr()))
2202 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002203 if (!CheckValidLValue())
2204 return false;
2205 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002206 }
2207 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002208
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002209 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002210
Eli Friedman4efaa272008-11-12 09:44:48 +00002211};
2212} // end anonymous namespace
2213
Richard Smithc49bd112011-10-28 17:51:58 +00002214/// Evaluate an expression as an lvalue. This can be legitimately called on
2215/// expressions which are not glvalues, in a few cases:
2216/// * function designators in C,
2217/// * "extern void" objects,
2218/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002219static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002220 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2221 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2222 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002223 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002224}
2225
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002226bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2228 return Success(FD);
2229 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002230 return VisitVarDecl(E, VD);
2231 return Error(E);
2232}
Richard Smith436c8892011-10-24 23:14:33 +00002233
Richard Smithc49bd112011-10-28 17:51:58 +00002234bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002235 if (!VD->getType()->isReferenceType()) {
2236 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002237 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002238 return true;
2239 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002240 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002241 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002242
Richard Smith47a1eed2011-10-29 20:57:55 +00002243 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002244 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2245 return false;
2246 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002247}
2248
Richard Smithbd552ef2011-10-31 05:52:43 +00002249bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2250 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002251 if (E->GetTemporaryExpr()->isRValue()) {
2252 if (E->getType()->isRecordType() && E->getType()->isLiteralType())
2253 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2254
2255 Result.set(E, Info.CurrentCall);
2256 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2257 Result, E->GetTemporaryExpr());
2258 }
2259
2260 // Materialization of an lvalue temporary occurs when we need to force a copy
2261 // (for instance, if it's a bitfield).
2262 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2263 if (!Visit(E->GetTemporaryExpr()))
2264 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002265 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002266 Info.CurrentCall->Temporaries[E]))
2267 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002268 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002269 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002270}
2271
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002272bool
2273LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002274 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2275 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2276 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002277 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002278}
2279
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002280bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002281 // Handle static data members.
2282 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2283 VisitIgnoredValue(E->getBase());
2284 return VisitVarDecl(E, VD);
2285 }
2286
Richard Smithd0dccea2011-10-28 22:34:42 +00002287 // Handle static member functions.
2288 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2289 if (MD->isStatic()) {
2290 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002291 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002292 }
2293 }
2294
Richard Smith180f4792011-11-10 06:34:14 +00002295 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002296 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002297}
2298
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002299bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002300 // FIXME: Deal with vectors as array subscript bases.
2301 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002302 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002303
Anders Carlsson3068d112008-11-16 19:01:22 +00002304 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002305 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Anders Carlsson3068d112008-11-16 19:01:22 +00002307 APSInt Index;
2308 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002309 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002310 int64_t IndexValue
2311 = Index.isSigned() ? Index.getSExtValue()
2312 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002313
Richard Smithe24f5fc2011-11-17 22:56:20 +00002314 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002315 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002316}
Eli Friedman4efaa272008-11-12 09:44:48 +00002317
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002318bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002319 // FIXME: In C++11, require the result to be a valid lvalue.
John McCallefdb83e2010-05-07 21:00:08 +00002320 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002321}
2322
Eli Friedman4efaa272008-11-12 09:44:48 +00002323//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002324// Pointer Evaluation
2325//===----------------------------------------------------------------------===//
2326
Anders Carlssonc754aa62008-07-08 05:13:58 +00002327namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002328class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002329 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002330 LValue &Result;
2331
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002332 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002333 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002334 return true;
2335 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002336public:
Mike Stump1eb44332009-09-09 15:08:12 +00002337
John McCallefdb83e2010-05-07 21:00:08 +00002338 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002339 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002340
Richard Smith47a1eed2011-10-29 20:57:55 +00002341 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002342 Result.setFrom(V);
2343 return true;
2344 }
Richard Smithf10d9172011-10-11 21:43:33 +00002345 bool ValueInitialization(const Expr *E) {
2346 return Success((Expr*)0);
2347 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002348
John McCallefdb83e2010-05-07 21:00:08 +00002349 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002350 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002351 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002352 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002353 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002354 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002355 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002356 bool VisitCallExpr(const CallExpr *E);
2357 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002358 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002359 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002360 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002361 }
Richard Smith180f4792011-11-10 06:34:14 +00002362 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2363 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002364 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002365 Result = *Info.CurrentCall->This;
2366 return true;
2367 }
John McCall56ca35d2011-02-17 10:25:35 +00002368
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002369 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002370};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002371} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002372
John McCallefdb83e2010-05-07 21:00:08 +00002373static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002374 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002375 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002376}
2377
John McCallefdb83e2010-05-07 21:00:08 +00002378bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002379 if (E->getOpcode() != BO_Add &&
2380 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002381 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002383 const Expr *PExp = E->getLHS();
2384 const Expr *IExp = E->getRHS();
2385 if (IExp->getType()->isPointerType())
2386 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002387
John McCallefdb83e2010-05-07 21:00:08 +00002388 if (!EvaluatePointer(PExp, Result, Info))
2389 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002390
John McCallefdb83e2010-05-07 21:00:08 +00002391 llvm::APSInt Offset;
2392 if (!EvaluateInteger(IExp, Offset, Info))
2393 return false;
2394 int64_t AdditionalOffset
2395 = Offset.isSigned() ? Offset.getSExtValue()
2396 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002397 if (E->getOpcode() == BO_Sub)
2398 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002399
Richard Smith180f4792011-11-10 06:34:14 +00002400 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002401 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002402 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002403}
Eli Friedman4efaa272008-11-12 09:44:48 +00002404
John McCallefdb83e2010-05-07 21:00:08 +00002405bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2406 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002407}
Mike Stump1eb44332009-09-09 15:08:12 +00002408
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002409bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2410 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002411
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002412 switch (E->getCastKind()) {
2413 default:
2414 break;
2415
John McCall2de56d12010-08-25 11:45:40 +00002416 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002417 case CK_CPointerToObjCPointerCast:
2418 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002419 case CK_AnyPointerToBlockPointerCast:
Richard Smithc216a012011-12-12 12:46:16 +00002420 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2421 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2422 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002423 if (!E->getType()->isVoidPointerType()) {
2424 if (SubExpr->getType()->isVoidPointerType())
2425 CCEDiag(E, diag::note_constexpr_invalid_cast)
2426 << 3 << SubExpr->getType();
2427 else
2428 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2429 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002430 if (!Visit(SubExpr))
2431 return false;
2432 Result.Designator.setInvalid();
2433 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002434
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002435 case CK_DerivedToBase:
2436 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002437 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002438 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002439 if (!Result.Base && Result.Offset.isZero())
2440 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002441
Richard Smith180f4792011-11-10 06:34:14 +00002442 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002443 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002444 QualType Type =
2445 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002446
Richard Smith180f4792011-11-10 06:34:14 +00002447 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002448 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smith180f4792011-11-10 06:34:14 +00002449 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002450 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002451 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002452 }
2453
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002454 return true;
2455 }
2456
Richard Smithe24f5fc2011-11-17 22:56:20 +00002457 case CK_BaseToDerived:
2458 if (!Visit(E->getSubExpr()))
2459 return false;
2460 if (!Result.Base && Result.Offset.isZero())
2461 return true;
2462 return HandleBaseToDerivedCast(Info, E, Result);
2463
Richard Smith47a1eed2011-10-29 20:57:55 +00002464 case CK_NullToPointer:
2465 return ValueInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002466
John McCall2de56d12010-08-25 11:45:40 +00002467 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002468 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2469
Richard Smith47a1eed2011-10-29 20:57:55 +00002470 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002471 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002472 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002473
John McCallefdb83e2010-05-07 21:00:08 +00002474 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002475 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2476 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002477 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002478 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002479 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002480 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002481 return true;
2482 } else {
2483 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002484 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002485 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002486 }
2487 }
John McCall2de56d12010-08-25 11:45:40 +00002488 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002489 if (SubExpr->isGLValue()) {
2490 if (!EvaluateLValue(SubExpr, Result, Info))
2491 return false;
2492 } else {
2493 Result.set(SubExpr, Info.CurrentCall);
2494 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2495 Info, Result, SubExpr))
2496 return false;
2497 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002498 // The result is a pointer to the first element of the array.
2499 Result.Designator.addIndex(0);
2500 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002501
John McCall2de56d12010-08-25 11:45:40 +00002502 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002503 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002504 }
2505
Richard Smithc49bd112011-10-28 17:51:58 +00002506 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002507}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002508
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002509bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002510 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002511 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002512
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002513 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002514}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002515
2516//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002517// Member Pointer Evaluation
2518//===----------------------------------------------------------------------===//
2519
2520namespace {
2521class MemberPointerExprEvaluator
2522 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2523 MemberPtr &Result;
2524
2525 bool Success(const ValueDecl *D) {
2526 Result = MemberPtr(D);
2527 return true;
2528 }
2529public:
2530
2531 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2532 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2533
2534 bool Success(const CCValue &V, const Expr *E) {
2535 Result.setFrom(V);
2536 return true;
2537 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002538 bool ValueInitialization(const Expr *E) {
2539 return Success((const ValueDecl*)0);
2540 }
2541
2542 bool VisitCastExpr(const CastExpr *E);
2543 bool VisitUnaryAddrOf(const UnaryOperator *E);
2544};
2545} // end anonymous namespace
2546
2547static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2548 EvalInfo &Info) {
2549 assert(E->isRValue() && E->getType()->isMemberPointerType());
2550 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2551}
2552
2553bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2554 switch (E->getCastKind()) {
2555 default:
2556 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2557
2558 case CK_NullToMemberPointer:
2559 return ValueInitialization(E);
2560
2561 case CK_BaseToDerivedMemberPointer: {
2562 if (!Visit(E->getSubExpr()))
2563 return false;
2564 if (E->path_empty())
2565 return true;
2566 // Base-to-derived member pointer casts store the path in derived-to-base
2567 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2568 // the wrong end of the derived->base arc, so stagger the path by one class.
2569 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2570 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2571 PathI != PathE; ++PathI) {
2572 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2573 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2574 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002575 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002576 }
2577 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2578 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002579 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002580 return true;
2581 }
2582
2583 case CK_DerivedToBaseMemberPointer:
2584 if (!Visit(E->getSubExpr()))
2585 return false;
2586 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2587 PathE = E->path_end(); PathI != PathE; ++PathI) {
2588 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2589 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2590 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002591 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002592 }
2593 return true;
2594 }
2595}
2596
2597bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2598 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2599 // member can be formed.
2600 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2601}
2602
2603//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002604// Record Evaluation
2605//===----------------------------------------------------------------------===//
2606
2607namespace {
2608 class RecordExprEvaluator
2609 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2610 const LValue &This;
2611 APValue &Result;
2612 public:
2613
2614 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2615 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2616
2617 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002618 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002619 }
Richard Smith180f4792011-11-10 06:34:14 +00002620
Richard Smith59efe262011-11-11 04:05:33 +00002621 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002622 bool VisitInitListExpr(const InitListExpr *E);
2623 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2624 };
2625}
2626
Richard Smith59efe262011-11-11 04:05:33 +00002627bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2628 switch (E->getCastKind()) {
2629 default:
2630 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2631
2632 case CK_ConstructorConversion:
2633 return Visit(E->getSubExpr());
2634
2635 case CK_DerivedToBase:
2636 case CK_UncheckedDerivedToBase: {
2637 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00002638 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00002639 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002640 if (!DerivedObject.isStruct())
2641 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00002642
2643 // Derived-to-base rvalue conversion: just slice off the derived part.
2644 APValue *Value = &DerivedObject;
2645 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2646 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2647 PathE = E->path_end(); PathI != PathE; ++PathI) {
2648 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2649 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2650 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2651 RD = Base;
2652 }
2653 Result = *Value;
2654 return true;
2655 }
2656 }
2657}
2658
Richard Smith180f4792011-11-10 06:34:14 +00002659bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2660 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2661 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2662
2663 if (RD->isUnion()) {
2664 Result = APValue(E->getInitializedFieldInUnion());
2665 if (!E->getNumInits())
2666 return true;
2667 LValue Subobject = This;
2668 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2669 &Layout);
2670 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2671 Subobject, E->getInit(0));
2672 }
2673
2674 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2675 "initializer list for class with base classes");
2676 Result = APValue(APValue::UninitStruct(), 0,
2677 std::distance(RD->field_begin(), RD->field_end()));
2678 unsigned ElementNo = 0;
2679 for (RecordDecl::field_iterator Field = RD->field_begin(),
2680 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2681 // Anonymous bit-fields are not considered members of the class for
2682 // purposes of aggregate initialization.
2683 if (Field->isUnnamedBitfield())
2684 continue;
2685
2686 LValue Subobject = This;
2687 HandleLValueMember(Info, Subobject, *Field, &Layout);
2688
2689 if (ElementNo < E->getNumInits()) {
2690 if (!EvaluateConstantExpression(
2691 Result.getStructField((*Field)->getFieldIndex()),
2692 Info, Subobject, E->getInit(ElementNo++)))
2693 return false;
2694 } else {
2695 // Perform an implicit value-initialization for members beyond the end of
2696 // the initializer list.
2697 ImplicitValueInitExpr VIE(Field->getType());
2698 if (!EvaluateConstantExpression(
2699 Result.getStructField((*Field)->getFieldIndex()),
2700 Info, Subobject, &VIE))
2701 return false;
2702 }
2703 }
2704
2705 return true;
2706}
2707
2708bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2709 const CXXConstructorDecl *FD = E->getConstructor();
2710 const FunctionDecl *Definition = 0;
2711 FD->getBody(Definition);
2712
Richard Smithc1c5f272011-12-13 06:39:58 +00002713 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2714 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002715
2716 // FIXME: Elide the copy/move construction wherever we can.
2717 if (E->isElidable())
2718 if (const MaterializeTemporaryExpr *ME
2719 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2720 return Visit(ME->GetTemporaryExpr());
2721
2722 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00002723 return HandleConstructorCall(E, This, Args,
2724 cast<CXXConstructorDecl>(Definition), Info,
2725 Result);
Richard Smith180f4792011-11-10 06:34:14 +00002726}
2727
2728static bool EvaluateRecord(const Expr *E, const LValue &This,
2729 APValue &Result, EvalInfo &Info) {
2730 assert(E->isRValue() && E->getType()->isRecordType() &&
2731 E->getType()->isLiteralType() &&
2732 "can't evaluate expression as a record rvalue");
2733 return RecordExprEvaluator(Info, This, Result).Visit(E);
2734}
2735
2736//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002737// Temporary Evaluation
2738//
2739// Temporaries are represented in the AST as rvalues, but generally behave like
2740// lvalues. The full-object of which the temporary is a subobject is implicitly
2741// materialized so that a reference can bind to it.
2742//===----------------------------------------------------------------------===//
2743namespace {
2744class TemporaryExprEvaluator
2745 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2746public:
2747 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2748 LValueExprEvaluatorBaseTy(Info, Result) {}
2749
2750 /// Visit an expression which constructs the value of this temporary.
2751 bool VisitConstructExpr(const Expr *E) {
2752 Result.set(E, Info.CurrentCall);
2753 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2754 Result, E);
2755 }
2756
2757 bool VisitCastExpr(const CastExpr *E) {
2758 switch (E->getCastKind()) {
2759 default:
2760 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2761
2762 case CK_ConstructorConversion:
2763 return VisitConstructExpr(E->getSubExpr());
2764 }
2765 }
2766 bool VisitInitListExpr(const InitListExpr *E) {
2767 return VisitConstructExpr(E);
2768 }
2769 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2770 return VisitConstructExpr(E);
2771 }
2772 bool VisitCallExpr(const CallExpr *E) {
2773 return VisitConstructExpr(E);
2774 }
2775};
2776} // end anonymous namespace
2777
2778/// Evaluate an expression of record type as a temporary.
2779static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
2780 assert(E->isRValue() && E->getType()->isRecordType() &&
2781 E->getType()->isLiteralType());
2782 return TemporaryExprEvaluator(Info, Result).Visit(E);
2783}
2784
2785//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00002786// Vector Evaluation
2787//===----------------------------------------------------------------------===//
2788
2789namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002790 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00002791 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2792 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00002793 public:
Mike Stump1eb44332009-09-09 15:08:12 +00002794
Richard Smith07fc6572011-10-22 21:10:00 +00002795 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2796 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Richard Smith07fc6572011-10-22 21:10:00 +00002798 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2799 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2800 // FIXME: remove this APValue copy.
2801 Result = APValue(V.data(), V.size());
2802 return true;
2803 }
Richard Smith69c2c502011-11-04 05:33:44 +00002804 bool Success(const CCValue &V, const Expr *E) {
2805 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00002806 Result = V;
2807 return true;
2808 }
Richard Smith07fc6572011-10-22 21:10:00 +00002809 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Richard Smith07fc6572011-10-22 21:10:00 +00002811 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00002812 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00002813 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00002814 bool VisitInitListExpr(const InitListExpr *E);
2815 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002816 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00002817 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00002818 // shufflevector, ExtVectorElementExpr
2819 // (Note that these require implementing conversions
2820 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00002821 };
2822} // end anonymous namespace
2823
2824static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002825 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00002826 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002827}
2828
Richard Smith07fc6572011-10-22 21:10:00 +00002829bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2830 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00002831 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Richard Smithd62ca372011-12-06 22:44:34 +00002833 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00002834 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00002835
Eli Friedman46a52322011-03-25 00:43:55 +00002836 switch (E->getCastKind()) {
2837 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00002838 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00002839 if (SETy->isIntegerType()) {
2840 APSInt IntResult;
2841 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002842 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00002843 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00002844 } else if (SETy->isRealFloatingType()) {
2845 APFloat F(0.0);
2846 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002847 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00002848 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00002849 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00002850 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002851 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00002852
2853 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00002854 SmallVector<APValue, 4> Elts(NElts, Val);
2855 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00002856 }
Eli Friedman46a52322011-03-25 00:43:55 +00002857 default:
Richard Smithc49bd112011-10-28 17:51:58 +00002858 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002859 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002860}
2861
Richard Smith07fc6572011-10-22 21:10:00 +00002862bool
Nate Begeman59b5da62009-01-18 03:20:47 +00002863VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00002864 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00002865 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00002866 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002867
Nate Begeman59b5da62009-01-18 03:20:47 +00002868 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002869 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00002870
John McCalla7d6c222010-06-11 17:54:15 +00002871 // If a vector is initialized with a single element, that value
2872 // becomes every element of the vector, not just the first.
2873 // This is the behavior described in the IBM AltiVec documentation.
2874 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00002875
2876 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00002877 // vector (OpenCL 6.1.6).
2878 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00002879 return Visit(E->getInit(0));
2880
John McCalla7d6c222010-06-11 17:54:15 +00002881 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00002882 if (EltTy->isIntegerType()) {
2883 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00002884 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002885 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002886 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00002887 } else {
2888 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00002889 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002890 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002891 InitValue = APValue(f);
2892 }
2893 for (unsigned i = 0; i < NumElements; i++) {
2894 Elements.push_back(InitValue);
2895 }
2896 } else {
2897 for (unsigned i = 0; i < NumElements; i++) {
2898 if (EltTy->isIntegerType()) {
2899 llvm::APSInt sInt(32);
2900 if (i < NumInits) {
2901 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002902 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002903 } else {
2904 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2905 }
2906 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00002907 } else {
John McCalla7d6c222010-06-11 17:54:15 +00002908 llvm::APFloat f(0.0);
2909 if (i < NumInits) {
2910 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002911 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002912 } else {
2913 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2914 }
2915 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00002916 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002917 }
2918 }
Richard Smith07fc6572011-10-22 21:10:00 +00002919 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002920}
2921
Richard Smith07fc6572011-10-22 21:10:00 +00002922bool
2923VectorExprEvaluator::ValueInitialization(const Expr *E) {
2924 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00002925 QualType EltTy = VT->getElementType();
2926 APValue ZeroElement;
2927 if (EltTy->isIntegerType())
2928 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2929 else
2930 ZeroElement =
2931 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2932
Chris Lattner5f9e2722011-07-23 10:55:15 +00002933 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00002934 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002935}
2936
Richard Smith07fc6572011-10-22 21:10:00 +00002937bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00002938 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00002939 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002940}
2941
Nate Begeman59b5da62009-01-18 03:20:47 +00002942//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00002943// Array Evaluation
2944//===----------------------------------------------------------------------===//
2945
2946namespace {
2947 class ArrayExprEvaluator
2948 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00002949 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002950 APValue &Result;
2951 public:
2952
Richard Smith180f4792011-11-10 06:34:14 +00002953 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2954 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00002955
2956 bool Success(const APValue &V, const Expr *E) {
2957 assert(V.isArray() && "Expected array type");
2958 Result = V;
2959 return true;
2960 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00002961
Richard Smith180f4792011-11-10 06:34:14 +00002962 bool ValueInitialization(const Expr *E) {
2963 const ConstantArrayType *CAT =
2964 Info.Ctx.getAsConstantArrayType(E->getType());
2965 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00002966 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002967
2968 Result = APValue(APValue::UninitArray(), 0,
2969 CAT->getSize().getZExtValue());
2970 if (!Result.hasArrayFiller()) return true;
2971
2972 // Value-initialize all elements.
2973 LValue Subobject = This;
2974 Subobject.Designator.addIndex(0);
2975 ImplicitValueInitExpr VIE(CAT->getElementType());
2976 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2977 Subobject, &VIE);
2978 }
2979
Richard Smithcc5d4f62011-11-07 09:22:26 +00002980 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002981 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002982 };
2983} // end anonymous namespace
2984
Richard Smith180f4792011-11-10 06:34:14 +00002985static bool EvaluateArray(const Expr *E, const LValue &This,
2986 APValue &Result, EvalInfo &Info) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00002987 assert(E->isRValue() && E->getType()->isArrayType() &&
2988 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00002989 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002990}
2991
2992bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2993 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2994 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00002995 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002996
2997 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2998 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00002999 LValue Subobject = This;
3000 Subobject.Designator.addIndex(0);
3001 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003002 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003003 I != End; ++I, ++Index) {
3004 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3005 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003006 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003007 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3008 return false;
3009 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003010
3011 if (!Result.hasArrayFiller()) return true;
3012 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003013 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3014 // but sometimes does:
3015 // struct S { constexpr S() : p(&p) {} void *p; };
3016 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003017 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00003018 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00003019}
3020
Richard Smithe24f5fc2011-11-17 22:56:20 +00003021bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3022 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3023 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003024 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003025
3026 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3027 if (!Result.hasArrayFiller())
3028 return true;
3029
3030 const CXXConstructorDecl *FD = E->getConstructor();
3031 const FunctionDecl *Definition = 0;
3032 FD->getBody(Definition);
3033
Richard Smithc1c5f272011-12-13 06:39:58 +00003034 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3035 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003036
3037 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3038 // but sometimes does:
3039 // struct S { constexpr S() : p(&p) {} void *p; };
3040 // S s[10];
3041 LValue Subobject = This;
3042 Subobject.Designator.addIndex(0);
3043 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003044 return HandleConstructorCall(E, Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003045 cast<CXXConstructorDecl>(Definition),
3046 Info, Result.getArrayFiller());
3047}
3048
Richard Smithcc5d4f62011-11-07 09:22:26 +00003049//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003050// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003051//
3052// As a GNU extension, we support casting pointers to sufficiently-wide integer
3053// types and back in constant folding. Integer values are thus represented
3054// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003055//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003056
3057namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003058class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003059 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003060 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003061public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003062 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003063 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003064
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003065 bool Success(const llvm::APSInt &SI, const Expr *E) {
3066 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003067 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003068 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003069 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003070 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003071 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003072 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003073 return true;
3074 }
3075
Daniel Dunbar131eb432009-02-19 09:06:44 +00003076 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003077 assert(E->getType()->isIntegralOrEnumerationType() &&
3078 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003079 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003080 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003081 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003082 Result.getInt().setIsUnsigned(
3083 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003084 return true;
3085 }
3086
3087 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003088 assert(E->getType()->isIntegralOrEnumerationType() &&
3089 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003090 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003091 return true;
3092 }
3093
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003094 bool Success(CharUnits Size, const Expr *E) {
3095 return Success(Size.getQuantity(), E);
3096 }
3097
Richard Smith47a1eed2011-10-29 20:57:55 +00003098 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00003099 if (V.isLValue()) {
3100 Result = V;
3101 return true;
3102 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003103 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003104 }
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Richard Smithf10d9172011-10-11 21:43:33 +00003106 bool ValueInitialization(const Expr *E) { return Success(0, E); }
3107
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003108 //===--------------------------------------------------------------------===//
3109 // Visitor Methods
3110 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003111
Chris Lattner4c4867e2008-07-12 00:38:25 +00003112 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003113 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003114 }
3115 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003116 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003117 }
Eli Friedman04309752009-11-24 05:28:59 +00003118
3119 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3120 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003121 if (CheckReferencedDecl(E, E->getDecl()))
3122 return true;
3123
3124 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003125 }
3126 bool VisitMemberExpr(const MemberExpr *E) {
3127 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003128 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003129 return true;
3130 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003131
3132 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003133 }
3134
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003135 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003136 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003137 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003138 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003139
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003140 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003141 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003142
Anders Carlsson3068d112008-11-16 19:01:22 +00003143 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003144 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003145 }
Mike Stump1eb44332009-09-09 15:08:12 +00003146
Richard Smithf10d9172011-10-11 21:43:33 +00003147 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003148 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003149 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003150 }
3151
Sebastian Redl64b45f72009-01-05 20:52:13 +00003152 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003153 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003154 }
3155
Francois Pichet6ad6f282010-12-07 00:08:36 +00003156 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3157 return Success(E->getValue(), E);
3158 }
3159
John Wiegley21ff2e52011-04-28 00:16:57 +00003160 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3161 return Success(E->getValue(), E);
3162 }
3163
John Wiegley55262202011-04-25 06:54:41 +00003164 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3165 return Success(E->getValue(), E);
3166 }
3167
Eli Friedman722c7172009-02-28 03:59:05 +00003168 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003169 bool VisitUnaryImag(const UnaryOperator *E);
3170
Sebastian Redl295995c2010-09-10 20:55:47 +00003171 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003172 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003173
Chris Lattnerfcee0012008-07-11 21:24:13 +00003174private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003175 CharUnits GetAlignOfExpr(const Expr *E);
3176 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003177 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003178 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003179 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003180};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003181} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003182
Richard Smithc49bd112011-10-28 17:51:58 +00003183/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3184/// produce either the integer value or a pointer.
3185///
3186/// GCC has a heinous extension which folds casts between pointer types and
3187/// pointer-sized integral types. We support this by allowing the evaluation of
3188/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3189/// Some simple arithmetic on such values is supported (they are treated much
3190/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003191static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003192 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003193 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003194 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003195}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003196
Richard Smithf48fdb02011-12-09 22:58:01 +00003197static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003198 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003199 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003200 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003201 if (!Val.isInt()) {
3202 // FIXME: It would be better to produce the diagnostic for casting
3203 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003204 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003205 return false;
3206 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003207 Result = Val.getInt();
3208 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003209}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003210
Richard Smithf48fdb02011-12-09 22:58:01 +00003211/// Check whether the given declaration can be directly converted to an integral
3212/// rvalue. If not, no diagnostic is produced; there are other things we can
3213/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003214bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003215 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003216 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003217 // Check for signedness/width mismatches between E type and ECD value.
3218 bool SameSign = (ECD->getInitVal().isSigned()
3219 == E->getType()->isSignedIntegerOrEnumerationType());
3220 bool SameWidth = (ECD->getInitVal().getBitWidth()
3221 == Info.Ctx.getIntWidth(E->getType()));
3222 if (SameSign && SameWidth)
3223 return Success(ECD->getInitVal(), E);
3224 else {
3225 // Get rid of mismatch (otherwise Success assertions will fail)
3226 // by computing a new value matching the type of E.
3227 llvm::APSInt Val = ECD->getInitVal();
3228 if (!SameSign)
3229 Val.setIsSigned(!ECD->getInitVal().isSigned());
3230 if (!SameWidth)
3231 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3232 return Success(Val, E);
3233 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003234 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003235 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003236}
3237
Chris Lattnera4d55d82008-10-06 06:40:35 +00003238/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3239/// as GCC.
3240static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3241 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003242 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003243 enum gcc_type_class {
3244 no_type_class = -1,
3245 void_type_class, integer_type_class, char_type_class,
3246 enumeral_type_class, boolean_type_class,
3247 pointer_type_class, reference_type_class, offset_type_class,
3248 real_type_class, complex_type_class,
3249 function_type_class, method_type_class,
3250 record_type_class, union_type_class,
3251 array_type_class, string_type_class,
3252 lang_type_class
3253 };
Mike Stump1eb44332009-09-09 15:08:12 +00003254
3255 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003256 // ideal, however it is what gcc does.
3257 if (E->getNumArgs() == 0)
3258 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003259
Chris Lattnera4d55d82008-10-06 06:40:35 +00003260 QualType ArgTy = E->getArg(0)->getType();
3261 if (ArgTy->isVoidType())
3262 return void_type_class;
3263 else if (ArgTy->isEnumeralType())
3264 return enumeral_type_class;
3265 else if (ArgTy->isBooleanType())
3266 return boolean_type_class;
3267 else if (ArgTy->isCharType())
3268 return string_type_class; // gcc doesn't appear to use char_type_class
3269 else if (ArgTy->isIntegerType())
3270 return integer_type_class;
3271 else if (ArgTy->isPointerType())
3272 return pointer_type_class;
3273 else if (ArgTy->isReferenceType())
3274 return reference_type_class;
3275 else if (ArgTy->isRealType())
3276 return real_type_class;
3277 else if (ArgTy->isComplexType())
3278 return complex_type_class;
3279 else if (ArgTy->isFunctionType())
3280 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003281 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003282 return record_type_class;
3283 else if (ArgTy->isUnionType())
3284 return union_type_class;
3285 else if (ArgTy->isArrayType())
3286 return array_type_class;
3287 else if (ArgTy->isUnionType())
3288 return union_type_class;
3289 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003290 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003291 return -1;
3292}
3293
John McCall42c8f872010-05-10 23:27:23 +00003294/// Retrieves the "underlying object type" of the given expression,
3295/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003296QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3297 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3298 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003299 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003300 } else if (const Expr *E = B.get<const Expr*>()) {
3301 if (isa<CompoundLiteralExpr>(E))
3302 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003303 }
3304
3305 return QualType();
3306}
3307
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003308bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003309 // TODO: Perhaps we should let LLVM lower this?
3310 LValue Base;
3311 if (!EvaluatePointer(E->getArg(0), Base, Info))
3312 return false;
3313
3314 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003315 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003316
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003317 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003318 if (T.isNull() ||
3319 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003320 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003321 T->isVariablyModifiedType() ||
3322 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003323 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003324
3325 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3326 CharUnits Offset = Base.getLValueOffset();
3327
3328 if (!Offset.isNegative() && Offset <= Size)
3329 Size -= Offset;
3330 else
3331 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003332 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003333}
3334
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003335bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003336 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003337 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003338 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003339
3340 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003341 if (TryEvaluateBuiltinObjectSize(E))
3342 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003343
Eric Christopherb2aaf512010-01-19 22:58:35 +00003344 // If evaluating the argument has side-effects we can't determine
3345 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003346 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003347 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003348 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003349 return Success(0, E);
3350 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003351
Richard Smithf48fdb02011-12-09 22:58:01 +00003352 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003353 }
3354
Chris Lattner019f4e82008-10-06 05:28:25 +00003355 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003356 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Richard Smithe052d462011-12-09 02:04:48 +00003358 case Builtin::BI__builtin_constant_p: {
3359 const Expr *Arg = E->getArg(0);
3360 QualType ArgType = Arg->getType();
3361 // __builtin_constant_p always has one operand. The rules which gcc follows
3362 // are not precisely documented, but are as follows:
3363 //
3364 // - If the operand is of integral, floating, complex or enumeration type,
3365 // and can be folded to a known value of that type, it returns 1.
3366 // - If the operand and can be folded to a pointer to the first character
3367 // of a string literal (or such a pointer cast to an integral type), it
3368 // returns 1.
3369 //
3370 // Otherwise, it returns 0.
3371 //
3372 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3373 // its support for this does not currently work.
3374 int IsConstant = 0;
3375 if (ArgType->isIntegralOrEnumerationType()) {
3376 // Note, a pointer cast to an integral type is only a constant if it is
3377 // a pointer to the first character of a string literal.
3378 Expr::EvalResult Result;
3379 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3380 APValue &V = Result.Val;
3381 if (V.getKind() == APValue::LValue) {
3382 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3383 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3384 } else {
3385 IsConstant = 1;
3386 }
3387 }
3388 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3389 IsConstant = Arg->isEvaluatable(Info.Ctx);
3390 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3391 LValue LV;
3392 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3393 // during the check.
3394 Expr::EvalStatus Status;
3395 EvalInfo SubInfo(Info.Ctx, Status);
3396 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3397 : EvaluatePointer(Arg, LV, SubInfo)) &&
3398 !Status.HasSideEffects)
3399 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3400 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3401 }
3402
3403 return Success(IsConstant, E);
3404 }
Chris Lattner21fb98e2009-09-23 06:06:36 +00003405 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003406 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003407 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003408 return Success(Operand, E);
3409 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003410
3411 case Builtin::BI__builtin_expect:
3412 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00003413
3414 case Builtin::BIstrlen:
3415 case Builtin::BI__builtin_strlen:
3416 // As an extension, we support strlen() and __builtin_strlen() as constant
3417 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003418 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003419 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3420 // The string literal may have embedded null characters. Find the first
3421 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003422 StringRef Str = S->getString();
3423 StringRef::size_type Pos = Str.find(0);
3424 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003425 Str = Str.substr(0, Pos);
3426
3427 return Success(Str.size(), E);
3428 }
3429
Richard Smithf48fdb02011-12-09 22:58:01 +00003430 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003431
3432 case Builtin::BI__atomic_is_lock_free: {
3433 APSInt SizeVal;
3434 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3435 return false;
3436
3437 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3438 // of two less than the maximum inline atomic width, we know it is
3439 // lock-free. If the size isn't a power of two, or greater than the
3440 // maximum alignment where we promote atomics, we know it is not lock-free
3441 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3442 // the answer can only be determined at runtime; for example, 16-byte
3443 // atomics have lock-free implementations on some, but not all,
3444 // x86-64 processors.
3445
3446 // Check power-of-two.
3447 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3448 if (!Size.isPowerOfTwo())
3449#if 0
3450 // FIXME: Suppress this folding until the ABI for the promotion width
3451 // settles.
3452 return Success(0, E);
3453#else
Richard Smithf48fdb02011-12-09 22:58:01 +00003454 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003455#endif
3456
3457#if 0
3458 // Check against promotion width.
3459 // FIXME: Suppress this folding until the ABI for the promotion width
3460 // settles.
3461 unsigned PromoteWidthBits =
3462 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3463 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3464 return Success(0, E);
3465#endif
3466
3467 // Check against inlining width.
3468 unsigned InlineWidthBits =
3469 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3470 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3471 return Success(1, E);
3472
Richard Smithf48fdb02011-12-09 22:58:01 +00003473 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003474 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003475 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00003476}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003477
Richard Smith625b8072011-10-31 01:37:14 +00003478static bool HasSameBase(const LValue &A, const LValue &B) {
3479 if (!A.getLValueBase())
3480 return !B.getLValueBase();
3481 if (!B.getLValueBase())
3482 return false;
3483
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003484 if (A.getLValueBase().getOpaqueValue() !=
3485 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00003486 const Decl *ADecl = GetLValueBaseDecl(A);
3487 if (!ADecl)
3488 return false;
3489 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00003490 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00003491 return false;
3492 }
3493
3494 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00003495 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00003496}
3497
Chris Lattnerb542afe2008-07-11 19:10:17 +00003498bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003499 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003500 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003501
John McCall2de56d12010-08-25 11:45:40 +00003502 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003503 VisitIgnoredValue(E->getLHS());
3504 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00003505 }
3506
3507 if (E->isLogicalOp()) {
3508 // These need to be handled specially because the operands aren't
3509 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003510 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00003511
Richard Smithc49bd112011-10-28 17:51:58 +00003512 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00003513 // We were able to evaluate the LHS, see if we can get away with not
3514 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00003515 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003516 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003517
Richard Smithc49bd112011-10-28 17:51:58 +00003518 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00003519 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003520 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003521 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00003522 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003523 }
3524 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00003525 // FIXME: If both evaluations fail, we should produce the diagnostic from
3526 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3527 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00003528 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003529 // We can't evaluate the LHS; however, sometimes the result
3530 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00003531 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003532 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003533 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00003534 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003535
3536 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003537 }
3538 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00003539 }
Eli Friedmana6afa762008-11-13 06:09:17 +00003540
Eli Friedmana6afa762008-11-13 06:09:17 +00003541 return false;
3542 }
3543
Anders Carlsson286f85e2008-11-16 07:17:21 +00003544 QualType LHSTy = E->getLHS()->getType();
3545 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00003546
3547 if (LHSTy->isAnyComplexType()) {
3548 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00003549 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00003550
3551 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3552 return false;
3553
3554 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3555 return false;
3556
3557 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003558 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003559 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00003560 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003561 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3562
John McCall2de56d12010-08-25 11:45:40 +00003563 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003564 return Success((CR_r == APFloat::cmpEqual &&
3565 CR_i == APFloat::cmpEqual), E);
3566 else {
John McCall2de56d12010-08-25 11:45:40 +00003567 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003568 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00003569 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003570 CR_r == APFloat::cmpLessThan ||
3571 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003572 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003573 CR_i == APFloat::cmpLessThan ||
3574 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00003575 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003576 } else {
John McCall2de56d12010-08-25 11:45:40 +00003577 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003578 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3579 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3580 else {
John McCall2de56d12010-08-25 11:45:40 +00003581 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003582 "Invalid compex comparison.");
3583 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3584 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3585 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003586 }
3587 }
Mike Stump1eb44332009-09-09 15:08:12 +00003588
Anders Carlsson286f85e2008-11-16 07:17:21 +00003589 if (LHSTy->isRealFloatingType() &&
3590 RHSTy->isRealFloatingType()) {
3591 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00003592
Anders Carlsson286f85e2008-11-16 07:17:21 +00003593 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3594 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003595
Anders Carlsson286f85e2008-11-16 07:17:21 +00003596 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3597 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003598
Anders Carlsson286f85e2008-11-16 07:17:21 +00003599 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00003600
Anders Carlsson286f85e2008-11-16 07:17:21 +00003601 switch (E->getOpcode()) {
3602 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003603 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00003604 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003605 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003606 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003607 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003608 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003609 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003610 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00003611 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00003612 E);
John McCall2de56d12010-08-25 11:45:40 +00003613 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003614 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003615 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00003616 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00003617 || CR == APFloat::cmpLessThan
3618 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00003619 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00003620 }
Mike Stump1eb44332009-09-09 15:08:12 +00003621
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003622 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00003623 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00003624 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003625 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3626 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003627
John McCallefdb83e2010-05-07 21:00:08 +00003628 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003629 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3630 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003631
Richard Smith625b8072011-10-31 01:37:14 +00003632 // Reject differing bases from the normal codepath; we special-case
3633 // comparisons to null.
3634 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00003635 // Inequalities and subtractions between unrelated pointers have
3636 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00003637 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003638 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00003639 // A constant address may compare equal to the address of a symbol.
3640 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00003641 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00003642 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3643 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003644 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003645 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00003646 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00003647 // distinct. However, we do know that the address of a literal will be
3648 // non-null.
3649 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3650 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00003651 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003652 // We can't tell whether weak symbols will end up pointing to the same
3653 // object.
3654 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00003655 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003656 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00003657 // (Note that clang defaults to -fmerge-all-constants, which can
3658 // lead to inconsistent results for comparisons involving the address
3659 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00003660 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00003661 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003662
Richard Smithcc5d4f62011-11-07 09:22:26 +00003663 // FIXME: Implement the C++11 restrictions:
3664 // - Pointer subtractions must be on elements of the same array.
3665 // - Pointer comparisons must be between members with the same access.
3666
John McCall2de56d12010-08-25 11:45:40 +00003667 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00003668 QualType Type = E->getLHS()->getType();
3669 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00003670
Richard Smith180f4792011-11-10 06:34:14 +00003671 CharUnits ElementSize;
3672 if (!HandleSizeof(Info, ElementType, ElementSize))
3673 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003674
Richard Smith180f4792011-11-10 06:34:14 +00003675 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00003676 RHSValue.getLValueOffset();
3677 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003678 }
Richard Smith625b8072011-10-31 01:37:14 +00003679
3680 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3681 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3682 switch (E->getOpcode()) {
3683 default: llvm_unreachable("missing comparison operator");
3684 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3685 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3686 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3687 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3688 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3689 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003690 }
Anders Carlsson3068d112008-11-16 19:01:22 +00003691 }
3692 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003693 if (!LHSTy->isIntegralOrEnumerationType() ||
3694 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003695 // We can't continue from here for non-integral types.
3696 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003697 }
3698
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003699 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00003700 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00003701 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003702 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00003703
Richard Smithc49bd112011-10-28 17:51:58 +00003704 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003705 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00003706 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003707
3708 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00003709 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00003710 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3711 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00003712 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00003713 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003714 else
Richard Smith47a1eed2011-10-29 20:57:55 +00003715 LHSVal.getLValueOffset() -= AdditionalOffset;
3716 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003717 return true;
3718 }
3719
3720 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00003721 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00003722 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003723 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3724 LHSVal.getInt().getZExtValue());
3725 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00003726 return true;
3727 }
3728
3729 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00003730 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00003731 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003732
Richard Smithc49bd112011-10-28 17:51:58 +00003733 APSInt &LHS = LHSVal.getInt();
3734 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00003735
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003736 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00003737 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00003738 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003739 case BO_Mul: return Success(LHS * RHS, E);
3740 case BO_Add: return Success(LHS + RHS, E);
3741 case BO_Sub: return Success(LHS - RHS, E);
3742 case BO_And: return Success(LHS & RHS, E);
3743 case BO_Xor: return Success(LHS ^ RHS, E);
3744 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003745 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00003746 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003747 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00003748 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003749 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00003750 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003751 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00003752 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003753 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00003754 // During constant-folding, a negative shift is an opposite shift.
3755 if (RHS.isSigned() && RHS.isNegative()) {
3756 RHS = -RHS;
3757 goto shift_right;
3758 }
3759
3760 shift_left:
3761 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00003762 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3763 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003764 }
John McCall2de56d12010-08-25 11:45:40 +00003765 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00003766 // During constant-folding, a negative shift is an opposite shift.
3767 if (RHS.isSigned() && RHS.isNegative()) {
3768 RHS = -RHS;
3769 goto shift_left;
3770 }
3771
3772 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00003773 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00003774 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3775 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003776 }
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Richard Smithc49bd112011-10-28 17:51:58 +00003778 case BO_LT: return Success(LHS < RHS, E);
3779 case BO_GT: return Success(LHS > RHS, E);
3780 case BO_LE: return Success(LHS <= RHS, E);
3781 case BO_GE: return Success(LHS >= RHS, E);
3782 case BO_EQ: return Success(LHS == RHS, E);
3783 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00003784 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003785}
3786
Ken Dyck8b752f12010-01-27 17:10:57 +00003787CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00003788 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3789 // the result is the size of the referenced type."
3790 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3791 // result shall be the alignment of the referenced type."
3792 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3793 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00003794
3795 // __alignof is defined to return the preferred alignment.
3796 return Info.Ctx.toCharUnitsFromBits(
3797 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00003798}
3799
Ken Dyck8b752f12010-01-27 17:10:57 +00003800CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00003801 E = E->IgnoreParens();
3802
3803 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00003804 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00003805 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00003806 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3807 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00003808
Chris Lattneraf707ab2009-01-24 21:53:27 +00003809 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00003810 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3811 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00003812
Chris Lattnere9feb472009-01-24 21:09:06 +00003813 return GetAlignOfType(E->getType());
3814}
3815
3816
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003817/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3818/// a result as the expression's type.
3819bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3820 const UnaryExprOrTypeTraitExpr *E) {
3821 switch(E->getKind()) {
3822 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00003823 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003824 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00003825 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003826 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00003827 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003828
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003829 case UETT_VecStep: {
3830 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00003831
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003832 if (Ty->isVectorType()) {
3833 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00003834
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003835 // The vec_step built-in functions that take a 3-component
3836 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3837 if (n == 3)
3838 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00003839
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003840 return Success(n, E);
3841 } else
3842 return Success(1, E);
3843 }
3844
3845 case UETT_SizeOf: {
3846 QualType SrcTy = E->getTypeOfArgument();
3847 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3848 // the result is the size of the referenced type."
3849 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3850 // result shall be the alignment of the referenced type."
3851 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3852 SrcTy = Ref->getPointeeType();
3853
Richard Smith180f4792011-11-10 06:34:14 +00003854 CharUnits Sizeof;
3855 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003856 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003857 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003858 }
3859 }
3860
3861 llvm_unreachable("unknown expr/type trait");
Richard Smithf48fdb02011-12-09 22:58:01 +00003862 return Error(E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00003863}
3864
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003865bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003866 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003867 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003868 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003869 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003870 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003871 for (unsigned i = 0; i != n; ++i) {
3872 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3873 switch (ON.getKind()) {
3874 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003875 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003876 APSInt IdxResult;
3877 if (!EvaluateInteger(Idx, IdxResult, Info))
3878 return false;
3879 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3880 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003881 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003882 CurrentType = AT->getElementType();
3883 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3884 Result += IdxResult.getSExtValue() * ElementSize;
3885 break;
3886 }
Richard Smithf48fdb02011-12-09 22:58:01 +00003887
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003888 case OffsetOfExpr::OffsetOfNode::Field: {
3889 FieldDecl *MemberDecl = ON.getField();
3890 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00003891 if (!RT)
3892 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003893 RecordDecl *RD = RT->getDecl();
3894 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00003895 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003896 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00003897 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003898 CurrentType = MemberDecl->getType().getNonReferenceType();
3899 break;
3900 }
Richard Smithf48fdb02011-12-09 22:58:01 +00003901
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003902 case OffsetOfExpr::OffsetOfNode::Identifier:
3903 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00003904 return Error(OOE);
3905
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003906 case OffsetOfExpr::OffsetOfNode::Base: {
3907 CXXBaseSpecifier *BaseSpec = ON.getBase();
3908 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00003909 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003910
3911 // Find the layout of the class whose base we are looking into.
3912 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00003913 if (!RT)
3914 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003915 RecordDecl *RD = RT->getDecl();
3916 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3917
3918 // Find the base class itself.
3919 CurrentType = BaseSpec->getType();
3920 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3921 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003922 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003923
3924 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00003925 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003926 break;
3927 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003928 }
3929 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003930 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003931}
3932
Chris Lattnerb542afe2008-07-11 19:10:17 +00003933bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003934 switch (E->getOpcode()) {
3935 default:
3936 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3937 // See C99 6.6p3.
3938 return Error(E);
3939 case UO_Extension:
3940 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3941 // If so, we could clear the diagnostic ID.
3942 return Visit(E->getSubExpr());
3943 case UO_Plus:
3944 // The result is just the value.
3945 return Visit(E->getSubExpr());
3946 case UO_Minus: {
3947 if (!Visit(E->getSubExpr()))
3948 return false;
3949 if (!Result.isInt()) return Error(E);
3950 return Success(-Result.getInt(), E);
3951 }
3952 case UO_Not: {
3953 if (!Visit(E->getSubExpr()))
3954 return false;
3955 if (!Result.isInt()) return Error(E);
3956 return Success(~Result.getInt(), E);
3957 }
3958 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00003959 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00003960 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00003961 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003962 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003963 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003964 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003965}
Mike Stump1eb44332009-09-09 15:08:12 +00003966
Chris Lattner732b2232008-07-12 01:15:53 +00003967/// HandleCast - This is used to evaluate implicit or explicit casts where the
3968/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003969bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3970 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00003971 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00003972 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00003973
Eli Friedman46a52322011-03-25 00:43:55 +00003974 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00003975 case CK_BaseToDerived:
3976 case CK_DerivedToBase:
3977 case CK_UncheckedDerivedToBase:
3978 case CK_Dynamic:
3979 case CK_ToUnion:
3980 case CK_ArrayToPointerDecay:
3981 case CK_FunctionToPointerDecay:
3982 case CK_NullToPointer:
3983 case CK_NullToMemberPointer:
3984 case CK_BaseToDerivedMemberPointer:
3985 case CK_DerivedToBaseMemberPointer:
3986 case CK_ConstructorConversion:
3987 case CK_IntegralToPointer:
3988 case CK_ToVoid:
3989 case CK_VectorSplat:
3990 case CK_IntegralToFloating:
3991 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003992 case CK_CPointerToObjCPointerCast:
3993 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00003994 case CK_AnyPointerToBlockPointerCast:
3995 case CK_ObjCObjectLValueCast:
3996 case CK_FloatingRealToComplex:
3997 case CK_FloatingComplexToReal:
3998 case CK_FloatingComplexCast:
3999 case CK_FloatingComplexToIntegralComplex:
4000 case CK_IntegralRealToComplex:
4001 case CK_IntegralComplexCast:
4002 case CK_IntegralComplexToFloatingComplex:
4003 llvm_unreachable("invalid cast kind for integral value");
4004
Eli Friedmane50c2972011-03-25 19:07:11 +00004005 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004006 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004007 case CK_LValueBitCast:
4008 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00004009 case CK_ARCProduceObject:
4010 case CK_ARCConsumeObject:
4011 case CK_ARCReclaimReturnedObject:
4012 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004013 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004014
4015 case CK_LValueToRValue:
4016 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004017 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004018
4019 case CK_MemberPointerToBoolean:
4020 case CK_PointerToBoolean:
4021 case CK_IntegralToBoolean:
4022 case CK_FloatingToBoolean:
4023 case CK_FloatingComplexToBoolean:
4024 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004025 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004026 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004027 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004028 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004029 }
4030
Eli Friedman46a52322011-03-25 00:43:55 +00004031 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004032 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004033 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004034
Eli Friedmanbe265702009-02-20 01:15:07 +00004035 if (!Result.isInt()) {
4036 // Only allow casts of lvalues if they are lossless.
4037 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4038 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004039
Daniel Dunbardd211642009-02-19 22:24:01 +00004040 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004041 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004042 }
Mike Stump1eb44332009-09-09 15:08:12 +00004043
Eli Friedman46a52322011-03-25 00:43:55 +00004044 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004045 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4046
John McCallefdb83e2010-05-07 21:00:08 +00004047 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004048 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004049 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004050
Daniel Dunbardd211642009-02-19 22:24:01 +00004051 if (LV.getLValueBase()) {
4052 // Only allow based lvalue casts if they are lossless.
4053 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004054 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004055
Richard Smithb755a9d2011-11-16 07:18:12 +00004056 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004057 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004058 return true;
4059 }
4060
Ken Dycka7305832010-01-15 12:37:54 +00004061 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4062 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00004063 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004064 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004065
Eli Friedman46a52322011-03-25 00:43:55 +00004066 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004067 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004068 if (!EvaluateComplex(SubExpr, C, Info))
4069 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004070 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004071 }
Eli Friedman2217c872009-02-22 11:46:18 +00004072
Eli Friedman46a52322011-03-25 00:43:55 +00004073 case CK_FloatingToIntegral: {
4074 APFloat F(0.0);
4075 if (!EvaluateFloat(SubExpr, F, Info))
4076 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004077
Richard Smithc1c5f272011-12-13 06:39:58 +00004078 APSInt Value;
4079 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4080 return false;
4081 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004082 }
4083 }
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Eli Friedman46a52322011-03-25 00:43:55 +00004085 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004086 return Error(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004087}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004088
Eli Friedman722c7172009-02-28 03:59:05 +00004089bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4090 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004091 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004092 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4093 return false;
4094 if (!LV.isComplexInt())
4095 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004096 return Success(LV.getComplexIntReal(), E);
4097 }
4098
4099 return Visit(E->getSubExpr());
4100}
4101
Eli Friedman664a1042009-02-27 04:45:43 +00004102bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004103 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004104 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004105 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4106 return false;
4107 if (!LV.isComplexInt())
4108 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004109 return Success(LV.getComplexIntImag(), E);
4110 }
4111
Richard Smith8327fad2011-10-24 18:44:57 +00004112 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004113 return Success(0, E);
4114}
4115
Douglas Gregoree8aff02011-01-04 17:33:58 +00004116bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4117 return Success(E->getPackLength(), E);
4118}
4119
Sebastian Redl295995c2010-09-10 20:55:47 +00004120bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4121 return Success(E->getValue(), E);
4122}
4123
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004124//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004125// Float Evaluation
4126//===----------------------------------------------------------------------===//
4127
4128namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004129class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004130 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004131 APFloat &Result;
4132public:
4133 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004134 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004135
Richard Smith47a1eed2011-10-29 20:57:55 +00004136 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004137 Result = V.getFloat();
4138 return true;
4139 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004140
Richard Smithf10d9172011-10-11 21:43:33 +00004141 bool ValueInitialization(const Expr *E) {
4142 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4143 return true;
4144 }
4145
Chris Lattner019f4e82008-10-06 05:28:25 +00004146 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004147
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004148 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004149 bool VisitBinaryOperator(const BinaryOperator *E);
4150 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004151 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004152
John McCallabd3a852010-05-07 22:08:54 +00004153 bool VisitUnaryReal(const UnaryOperator *E);
4154 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004155
John McCallabd3a852010-05-07 22:08:54 +00004156 // FIXME: Missing: array subscript of vector, member of vector,
4157 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004158};
4159} // end anonymous namespace
4160
4161static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004162 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004163 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004164}
4165
Jay Foad4ba2a172011-01-12 09:06:06 +00004166static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004167 QualType ResultTy,
4168 const Expr *Arg,
4169 bool SNaN,
4170 llvm::APFloat &Result) {
4171 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4172 if (!S) return false;
4173
4174 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4175
4176 llvm::APInt fill;
4177
4178 // Treat empty strings as if they were zero.
4179 if (S->getString().empty())
4180 fill = llvm::APInt(32, 0);
4181 else if (S->getString().getAsInteger(0, fill))
4182 return false;
4183
4184 if (SNaN)
4185 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4186 else
4187 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4188 return true;
4189}
4190
Chris Lattner019f4e82008-10-06 05:28:25 +00004191bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004192 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004193 default:
4194 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4195
Chris Lattner019f4e82008-10-06 05:28:25 +00004196 case Builtin::BI__builtin_huge_val:
4197 case Builtin::BI__builtin_huge_valf:
4198 case Builtin::BI__builtin_huge_vall:
4199 case Builtin::BI__builtin_inf:
4200 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004201 case Builtin::BI__builtin_infl: {
4202 const llvm::fltSemantics &Sem =
4203 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004204 Result = llvm::APFloat::getInf(Sem);
4205 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004206 }
Mike Stump1eb44332009-09-09 15:08:12 +00004207
John McCalldb7b72a2010-02-28 13:00:19 +00004208 case Builtin::BI__builtin_nans:
4209 case Builtin::BI__builtin_nansf:
4210 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004211 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4212 true, Result))
4213 return Error(E);
4214 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004215
Chris Lattner9e621712008-10-06 06:31:58 +00004216 case Builtin::BI__builtin_nan:
4217 case Builtin::BI__builtin_nanf:
4218 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004219 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004220 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004221 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4222 false, Result))
4223 return Error(E);
4224 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004225
4226 case Builtin::BI__builtin_fabs:
4227 case Builtin::BI__builtin_fabsf:
4228 case Builtin::BI__builtin_fabsl:
4229 if (!EvaluateFloat(E->getArg(0), Result, Info))
4230 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004231
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004232 if (Result.isNegative())
4233 Result.changeSign();
4234 return true;
4235
Mike Stump1eb44332009-09-09 15:08:12 +00004236 case Builtin::BI__builtin_copysign:
4237 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004238 case Builtin::BI__builtin_copysignl: {
4239 APFloat RHS(0.);
4240 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4241 !EvaluateFloat(E->getArg(1), RHS, Info))
4242 return false;
4243 Result.copySign(RHS);
4244 return true;
4245 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004246 }
4247}
4248
John McCallabd3a852010-05-07 22:08:54 +00004249bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004250 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4251 ComplexValue CV;
4252 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4253 return false;
4254 Result = CV.FloatReal;
4255 return true;
4256 }
4257
4258 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004259}
4260
4261bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004262 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4263 ComplexValue CV;
4264 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4265 return false;
4266 Result = CV.FloatImag;
4267 return true;
4268 }
4269
Richard Smith8327fad2011-10-24 18:44:57 +00004270 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004271 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4272 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004273 return true;
4274}
4275
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004276bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004277 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004278 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004279 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004280 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004281 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004282 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4283 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004284 Result.changeSign();
4285 return true;
4286 }
4287}
Chris Lattner019f4e82008-10-06 05:28:25 +00004288
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004289bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004290 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4291 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004292
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004293 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004294 if (!EvaluateFloat(E->getLHS(), Result, Info))
4295 return false;
4296 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4297 return false;
4298
4299 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004300 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004301 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004302 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4303 return true;
John McCall2de56d12010-08-25 11:45:40 +00004304 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004305 Result.add(RHS, APFloat::rmNearestTiesToEven);
4306 return true;
John McCall2de56d12010-08-25 11:45:40 +00004307 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004308 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4309 return true;
John McCall2de56d12010-08-25 11:45:40 +00004310 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004311 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4312 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004313 }
4314}
4315
4316bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4317 Result = E->getValue();
4318 return true;
4319}
4320
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004321bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4322 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004323
Eli Friedman2a523ee2011-03-25 00:54:52 +00004324 switch (E->getCastKind()) {
4325 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004326 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004327
4328 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004329 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004330 return EvaluateInteger(SubExpr, IntResult, Info) &&
4331 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4332 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004333 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004334
4335 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004336 if (!Visit(SubExpr))
4337 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004338 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4339 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004340 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004341
Eli Friedman2a523ee2011-03-25 00:54:52 +00004342 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004343 ComplexValue V;
4344 if (!EvaluateComplex(SubExpr, V, Info))
4345 return false;
4346 Result = V.getComplexFloatReal();
4347 return true;
4348 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004349 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004350
Richard Smithf48fdb02011-12-09 22:58:01 +00004351 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004352}
4353
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004354//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004355// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004356//===----------------------------------------------------------------------===//
4357
4358namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004359class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004360 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004361 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004362
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004363public:
John McCallf4cf1a12010-05-07 17:22:02 +00004364 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004365 : ExprEvaluatorBaseTy(info), Result(Result) {}
4366
Richard Smith47a1eed2011-10-29 20:57:55 +00004367 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004368 Result.setFrom(V);
4369 return true;
4370 }
Mike Stump1eb44332009-09-09 15:08:12 +00004371
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004372 //===--------------------------------------------------------------------===//
4373 // Visitor Methods
4374 //===--------------------------------------------------------------------===//
4375
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004376 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004377
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004378 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004379
John McCallf4cf1a12010-05-07 17:22:02 +00004380 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004381 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004382 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004383};
4384} // end anonymous namespace
4385
John McCallf4cf1a12010-05-07 17:22:02 +00004386static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4387 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004388 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004389 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004390}
4391
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004392bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4393 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004394
4395 if (SubExpr->getType()->isRealFloatingType()) {
4396 Result.makeComplexFloat();
4397 APFloat &Imag = Result.FloatImag;
4398 if (!EvaluateFloat(SubExpr, Imag, Info))
4399 return false;
4400
4401 Result.FloatReal = APFloat(Imag.getSemantics());
4402 return true;
4403 } else {
4404 assert(SubExpr->getType()->isIntegerType() &&
4405 "Unexpected imaginary literal.");
4406
4407 Result.makeComplexInt();
4408 APSInt &Imag = Result.IntImag;
4409 if (!EvaluateInteger(SubExpr, Imag, Info))
4410 return false;
4411
4412 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4413 return true;
4414 }
4415}
4416
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004417bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004418
John McCall8786da72010-12-14 17:51:41 +00004419 switch (E->getCastKind()) {
4420 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00004421 case CK_BaseToDerived:
4422 case CK_DerivedToBase:
4423 case CK_UncheckedDerivedToBase:
4424 case CK_Dynamic:
4425 case CK_ToUnion:
4426 case CK_ArrayToPointerDecay:
4427 case CK_FunctionToPointerDecay:
4428 case CK_NullToPointer:
4429 case CK_NullToMemberPointer:
4430 case CK_BaseToDerivedMemberPointer:
4431 case CK_DerivedToBaseMemberPointer:
4432 case CK_MemberPointerToBoolean:
4433 case CK_ConstructorConversion:
4434 case CK_IntegralToPointer:
4435 case CK_PointerToIntegral:
4436 case CK_PointerToBoolean:
4437 case CK_ToVoid:
4438 case CK_VectorSplat:
4439 case CK_IntegralCast:
4440 case CK_IntegralToBoolean:
4441 case CK_IntegralToFloating:
4442 case CK_FloatingToIntegral:
4443 case CK_FloatingToBoolean:
4444 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004445 case CK_CPointerToObjCPointerCast:
4446 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00004447 case CK_AnyPointerToBlockPointerCast:
4448 case CK_ObjCObjectLValueCast:
4449 case CK_FloatingComplexToReal:
4450 case CK_FloatingComplexToBoolean:
4451 case CK_IntegralComplexToReal:
4452 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00004453 case CK_ARCProduceObject:
4454 case CK_ARCConsumeObject:
4455 case CK_ARCReclaimReturnedObject:
4456 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00004457 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00004458
John McCall8786da72010-12-14 17:51:41 +00004459 case CK_LValueToRValue:
4460 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004461 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00004462
4463 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004464 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00004465 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00004466 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00004467
4468 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004469 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00004470 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004471 return false;
4472
John McCall8786da72010-12-14 17:51:41 +00004473 Result.makeComplexFloat();
4474 Result.FloatImag = APFloat(Real.getSemantics());
4475 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004476 }
4477
John McCall8786da72010-12-14 17:51:41 +00004478 case CK_FloatingComplexCast: {
4479 if (!Visit(E->getSubExpr()))
4480 return false;
4481
4482 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4483 QualType From
4484 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4485
Richard Smithc1c5f272011-12-13 06:39:58 +00004486 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4487 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004488 }
4489
4490 case CK_FloatingComplexToIntegralComplex: {
4491 if (!Visit(E->getSubExpr()))
4492 return false;
4493
4494 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4495 QualType From
4496 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4497 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00004498 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4499 To, Result.IntReal) &&
4500 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4501 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00004502 }
4503
4504 case CK_IntegralRealToComplex: {
4505 APSInt &Real = Result.IntReal;
4506 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4507 return false;
4508
4509 Result.makeComplexInt();
4510 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4511 return true;
4512 }
4513
4514 case CK_IntegralComplexCast: {
4515 if (!Visit(E->getSubExpr()))
4516 return false;
4517
4518 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4519 QualType From
4520 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4521
4522 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4523 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4524 return true;
4525 }
4526
4527 case CK_IntegralComplexToFloatingComplex: {
4528 if (!Visit(E->getSubExpr()))
4529 return false;
4530
4531 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4532 QualType From
4533 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4534 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00004535 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4536 To, Result.FloatReal) &&
4537 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4538 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004539 }
4540 }
4541
4542 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004543 return Error(E);
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004544}
4545
John McCallf4cf1a12010-05-07 17:22:02 +00004546bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004547 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00004548 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4549
John McCallf4cf1a12010-05-07 17:22:02 +00004550 if (!Visit(E->getLHS()))
4551 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004552
John McCallf4cf1a12010-05-07 17:22:02 +00004553 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004554 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00004555 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004556
Daniel Dunbar3f279872009-01-29 01:32:56 +00004557 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4558 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004559 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004560 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004561 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004562 if (Result.isComplexFloat()) {
4563 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4564 APFloat::rmNearestTiesToEven);
4565 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4566 APFloat::rmNearestTiesToEven);
4567 } else {
4568 Result.getComplexIntReal() += RHS.getComplexIntReal();
4569 Result.getComplexIntImag() += RHS.getComplexIntImag();
4570 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004571 break;
John McCall2de56d12010-08-25 11:45:40 +00004572 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004573 if (Result.isComplexFloat()) {
4574 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4575 APFloat::rmNearestTiesToEven);
4576 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4577 APFloat::rmNearestTiesToEven);
4578 } else {
4579 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4580 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4581 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004582 break;
John McCall2de56d12010-08-25 11:45:40 +00004583 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00004584 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004585 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00004586 APFloat &LHS_r = LHS.getComplexFloatReal();
4587 APFloat &LHS_i = LHS.getComplexFloatImag();
4588 APFloat &RHS_r = RHS.getComplexFloatReal();
4589 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00004590
Daniel Dunbar3f279872009-01-29 01:32:56 +00004591 APFloat Tmp = LHS_r;
4592 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4593 Result.getComplexFloatReal() = Tmp;
4594 Tmp = LHS_i;
4595 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4596 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4597
4598 Tmp = LHS_r;
4599 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4600 Result.getComplexFloatImag() = Tmp;
4601 Tmp = LHS_i;
4602 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4603 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4604 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00004605 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004606 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004607 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4608 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00004609 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004610 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4611 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4612 }
4613 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004614 case BO_Div:
4615 if (Result.isComplexFloat()) {
4616 ComplexValue LHS = Result;
4617 APFloat &LHS_r = LHS.getComplexFloatReal();
4618 APFloat &LHS_i = LHS.getComplexFloatImag();
4619 APFloat &RHS_r = RHS.getComplexFloatReal();
4620 APFloat &RHS_i = RHS.getComplexFloatImag();
4621 APFloat &Res_r = Result.getComplexFloatReal();
4622 APFloat &Res_i = Result.getComplexFloatImag();
4623
4624 APFloat Den = RHS_r;
4625 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4626 APFloat Tmp = RHS_i;
4627 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4628 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4629
4630 Res_r = LHS_r;
4631 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4632 Tmp = LHS_i;
4633 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4634 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4635 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4636
4637 Res_i = LHS_i;
4638 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4639 Tmp = LHS_r;
4640 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4641 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4642 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4643 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004644 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4645 return Error(E, diag::note_expr_divide_by_zero);
4646
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004647 ComplexValue LHS = Result;
4648 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4649 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4650 Result.getComplexIntReal() =
4651 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4652 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4653 Result.getComplexIntImag() =
4654 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4655 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4656 }
4657 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004658 }
4659
John McCallf4cf1a12010-05-07 17:22:02 +00004660 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004661}
4662
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004663bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4664 // Get the operand value into 'Result'.
4665 if (!Visit(E->getSubExpr()))
4666 return false;
4667
4668 switch (E->getOpcode()) {
4669 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004670 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004671 case UO_Extension:
4672 return true;
4673 case UO_Plus:
4674 // The result is always just the subexpr.
4675 return true;
4676 case UO_Minus:
4677 if (Result.isComplexFloat()) {
4678 Result.getComplexFloatReal().changeSign();
4679 Result.getComplexFloatImag().changeSign();
4680 }
4681 else {
4682 Result.getComplexIntReal() = -Result.getComplexIntReal();
4683 Result.getComplexIntImag() = -Result.getComplexIntImag();
4684 }
4685 return true;
4686 case UO_Not:
4687 if (Result.isComplexFloat())
4688 Result.getComplexFloatImag().changeSign();
4689 else
4690 Result.getComplexIntImag() = -Result.getComplexIntImag();
4691 return true;
4692 }
4693}
4694
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004695//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00004696// Void expression evaluation, primarily for a cast to void on the LHS of a
4697// comma operator
4698//===----------------------------------------------------------------------===//
4699
4700namespace {
4701class VoidExprEvaluator
4702 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4703public:
4704 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4705
4706 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00004707
4708 bool VisitCastExpr(const CastExpr *E) {
4709 switch (E->getCastKind()) {
4710 default:
4711 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4712 case CK_ToVoid:
4713 VisitIgnoredValue(E->getSubExpr());
4714 return true;
4715 }
4716 }
4717};
4718} // end anonymous namespace
4719
4720static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4721 assert(E->isRValue() && E->getType()->isVoidType());
4722 return VoidExprEvaluator(Info).Visit(E);
4723}
4724
4725//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00004726// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004727//===----------------------------------------------------------------------===//
4728
Richard Smith47a1eed2011-10-29 20:57:55 +00004729static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004730 // In C, function designators are not lvalues, but we evaluate them as if they
4731 // are.
4732 if (E->isGLValue() || E->getType()->isFunctionType()) {
4733 LValue LV;
4734 if (!EvaluateLValue(E, LV, Info))
4735 return false;
4736 LV.moveInto(Result);
4737 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004738 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00004739 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00004740 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004741 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004742 return false;
John McCallefdb83e2010-05-07 21:00:08 +00004743 } else if (E->getType()->hasPointerRepresentation()) {
4744 LValue LV;
4745 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004746 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004747 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00004748 } else if (E->getType()->isRealFloatingType()) {
4749 llvm::APFloat F(0.0);
4750 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004751 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004752 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00004753 } else if (E->getType()->isAnyComplexType()) {
4754 ComplexValue C;
4755 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004756 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004757 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00004758 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004759 MemberPtr P;
4760 if (!EvaluateMemberPointer(E, P, Info))
4761 return false;
4762 P.moveInto(Result);
4763 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00004764 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00004765 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004766 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00004767 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00004768 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004769 Result = Info.CurrentCall->Temporaries[E];
Richard Smith69c2c502011-11-04 05:33:44 +00004770 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00004771 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004772 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00004773 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4774 return false;
4775 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00004776 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00004777 if (Info.getLangOpts().CPlusPlus0x)
4778 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
4779 << E->getType();
4780 else
4781 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00004782 if (!EvaluateVoid(E, Info))
4783 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004784 } else if (Info.getLangOpts().CPlusPlus0x) {
4785 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
4786 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004787 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00004788 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00004789 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004790 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004791
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00004792 return true;
4793}
4794
Richard Smith69c2c502011-11-04 05:33:44 +00004795/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4796/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4797/// since later initializers for an object can indirectly refer to subobjects
4798/// which were initialized earlier.
4799static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00004800 const LValue &This, const Expr *E,
4801 CheckConstantExpressionKind CCEK) {
Richard Smith69c2c502011-11-04 05:33:44 +00004802 if (E->isRValue() && E->getType()->isLiteralType()) {
4803 // Evaluate arrays and record types in-place, so that later initializers can
4804 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00004805 if (E->getType()->isArrayType())
4806 return EvaluateArray(E, This, Result, Info);
4807 else if (E->getType()->isRecordType())
4808 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00004809 }
4810
4811 // For any other type, in-place evaluation is unimportant.
4812 CCValue CoreConstResult;
4813 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00004814 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00004815}
4816
Richard Smithf48fdb02011-12-09 22:58:01 +00004817/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4818/// lvalue-to-rvalue cast if it is an lvalue.
4819static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4820 CCValue Value;
4821 if (!::Evaluate(Value, Info, E))
4822 return false;
4823
4824 if (E->isGLValue()) {
4825 LValue LV;
4826 LV.setFrom(Value);
4827 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4828 return false;
4829 }
4830
4831 // Check this core constant expression is a constant expression, and if so,
4832 // convert it to one.
4833 return CheckConstantExpression(Info, E, Value, Result);
4834}
Richard Smithc49bd112011-10-28 17:51:58 +00004835
Richard Smith51f47082011-10-29 00:50:52 +00004836/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00004837/// any crazy technique (that has nothing to do with language standards) that
4838/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00004839/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4840/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00004841bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00004842 // Fast-path evaluations of integer literals, since we sometimes see files
4843 // containing vast quantities of these.
4844 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4845 Result.Val = APValue(APSInt(L->getValue(),
4846 L->getType()->isUnsignedIntegerType()));
4847 return true;
4848 }
4849
Richard Smith1445bba2011-11-10 03:30:42 +00004850 // FIXME: Evaluating initializers for large arrays can cause performance
4851 // problems, and we don't use such values yet. Once we have a more efficient
4852 // array representation, this should be reinstated, and used by CodeGen.
Richard Smithe24f5fc2011-11-17 22:56:20 +00004853 // The same problem affects large records.
4854 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4855 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00004856 return false;
4857
Richard Smith180f4792011-11-10 06:34:14 +00004858 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf48fdb02011-12-09 22:58:01 +00004859 EvalInfo Info(Ctx, Result);
4860 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00004861}
4862
Jay Foad4ba2a172011-01-12 09:06:06 +00004863bool Expr::EvaluateAsBooleanCondition(bool &Result,
4864 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00004865 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00004866 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00004867 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00004868 Result);
John McCallcd7a4452010-01-05 23:42:56 +00004869}
4870
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004871bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00004872 EvalResult ExprResult;
Richard Smith51f47082011-10-29 00:50:52 +00004873 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf48fdb02011-12-09 22:58:01 +00004874 !ExprResult.Val.isInt())
Richard Smithc49bd112011-10-28 17:51:58 +00004875 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004876
Richard Smithc49bd112011-10-28 17:51:58 +00004877 Result = ExprResult.Val.getInt();
4878 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004879}
4880
Jay Foad4ba2a172011-01-12 09:06:06 +00004881bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00004882 EvalInfo Info(Ctx, Result);
4883
John McCallefdb83e2010-05-07 21:00:08 +00004884 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00004885 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00004886 CheckLValueConstantExpression(Info, this, LV, Result.Val,
4887 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00004888}
4889
Richard Smith51f47082011-10-29 00:50:52 +00004890/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4891/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00004892bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00004893 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00004894 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00004895}
Anders Carlsson51fe9962008-11-22 21:04:56 +00004896
Jay Foad4ba2a172011-01-12 09:06:06 +00004897bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00004898 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004899}
4900
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004901APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004902 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00004903 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00004904 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00004905 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004906 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00004907
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004908 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00004909}
John McCalld905f5a2010-05-07 05:32:02 +00004910
Abramo Bagnarae17a6432010-05-14 17:07:14 +00004911 bool Expr::EvalResult::isGlobalLValue() const {
4912 assert(Val.isLValue());
4913 return IsGlobalLValue(Val.getLValueBase());
4914 }
4915
4916
John McCalld905f5a2010-05-07 05:32:02 +00004917/// isIntegerConstantExpr - this recursive routine will test if an expression is
4918/// an integer constant expression.
4919
4920/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4921/// comma, etc
4922///
4923/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4924/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4925/// cast+dereference.
4926
4927// CheckICE - This function does the fundamental ICE checking: the returned
4928// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4929// Note that to reduce code duplication, this helper does no evaluation
4930// itself; the caller checks whether the expression is evaluatable, and
4931// in the rare cases where CheckICE actually cares about the evaluated
4932// value, it calls into Evalute.
4933//
4934// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00004935// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00004936// 1: This expression is not an ICE, but if it isn't evaluated, it's
4937// a legal subexpression for an ICE. This return value is used to handle
4938// the comma operator in C99 mode.
4939// 2: This expression is not an ICE, and is not a legal subexpression for one.
4940
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004941namespace {
4942
John McCalld905f5a2010-05-07 05:32:02 +00004943struct ICEDiag {
4944 unsigned Val;
4945 SourceLocation Loc;
4946
4947 public:
4948 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4949 ICEDiag() : Val(0) {}
4950};
4951
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004952}
4953
4954static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00004955
4956static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4957 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00004958 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00004959 !EVResult.Val.isInt()) {
4960 return ICEDiag(2, E->getLocStart());
4961 }
4962 return NoDiag();
4963}
4964
4965static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4966 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004967 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00004968 return ICEDiag(2, E->getLocStart());
4969 }
4970
4971 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00004972#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00004973#define STMT(Node, Base) case Expr::Node##Class:
4974#define EXPR(Node, Base)
4975#include "clang/AST/StmtNodes.inc"
4976 case Expr::PredefinedExprClass:
4977 case Expr::FloatingLiteralClass:
4978 case Expr::ImaginaryLiteralClass:
4979 case Expr::StringLiteralClass:
4980 case Expr::ArraySubscriptExprClass:
4981 case Expr::MemberExprClass:
4982 case Expr::CompoundAssignOperatorClass:
4983 case Expr::CompoundLiteralExprClass:
4984 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004985 case Expr::DesignatedInitExprClass:
4986 case Expr::ImplicitValueInitExprClass:
4987 case Expr::ParenListExprClass:
4988 case Expr::VAArgExprClass:
4989 case Expr::AddrLabelExprClass:
4990 case Expr::StmtExprClass:
4991 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00004992 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004993 case Expr::CXXDynamicCastExprClass:
4994 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00004995 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004996 case Expr::CXXNullPtrLiteralExprClass:
4997 case Expr::CXXThisExprClass:
4998 case Expr::CXXThrowExprClass:
4999 case Expr::CXXNewExprClass:
5000 case Expr::CXXDeleteExprClass:
5001 case Expr::CXXPseudoDestructorExprClass:
5002 case Expr::UnresolvedLookupExprClass:
5003 case Expr::DependentScopeDeclRefExprClass:
5004 case Expr::CXXConstructExprClass:
5005 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005006 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005007 case Expr::CXXTemporaryObjectExprClass:
5008 case Expr::CXXUnresolvedConstructExprClass:
5009 case Expr::CXXDependentScopeMemberExprClass:
5010 case Expr::UnresolvedMemberExprClass:
5011 case Expr::ObjCStringLiteralClass:
5012 case Expr::ObjCEncodeExprClass:
5013 case Expr::ObjCMessageExprClass:
5014 case Expr::ObjCSelectorExprClass:
5015 case Expr::ObjCProtocolExprClass:
5016 case Expr::ObjCIvarRefExprClass:
5017 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005018 case Expr::ObjCIsaExprClass:
5019 case Expr::ShuffleVectorExprClass:
5020 case Expr::BlockExprClass:
5021 case Expr::BlockDeclRefExprClass:
5022 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005023 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005024 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005025 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005026 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005027 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005028 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005029 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005030 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005031 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005032 return ICEDiag(2, E->getLocStart());
5033
Douglas Gregoree8aff02011-01-04 17:33:58 +00005034 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005035 case Expr::GNUNullExprClass:
5036 // GCC considers the GNU __null value to be an integral constant expression.
5037 return NoDiag();
5038
John McCall91a57552011-07-15 05:09:51 +00005039 case Expr::SubstNonTypeTemplateParmExprClass:
5040 return
5041 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5042
John McCalld905f5a2010-05-07 05:32:02 +00005043 case Expr::ParenExprClass:
5044 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005045 case Expr::GenericSelectionExprClass:
5046 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005047 case Expr::IntegerLiteralClass:
5048 case Expr::CharacterLiteralClass:
5049 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005050 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005051 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005052 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005053 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005054 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005055 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005056 return NoDiag();
5057 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005058 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005059 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5060 // constant expressions, but they can never be ICEs because an ICE cannot
5061 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005062 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005063 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005064 return CheckEvalInICE(E, Ctx);
5065 return ICEDiag(2, E->getLocStart());
5066 }
5067 case Expr::DeclRefExprClass:
5068 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5069 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005070 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005071 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5072
5073 // Parameter variables are never constants. Without this check,
5074 // getAnyInitializer() can find a default argument, which leads
5075 // to chaos.
5076 if (isa<ParmVarDecl>(D))
5077 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5078
5079 // C++ 7.1.5.1p2
5080 // A variable of non-volatile const-qualified integral or enumeration
5081 // type initialized by an ICE can be used in ICEs.
5082 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005083 if (!Dcl->getType()->isIntegralOrEnumerationType())
5084 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5085
John McCalld905f5a2010-05-07 05:32:02 +00005086 // Look for a declaration of this variable that has an initializer.
5087 const VarDecl *ID = 0;
5088 const Expr *Init = Dcl->getAnyInitializer(ID);
5089 if (Init) {
5090 if (ID->isInitKnownICE()) {
5091 // We have already checked whether this subexpression is an
5092 // integral constant expression.
5093 if (ID->isInitICE())
5094 return NoDiag();
5095 else
5096 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5097 }
5098
5099 // It's an ICE whether or not the definition we found is
5100 // out-of-line. See DR 721 and the discussion in Clang PR
5101 // 6206 for details.
5102
5103 if (Dcl->isCheckingICE()) {
5104 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5105 }
5106
5107 Dcl->setCheckingICE();
5108 ICEDiag Result = CheckICE(Init, Ctx);
5109 // Cache the result of the ICE test.
5110 Dcl->setInitKnownICE(Result.Val == 0);
5111 return Result;
5112 }
5113 }
5114 }
5115 return ICEDiag(2, E->getLocStart());
5116 case Expr::UnaryOperatorClass: {
5117 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5118 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005119 case UO_PostInc:
5120 case UO_PostDec:
5121 case UO_PreInc:
5122 case UO_PreDec:
5123 case UO_AddrOf:
5124 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005125 // C99 6.6/3 allows increment and decrement within unevaluated
5126 // subexpressions of constant expressions, but they can never be ICEs
5127 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005128 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005129 case UO_Extension:
5130 case UO_LNot:
5131 case UO_Plus:
5132 case UO_Minus:
5133 case UO_Not:
5134 case UO_Real:
5135 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005136 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005137 }
5138
5139 // OffsetOf falls through here.
5140 }
5141 case Expr::OffsetOfExprClass: {
5142 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005143 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005144 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005145 // compliance: we should warn earlier for offsetof expressions with
5146 // array subscripts that aren't ICEs, and if the array subscripts
5147 // are ICEs, the value of the offsetof must be an integer constant.
5148 return CheckEvalInICE(E, Ctx);
5149 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005150 case Expr::UnaryExprOrTypeTraitExprClass: {
5151 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5152 if ((Exp->getKind() == UETT_SizeOf) &&
5153 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005154 return ICEDiag(2, E->getLocStart());
5155 return NoDiag();
5156 }
5157 case Expr::BinaryOperatorClass: {
5158 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5159 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005160 case BO_PtrMemD:
5161 case BO_PtrMemI:
5162 case BO_Assign:
5163 case BO_MulAssign:
5164 case BO_DivAssign:
5165 case BO_RemAssign:
5166 case BO_AddAssign:
5167 case BO_SubAssign:
5168 case BO_ShlAssign:
5169 case BO_ShrAssign:
5170 case BO_AndAssign:
5171 case BO_XorAssign:
5172 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005173 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5174 // constant expressions, but they can never be ICEs because an ICE cannot
5175 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005176 return ICEDiag(2, E->getLocStart());
5177
John McCall2de56d12010-08-25 11:45:40 +00005178 case BO_Mul:
5179 case BO_Div:
5180 case BO_Rem:
5181 case BO_Add:
5182 case BO_Sub:
5183 case BO_Shl:
5184 case BO_Shr:
5185 case BO_LT:
5186 case BO_GT:
5187 case BO_LE:
5188 case BO_GE:
5189 case BO_EQ:
5190 case BO_NE:
5191 case BO_And:
5192 case BO_Xor:
5193 case BO_Or:
5194 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005195 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5196 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005197 if (Exp->getOpcode() == BO_Div ||
5198 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005199 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005200 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005201 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005202 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005203 if (REval == 0)
5204 return ICEDiag(1, E->getLocStart());
5205 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005206 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005207 if (LEval.isMinSignedValue())
5208 return ICEDiag(1, E->getLocStart());
5209 }
5210 }
5211 }
John McCall2de56d12010-08-25 11:45:40 +00005212 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005213 if (Ctx.getLangOptions().C99) {
5214 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5215 // if it isn't evaluated.
5216 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5217 return ICEDiag(1, E->getLocStart());
5218 } else {
5219 // In both C89 and C++, commas in ICEs are illegal.
5220 return ICEDiag(2, E->getLocStart());
5221 }
5222 }
5223 if (LHSResult.Val >= RHSResult.Val)
5224 return LHSResult;
5225 return RHSResult;
5226 }
John McCall2de56d12010-08-25 11:45:40 +00005227 case BO_LAnd:
5228 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005229 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5230 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5231 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5232 // Rare case where the RHS has a comma "side-effect"; we need
5233 // to actually check the condition to see whether the side
5234 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005235 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005236 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005237 return RHSResult;
5238 return NoDiag();
5239 }
5240
5241 if (LHSResult.Val >= RHSResult.Val)
5242 return LHSResult;
5243 return RHSResult;
5244 }
5245 }
5246 }
5247 case Expr::ImplicitCastExprClass:
5248 case Expr::CStyleCastExprClass:
5249 case Expr::CXXFunctionalCastExprClass:
5250 case Expr::CXXStaticCastExprClass:
5251 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005252 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005253 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005254 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith98326ed2011-10-25 00:21:54 +00005255 if (isa<ExplicitCastExpr>(E) &&
Richard Smith32cb4712011-10-24 18:26:35 +00005256 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
5257 return NoDiag();
Eli Friedmaneea0e812011-09-29 21:49:34 +00005258 switch (cast<CastExpr>(E)->getCastKind()) {
5259 case CK_LValueToRValue:
5260 case CK_NoOp:
5261 case CK_IntegralToBoolean:
5262 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00005263 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00005264 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005265 return ICEDiag(2, E->getLocStart());
5266 }
John McCalld905f5a2010-05-07 05:32:02 +00005267 }
John McCall56ca35d2011-02-17 10:25:35 +00005268 case Expr::BinaryConditionalOperatorClass: {
5269 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5270 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5271 if (CommonResult.Val == 2) return CommonResult;
5272 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5273 if (FalseResult.Val == 2) return FalseResult;
5274 if (CommonResult.Val == 1) return CommonResult;
5275 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005276 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00005277 return FalseResult;
5278 }
John McCalld905f5a2010-05-07 05:32:02 +00005279 case Expr::ConditionalOperatorClass: {
5280 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5281 // If the condition (ignoring parens) is a __builtin_constant_p call,
5282 // then only the true side is actually considered in an integer constant
5283 // expression, and it is fully evaluated. This is an important GNU
5284 // extension. See GCC PR38377 for discussion.
5285 if (const CallExpr *CallCE
5286 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith180f4792011-11-10 06:34:14 +00005287 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCalld905f5a2010-05-07 05:32:02 +00005288 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005289 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005290 !EVResult.Val.isInt()) {
5291 return ICEDiag(2, E->getLocStart());
5292 }
5293 return NoDiag();
5294 }
5295 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005296 if (CondResult.Val == 2)
5297 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00005298
Richard Smithf48fdb02011-12-09 22:58:01 +00005299 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5300 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00005301
John McCalld905f5a2010-05-07 05:32:02 +00005302 if (TrueResult.Val == 2)
5303 return TrueResult;
5304 if (FalseResult.Val == 2)
5305 return FalseResult;
5306 if (CondResult.Val == 1)
5307 return CondResult;
5308 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5309 return NoDiag();
5310 // Rare case where the diagnostics depend on which side is evaluated
5311 // Note that if we get here, CondResult is 0, and at least one of
5312 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005313 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00005314 return FalseResult;
5315 }
5316 return TrueResult;
5317 }
5318 case Expr::CXXDefaultArgExprClass:
5319 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5320 case Expr::ChooseExprClass: {
5321 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5322 }
5323 }
5324
5325 // Silence a GCC warning
5326 return ICEDiag(2, E->getLocStart());
5327}
5328
Richard Smithf48fdb02011-12-09 22:58:01 +00005329/// Evaluate an expression as a C++11 integral constant expression.
5330static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5331 const Expr *E,
5332 llvm::APSInt *Value,
5333 SourceLocation *Loc) {
5334 if (!E->getType()->isIntegralOrEnumerationType()) {
5335 if (Loc) *Loc = E->getExprLoc();
5336 return false;
5337 }
5338
5339 Expr::EvalResult Result;
Richard Smithdd1f29b2011-12-12 09:28:41 +00005340 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5341 Result.Diag = &Diags;
5342 EvalInfo Info(Ctx, Result);
5343
5344 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5345 if (!Diags.empty()) {
5346 IsICE = false;
5347 if (Loc) *Loc = Diags[0].first;
5348 } else if (!IsICE && Loc) {
5349 *Loc = E->getExprLoc();
Richard Smithf48fdb02011-12-09 22:58:01 +00005350 }
Richard Smithdd1f29b2011-12-12 09:28:41 +00005351
5352 if (!IsICE)
5353 return false;
5354
5355 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5356 if (Value) *Value = Result.Val.getInt();
5357 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00005358}
5359
Richard Smithdd1f29b2011-12-12 09:28:41 +00005360bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00005361 if (Ctx.getLangOptions().CPlusPlus0x)
5362 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5363
John McCalld905f5a2010-05-07 05:32:02 +00005364 ICEDiag d = CheckICE(this, Ctx);
5365 if (d.Val != 0) {
5366 if (Loc) *Loc = d.Loc;
5367 return false;
5368 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005369 return true;
5370}
5371
5372bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5373 SourceLocation *Loc, bool isEvaluated) const {
5374 if (Ctx.getLangOptions().CPlusPlus0x)
5375 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5376
5377 if (!isIntegerConstantExpr(Ctx, Loc))
5378 return false;
5379 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00005380 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00005381 return true;
5382}