blob: ff556c3094427ac41081ca44e8c11dcb5504010b [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000046 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000049
Richard Smithce40ad62011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smithd62306a2011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smith80815602011-11-07 05:07:52 +000079 /// Determine whether the described subobject is an array element.
80 static bool SubobjectIsArrayElement(QualType Base,
81 ArrayRef<APValue::LValuePathEntry> Path) {
82 bool IsArrayElement = false;
83 const Type *T = Base.getTypePtr();
84 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
85 IsArrayElement = T && T->isArrayType();
86 if (IsArrayElement)
87 T = T->getBaseElementTypeUnsafe();
Richard Smithd62306a2011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith80815602011-11-07 05:07:52 +000089 T = FD->getType().getTypePtr();
90 else
91 // Path[I] describes a base class.
92 T = 0;
93 }
94 return IsArrayElement;
95 }
96
Richard Smith96e0c102011-11-04 02:25:55 +000097 /// A path from a glvalue to a subobject of that glvalue.
98 struct SubobjectDesignator {
99 /// True if the subobject was named in a manner not supported by C++11. Such
100 /// lvalues can still be folded, but they are not core constant expressions
101 /// and we cannot perform lvalue-to-rvalue conversions on them.
102 bool Invalid : 1;
103
104 /// Whether this designates an array element.
105 bool ArrayElement : 1;
106
107 /// Whether this designates 'one past the end' of the current subobject.
108 bool OnePastTheEnd : 1;
109
Richard Smith80815602011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith96e0c102011-11-04 02:25:55 +0000112 /// The entries on the path from the glvalue to the designated subobject.
113 SmallVector<PathEntry, 8> Entries;
114
115 SubobjectDesignator() :
116 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
117
Richard Smith80815602011-11-07 05:07:52 +0000118 SubobjectDesignator(const APValue &V) :
119 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
120 OnePastTheEnd(false) {
121 if (!Invalid) {
122 ArrayRef<PathEntry> VEntries = V.getLValuePath();
123 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
124 if (V.getLValueBase())
Richard Smithce40ad62011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith80815602011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smith027bf112011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith96e0c102011-11-04 02:25:55 +0000133 void setInvalid() {
134 Invalid = true;
135 Entries.clear();
136 }
137 /// Update this designator to refer to the given element within this array.
138 void addIndex(uint64_t N) {
139 if (Invalid) return;
140 if (OnePastTheEnd) {
141 setInvalid();
142 return;
143 }
144 PathEntry Entry;
Richard Smith80815602011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith96e0c102011-11-04 02:25:55 +0000146 Entries.push_back(Entry);
147 ArrayElement = true;
148 }
149 /// Update this designator to refer to the given base or member of this
150 /// object.
Richard Smithd62306a2011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000160 Entries.push_back(Entry);
161 ArrayElement = false;
162 }
163 /// Add N to the address of this subobject.
164 void adjustIndex(uint64_t N) {
165 if (Invalid) return;
166 if (ArrayElement) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith80815602011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith96e0c102011-11-04 02:25:55 +0000169 return;
170 }
171 if (OnePastTheEnd && N == (uint64_t)-1)
172 OnePastTheEnd = false;
173 else if (!OnePastTheEnd && N == 1)
174 OnePastTheEnd = true;
175 else if (N != 0)
176 setInvalid();
177 }
178 };
179
Richard Smith0b0a0b62011-10-29 20:57:55 +0000180 /// A core constant value. This can be the value of any constant expression,
181 /// or a pointer or reference to a non-static object or function parameter.
Richard Smith027bf112011-11-17 22:56:20 +0000182 ///
183 /// For an LValue, the base and offset are stored in the APValue subobject,
184 /// but the other information is stored in the SubobjectDesignator. For all
185 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000189 /// If the value is a reference or pointer into a parameter or temporary,
190 /// this is the corresponding call stack frame.
191 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000192 /// If the value is a reference or pointer, this is a description of how the
193 /// subobject was specified.
194 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000195 public:
Richard Smithfec09922011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith0b0a0b62011-10-29 20:57:55 +0000198 CCValue() {}
199 explicit CCValue(const APSInt &I) : APValue(I) {}
200 explicit CCValue(const APFloat &F) : APValue(F) {}
201 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
202 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
203 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smithce40ad62011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith96e0c102011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith80815602011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith027bf112011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000213
Richard Smithfec09922011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000217 }
Richard Smith96e0c102011-11-04 02:25:55 +0000218 SubobjectDesignator &getLValueDesignator() {
219 assert(getKind() == LValue);
220 return Designator;
221 }
222 const SubobjectDesignator &getLValueDesignator() const {
223 return const_cast<CCValue*>(this)->getLValueDesignator();
224 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000225 };
226
Richard Smith254a73d2011-10-28 22:34:42 +0000227 /// A stack frame in the constexpr call stack.
228 struct CallStackFrame {
229 EvalInfo &Info;
230
231 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000233
Richard Smithf6f003a2011-12-16 19:06:07 +0000234 /// CallLoc - The location of the call expression for this call.
235 SourceLocation CallLoc;
236
237 /// Callee - The function which was called.
238 const FunctionDecl *Callee;
239
Richard Smithd62306a2011-11-10 06:34:14 +0000240 /// This - The binding for the this pointer in this call, if any.
241 const LValue *This;
242
Richard Smith254a73d2011-10-28 22:34:42 +0000243 /// ParmBindings - Parameter bindings for this function call, indexed by
244 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000245 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000246
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000247 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
248 typedef MapTy::const_iterator temp_iterator;
249 /// Temporaries - Temporary lvalues materialized within this stack frame.
250 MapTy Temporaries;
251
Richard Smithf6f003a2011-12-16 19:06:07 +0000252 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
253 const FunctionDecl *Callee, const LValue *This,
Richard Smithd62306a2011-11-10 06:34:14 +0000254 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000255 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000256 };
257
Richard Smith92b1ce02011-12-12 09:28:41 +0000258 /// A partial diagnostic which we might know in advance that we are not going
259 /// to emit.
260 class OptionalDiagnostic {
261 PartialDiagnostic *Diag;
262
263 public:
264 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
265
266 template<typename T>
267 OptionalDiagnostic &operator<<(const T &v) {
268 if (Diag)
269 *Diag << v;
270 return *this;
271 }
272 };
273
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000274 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000275 ASTContext &Ctx;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000276
277 /// EvalStatus - Contains information about the evaluation.
278 Expr::EvalStatus &EvalStatus;
279
280 /// CurrentCall - The top of the constexpr call stack.
281 CallStackFrame *CurrentCall;
282
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000283 /// CallStackDepth - The number of calls in the call stack right now.
284 unsigned CallStackDepth;
285
286 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
287 /// OpaqueValues - Values used as the common expression in a
288 /// BinaryConditionalOperator.
289 MapTy OpaqueValues;
290
291 /// BottomFrame - The frame in which evaluation started. This must be
292 /// initialized last.
293 CallStackFrame BottomFrame;
294
Richard Smithd62306a2011-11-10 06:34:14 +0000295 /// EvaluatingDecl - This is the declaration whose initializer is being
296 /// evaluated, if any.
297 const VarDecl *EvaluatingDecl;
298
299 /// EvaluatingDeclValue - This is the value being constructed for the
300 /// declaration whose initializer is being evaluated, if any.
301 APValue *EvaluatingDeclValue;
302
Richard Smith357362d2011-12-13 06:39:58 +0000303 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
304 /// notes attached to it will also be stored, otherwise they will not be.
305 bool HasActiveDiagnostic;
306
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000307
308 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000309 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithf6f003a2011-12-16 19:06:07 +0000310 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
311 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000313 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
314 MapTy::const_iterator i = OpaqueValues.find(e);
315 if (i == OpaqueValues.end()) return 0;
316 return &i->second;
317 }
318
Richard Smithd62306a2011-11-10 06:34:14 +0000319 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
320 EvaluatingDecl = VD;
321 EvaluatingDeclValue = &Value;
322 }
323
Richard Smith9a568822011-11-21 19:36:32 +0000324 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
325
Richard Smith357362d2011-12-13 06:39:58 +0000326 bool CheckCallLimit(SourceLocation Loc) {
327 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
328 return true;
329 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
330 << getLangOpts().ConstexprCallDepth;
331 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000332 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000333
Richard Smith357362d2011-12-13 06:39:58 +0000334 private:
335 /// Add a diagnostic to the diagnostics list.
336 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
337 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
338 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
339 return EvalStatus.Diag->back().second;
340 }
341
Richard Smithf6f003a2011-12-16 19:06:07 +0000342 /// Add notes containing a call stack to the current point of evaluation.
343 void addCallStack(unsigned Limit);
344
Richard Smith357362d2011-12-13 06:39:58 +0000345 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000346 /// Diagnose that the evaluation cannot be folded.
Richard Smith357362d2011-12-13 06:39:58 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
348 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-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 Smith92b1ce02011-12-12 09:28:41 +0000352 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-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 Smith357362d2011-12-13 06:39:58 +0000358 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000359 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-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 Smith92b1ce02011-12-12 09:28:41 +0000364 }
Richard Smith357362d2011-12-13 06:39:58 +0000365 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-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 Smith357362d2011-12-13 06:39:58 +0000371 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId,
372 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000373 // Don't override a previous diagnostic.
374 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
375 return OptionalDiagnostic();
Richard Smith357362d2011-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 Smithf57d8cb2011-12-09 22:58:01 +0000384 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000385
386 /// Add a stack of notes to a prior diagnostic.
387 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
388 if (HasActiveDiagnostic) {
389 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
390 Diags.begin(), Diags.end());
391 }
392 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000393 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000394}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000395
Richard Smithf6f003a2011-12-16 19:06:07 +0000396CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
397 const FunctionDecl *Callee, const LValue *This,
398 const CCValue *Arguments)
399 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
400 This(This), Arguments(Arguments) {
401 Info.CurrentCall = this;
402 ++Info.CallStackDepth;
403}
404
405CallStackFrame::~CallStackFrame() {
406 assert(Info.CurrentCall == this && "calls retired out of order");
407 --Info.CallStackDepth;
408 Info.CurrentCall = Caller;
409}
410
411/// Produce a string describing the given constexpr call.
412static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
413 unsigned ArgIndex = 0;
414 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
415 !isa<CXXConstructorDecl>(Frame->Callee);
416
417 if (!IsMemberCall)
418 Out << *Frame->Callee << '(';
419
420 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
421 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
422 if (ArgIndex > IsMemberCall)
423 Out << ", ";
424
425 const ParmVarDecl *Param = *I;
426 const CCValue &Arg = Frame->Arguments[ArgIndex];
427 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
428 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
429 else {
430 // Deliberately slice off the frame to form an APValue we can print.
431 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
432 Arg.getLValueDesignator().Entries,
433 Arg.getLValueDesignator().OnePastTheEnd);
434 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
435 }
436
437 if (ArgIndex == 0 && IsMemberCall)
438 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 }
440
Richard Smithf6f003a2011-12-16 19:06:07 +0000441 Out << ')';
442}
443
444void EvalInfo::addCallStack(unsigned Limit) {
445 // Determine which calls to skip, if any.
446 unsigned ActiveCalls = CallStackDepth - 1;
447 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
448 if (Limit && Limit < ActiveCalls) {
449 SkipStart = Limit / 2 + Limit % 2;
450 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000451 }
452
Richard Smithf6f003a2011-12-16 19:06:07 +0000453 // Walk the call stack and add the diagnostics.
454 unsigned CallIdx = 0;
455 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
456 Frame = Frame->Caller, ++CallIdx) {
457 // Skip this call?
458 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
459 if (CallIdx == SkipStart) {
460 // Note that we're skipping calls.
461 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
462 << unsigned(ActiveCalls - Limit);
463 }
464 continue;
465 }
466
467 llvm::SmallVector<char, 128> Buffer;
468 llvm::raw_svector_ostream Out(Buffer);
469 describeCall(Frame, Out);
470 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
471 }
472}
473
474namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000475 struct ComplexValue {
476 private:
477 bool IsInt;
478
479 public:
480 APSInt IntReal, IntImag;
481 APFloat FloatReal, FloatImag;
482
483 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
484
485 void makeComplexFloat() { IsInt = false; }
486 bool isComplexFloat() const { return !IsInt; }
487 APFloat &getComplexFloatReal() { return FloatReal; }
488 APFloat &getComplexFloatImag() { return FloatImag; }
489
490 void makeComplexInt() { IsInt = true; }
491 bool isComplexInt() const { return IsInt; }
492 APSInt &getComplexIntReal() { return IntReal; }
493 APSInt &getComplexIntImag() { return IntImag; }
494
Richard Smith0b0a0b62011-10-29 20:57:55 +0000495 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000496 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000497 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000498 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000499 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000500 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000501 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000502 assert(v.isComplexFloat() || v.isComplexInt());
503 if (v.isComplexFloat()) {
504 makeComplexFloat();
505 FloatReal = v.getComplexFloatReal();
506 FloatImag = v.getComplexFloatImag();
507 } else {
508 makeComplexInt();
509 IntReal = v.getComplexIntReal();
510 IntImag = v.getComplexIntImag();
511 }
512 }
John McCall93d91dc2010-05-07 17:22:02 +0000513 };
John McCall45d55e42010-05-07 21:00:08 +0000514
515 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000516 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000517 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000518 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000519 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000520
Richard Smithce40ad62011-11-12 22:28:03 +0000521 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000522 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000523 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000524 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000525 SubobjectDesignator &getLValueDesignator() { return Designator; }
526 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000527
Richard Smith0b0a0b62011-10-29 20:57:55 +0000528 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000529 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000530 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000531 void setFrom(const CCValue &V) {
532 assert(V.isLValue());
533 Base = V.getLValueBase();
534 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000535 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000536 Designator = V.getLValueDesignator();
537 }
538
Richard Smithce40ad62011-11-12 22:28:03 +0000539 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
540 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000541 Offset = CharUnits::Zero();
542 Frame = F;
543 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000544 }
John McCall45d55e42010-05-07 21:00:08 +0000545 };
Richard Smith027bf112011-11-17 22:56:20 +0000546
547 struct MemberPtr {
548 MemberPtr() {}
549 explicit MemberPtr(const ValueDecl *Decl) :
550 DeclAndIsDerivedMember(Decl, false), Path() {}
551
552 /// The member or (direct or indirect) field referred to by this member
553 /// pointer, or 0 if this is a null member pointer.
554 const ValueDecl *getDecl() const {
555 return DeclAndIsDerivedMember.getPointer();
556 }
557 /// Is this actually a member of some type derived from the relevant class?
558 bool isDerivedMember() const {
559 return DeclAndIsDerivedMember.getInt();
560 }
561 /// Get the class which the declaration actually lives in.
562 const CXXRecordDecl *getContainingRecord() const {
563 return cast<CXXRecordDecl>(
564 DeclAndIsDerivedMember.getPointer()->getDeclContext());
565 }
566
567 void moveInto(CCValue &V) const {
568 V = CCValue(getDecl(), isDerivedMember(), Path);
569 }
570 void setFrom(const CCValue &V) {
571 assert(V.isMemberPointer());
572 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
573 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
574 Path.clear();
575 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
576 Path.insert(Path.end(), P.begin(), P.end());
577 }
578
579 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
580 /// whether the member is a member of some class derived from the class type
581 /// of the member pointer.
582 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
583 /// Path - The path of base/derived classes from the member declaration's
584 /// class (exclusive) to the class type of the member pointer (inclusive).
585 SmallVector<const CXXRecordDecl*, 4> Path;
586
587 /// Perform a cast towards the class of the Decl (either up or down the
588 /// hierarchy).
589 bool castBack(const CXXRecordDecl *Class) {
590 assert(!Path.empty());
591 const CXXRecordDecl *Expected;
592 if (Path.size() >= 2)
593 Expected = Path[Path.size() - 2];
594 else
595 Expected = getContainingRecord();
596 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
597 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
598 // if B does not contain the original member and is not a base or
599 // derived class of the class containing the original member, the result
600 // of the cast is undefined.
601 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
602 // (D::*). We consider that to be a language defect.
603 return false;
604 }
605 Path.pop_back();
606 return true;
607 }
608 /// Perform a base-to-derived member pointer cast.
609 bool castToDerived(const CXXRecordDecl *Derived) {
610 if (!getDecl())
611 return true;
612 if (!isDerivedMember()) {
613 Path.push_back(Derived);
614 return true;
615 }
616 if (!castBack(Derived))
617 return false;
618 if (Path.empty())
619 DeclAndIsDerivedMember.setInt(false);
620 return true;
621 }
622 /// Perform a derived-to-base member pointer cast.
623 bool castToBase(const CXXRecordDecl *Base) {
624 if (!getDecl())
625 return true;
626 if (Path.empty())
627 DeclAndIsDerivedMember.setInt(true);
628 if (isDerivedMember()) {
629 Path.push_back(Base);
630 return true;
631 }
632 return castBack(Base);
633 }
634 };
Richard Smith357362d2011-12-13 06:39:58 +0000635
636 /// Kinds of constant expression checking, for diagnostics.
637 enum CheckConstantExpressionKind {
638 CCEK_Constant, ///< A normal constant.
639 CCEK_ReturnValue, ///< A constexpr function return value.
640 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
641 };
John McCall93d91dc2010-05-07 17:22:02 +0000642}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000643
Richard Smith0b0a0b62011-10-29 20:57:55 +0000644static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000645static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +0000646 const LValue &This, const Expr *E,
647 CheckConstantExpressionKind CCEK
648 = CCEK_Constant);
John McCall45d55e42010-05-07 21:00:08 +0000649static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
650static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000651static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
652 EvalInfo &Info);
653static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000654static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000655static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000656 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000657static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000658static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000659
660//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000661// Misc utilities
662//===----------------------------------------------------------------------===//
663
Richard Smithd62306a2011-11-10 06:34:14 +0000664/// Should this call expression be treated as a string literal?
665static bool IsStringLiteralCall(const CallExpr *E) {
666 unsigned Builtin = E->isBuiltinCall();
667 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
668 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
669}
670
Richard Smithce40ad62011-11-12 22:28:03 +0000671static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000672 // C++11 [expr.const]p3 An address constant expression is a prvalue core
673 // constant expression of pointer type that evaluates to...
674
675 // ... a null pointer value, or a prvalue core constant expression of type
676 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000677 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000678
Richard Smithce40ad62011-11-12 22:28:03 +0000679 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
680 // ... the address of an object with static storage duration,
681 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
682 return VD->hasGlobalStorage();
683 // ... the address of a function,
684 return isa<FunctionDecl>(D);
685 }
686
687 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000688 switch (E->getStmtClass()) {
689 default:
690 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000691 case Expr::CompoundLiteralExprClass:
692 return cast<CompoundLiteralExpr>(E)->isFileScope();
693 // A string literal has static storage duration.
694 case Expr::StringLiteralClass:
695 case Expr::PredefinedExprClass:
696 case Expr::ObjCStringLiteralClass:
697 case Expr::ObjCEncodeExprClass:
698 return true;
699 case Expr::CallExprClass:
700 return IsStringLiteralCall(cast<CallExpr>(E));
701 // For GCC compatibility, &&label has static storage duration.
702 case Expr::AddrLabelExprClass:
703 return true;
704 // A Block literal expression may be used as the initialization value for
705 // Block variables at global or local static scope.
706 case Expr::BlockExprClass:
707 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
708 }
John McCall95007602010-05-10 23:27:23 +0000709}
710
Richard Smith80815602011-11-07 05:07:52 +0000711/// Check that this reference or pointer core constant expression is a valid
712/// value for a constant expression. Type T should be either LValue or CCValue.
713template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000714static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000715 const T &LVal, APValue &Value,
716 CheckConstantExpressionKind CCEK) {
717 APValue::LValueBase Base = LVal.getLValueBase();
718 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
719
720 if (!IsGlobalLValue(Base)) {
721 if (Info.getLangOpts().CPlusPlus0x) {
722 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
723 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
724 << E->isGLValue() << !Designator.Entries.empty()
725 << !!VD << CCEK << VD;
726 if (VD)
727 Info.Note(VD->getLocation(), diag::note_declared_at);
728 else
729 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
730 diag::note_constexpr_temporary_here);
731 } else {
732 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
733 }
Richard Smith80815602011-11-07 05:07:52 +0000734 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000735 }
Richard Smith80815602011-11-07 05:07:52 +0000736
Richard Smith80815602011-11-07 05:07:52 +0000737 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000738 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000739 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith357362d2011-12-13 06:39:58 +0000740 // FIXME: This is not a core constant expression. We should have already
741 // produced a CCE diagnostic.
Richard Smith80815602011-11-07 05:07:52 +0000742 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
743 APValue::NoLValuePath());
744 return true;
745 }
746
Richard Smith357362d2011-12-13 06:39:58 +0000747 // Does this refer one past the end of some object?
748 // This is technically not an address constant expression nor a reference
749 // constant expression, but we allow it for address constant expressions.
750 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
751 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
752 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
753 << !Designator.Entries.empty() << !!VD << VD;
754 if (VD)
755 Info.Note(VD->getLocation(), diag::note_declared_at);
756 else
757 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
758 diag::note_constexpr_temporary_here);
759 return false;
760 }
761
Richard Smith80815602011-11-07 05:07:52 +0000762 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000763 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000764 return true;
765}
766
Richard Smith0b0a0b62011-10-29 20:57:55 +0000767/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000768/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000769/// If not, report an appropriate diagnostic.
770static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000771 const CCValue &CCValue, APValue &Value,
772 CheckConstantExpressionKind CCEK
773 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000774 if (!CCValue.isLValue()) {
775 Value = CCValue;
776 return true;
777 }
Richard Smith357362d2011-12-13 06:39:58 +0000778 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000779}
780
Richard Smith83c68212011-10-31 05:11:32 +0000781const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000782 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000783}
784
785static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000786 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000787}
788
Richard Smithcecf1842011-11-01 21:06:14 +0000789static bool IsWeakLValue(const LValue &Value) {
790 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000791 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000792}
793
Richard Smith027bf112011-11-17 22:56:20 +0000794static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000795 // A null base expression indicates a null pointer. These are always
796 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000797 if (!Value.getLValueBase()) {
798 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000799 return true;
800 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000801
John McCall95007602010-05-10 23:27:23 +0000802 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000803 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000804 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000805
Richard Smith027bf112011-11-17 22:56:20 +0000806 // We have a non-null base. These are generally known to be true, but if it's
807 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000808 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000809 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000810 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000811}
812
Richard Smith0b0a0b62011-10-29 20:57:55 +0000813static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000814 switch (Val.getKind()) {
815 case APValue::Uninitialized:
816 return false;
817 case APValue::Int:
818 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000819 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000820 case APValue::Float:
821 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000822 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000823 case APValue::ComplexInt:
824 Result = Val.getComplexIntReal().getBoolValue() ||
825 Val.getComplexIntImag().getBoolValue();
826 return true;
827 case APValue::ComplexFloat:
828 Result = !Val.getComplexFloatReal().isZero() ||
829 !Val.getComplexFloatImag().isZero();
830 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000831 case APValue::LValue:
832 return EvalPointerValueAsBool(Val, Result);
833 case APValue::MemberPointer:
834 Result = Val.getMemberPointerDecl();
835 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000836 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000837 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000838 case APValue::Struct:
839 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000840 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000841 }
842
Richard Smith11562c52011-10-28 17:51:58 +0000843 llvm_unreachable("unknown APValue kind");
844}
845
846static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
847 EvalInfo &Info) {
848 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000849 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000850 if (!Evaluate(Val, Info, E))
851 return false;
852 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000853}
854
Richard Smith357362d2011-12-13 06:39:58 +0000855template<typename T>
856static bool HandleOverflow(EvalInfo &Info, const Expr *E,
857 const T &SrcValue, QualType DestType) {
858 llvm::SmallVector<char, 32> Buffer;
859 SrcValue.toString(Buffer);
860 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
861 << StringRef(Buffer.data(), Buffer.size()) << DestType;
862 return false;
863}
864
865static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
866 QualType SrcType, const APFloat &Value,
867 QualType DestType, APSInt &Result) {
868 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000869 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000870 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000871
Richard Smith357362d2011-12-13 06:39:58 +0000872 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000873 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000874 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
875 & APFloat::opInvalidOp)
876 return HandleOverflow(Info, E, Value, DestType);
877 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000878}
879
Richard Smith357362d2011-12-13 06:39:58 +0000880static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
881 QualType SrcType, QualType DestType,
882 APFloat &Result) {
883 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000884 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000885 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
886 APFloat::rmNearestTiesToEven, &ignored)
887 & APFloat::opOverflow)
888 return HandleOverflow(Info, E, Value, DestType);
889 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000890}
891
Mike Stump11289f42009-09-09 15:08:12 +0000892static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000893 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000894 unsigned DestWidth = Ctx.getIntWidth(DestType);
895 APSInt Result = Value;
896 // Figure out if this is a truncate, extend or noop cast.
897 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000898 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000899 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000900 return Result;
901}
902
Richard Smith357362d2011-12-13 06:39:58 +0000903static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
904 QualType SrcType, const APSInt &Value,
905 QualType DestType, APFloat &Result) {
906 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
907 if (Result.convertFromAPInt(Value, Value.isSigned(),
908 APFloat::rmNearestTiesToEven)
909 & APFloat::opOverflow)
910 return HandleOverflow(Info, E, Value, DestType);
911 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000912}
913
Richard Smith027bf112011-11-17 22:56:20 +0000914static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
915 const CXXRecordDecl *&MostDerivedType,
916 unsigned &MostDerivedPathLength,
917 bool &MostDerivedIsArrayElement) {
918 const SubobjectDesignator &D = LVal.Designator;
919 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000920 return false;
921
Richard Smith027bf112011-11-17 22:56:20 +0000922 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000923
924 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000925 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000926 MostDerivedPathLength = 0;
927 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000928
929 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
930 bool IsArray = T && T->isArrayType();
931 if (IsArray)
932 T = T->getBaseElementTypeUnsafe();
933 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
934 T = FD->getType().getTypePtr();
935 else
936 T = 0;
937
938 if (T) {
939 MostDerivedType = T->getAsCXXRecordDecl();
940 MostDerivedPathLength = I + 1;
941 MostDerivedIsArrayElement = IsArray;
942 }
943 }
944
Richard Smithd62306a2011-11-10 06:34:14 +0000945 // (B*)&d + 1 has no most-derived object.
946 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
947 return false;
948
Richard Smith027bf112011-11-17 22:56:20 +0000949 return MostDerivedType != 0;
950}
951
952static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
953 const RecordDecl *TruncatedType,
954 unsigned TruncatedElements,
955 bool IsArrayElement) {
956 SubobjectDesignator &D = Result.Designator;
957 const RecordDecl *RD = TruncatedType;
958 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +0000959 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
960 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +0000961 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +0000962 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +0000963 else
Richard Smithd62306a2011-11-10 06:34:14 +0000964 Result.Offset -= Layout.getBaseClassOffset(Base);
965 RD = Base;
966 }
Richard Smith027bf112011-11-17 22:56:20 +0000967 D.Entries.resize(TruncatedElements);
968 D.ArrayElement = IsArrayElement;
969}
970
971/// If the given LValue refers to a base subobject of some object, find the most
972/// derived object and the corresponding complete record type. This is necessary
973/// in order to find the offset of a virtual base class.
974static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
975 const CXXRecordDecl *&MostDerivedType) {
976 unsigned MostDerivedPathLength;
977 bool MostDerivedIsArrayElement;
978 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
979 MostDerivedPathLength, MostDerivedIsArrayElement))
980 return false;
981
982 // Remove the trailing base class path entries and their offsets.
983 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
984 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +0000985 return true;
986}
987
988static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
989 const CXXRecordDecl *Derived,
990 const CXXRecordDecl *Base,
991 const ASTRecordLayout *RL = 0) {
992 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
993 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
994 Obj.Designator.addDecl(Base, /*Virtual*/ false);
995}
996
997static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
998 const CXXRecordDecl *DerivedDecl,
999 const CXXBaseSpecifier *Base) {
1000 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1001
1002 if (!Base->isVirtual()) {
1003 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1004 return true;
1005 }
1006
1007 // Extract most-derived object and corresponding type.
1008 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1009 return false;
1010
1011 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1012 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1013 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1014 return true;
1015}
1016
1017/// Update LVal to refer to the given field, which must be a member of the type
1018/// currently described by LVal.
1019static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1020 const FieldDecl *FD,
1021 const ASTRecordLayout *RL = 0) {
1022 if (!RL)
1023 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1024
1025 unsigned I = FD->getFieldIndex();
1026 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1027 LVal.Designator.addDecl(FD);
1028}
1029
1030/// Get the size of the given type in char units.
1031static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1032 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1033 // extension.
1034 if (Type->isVoidType() || Type->isFunctionType()) {
1035 Size = CharUnits::One();
1036 return true;
1037 }
1038
1039 if (!Type->isConstantSizeType()) {
1040 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1041 return false;
1042 }
1043
1044 Size = Info.Ctx.getTypeSizeInChars(Type);
1045 return true;
1046}
1047
1048/// Update a pointer value to model pointer arithmetic.
1049/// \param Info - Information about the ongoing evaluation.
1050/// \param LVal - The pointer value to be updated.
1051/// \param EltTy - The pointee type represented by LVal.
1052/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1053static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1054 QualType EltTy, int64_t Adjustment) {
1055 CharUnits SizeOfPointee;
1056 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1057 return false;
1058
1059 // Compute the new offset in the appropriate width.
1060 LVal.Offset += Adjustment * SizeOfPointee;
1061 LVal.Designator.adjustIndex(Adjustment);
1062 return true;
1063}
1064
Richard Smith27908702011-10-24 17:54:18 +00001065/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001066static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1067 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001068 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001069 // If this is a parameter to an active constexpr function call, perform
1070 // argument substitution.
1071 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001072 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001073 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001074 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001075 }
Richard Smithfec09922011-11-01 16:57:24 +00001076 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1077 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001078 }
Richard Smith27908702011-10-24 17:54:18 +00001079
Richard Smithd0b4dd62011-12-19 06:19:21 +00001080 // Dig out the initializer, and use the declaration which it's attached to.
1081 const Expr *Init = VD->getAnyInitializer(VD);
1082 if (!Init || Init->isValueDependent()) {
1083 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1084 return false;
1085 }
1086
Richard Smithd62306a2011-11-10 06:34:14 +00001087 // If we're currently evaluating the initializer of this declaration, use that
1088 // in-flight value.
1089 if (Info.EvaluatingDecl == VD) {
1090 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1091 return !Result.isUninit();
1092 }
1093
Richard Smithcecf1842011-11-01 21:06:14 +00001094 // Never evaluate the initializer of a weak variable. We can't be sure that
1095 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001096 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001097 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001098 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001099 }
Richard Smithcecf1842011-11-01 21:06:14 +00001100
Richard Smithd0b4dd62011-12-19 06:19:21 +00001101 // Check that we can fold the initializer. In C++, we will have already done
1102 // this in the cases where it matters for conformance.
1103 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1104 if (!VD->evaluateValue(Notes)) {
1105 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1106 Notes.size() + 1) << VD;
1107 Info.Note(VD->getLocation(), diag::note_declared_at);
1108 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001109 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001110 } else if (!VD->checkInitIsICE()) {
1111 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1112 Notes.size() + 1) << VD;
1113 Info.Note(VD->getLocation(), diag::note_declared_at);
1114 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001115 }
Richard Smith27908702011-10-24 17:54:18 +00001116
Richard Smithd0b4dd62011-12-19 06:19:21 +00001117 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001118 return true;
Richard Smith27908702011-10-24 17:54:18 +00001119}
1120
Richard Smith11562c52011-10-28 17:51:58 +00001121static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001122 Qualifiers Quals = T.getQualifiers();
1123 return Quals.hasConst() && !Quals.hasVolatile();
1124}
1125
Richard Smithe97cbd72011-11-11 04:05:33 +00001126/// Get the base index of the given base class within an APValue representing
1127/// the given derived class.
1128static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1129 const CXXRecordDecl *Base) {
1130 Base = Base->getCanonicalDecl();
1131 unsigned Index = 0;
1132 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1133 E = Derived->bases_end(); I != E; ++I, ++Index) {
1134 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1135 return Index;
1136 }
1137
1138 llvm_unreachable("base class missing from derived class's bases list");
1139}
1140
Richard Smithf3e9e432011-11-07 09:22:26 +00001141/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001142static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1143 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001144 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001145 if (Sub.Invalid || Sub.OnePastTheEnd) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001146 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001147 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001148 }
Richard Smith6804be52011-11-11 08:28:03 +00001149 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001150 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001151
1152 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1153 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001154 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001155 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001156 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001157 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001158 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001159 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001160 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001161 if (CAT->getSize().ule(Index)) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001162 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001163 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001164 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001165 if (O->getArrayInitializedElts() > Index)
1166 O = &O->getArrayInitializedElt(Index);
1167 else
1168 O = &O->getArrayFiller();
1169 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001170 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1171 // Next subobject is a class, struct or union field.
1172 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1173 if (RD->isUnion()) {
1174 const FieldDecl *UnionField = O->getUnionField();
1175 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001176 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001177 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001178 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001179 }
Richard Smithd62306a2011-11-10 06:34:14 +00001180 O = &O->getUnionValue();
1181 } else
1182 O = &O->getStructField(Field->getFieldIndex());
1183 ObjType = Field->getType();
Richard Smithf3e9e432011-11-07 09:22:26 +00001184 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001185 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001186 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1187 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1188 O = &O->getStructBase(getBaseIndex(Derived, Base));
1189 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001190 }
Richard Smithd62306a2011-11-10 06:34:14 +00001191
Richard Smithf57d8cb2011-12-09 22:58:01 +00001192 if (O->isUninit()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001193 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001194 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001195 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001196 }
1197
Richard Smithf3e9e432011-11-07 09:22:26 +00001198 Obj = CCValue(*O, CCValue::GlobalValue());
1199 return true;
1200}
1201
Richard Smithd62306a2011-11-10 06:34:14 +00001202/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1203/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1204/// for looking up the glvalue referred to by an entity of reference type.
1205///
1206/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001207/// \param Conv - The expression for which we are performing the conversion.
1208/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001209/// \param Type - The type we expect this conversion to produce.
1210/// \param LVal - The glvalue on which we are attempting to perform this action.
1211/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001212static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1213 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001214 const LValue &LVal, CCValue &RVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001215 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001216 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +00001217
Richard Smithf57d8cb2011-12-09 22:58:01 +00001218 if (!LVal.Base) {
1219 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith92b1ce02011-12-12 09:28:41 +00001220 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith11562c52011-10-28 17:51:58 +00001221 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001222 }
Richard Smith11562c52011-10-28 17:51:58 +00001223
Richard Smithce40ad62011-11-12 22:28:03 +00001224 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001225 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1226 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001227 // expressions are constant expressions too. Inside constexpr functions,
1228 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001229 // In C, such things can also be folded, although they are not ICEs.
1230 //
Richard Smith254a73d2011-10-28 22:34:42 +00001231 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1232 // interpretation of C++11 suggests that volatile parameters are OK if
1233 // they're never read (there's no prohibition against constructing volatile
1234 // objects in constant expressions), but lvalue-to-rvalue conversions on
1235 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +00001236 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001237 if (!VD || VD->isInvalidDecl()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001238 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001239 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001240 }
1241
Richard Smithce40ad62011-11-12 22:28:03 +00001242 QualType VT = VD->getType();
Richard Smith96e0c102011-11-04 02:25:55 +00001243 if (!isa<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001244 if (!IsConstNonVolatile(VT)) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001245 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001246 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001247 }
Richard Smitha08acd82011-11-07 03:22:51 +00001248 // FIXME: Allow folding of values of any literal type in all languages.
1249 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00001250 !VD->isConstexpr()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001251 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001252 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001253 }
Richard Smith96e0c102011-11-04 02:25:55 +00001254 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001255 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001256 return false;
1257
Richard Smith0b0a0b62011-10-29 20:57:55 +00001258 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001259 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001260
1261 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1262 // conversion. This happens when the declaration and the lvalue should be
1263 // considered synonymous, for instance when initializing an array of char
1264 // from a string literal. Continue as if the initializer lvalue was the
1265 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001266 assert(RVal.getLValueOffset().isZero() &&
1267 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001268 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001269 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001270 }
1271
Richard Smith96e0c102011-11-04 02:25:55 +00001272 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1273 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1274 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001275 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001276 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001277 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001278 }
Richard Smith96e0c102011-11-04 02:25:55 +00001279
1280 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001281 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001282 if (Index > S->getLength()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001283 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001284 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001285 }
Richard Smith96e0c102011-11-04 02:25:55 +00001286 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1287 Type->isUnsignedIntegerType());
1288 if (Index < S->getLength())
1289 Value = S->getCodeUnit(Index);
1290 RVal = CCValue(Value);
1291 return true;
1292 }
1293
Richard Smithf3e9e432011-11-07 09:22:26 +00001294 if (Frame) {
1295 // If this is a temporary expression with a nontrivial initializer, grab the
1296 // value from the relevant stack frame.
1297 RVal = Frame->Temporaries[Base];
1298 } else if (const CompoundLiteralExpr *CLE
1299 = dyn_cast<CompoundLiteralExpr>(Base)) {
1300 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1301 // initializer until now for such expressions. Such an expression can't be
1302 // an ICE in C, so this only matters for fold.
1303 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1304 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1305 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001306 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001307 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001308 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001309 }
Richard Smith96e0c102011-11-04 02:25:55 +00001310
Richard Smithf57d8cb2011-12-09 22:58:01 +00001311 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1312 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001313}
1314
Richard Smithe97cbd72011-11-11 04:05:33 +00001315/// Build an lvalue for the object argument of a member function call.
1316static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1317 LValue &This) {
1318 if (Object->getType()->isPointerType())
1319 return EvaluatePointer(Object, This, Info);
1320
1321 if (Object->isGLValue())
1322 return EvaluateLValue(Object, This, Info);
1323
Richard Smith027bf112011-11-17 22:56:20 +00001324 if (Object->getType()->isLiteralType())
1325 return EvaluateTemporary(Object, This, Info);
1326
1327 return false;
1328}
1329
1330/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1331/// lvalue referring to the result.
1332///
1333/// \param Info - Information about the ongoing evaluation.
1334/// \param BO - The member pointer access operation.
1335/// \param LV - Filled in with a reference to the resulting object.
1336/// \param IncludeMember - Specifies whether the member itself is included in
1337/// the resulting LValue subobject designator. This is not possible when
1338/// creating a bound member function.
1339/// \return The field or method declaration to which the member pointer refers,
1340/// or 0 if evaluation fails.
1341static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1342 const BinaryOperator *BO,
1343 LValue &LV,
1344 bool IncludeMember = true) {
1345 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1346
1347 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1348 return 0;
1349
1350 MemberPtr MemPtr;
1351 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1352 return 0;
1353
1354 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1355 // member value, the behavior is undefined.
1356 if (!MemPtr.getDecl())
1357 return 0;
1358
1359 if (MemPtr.isDerivedMember()) {
1360 // This is a member of some derived class. Truncate LV appropriately.
1361 const CXXRecordDecl *MostDerivedType;
1362 unsigned MostDerivedPathLength;
1363 bool MostDerivedIsArrayElement;
1364 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1365 MostDerivedIsArrayElement))
1366 return 0;
1367
1368 // The end of the derived-to-base path for the base object must match the
1369 // derived-to-base path for the member pointer.
1370 if (MostDerivedPathLength + MemPtr.Path.size() >
1371 LV.Designator.Entries.size())
1372 return 0;
1373 unsigned PathLengthToMember =
1374 LV.Designator.Entries.size() - MemPtr.Path.size();
1375 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1376 const CXXRecordDecl *LVDecl = getAsBaseClass(
1377 LV.Designator.Entries[PathLengthToMember + I]);
1378 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1379 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1380 return 0;
1381 }
1382
1383 // Truncate the lvalue to the appropriate derived class.
1384 bool ResultIsArray = false;
1385 if (PathLengthToMember == MostDerivedPathLength)
1386 ResultIsArray = MostDerivedIsArrayElement;
1387 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1388 PathLengthToMember, ResultIsArray);
1389 } else if (!MemPtr.Path.empty()) {
1390 // Extend the LValue path with the member pointer's path.
1391 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1392 MemPtr.Path.size() + IncludeMember);
1393
1394 // Walk down to the appropriate base class.
1395 QualType LVType = BO->getLHS()->getType();
1396 if (const PointerType *PT = LVType->getAs<PointerType>())
1397 LVType = PT->getPointeeType();
1398 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1399 assert(RD && "member pointer access on non-class-type expression");
1400 // The first class in the path is that of the lvalue.
1401 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1402 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1403 HandleLValueDirectBase(Info, LV, RD, Base);
1404 RD = Base;
1405 }
1406 // Finally cast to the class containing the member.
1407 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1408 }
1409
1410 // Add the member. Note that we cannot build bound member functions here.
1411 if (IncludeMember) {
1412 // FIXME: Deal with IndirectFieldDecls.
1413 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1414 if (!FD) return 0;
1415 HandleLValueMember(Info, LV, FD);
1416 }
1417
1418 return MemPtr.getDecl();
1419}
1420
1421/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1422/// the provided lvalue, which currently refers to the base object.
1423static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1424 LValue &Result) {
1425 const CXXRecordDecl *MostDerivedType;
1426 unsigned MostDerivedPathLength;
1427 bool MostDerivedIsArrayElement;
1428
1429 // Check this cast doesn't take us outside the object.
1430 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1431 MostDerivedPathLength,
1432 MostDerivedIsArrayElement))
1433 return false;
1434 SubobjectDesignator &D = Result.Designator;
1435 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1436 return false;
1437
1438 // Check the type of the final cast. We don't need to check the path,
1439 // since a cast can only be formed if the path is unique.
1440 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1441 bool ResultIsArray = false;
1442 QualType TargetQT = E->getType();
1443 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1444 TargetQT = PT->getPointeeType();
1445 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1446 const CXXRecordDecl *FinalType;
1447 if (NewEntriesSize == MostDerivedPathLength) {
1448 ResultIsArray = MostDerivedIsArrayElement;
1449 FinalType = MostDerivedType;
1450 } else
1451 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1452 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1453 return false;
1454
1455 // Truncate the lvalue to the appropriate derived class.
1456 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1457 ResultIsArray);
1458 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001459}
1460
Mike Stump876387b2009-10-27 22:09:17 +00001461namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001462enum EvalStmtResult {
1463 /// Evaluation failed.
1464 ESR_Failed,
1465 /// Hit a 'return' statement.
1466 ESR_Returned,
1467 /// Evaluation succeeded.
1468 ESR_Succeeded
1469};
1470}
1471
1472// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001473static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001474 const Stmt *S) {
1475 switch (S->getStmtClass()) {
1476 default:
1477 return ESR_Failed;
1478
1479 case Stmt::NullStmtClass:
1480 case Stmt::DeclStmtClass:
1481 return ESR_Succeeded;
1482
Richard Smith357362d2011-12-13 06:39:58 +00001483 case Stmt::ReturnStmtClass: {
1484 CCValue CCResult;
1485 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1486 if (!Evaluate(CCResult, Info, RetExpr) ||
1487 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1488 CCEK_ReturnValue))
1489 return ESR_Failed;
1490 return ESR_Returned;
1491 }
Richard Smith254a73d2011-10-28 22:34:42 +00001492
1493 case Stmt::CompoundStmtClass: {
1494 const CompoundStmt *CS = cast<CompoundStmt>(S);
1495 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1496 BE = CS->body_end(); BI != BE; ++BI) {
1497 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1498 if (ESR != ESR_Succeeded)
1499 return ESR;
1500 }
1501 return ESR_Succeeded;
1502 }
1503 }
1504}
1505
Richard Smith357362d2011-12-13 06:39:58 +00001506/// CheckConstexprFunction - Check that a function can be called in a constant
1507/// expression.
1508static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1509 const FunctionDecl *Declaration,
1510 const FunctionDecl *Definition) {
1511 // Can we evaluate this function call?
1512 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1513 return true;
1514
1515 if (Info.getLangOpts().CPlusPlus0x) {
1516 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001517 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1518 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001519 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1520 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1521 << DiagDecl;
1522 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1523 } else {
1524 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1525 }
1526 return false;
1527}
1528
Richard Smithd62306a2011-11-10 06:34:14 +00001529namespace {
Richard Smith60494462011-11-11 05:48:57 +00001530typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001531}
1532
1533/// EvaluateArgs - Evaluate the arguments to a function call.
1534static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1535 EvalInfo &Info) {
1536 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1537 I != E; ++I)
1538 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1539 return false;
1540 return true;
1541}
1542
Richard Smith254a73d2011-10-28 22:34:42 +00001543/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001544static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1545 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001546 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001547 EvalInfo &Info, APValue &Result) {
1548 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001549 return false;
1550
Richard Smithd62306a2011-11-10 06:34:14 +00001551 ArgVector ArgValues(Args.size());
1552 if (!EvaluateArgs(Args, ArgValues, Info))
1553 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001554
Richard Smithf6f003a2011-12-16 19:06:07 +00001555 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1556 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001557 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1558}
1559
Richard Smithd62306a2011-11-10 06:34:14 +00001560/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001561static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001562 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001563 const CXXConstructorDecl *Definition,
Richard Smithe97cbd72011-11-11 04:05:33 +00001564 EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00001565 APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001566 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001567 return false;
1568
1569 ArgVector ArgValues(Args.size());
1570 if (!EvaluateArgs(Args, ArgValues, Info))
1571 return false;
1572
Richard Smithf6f003a2011-12-16 19:06:07 +00001573 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1574 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001575
1576 // If it's a delegating constructor, just delegate.
1577 if (Definition->isDelegatingConstructor()) {
1578 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1579 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1580 }
1581
1582 // Reserve space for the struct members.
1583 const CXXRecordDecl *RD = Definition->getParent();
1584 if (!RD->isUnion())
1585 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1586 std::distance(RD->field_begin(), RD->field_end()));
1587
1588 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1589
1590 unsigned BasesSeen = 0;
1591#ifndef NDEBUG
1592 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1593#endif
1594 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1595 E = Definition->init_end(); I != E; ++I) {
1596 if ((*I)->isBaseInitializer()) {
1597 QualType BaseType((*I)->getBaseClass(), 0);
1598#ifndef NDEBUG
1599 // Non-virtual base classes are initialized in the order in the class
1600 // definition. We cannot have a virtual base class for a literal type.
1601 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1602 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1603 "base class initializers not in expected order");
1604 ++BaseIt;
1605#endif
1606 LValue Subobject = This;
1607 HandleLValueDirectBase(Info, Subobject, RD,
1608 BaseType->getAsCXXRecordDecl(), &Layout);
1609 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1610 Subobject, (*I)->getInit()))
1611 return false;
1612 } else if (FieldDecl *FD = (*I)->getMember()) {
1613 LValue Subobject = This;
1614 HandleLValueMember(Info, Subobject, FD, &Layout);
1615 if (RD->isUnion()) {
1616 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001617 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1618 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001619 return false;
1620 } else if (!EvaluateConstantExpression(
1621 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001622 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001623 return false;
1624 } else {
1625 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001626 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001627 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001628 return false;
1629 }
1630 }
1631
1632 return true;
1633}
1634
Richard Smith254a73d2011-10-28 22:34:42 +00001635namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001636class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001637 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001638 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001639public:
1640
Richard Smith725810a2011-10-16 21:26:27 +00001641 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001642
1643 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001644 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001645 return true;
1646 }
1647
Peter Collingbournee9200682011-05-13 03:29:01 +00001648 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1649 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001650 return Visit(E->getResultExpr());
1651 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001652 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001653 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001654 return true;
1655 return false;
1656 }
John McCall31168b02011-06-15 23:02:42 +00001657 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001658 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001659 return true;
1660 return false;
1661 }
1662 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001663 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001664 return true;
1665 return false;
1666 }
1667
Mike Stump876387b2009-10-27 22:09:17 +00001668 // We don't want to evaluate BlockExprs multiple times, as they generate
1669 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001670 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1671 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1672 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001673 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001674 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1675 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1676 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1677 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1678 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1679 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001680 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001681 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001682 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001683 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001684 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001685 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1686 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1687 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1688 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001689 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001690 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1691 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1692 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1693 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1694 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001695 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001696 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001697 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001698 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001699 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001700
1701 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001702 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001703 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1704 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001705 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001706 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001707 return false;
1708 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001709
Peter Collingbournee9200682011-05-13 03:29:01 +00001710 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001711};
1712
John McCallc07a0c72011-02-17 10:25:35 +00001713class OpaqueValueEvaluation {
1714 EvalInfo &info;
1715 OpaqueValueExpr *opaqueValue;
1716
1717public:
1718 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1719 Expr *value)
1720 : info(info), opaqueValue(opaqueValue) {
1721
1722 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001723 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001724 this->opaqueValue = 0;
1725 return;
1726 }
John McCallc07a0c72011-02-17 10:25:35 +00001727 }
1728
1729 bool hasError() const { return opaqueValue == 0; }
1730
1731 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001732 // FIXME: This will not work for recursive constexpr functions using opaque
1733 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001734 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1735 }
1736};
1737
Mike Stump876387b2009-10-27 22:09:17 +00001738} // end anonymous namespace
1739
Eli Friedman9a156e52008-11-12 09:44:48 +00001740//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001741// Generic Evaluation
1742//===----------------------------------------------------------------------===//
1743namespace {
1744
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745// FIXME: RetTy is always bool. Remove it.
1746template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001747class ExprEvaluatorBase
1748 : public ConstStmtVisitor<Derived, RetTy> {
1749private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001750 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001751 return static_cast<Derived*>(this)->Success(V, E);
1752 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001753 RetTy DerivedValueInitialization(const Expr *E) {
1754 return static_cast<Derived*>(this)->ValueInitialization(E);
1755 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001756
1757protected:
1758 EvalInfo &Info;
1759 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1760 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1761
Richard Smith92b1ce02011-12-12 09:28:41 +00001762 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001763 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001764 }
1765
1766 /// Report an evaluation error. This should only be called when an error is
1767 /// first discovered. When propagating an error, just return false.
1768 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001769 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001770 return false;
1771 }
1772 bool Error(const Expr *E) {
1773 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1774 }
1775
1776 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001777
Peter Collingbournee9200682011-05-13 03:29:01 +00001778public:
1779 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1780
1781 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001782 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001783 }
1784 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001785 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001786 }
1787
1788 RetTy VisitParenExpr(const ParenExpr *E)
1789 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1790 RetTy VisitUnaryExtension(const UnaryOperator *E)
1791 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1792 RetTy VisitUnaryPlus(const UnaryOperator *E)
1793 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1794 RetTy VisitChooseExpr(const ChooseExpr *E)
1795 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1796 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1797 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001798 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1799 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001800 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1801 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001802
Richard Smith6d6ecc32011-12-12 12:46:16 +00001803 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1804 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1805 return static_cast<Derived*>(this)->VisitCastExpr(E);
1806 }
1807 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1808 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1809 return static_cast<Derived*>(this)->VisitCastExpr(E);
1810 }
1811
Richard Smith027bf112011-11-17 22:56:20 +00001812 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1813 switch (E->getOpcode()) {
1814 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001815 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001816
1817 case BO_Comma:
1818 VisitIgnoredValue(E->getLHS());
1819 return StmtVisitorTy::Visit(E->getRHS());
1820
1821 case BO_PtrMemD:
1822 case BO_PtrMemI: {
1823 LValue Obj;
1824 if (!HandleMemberPointerAccess(Info, E, Obj))
1825 return false;
1826 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001827 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00001828 return false;
1829 return DerivedSuccess(Result, E);
1830 }
1831 }
1832 }
1833
Peter Collingbournee9200682011-05-13 03:29:01 +00001834 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1835 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1836 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001837 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001838
1839 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00001840 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001841 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001842
1843 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1844 }
1845
1846 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1847 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00001848 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001849 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001850
Richard Smith11562c52011-10-28 17:51:58 +00001851 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00001852 return StmtVisitorTy::Visit(EvalExpr);
1853 }
1854
1855 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001856 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001857 if (!Value) {
1858 const Expr *Source = E->getSourceExpr();
1859 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001860 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001861 if (Source == E) { // sanity checking.
1862 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00001863 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001864 }
1865 return StmtVisitorTy::Visit(Source);
1866 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001867 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001868 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001869
Richard Smith254a73d2011-10-28 22:34:42 +00001870 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00001871 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00001872 QualType CalleeType = Callee->getType();
1873
Richard Smith254a73d2011-10-28 22:34:42 +00001874 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00001875 LValue *This = 0, ThisVal;
1876 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00001877
Richard Smithe97cbd72011-11-11 04:05:33 +00001878 // Extract function decl and 'this' pointer from the callee.
1879 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001880 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00001881 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1882 // Explicit bound member calls, such as x.f() or p->g();
1883 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001884 return false;
1885 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00001886 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001887 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1888 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00001889 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1890 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00001891 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001892 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001893 return Error(Callee);
1894
1895 FD = dyn_cast<FunctionDecl>(Member);
1896 if (!FD)
1897 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001898 } else if (CalleeType->isFunctionPointerType()) {
1899 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001900 if (!Evaluate(Call, Info, Callee))
1901 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00001902
Richard Smithf57d8cb2011-12-09 22:58:01 +00001903 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1904 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00001905 FD = dyn_cast_or_null<FunctionDecl>(
1906 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00001907 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001908 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001909
1910 // Overloaded operator calls to member functions are represented as normal
1911 // calls with '*this' as the first argument.
1912 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1913 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001914 // FIXME: When selecting an implicit conversion for an overloaded
1915 // operator delete, we sometimes try to evaluate calls to conversion
1916 // operators without a 'this' parameter!
1917 if (Args.empty())
1918 return Error(E);
1919
Richard Smithe97cbd72011-11-11 04:05:33 +00001920 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1921 return false;
1922 This = &ThisVal;
1923 Args = Args.slice(1);
1924 }
1925
1926 // Don't call function pointers which have been cast to some other type.
1927 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001928 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00001929 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001930 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001931
Richard Smith357362d2011-12-13 06:39:58 +00001932 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00001933 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00001934 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00001935
Richard Smith357362d2011-12-13 06:39:58 +00001936 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00001937 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001938 return false;
1939
1940 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00001941 }
1942
Richard Smith11562c52011-10-28 17:51:58 +00001943 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1944 return StmtVisitorTy::Visit(E->getInitializer());
1945 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001946 RetTy VisitInitListExpr(const InitListExpr *E) {
1947 if (Info.getLangOpts().CPlusPlus0x) {
1948 if (E->getNumInits() == 0)
1949 return DerivedValueInitialization(E);
1950 if (E->getNumInits() == 1)
1951 return StmtVisitorTy::Visit(E->getInit(0));
1952 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001953 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001954 }
1955 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1956 return DerivedValueInitialization(E);
1957 }
1958 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1959 return DerivedValueInitialization(E);
1960 }
Richard Smith027bf112011-11-17 22:56:20 +00001961 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1962 return DerivedValueInitialization(E);
1963 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001964
Richard Smithd62306a2011-11-10 06:34:14 +00001965 /// A member expression where the object is a prvalue is itself a prvalue.
1966 RetTy VisitMemberExpr(const MemberExpr *E) {
1967 assert(!E->isArrow() && "missing call to bound member function?");
1968
1969 CCValue Val;
1970 if (!Evaluate(Val, Info, E->getBase()))
1971 return false;
1972
1973 QualType BaseTy = E->getBase()->getType();
1974
1975 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00001976 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00001977 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1978 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1979 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1980
1981 SubobjectDesignator Designator;
1982 Designator.addDecl(FD);
1983
Richard Smithf57d8cb2011-12-09 22:58:01 +00001984 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00001985 DerivedSuccess(Val, E);
1986 }
1987
Richard Smith11562c52011-10-28 17:51:58 +00001988 RetTy VisitCastExpr(const CastExpr *E) {
1989 switch (E->getCastKind()) {
1990 default:
1991 break;
1992
1993 case CK_NoOp:
1994 return StmtVisitorTy::Visit(E->getSubExpr());
1995
1996 case CK_LValueToRValue: {
1997 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001998 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
1999 return false;
2000 CCValue RVal;
2001 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2002 return false;
2003 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002004 }
2005 }
2006
Richard Smithf57d8cb2011-12-09 22:58:01 +00002007 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002008 }
2009
Richard Smith4a678122011-10-24 18:44:57 +00002010 /// Visit a value which is evaluated, but whose value is ignored.
2011 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002012 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002013 if (!Evaluate(Scratch, Info, E))
2014 Info.EvalStatus.HasSideEffects = true;
2015 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002016};
2017
2018}
2019
2020//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002021// Common base class for lvalue and temporary evaluation.
2022//===----------------------------------------------------------------------===//
2023namespace {
2024template<class Derived>
2025class LValueExprEvaluatorBase
2026 : public ExprEvaluatorBase<Derived, bool> {
2027protected:
2028 LValue &Result;
2029 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2030 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2031
2032 bool Success(APValue::LValueBase B) {
2033 Result.set(B);
2034 return true;
2035 }
2036
2037public:
2038 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2039 ExprEvaluatorBaseTy(Info), Result(Result) {}
2040
2041 bool Success(const CCValue &V, const Expr *E) {
2042 Result.setFrom(V);
2043 return true;
2044 }
Richard Smith027bf112011-11-17 22:56:20 +00002045
2046 bool CheckValidLValue() {
2047 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2048 // there are no null references, nor once-past-the-end references.
2049 // FIXME: Check for one-past-the-end array indices
2050 return Result.Base && !Result.Designator.Invalid &&
2051 !Result.Designator.OnePastTheEnd;
2052 }
2053
2054 bool VisitMemberExpr(const MemberExpr *E) {
2055 // Handle non-static data members.
2056 QualType BaseTy;
2057 if (E->isArrow()) {
2058 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2059 return false;
2060 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002061 } else if (E->getBase()->isRValue()) {
Eli Friedman79281d12011-12-17 02:24:21 +00002062 if (!E->getBase()->getType()->isRecordType() ||
2063 !E->getBase()->getType()->isLiteralType())
2064 return false;
Richard Smith357362d2011-12-13 06:39:58 +00002065 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2066 return false;
2067 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002068 } else {
2069 if (!this->Visit(E->getBase()))
2070 return false;
2071 BaseTy = E->getBase()->getType();
2072 }
2073 // FIXME: In C++11, require the result to be a valid lvalue.
2074
2075 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2076 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002077 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002078 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2079 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2080 (void)BaseTy;
2081
2082 HandleLValueMember(this->Info, Result, FD);
2083
2084 if (FD->getType()->isReferenceType()) {
2085 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002086 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002087 RefValue))
2088 return false;
2089 return Success(RefValue, E);
2090 }
2091 return true;
2092 }
2093
2094 bool VisitBinaryOperator(const BinaryOperator *E) {
2095 switch (E->getOpcode()) {
2096 default:
2097 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2098
2099 case BO_PtrMemD:
2100 case BO_PtrMemI:
2101 return HandleMemberPointerAccess(this->Info, E, Result);
2102 }
2103 }
2104
2105 bool VisitCastExpr(const CastExpr *E) {
2106 switch (E->getCastKind()) {
2107 default:
2108 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2109
2110 case CK_DerivedToBase:
2111 case CK_UncheckedDerivedToBase: {
2112 if (!this->Visit(E->getSubExpr()))
2113 return false;
2114 if (!CheckValidLValue())
2115 return false;
2116
2117 // Now figure out the necessary offset to add to the base LV to get from
2118 // the derived class to the base class.
2119 QualType Type = E->getSubExpr()->getType();
2120
2121 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2122 PathE = E->path_end(); PathI != PathE; ++PathI) {
2123 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2124 *PathI))
2125 return false;
2126 Type = (*PathI)->getType();
2127 }
2128
2129 return true;
2130 }
2131 }
2132 }
2133};
2134}
2135
2136//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002137// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002138//
2139// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2140// function designators (in C), decl references to void objects (in C), and
2141// temporaries (if building with -Wno-address-of-temporary).
2142//
2143// LValue evaluation produces values comprising a base expression of one of the
2144// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002145// - Declarations
2146// * VarDecl
2147// * FunctionDecl
2148// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002149// * CompoundLiteralExpr in C
2150// * StringLiteral
2151// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002152// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002153// * ObjCEncodeExpr
2154// * AddrLabelExpr
2155// * BlockExpr
2156// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002157// - Locals and temporaries
2158// * Any Expr, with a Frame indicating the function in which the temporary was
2159// evaluated.
2160// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002161//===----------------------------------------------------------------------===//
2162namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002163class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002164 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002165public:
Richard Smith027bf112011-11-17 22:56:20 +00002166 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2167 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002168
Richard Smith11562c52011-10-28 17:51:58 +00002169 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2170
Peter Collingbournee9200682011-05-13 03:29:01 +00002171 bool VisitDeclRefExpr(const DeclRefExpr *E);
2172 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002173 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002174 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2175 bool VisitMemberExpr(const MemberExpr *E);
2176 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2177 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2178 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2179 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002180
Peter Collingbournee9200682011-05-13 03:29:01 +00002181 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002182 switch (E->getCastKind()) {
2183 default:
Richard Smith027bf112011-11-17 22:56:20 +00002184 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002185
Eli Friedmance3e02a2011-10-11 00:13:24 +00002186 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002187 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002188 if (!Visit(E->getSubExpr()))
2189 return false;
2190 Result.Designator.setInvalid();
2191 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002192
Richard Smith027bf112011-11-17 22:56:20 +00002193 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002194 if (!Visit(E->getSubExpr()))
2195 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002196 if (!CheckValidLValue())
2197 return false;
2198 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002199 }
2200 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002201
Eli Friedman449fe542009-03-23 04:56:01 +00002202 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002203
Eli Friedman9a156e52008-11-12 09:44:48 +00002204};
2205} // end anonymous namespace
2206
Richard Smith11562c52011-10-28 17:51:58 +00002207/// Evaluate an expression as an lvalue. This can be legitimately called on
2208/// expressions which are not glvalues, in a few cases:
2209/// * function designators in C,
2210/// * "extern void" objects,
2211/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002212static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002213 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2214 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2215 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002216 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002217}
2218
Peter Collingbournee9200682011-05-13 03:29:01 +00002219bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002220 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2221 return Success(FD);
2222 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002223 return VisitVarDecl(E, VD);
2224 return Error(E);
2225}
Richard Smith733237d2011-10-24 23:14:33 +00002226
Richard Smith11562c52011-10-28 17:51:58 +00002227bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002228 if (!VD->getType()->isReferenceType()) {
2229 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002230 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002231 return true;
2232 }
Richard Smithce40ad62011-11-12 22:28:03 +00002233 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002234 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002235
Richard Smith0b0a0b62011-10-29 20:57:55 +00002236 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002237 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2238 return false;
2239 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002240}
2241
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002242bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2243 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002244 if (E->GetTemporaryExpr()->isRValue()) {
2245 if (E->getType()->isRecordType() && E->getType()->isLiteralType())
2246 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2247
2248 Result.set(E, Info.CurrentCall);
2249 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2250 Result, E->GetTemporaryExpr());
2251 }
2252
2253 // Materialization of an lvalue temporary occurs when we need to force a copy
2254 // (for instance, if it's a bitfield).
2255 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2256 if (!Visit(E->GetTemporaryExpr()))
2257 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002258 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002259 Info.CurrentCall->Temporaries[E]))
2260 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002261 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002262 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002263}
2264
Peter Collingbournee9200682011-05-13 03:29:01 +00002265bool
2266LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002267 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2268 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2269 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002270 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002271}
2272
Peter Collingbournee9200682011-05-13 03:29:01 +00002273bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002274 // Handle static data members.
2275 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2276 VisitIgnoredValue(E->getBase());
2277 return VisitVarDecl(E, VD);
2278 }
2279
Richard Smith254a73d2011-10-28 22:34:42 +00002280 // Handle static member functions.
2281 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2282 if (MD->isStatic()) {
2283 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002284 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002285 }
2286 }
2287
Richard Smithd62306a2011-11-10 06:34:14 +00002288 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002289 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002290}
2291
Peter Collingbournee9200682011-05-13 03:29:01 +00002292bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002293 // FIXME: Deal with vectors as array subscript bases.
2294 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002295 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002296
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002297 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002298 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002299
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002300 APSInt Index;
2301 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002302 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002303 int64_t IndexValue
2304 = Index.isSigned() ? Index.getSExtValue()
2305 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002306
Richard Smith027bf112011-11-17 22:56:20 +00002307 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002308 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002309}
Eli Friedman9a156e52008-11-12 09:44:48 +00002310
Peter Collingbournee9200682011-05-13 03:29:01 +00002311bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002312 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002313 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002314}
2315
Eli Friedman9a156e52008-11-12 09:44:48 +00002316//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002317// Pointer Evaluation
2318//===----------------------------------------------------------------------===//
2319
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002320namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002321class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002322 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002323 LValue &Result;
2324
Peter Collingbournee9200682011-05-13 03:29:01 +00002325 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002326 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002327 return true;
2328 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002329public:
Mike Stump11289f42009-09-09 15:08:12 +00002330
John McCall45d55e42010-05-07 21:00:08 +00002331 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002332 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002333
Richard Smith0b0a0b62011-10-29 20:57:55 +00002334 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002335 Result.setFrom(V);
2336 return true;
2337 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002338 bool ValueInitialization(const Expr *E) {
2339 return Success((Expr*)0);
2340 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002341
John McCall45d55e42010-05-07 21:00:08 +00002342 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002343 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002344 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002345 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002346 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002347 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002348 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002349 bool VisitCallExpr(const CallExpr *E);
2350 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002351 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002352 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002353 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002354 }
Richard Smithd62306a2011-11-10 06:34:14 +00002355 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2356 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002357 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002358 Result = *Info.CurrentCall->This;
2359 return true;
2360 }
John McCallc07a0c72011-02-17 10:25:35 +00002361
Eli Friedman449fe542009-03-23 04:56:01 +00002362 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002363};
Chris Lattner05706e882008-07-11 18:11:29 +00002364} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002365
John McCall45d55e42010-05-07 21:00:08 +00002366static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002367 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002368 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002369}
2370
John McCall45d55e42010-05-07 21:00:08 +00002371bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002372 if (E->getOpcode() != BO_Add &&
2373 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002374 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002375
Chris Lattner05706e882008-07-11 18:11:29 +00002376 const Expr *PExp = E->getLHS();
2377 const Expr *IExp = E->getRHS();
2378 if (IExp->getType()->isPointerType())
2379 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002380
John McCall45d55e42010-05-07 21:00:08 +00002381 if (!EvaluatePointer(PExp, Result, Info))
2382 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002383
John McCall45d55e42010-05-07 21:00:08 +00002384 llvm::APSInt Offset;
2385 if (!EvaluateInteger(IExp, Offset, Info))
2386 return false;
2387 int64_t AdditionalOffset
2388 = Offset.isSigned() ? Offset.getSExtValue()
2389 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002390 if (E->getOpcode() == BO_Sub)
2391 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002392
Richard Smithd62306a2011-11-10 06:34:14 +00002393 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002394 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002395 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002396}
Eli Friedman9a156e52008-11-12 09:44:48 +00002397
John McCall45d55e42010-05-07 21:00:08 +00002398bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2399 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002400}
Mike Stump11289f42009-09-09 15:08:12 +00002401
Peter Collingbournee9200682011-05-13 03:29:01 +00002402bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2403 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002404
Eli Friedman847a2bc2009-12-27 05:43:15 +00002405 switch (E->getCastKind()) {
2406 default:
2407 break;
2408
John McCalle3027922010-08-25 11:45:40 +00002409 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002410 case CK_CPointerToObjCPointerCast:
2411 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002412 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002413 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2414 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2415 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002416 if (!E->getType()->isVoidPointerType()) {
2417 if (SubExpr->getType()->isVoidPointerType())
2418 CCEDiag(E, diag::note_constexpr_invalid_cast)
2419 << 3 << SubExpr->getType();
2420 else
2421 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2422 }
Richard Smith96e0c102011-11-04 02:25:55 +00002423 if (!Visit(SubExpr))
2424 return false;
2425 Result.Designator.setInvalid();
2426 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002427
Anders Carlsson18275092010-10-31 20:41:46 +00002428 case CK_DerivedToBase:
2429 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002430 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002431 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002432 if (!Result.Base && Result.Offset.isZero())
2433 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002434
Richard Smithd62306a2011-11-10 06:34:14 +00002435 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002436 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002437 QualType Type =
2438 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002439
Richard Smithd62306a2011-11-10 06:34:14 +00002440 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002441 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002442 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002443 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002444 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002445 }
2446
Anders Carlsson18275092010-10-31 20:41:46 +00002447 return true;
2448 }
2449
Richard Smith027bf112011-11-17 22:56:20 +00002450 case CK_BaseToDerived:
2451 if (!Visit(E->getSubExpr()))
2452 return false;
2453 if (!Result.Base && Result.Offset.isZero())
2454 return true;
2455 return HandleBaseToDerivedCast(Info, E, Result);
2456
Richard Smith0b0a0b62011-10-29 20:57:55 +00002457 case CK_NullToPointer:
2458 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002459
John McCalle3027922010-08-25 11:45:40 +00002460 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002461 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2462
Richard Smith0b0a0b62011-10-29 20:57:55 +00002463 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002464 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002465 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002466
John McCall45d55e42010-05-07 21:00:08 +00002467 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002468 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2469 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002470 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002471 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002472 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002473 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002474 return true;
2475 } else {
2476 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002477 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002478 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002479 }
2480 }
John McCalle3027922010-08-25 11:45:40 +00002481 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002482 if (SubExpr->isGLValue()) {
2483 if (!EvaluateLValue(SubExpr, Result, Info))
2484 return false;
2485 } else {
2486 Result.set(SubExpr, Info.CurrentCall);
2487 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2488 Info, Result, SubExpr))
2489 return false;
2490 }
Richard Smith96e0c102011-11-04 02:25:55 +00002491 // The result is a pointer to the first element of the array.
2492 Result.Designator.addIndex(0);
2493 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002494
John McCalle3027922010-08-25 11:45:40 +00002495 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002496 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002497 }
2498
Richard Smith11562c52011-10-28 17:51:58 +00002499 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002500}
Chris Lattner05706e882008-07-11 18:11:29 +00002501
Peter Collingbournee9200682011-05-13 03:29:01 +00002502bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002503 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002504 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002505
Peter Collingbournee9200682011-05-13 03:29:01 +00002506 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002507}
Chris Lattner05706e882008-07-11 18:11:29 +00002508
2509//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002510// Member Pointer Evaluation
2511//===----------------------------------------------------------------------===//
2512
2513namespace {
2514class MemberPointerExprEvaluator
2515 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2516 MemberPtr &Result;
2517
2518 bool Success(const ValueDecl *D) {
2519 Result = MemberPtr(D);
2520 return true;
2521 }
2522public:
2523
2524 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2525 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2526
2527 bool Success(const CCValue &V, const Expr *E) {
2528 Result.setFrom(V);
2529 return true;
2530 }
Richard Smith027bf112011-11-17 22:56:20 +00002531 bool ValueInitialization(const Expr *E) {
2532 return Success((const ValueDecl*)0);
2533 }
2534
2535 bool VisitCastExpr(const CastExpr *E);
2536 bool VisitUnaryAddrOf(const UnaryOperator *E);
2537};
2538} // end anonymous namespace
2539
2540static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2541 EvalInfo &Info) {
2542 assert(E->isRValue() && E->getType()->isMemberPointerType());
2543 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2544}
2545
2546bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2547 switch (E->getCastKind()) {
2548 default:
2549 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2550
2551 case CK_NullToMemberPointer:
2552 return ValueInitialization(E);
2553
2554 case CK_BaseToDerivedMemberPointer: {
2555 if (!Visit(E->getSubExpr()))
2556 return false;
2557 if (E->path_empty())
2558 return true;
2559 // Base-to-derived member pointer casts store the path in derived-to-base
2560 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2561 // the wrong end of the derived->base arc, so stagger the path by one class.
2562 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2563 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2564 PathI != PathE; ++PathI) {
2565 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2566 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2567 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002568 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002569 }
2570 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2571 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002572 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002573 return true;
2574 }
2575
2576 case CK_DerivedToBaseMemberPointer:
2577 if (!Visit(E->getSubExpr()))
2578 return false;
2579 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2580 PathE = E->path_end(); PathI != PathE; ++PathI) {
2581 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2582 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2583 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002584 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002585 }
2586 return true;
2587 }
2588}
2589
2590bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2591 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2592 // member can be formed.
2593 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2594}
2595
2596//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002597// Record Evaluation
2598//===----------------------------------------------------------------------===//
2599
2600namespace {
2601 class RecordExprEvaluator
2602 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2603 const LValue &This;
2604 APValue &Result;
2605 public:
2606
2607 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2608 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2609
2610 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002611 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002612 }
Richard Smithd62306a2011-11-10 06:34:14 +00002613
Richard Smithe97cbd72011-11-11 04:05:33 +00002614 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002615 bool VisitInitListExpr(const InitListExpr *E);
2616 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2617 };
2618}
2619
Richard Smithe97cbd72011-11-11 04:05:33 +00002620bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2621 switch (E->getCastKind()) {
2622 default:
2623 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2624
2625 case CK_ConstructorConversion:
2626 return Visit(E->getSubExpr());
2627
2628 case CK_DerivedToBase:
2629 case CK_UncheckedDerivedToBase: {
2630 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002631 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002632 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002633 if (!DerivedObject.isStruct())
2634 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002635
2636 // Derived-to-base rvalue conversion: just slice off the derived part.
2637 APValue *Value = &DerivedObject;
2638 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2639 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2640 PathE = E->path_end(); PathI != PathE; ++PathI) {
2641 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2642 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2643 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2644 RD = Base;
2645 }
2646 Result = *Value;
2647 return true;
2648 }
2649 }
2650}
2651
Richard Smithd62306a2011-11-10 06:34:14 +00002652bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2653 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2654 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2655
2656 if (RD->isUnion()) {
2657 Result = APValue(E->getInitializedFieldInUnion());
2658 if (!E->getNumInits())
2659 return true;
2660 LValue Subobject = This;
2661 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2662 &Layout);
2663 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2664 Subobject, E->getInit(0));
2665 }
2666
2667 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2668 "initializer list for class with base classes");
2669 Result = APValue(APValue::UninitStruct(), 0,
2670 std::distance(RD->field_begin(), RD->field_end()));
2671 unsigned ElementNo = 0;
2672 for (RecordDecl::field_iterator Field = RD->field_begin(),
2673 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2674 // Anonymous bit-fields are not considered members of the class for
2675 // purposes of aggregate initialization.
2676 if (Field->isUnnamedBitfield())
2677 continue;
2678
2679 LValue Subobject = This;
2680 HandleLValueMember(Info, Subobject, *Field, &Layout);
2681
2682 if (ElementNo < E->getNumInits()) {
2683 if (!EvaluateConstantExpression(
2684 Result.getStructField((*Field)->getFieldIndex()),
2685 Info, Subobject, E->getInit(ElementNo++)))
2686 return false;
2687 } else {
2688 // Perform an implicit value-initialization for members beyond the end of
2689 // the initializer list.
2690 ImplicitValueInitExpr VIE(Field->getType());
2691 if (!EvaluateConstantExpression(
2692 Result.getStructField((*Field)->getFieldIndex()),
2693 Info, Subobject, &VIE))
2694 return false;
2695 }
2696 }
2697
2698 return true;
2699}
2700
2701bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2702 const CXXConstructorDecl *FD = E->getConstructor();
2703 const FunctionDecl *Definition = 0;
2704 FD->getBody(Definition);
2705
Richard Smith357362d2011-12-13 06:39:58 +00002706 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2707 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002708
2709 // FIXME: Elide the copy/move construction wherever we can.
2710 if (E->isElidable())
2711 if (const MaterializeTemporaryExpr *ME
2712 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2713 return Visit(ME->GetTemporaryExpr());
2714
2715 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002716 return HandleConstructorCall(E, This, Args,
2717 cast<CXXConstructorDecl>(Definition), Info,
2718 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002719}
2720
2721static bool EvaluateRecord(const Expr *E, const LValue &This,
2722 APValue &Result, EvalInfo &Info) {
2723 assert(E->isRValue() && E->getType()->isRecordType() &&
2724 E->getType()->isLiteralType() &&
2725 "can't evaluate expression as a record rvalue");
2726 return RecordExprEvaluator(Info, This, Result).Visit(E);
2727}
2728
2729//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002730// Temporary Evaluation
2731//
2732// Temporaries are represented in the AST as rvalues, but generally behave like
2733// lvalues. The full-object of which the temporary is a subobject is implicitly
2734// materialized so that a reference can bind to it.
2735//===----------------------------------------------------------------------===//
2736namespace {
2737class TemporaryExprEvaluator
2738 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2739public:
2740 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2741 LValueExprEvaluatorBaseTy(Info, Result) {}
2742
2743 /// Visit an expression which constructs the value of this temporary.
2744 bool VisitConstructExpr(const Expr *E) {
2745 Result.set(E, Info.CurrentCall);
2746 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2747 Result, E);
2748 }
2749
2750 bool VisitCastExpr(const CastExpr *E) {
2751 switch (E->getCastKind()) {
2752 default:
2753 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2754
2755 case CK_ConstructorConversion:
2756 return VisitConstructExpr(E->getSubExpr());
2757 }
2758 }
2759 bool VisitInitListExpr(const InitListExpr *E) {
2760 return VisitConstructExpr(E);
2761 }
2762 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2763 return VisitConstructExpr(E);
2764 }
2765 bool VisitCallExpr(const CallExpr *E) {
2766 return VisitConstructExpr(E);
2767 }
2768};
2769} // end anonymous namespace
2770
2771/// Evaluate an expression of record type as a temporary.
2772static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
2773 assert(E->isRValue() && E->getType()->isRecordType() &&
2774 E->getType()->isLiteralType());
2775 return TemporaryExprEvaluator(Info, Result).Visit(E);
2776}
2777
2778//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002779// Vector Evaluation
2780//===----------------------------------------------------------------------===//
2781
2782namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002783 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00002784 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2785 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002786 public:
Mike Stump11289f42009-09-09 15:08:12 +00002787
Richard Smith2d406342011-10-22 21:10:00 +00002788 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2789 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002790
Richard Smith2d406342011-10-22 21:10:00 +00002791 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2792 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2793 // FIXME: remove this APValue copy.
2794 Result = APValue(V.data(), V.size());
2795 return true;
2796 }
Richard Smithed5165f2011-11-04 05:33:44 +00002797 bool Success(const CCValue &V, const Expr *E) {
2798 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00002799 Result = V;
2800 return true;
2801 }
Richard Smith2d406342011-10-22 21:10:00 +00002802 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002803
Richard Smith2d406342011-10-22 21:10:00 +00002804 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00002805 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00002806 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00002807 bool VisitInitListExpr(const InitListExpr *E);
2808 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002809 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00002810 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00002811 // shufflevector, ExtVectorElementExpr
2812 // (Note that these require implementing conversions
2813 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002814 };
2815} // end anonymous namespace
2816
2817static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002818 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00002819 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002820}
2821
Richard Smith2d406342011-10-22 21:10:00 +00002822bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2823 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002824 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002825
Richard Smith161f09a2011-12-06 22:44:34 +00002826 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00002827 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002828
Eli Friedmanc757de22011-03-25 00:43:55 +00002829 switch (E->getCastKind()) {
2830 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00002831 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00002832 if (SETy->isIntegerType()) {
2833 APSInt IntResult;
2834 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002835 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002836 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00002837 } else if (SETy->isRealFloatingType()) {
2838 APFloat F(0.0);
2839 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002840 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002841 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00002842 } else {
Richard Smith2d406342011-10-22 21:10:00 +00002843 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002844 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002845
2846 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00002847 SmallVector<APValue, 4> Elts(NElts, Val);
2848 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00002849 }
Eli Friedmanc757de22011-03-25 00:43:55 +00002850 default:
Richard Smith11562c52011-10-28 17:51:58 +00002851 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002852 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002853}
2854
Richard Smith2d406342011-10-22 21:10:00 +00002855bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002856VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00002857 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002858 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00002859 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002860
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002861 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002862 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002863
John McCall875679e2010-06-11 17:54:15 +00002864 // If a vector is initialized with a single element, that value
2865 // becomes every element of the vector, not just the first.
2866 // This is the behavior described in the IBM AltiVec documentation.
2867 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00002868
2869 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00002870 // vector (OpenCL 6.1.6).
2871 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00002872 return Visit(E->getInit(0));
2873
John McCall875679e2010-06-11 17:54:15 +00002874 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002875 if (EltTy->isIntegerType()) {
2876 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00002877 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002878 return false;
John McCall875679e2010-06-11 17:54:15 +00002879 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002880 } else {
2881 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00002882 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002883 return false;
John McCall875679e2010-06-11 17:54:15 +00002884 InitValue = APValue(f);
2885 }
2886 for (unsigned i = 0; i < NumElements; i++) {
2887 Elements.push_back(InitValue);
2888 }
2889 } else {
2890 for (unsigned i = 0; i < NumElements; i++) {
2891 if (EltTy->isIntegerType()) {
2892 llvm::APSInt sInt(32);
2893 if (i < NumInits) {
2894 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002895 return false;
John McCall875679e2010-06-11 17:54:15 +00002896 } else {
2897 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2898 }
2899 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00002900 } else {
John McCall875679e2010-06-11 17:54:15 +00002901 llvm::APFloat f(0.0);
2902 if (i < NumInits) {
2903 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002904 return false;
John McCall875679e2010-06-11 17:54:15 +00002905 } else {
2906 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2907 }
2908 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00002909 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002910 }
2911 }
Richard Smith2d406342011-10-22 21:10:00 +00002912 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002913}
2914
Richard Smith2d406342011-10-22 21:10:00 +00002915bool
2916VectorExprEvaluator::ValueInitialization(const Expr *E) {
2917 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00002918 QualType EltTy = VT->getElementType();
2919 APValue ZeroElement;
2920 if (EltTy->isIntegerType())
2921 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2922 else
2923 ZeroElement =
2924 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2925
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002926 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00002927 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002928}
2929
Richard Smith2d406342011-10-22 21:10:00 +00002930bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00002931 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00002932 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002933}
2934
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002935//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00002936// Array Evaluation
2937//===----------------------------------------------------------------------===//
2938
2939namespace {
2940 class ArrayExprEvaluator
2941 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00002942 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00002943 APValue &Result;
2944 public:
2945
Richard Smithd62306a2011-11-10 06:34:14 +00002946 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2947 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00002948
2949 bool Success(const APValue &V, const Expr *E) {
2950 assert(V.isArray() && "Expected array type");
2951 Result = V;
2952 return true;
2953 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002954
Richard Smithd62306a2011-11-10 06:34:14 +00002955 bool ValueInitialization(const Expr *E) {
2956 const ConstantArrayType *CAT =
2957 Info.Ctx.getAsConstantArrayType(E->getType());
2958 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002959 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002960
2961 Result = APValue(APValue::UninitArray(), 0,
2962 CAT->getSize().getZExtValue());
2963 if (!Result.hasArrayFiller()) return true;
2964
2965 // Value-initialize all elements.
2966 LValue Subobject = This;
2967 Subobject.Designator.addIndex(0);
2968 ImplicitValueInitExpr VIE(CAT->getElementType());
2969 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2970 Subobject, &VIE);
2971 }
2972
Richard Smithf3e9e432011-11-07 09:22:26 +00002973 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00002974 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002975 };
2976} // end anonymous namespace
2977
Richard Smithd62306a2011-11-10 06:34:14 +00002978static bool EvaluateArray(const Expr *E, const LValue &This,
2979 APValue &Result, EvalInfo &Info) {
Richard Smithf3e9e432011-11-07 09:22:26 +00002980 assert(E->isRValue() && E->getType()->isArrayType() &&
2981 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00002982 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002983}
2984
2985bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2986 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2987 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002988 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002989
2990 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2991 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00002992 LValue Subobject = This;
2993 Subobject.Designator.addIndex(0);
2994 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002995 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00002996 I != End; ++I, ++Index) {
2997 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2998 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00002999 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003000 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3001 return false;
3002 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003003
3004 if (!Result.hasArrayFiller()) return true;
3005 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003006 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3007 // but sometimes does:
3008 // struct S { constexpr S() : p(&p) {} void *p; };
3009 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003010 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003011 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003012}
3013
Richard Smith027bf112011-11-17 22:56:20 +00003014bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3015 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3016 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003017 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003018
3019 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3020 if (!Result.hasArrayFiller())
3021 return true;
3022
3023 const CXXConstructorDecl *FD = E->getConstructor();
3024 const FunctionDecl *Definition = 0;
3025 FD->getBody(Definition);
3026
Richard Smith357362d2011-12-13 06:39:58 +00003027 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3028 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003029
3030 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3031 // but sometimes does:
3032 // struct S { constexpr S() : p(&p) {} void *p; };
3033 // S s[10];
3034 LValue Subobject = This;
3035 Subobject.Designator.addIndex(0);
3036 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003037 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003038 cast<CXXConstructorDecl>(Definition),
3039 Info, Result.getArrayFiller());
3040}
3041
Richard Smithf3e9e432011-11-07 09:22:26 +00003042//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003043// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003044//
3045// As a GNU extension, we support casting pointers to sufficiently-wide integer
3046// types and back in constant folding. Integer values are thus represented
3047// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003048//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003049
3050namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003051class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003052 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003053 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003054public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003055 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003056 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003057
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003058 bool Success(const llvm::APSInt &SI, const Expr *E) {
3059 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003060 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003061 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003062 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003063 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003064 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003065 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003066 return true;
3067 }
3068
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003069 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003070 assert(E->getType()->isIntegralOrEnumerationType() &&
3071 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003072 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003073 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003074 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003075 Result.getInt().setIsUnsigned(
3076 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003077 return true;
3078 }
3079
3080 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003081 assert(E->getType()->isIntegralOrEnumerationType() &&
3082 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003083 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003084 return true;
3085 }
3086
Ken Dyckdbc01912011-03-11 02:13:43 +00003087 bool Success(CharUnits Size, const Expr *E) {
3088 return Success(Size.getQuantity(), E);
3089 }
3090
Richard Smith0b0a0b62011-10-29 20:57:55 +00003091 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003092 if (V.isLValue()) {
3093 Result = V;
3094 return true;
3095 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003096 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003097 }
Mike Stump11289f42009-09-09 15:08:12 +00003098
Richard Smith4ce706a2011-10-11 21:43:33 +00003099 bool ValueInitialization(const Expr *E) { return Success(0, E); }
3100
Peter Collingbournee9200682011-05-13 03:29:01 +00003101 //===--------------------------------------------------------------------===//
3102 // Visitor Methods
3103 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003104
Chris Lattner7174bf32008-07-12 00:38:25 +00003105 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003106 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003107 }
3108 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003109 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003110 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003111
3112 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3113 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003114 if (CheckReferencedDecl(E, E->getDecl()))
3115 return true;
3116
3117 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003118 }
3119 bool VisitMemberExpr(const MemberExpr *E) {
3120 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003121 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003122 return true;
3123 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003124
3125 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003126 }
3127
Peter Collingbournee9200682011-05-13 03:29:01 +00003128 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003129 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003130 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003131 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003132
Peter Collingbournee9200682011-05-13 03:29:01 +00003133 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003134 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003135
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003136 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003137 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003138 }
Mike Stump11289f42009-09-09 15:08:12 +00003139
Richard Smith4ce706a2011-10-11 21:43:33 +00003140 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003141 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003142 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003143 }
3144
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003145 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003146 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003147 }
3148
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003149 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3150 return Success(E->getValue(), E);
3151 }
3152
John Wiegley6242b6a2011-04-28 00:16:57 +00003153 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3154 return Success(E->getValue(), E);
3155 }
3156
John Wiegleyf9f65842011-04-25 06:54:41 +00003157 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3158 return Success(E->getValue(), E);
3159 }
3160
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003161 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003162 bool VisitUnaryImag(const UnaryOperator *E);
3163
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003164 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003165 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003166
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003167private:
Ken Dyck160146e2010-01-27 17:10:57 +00003168 CharUnits GetAlignOfExpr(const Expr *E);
3169 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003170 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003171 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003172 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003173};
Chris Lattner05706e882008-07-11 18:11:29 +00003174} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003175
Richard Smith11562c52011-10-28 17:51:58 +00003176/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3177/// produce either the integer value or a pointer.
3178///
3179/// GCC has a heinous extension which folds casts between pointer types and
3180/// pointer-sized integral types. We support this by allowing the evaluation of
3181/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3182/// Some simple arithmetic on such values is supported (they are treated much
3183/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003184static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003185 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003186 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003187 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003188}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003189
Richard Smithf57d8cb2011-12-09 22:58:01 +00003190static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003191 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003192 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003193 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003194 if (!Val.isInt()) {
3195 // FIXME: It would be better to produce the diagnostic for casting
3196 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003197 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003198 return false;
3199 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003200 Result = Val.getInt();
3201 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003202}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003203
Richard Smithf57d8cb2011-12-09 22:58:01 +00003204/// Check whether the given declaration can be directly converted to an integral
3205/// rvalue. If not, no diagnostic is produced; there are other things we can
3206/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003207bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003208 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003209 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003210 // Check for signedness/width mismatches between E type and ECD value.
3211 bool SameSign = (ECD->getInitVal().isSigned()
3212 == E->getType()->isSignedIntegerOrEnumerationType());
3213 bool SameWidth = (ECD->getInitVal().getBitWidth()
3214 == Info.Ctx.getIntWidth(E->getType()));
3215 if (SameSign && SameWidth)
3216 return Success(ECD->getInitVal(), E);
3217 else {
3218 // Get rid of mismatch (otherwise Success assertions will fail)
3219 // by computing a new value matching the type of E.
3220 llvm::APSInt Val = ECD->getInitVal();
3221 if (!SameSign)
3222 Val.setIsSigned(!ECD->getInitVal().isSigned());
3223 if (!SameWidth)
3224 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3225 return Success(Val, E);
3226 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003227 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003228 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003229}
3230
Chris Lattner86ee2862008-10-06 06:40:35 +00003231/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3232/// as GCC.
3233static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3234 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003235 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003236 enum gcc_type_class {
3237 no_type_class = -1,
3238 void_type_class, integer_type_class, char_type_class,
3239 enumeral_type_class, boolean_type_class,
3240 pointer_type_class, reference_type_class, offset_type_class,
3241 real_type_class, complex_type_class,
3242 function_type_class, method_type_class,
3243 record_type_class, union_type_class,
3244 array_type_class, string_type_class,
3245 lang_type_class
3246 };
Mike Stump11289f42009-09-09 15:08:12 +00003247
3248 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003249 // ideal, however it is what gcc does.
3250 if (E->getNumArgs() == 0)
3251 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003252
Chris Lattner86ee2862008-10-06 06:40:35 +00003253 QualType ArgTy = E->getArg(0)->getType();
3254 if (ArgTy->isVoidType())
3255 return void_type_class;
3256 else if (ArgTy->isEnumeralType())
3257 return enumeral_type_class;
3258 else if (ArgTy->isBooleanType())
3259 return boolean_type_class;
3260 else if (ArgTy->isCharType())
3261 return string_type_class; // gcc doesn't appear to use char_type_class
3262 else if (ArgTy->isIntegerType())
3263 return integer_type_class;
3264 else if (ArgTy->isPointerType())
3265 return pointer_type_class;
3266 else if (ArgTy->isReferenceType())
3267 return reference_type_class;
3268 else if (ArgTy->isRealType())
3269 return real_type_class;
3270 else if (ArgTy->isComplexType())
3271 return complex_type_class;
3272 else if (ArgTy->isFunctionType())
3273 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003274 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003275 return record_type_class;
3276 else if (ArgTy->isUnionType())
3277 return union_type_class;
3278 else if (ArgTy->isArrayType())
3279 return array_type_class;
3280 else if (ArgTy->isUnionType())
3281 return union_type_class;
3282 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003283 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003284 return -1;
3285}
3286
John McCall95007602010-05-10 23:27:23 +00003287/// Retrieves the "underlying object type" of the given expression,
3288/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003289QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3290 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3291 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003292 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003293 } else if (const Expr *E = B.get<const Expr*>()) {
3294 if (isa<CompoundLiteralExpr>(E))
3295 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003296 }
3297
3298 return QualType();
3299}
3300
Peter Collingbournee9200682011-05-13 03:29:01 +00003301bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003302 // TODO: Perhaps we should let LLVM lower this?
3303 LValue Base;
3304 if (!EvaluatePointer(E->getArg(0), Base, Info))
3305 return false;
3306
3307 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003308 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003309
Richard Smithce40ad62011-11-12 22:28:03 +00003310 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003311 if (T.isNull() ||
3312 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003313 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003314 T->isVariablyModifiedType() ||
3315 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003316 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003317
3318 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3319 CharUnits Offset = Base.getLValueOffset();
3320
3321 if (!Offset.isNegative() && Offset <= Size)
3322 Size -= Offset;
3323 else
3324 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003325 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003326}
3327
Peter Collingbournee9200682011-05-13 03:29:01 +00003328bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003329 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003330 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003331 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003332
3333 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003334 if (TryEvaluateBuiltinObjectSize(E))
3335 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003336
Eric Christopher99469702010-01-19 22:58:35 +00003337 // If evaluating the argument has side-effects we can't determine
3338 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003339 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003340 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003341 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003342 return Success(0, E);
3343 }
Mike Stump876387b2009-10-27 22:09:17 +00003344
Richard Smithf57d8cb2011-12-09 22:58:01 +00003345 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003346 }
3347
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003348 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003349 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003350
Richard Smith10c7c902011-12-09 02:04:48 +00003351 case Builtin::BI__builtin_constant_p: {
3352 const Expr *Arg = E->getArg(0);
3353 QualType ArgType = Arg->getType();
3354 // __builtin_constant_p always has one operand. The rules which gcc follows
3355 // are not precisely documented, but are as follows:
3356 //
3357 // - If the operand is of integral, floating, complex or enumeration type,
3358 // and can be folded to a known value of that type, it returns 1.
3359 // - If the operand and can be folded to a pointer to the first character
3360 // of a string literal (or such a pointer cast to an integral type), it
3361 // returns 1.
3362 //
3363 // Otherwise, it returns 0.
3364 //
3365 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3366 // its support for this does not currently work.
3367 int IsConstant = 0;
3368 if (ArgType->isIntegralOrEnumerationType()) {
3369 // Note, a pointer cast to an integral type is only a constant if it is
3370 // a pointer to the first character of a string literal.
3371 Expr::EvalResult Result;
3372 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3373 APValue &V = Result.Val;
3374 if (V.getKind() == APValue::LValue) {
3375 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3376 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3377 } else {
3378 IsConstant = 1;
3379 }
3380 }
3381 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3382 IsConstant = Arg->isEvaluatable(Info.Ctx);
3383 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3384 LValue LV;
3385 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3386 // during the check.
3387 Expr::EvalStatus Status;
3388 EvalInfo SubInfo(Info.Ctx, Status);
3389 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3390 : EvaluatePointer(Arg, LV, SubInfo)) &&
3391 !Status.HasSideEffects)
3392 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3393 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3394 }
3395
3396 return Success(IsConstant, E);
3397 }
Chris Lattnerd545ad12009-09-23 06:06:36 +00003398 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003399 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003400 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003401 return Success(Operand, E);
3402 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003403
3404 case Builtin::BI__builtin_expect:
3405 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003406
3407 case Builtin::BIstrlen:
3408 case Builtin::BI__builtin_strlen:
3409 // As an extension, we support strlen() and __builtin_strlen() as constant
3410 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003411 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003412 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3413 // The string literal may have embedded null characters. Find the first
3414 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003415 StringRef Str = S->getString();
3416 StringRef::size_type Pos = Str.find(0);
3417 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003418 Str = Str.substr(0, Pos);
3419
3420 return Success(Str.size(), E);
3421 }
3422
Richard Smithf57d8cb2011-12-09 22:58:01 +00003423 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003424
3425 case Builtin::BI__atomic_is_lock_free: {
3426 APSInt SizeVal;
3427 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3428 return false;
3429
3430 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3431 // of two less than the maximum inline atomic width, we know it is
3432 // lock-free. If the size isn't a power of two, or greater than the
3433 // maximum alignment where we promote atomics, we know it is not lock-free
3434 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3435 // the answer can only be determined at runtime; for example, 16-byte
3436 // atomics have lock-free implementations on some, but not all,
3437 // x86-64 processors.
3438
3439 // Check power-of-two.
3440 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3441 if (!Size.isPowerOfTwo())
3442#if 0
3443 // FIXME: Suppress this folding until the ABI for the promotion width
3444 // settles.
3445 return Success(0, E);
3446#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003447 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003448#endif
3449
3450#if 0
3451 // Check against promotion width.
3452 // FIXME: Suppress this folding until the ABI for the promotion width
3453 // settles.
3454 unsigned PromoteWidthBits =
3455 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3456 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3457 return Success(0, E);
3458#endif
3459
3460 // Check against inlining width.
3461 unsigned InlineWidthBits =
3462 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3463 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3464 return Success(1, E);
3465
Richard Smithf57d8cb2011-12-09 22:58:01 +00003466 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003467 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003468 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003469}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003470
Richard Smith8b3497e2011-10-31 01:37:14 +00003471static bool HasSameBase(const LValue &A, const LValue &B) {
3472 if (!A.getLValueBase())
3473 return !B.getLValueBase();
3474 if (!B.getLValueBase())
3475 return false;
3476
Richard Smithce40ad62011-11-12 22:28:03 +00003477 if (A.getLValueBase().getOpaqueValue() !=
3478 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003479 const Decl *ADecl = GetLValueBaseDecl(A);
3480 if (!ADecl)
3481 return false;
3482 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003483 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003484 return false;
3485 }
3486
3487 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003488 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003489}
3490
Chris Lattnere13042c2008-07-11 19:10:17 +00003491bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003492 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003493 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003494
John McCalle3027922010-08-25 11:45:40 +00003495 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003496 VisitIgnoredValue(E->getLHS());
3497 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003498 }
3499
3500 if (E->isLogicalOp()) {
3501 // These need to be handled specially because the operands aren't
3502 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003503 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003504
Richard Smith11562c52011-10-28 17:51:58 +00003505 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003506 // We were able to evaluate the LHS, see if we can get away with not
3507 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003508 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003509 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003510
Richard Smith11562c52011-10-28 17:51:58 +00003511 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003512 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003513 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003514 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003515 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003516 }
3517 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003518 // FIXME: If both evaluations fail, we should produce the diagnostic from
3519 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3520 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003521 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003522 // We can't evaluate the LHS; however, sometimes the result
3523 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003524 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003525 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003526 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003527 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003528
3529 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003530 }
3531 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003532 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003533
Eli Friedman5a332ea2008-11-13 06:09:17 +00003534 return false;
3535 }
3536
Anders Carlssonacc79812008-11-16 07:17:21 +00003537 QualType LHSTy = E->getLHS()->getType();
3538 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003539
3540 if (LHSTy->isAnyComplexType()) {
3541 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003542 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003543
3544 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3545 return false;
3546
3547 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3548 return false;
3549
3550 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003551 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003552 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003553 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003554 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3555
John McCalle3027922010-08-25 11:45:40 +00003556 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003557 return Success((CR_r == APFloat::cmpEqual &&
3558 CR_i == APFloat::cmpEqual), E);
3559 else {
John McCalle3027922010-08-25 11:45:40 +00003560 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003561 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003562 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003563 CR_r == APFloat::cmpLessThan ||
3564 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003565 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003566 CR_i == APFloat::cmpLessThan ||
3567 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003568 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003569 } else {
John McCalle3027922010-08-25 11:45:40 +00003570 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003571 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3572 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3573 else {
John McCalle3027922010-08-25 11:45:40 +00003574 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003575 "Invalid compex comparison.");
3576 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3577 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3578 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003579 }
3580 }
Mike Stump11289f42009-09-09 15:08:12 +00003581
Anders Carlssonacc79812008-11-16 07:17:21 +00003582 if (LHSTy->isRealFloatingType() &&
3583 RHSTy->isRealFloatingType()) {
3584 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003585
Anders Carlssonacc79812008-11-16 07:17:21 +00003586 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3587 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003588
Anders Carlssonacc79812008-11-16 07:17:21 +00003589 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3590 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003591
Anders Carlssonacc79812008-11-16 07:17:21 +00003592 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003593
Anders Carlssonacc79812008-11-16 07:17:21 +00003594 switch (E->getOpcode()) {
3595 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003596 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003597 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003598 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003599 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003600 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003601 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003602 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003603 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003604 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003605 E);
John McCalle3027922010-08-25 11:45:40 +00003606 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003607 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003608 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003609 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003610 || CR == APFloat::cmpLessThan
3611 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003612 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003613 }
Mike Stump11289f42009-09-09 15:08:12 +00003614
Eli Friedmana38da572009-04-28 19:17:36 +00003615 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003616 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003617 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003618 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3619 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003620
John McCall45d55e42010-05-07 21:00:08 +00003621 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003622 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3623 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003624
Richard Smith8b3497e2011-10-31 01:37:14 +00003625 // Reject differing bases from the normal codepath; we special-case
3626 // comparisons to null.
3627 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00003628 // Inequalities and subtractions between unrelated pointers have
3629 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00003630 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003631 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003632 // A constant address may compare equal to the address of a symbol.
3633 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00003634 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003635 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3636 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003637 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003638 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00003639 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00003640 // distinct. However, we do know that the address of a literal will be
3641 // non-null.
3642 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3643 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003644 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003645 // We can't tell whether weak symbols will end up pointing to the same
3646 // object.
3647 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003648 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003649 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00003650 // (Note that clang defaults to -fmerge-all-constants, which can
3651 // lead to inconsistent results for comparisons involving the address
3652 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00003653 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00003654 }
Eli Friedman64004332009-03-23 04:38:34 +00003655
Richard Smithf3e9e432011-11-07 09:22:26 +00003656 // FIXME: Implement the C++11 restrictions:
3657 // - Pointer subtractions must be on elements of the same array.
3658 // - Pointer comparisons must be between members with the same access.
3659
John McCalle3027922010-08-25 11:45:40 +00003660 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00003661 QualType Type = E->getLHS()->getType();
3662 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003663
Richard Smithd62306a2011-11-10 06:34:14 +00003664 CharUnits ElementSize;
3665 if (!HandleSizeof(Info, ElementType, ElementSize))
3666 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003667
Richard Smithd62306a2011-11-10 06:34:14 +00003668 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00003669 RHSValue.getLValueOffset();
3670 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003671 }
Richard Smith8b3497e2011-10-31 01:37:14 +00003672
3673 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3674 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3675 switch (E->getOpcode()) {
3676 default: llvm_unreachable("missing comparison operator");
3677 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3678 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3679 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3680 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3681 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3682 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003683 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003684 }
3685 }
Douglas Gregorb90df602010-06-16 00:17:44 +00003686 if (!LHSTy->isIntegralOrEnumerationType() ||
3687 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00003688 // We can't continue from here for non-integral types.
3689 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003690 }
3691
Anders Carlsson9c181652008-07-08 14:35:21 +00003692 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003693 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00003694 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003695 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00003696
Richard Smith11562c52011-10-28 17:51:58 +00003697 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003698 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003699 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00003700
3701 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00003702 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00003703 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3704 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00003705 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00003706 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00003707 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00003708 LHSVal.getLValueOffset() -= AdditionalOffset;
3709 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00003710 return true;
3711 }
3712
3713 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00003714 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00003715 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003716 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3717 LHSVal.getInt().getZExtValue());
3718 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00003719 return true;
3720 }
3721
3722 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00003723 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003724 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003725
Richard Smith11562c52011-10-28 17:51:58 +00003726 APSInt &LHS = LHSVal.getInt();
3727 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00003728
Anders Carlsson9c181652008-07-08 14:35:21 +00003729 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003730 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003731 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003732 case BO_Mul: return Success(LHS * RHS, E);
3733 case BO_Add: return Success(LHS + RHS, E);
3734 case BO_Sub: return Success(LHS - RHS, E);
3735 case BO_And: return Success(LHS & RHS, E);
3736 case BO_Xor: return Success(LHS ^ RHS, E);
3737 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003738 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00003739 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003740 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003741 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003742 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00003743 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003744 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003745 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003746 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00003747 // During constant-folding, a negative shift is an opposite shift.
3748 if (RHS.isSigned() && RHS.isNegative()) {
3749 RHS = -RHS;
3750 goto shift_right;
3751 }
3752
3753 shift_left:
3754 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00003755 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3756 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003757 }
John McCalle3027922010-08-25 11:45:40 +00003758 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00003759 // During constant-folding, a negative shift is an opposite shift.
3760 if (RHS.isSigned() && RHS.isNegative()) {
3761 RHS = -RHS;
3762 goto shift_left;
3763 }
3764
3765 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00003766 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00003767 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3768 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003769 }
Mike Stump11289f42009-09-09 15:08:12 +00003770
Richard Smith11562c52011-10-28 17:51:58 +00003771 case BO_LT: return Success(LHS < RHS, E);
3772 case BO_GT: return Success(LHS > RHS, E);
3773 case BO_LE: return Success(LHS <= RHS, E);
3774 case BO_GE: return Success(LHS >= RHS, E);
3775 case BO_EQ: return Success(LHS == RHS, E);
3776 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00003777 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003778}
3779
Ken Dyck160146e2010-01-27 17:10:57 +00003780CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003781 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3782 // the result is the size of the referenced type."
3783 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3784 // result shall be the alignment of the referenced type."
3785 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3786 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00003787
3788 // __alignof is defined to return the preferred alignment.
3789 return Info.Ctx.toCharUnitsFromBits(
3790 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00003791}
3792
Ken Dyck160146e2010-01-27 17:10:57 +00003793CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00003794 E = E->IgnoreParens();
3795
3796 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00003797 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00003798 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003799 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3800 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00003801
Chris Lattner68061312009-01-24 21:53:27 +00003802 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003803 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3804 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00003805
Chris Lattner24aeeab2009-01-24 21:09:06 +00003806 return GetAlignOfType(E->getType());
3807}
3808
3809
Peter Collingbournee190dee2011-03-11 19:24:49 +00003810/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3811/// a result as the expression's type.
3812bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3813 const UnaryExprOrTypeTraitExpr *E) {
3814 switch(E->getKind()) {
3815 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00003816 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00003817 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003818 else
Ken Dyckdbc01912011-03-11 02:13:43 +00003819 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003820 }
Eli Friedman64004332009-03-23 04:38:34 +00003821
Peter Collingbournee190dee2011-03-11 19:24:49 +00003822 case UETT_VecStep: {
3823 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00003824
Peter Collingbournee190dee2011-03-11 19:24:49 +00003825 if (Ty->isVectorType()) {
3826 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00003827
Peter Collingbournee190dee2011-03-11 19:24:49 +00003828 // The vec_step built-in functions that take a 3-component
3829 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3830 if (n == 3)
3831 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00003832
Peter Collingbournee190dee2011-03-11 19:24:49 +00003833 return Success(n, E);
3834 } else
3835 return Success(1, E);
3836 }
3837
3838 case UETT_SizeOf: {
3839 QualType SrcTy = E->getTypeOfArgument();
3840 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3841 // the result is the size of the referenced type."
3842 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3843 // result shall be the alignment of the referenced type."
3844 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3845 SrcTy = Ref->getPointeeType();
3846
Richard Smithd62306a2011-11-10 06:34:14 +00003847 CharUnits Sizeof;
3848 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00003849 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003850 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003851 }
3852 }
3853
3854 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003855 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003856}
3857
Peter Collingbournee9200682011-05-13 03:29:01 +00003858bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00003859 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00003860 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00003861 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003862 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00003863 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00003864 for (unsigned i = 0; i != n; ++i) {
3865 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3866 switch (ON.getKind()) {
3867 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00003868 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00003869 APSInt IdxResult;
3870 if (!EvaluateInteger(Idx, IdxResult, Info))
3871 return false;
3872 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3873 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003874 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003875 CurrentType = AT->getElementType();
3876 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3877 Result += IdxResult.getSExtValue() * ElementSize;
3878 break;
3879 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003880
Douglas Gregor882211c2010-04-28 22:16:22 +00003881 case OffsetOfExpr::OffsetOfNode::Field: {
3882 FieldDecl *MemberDecl = ON.getField();
3883 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003884 if (!RT)
3885 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003886 RecordDecl *RD = RT->getDecl();
3887 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00003888 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00003889 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003890 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00003891 CurrentType = MemberDecl->getType().getNonReferenceType();
3892 break;
3893 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003894
Douglas Gregor882211c2010-04-28 22:16:22 +00003895 case OffsetOfExpr::OffsetOfNode::Identifier:
3896 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003897 return Error(OOE);
3898
Douglas Gregord1702062010-04-29 00:18:15 +00003899 case OffsetOfExpr::OffsetOfNode::Base: {
3900 CXXBaseSpecifier *BaseSpec = ON.getBase();
3901 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003902 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003903
3904 // Find the layout of the class whose base we are looking into.
3905 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003906 if (!RT)
3907 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003908 RecordDecl *RD = RT->getDecl();
3909 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3910
3911 // Find the base class itself.
3912 CurrentType = BaseSpec->getType();
3913 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3914 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003915 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003916
3917 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00003918 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00003919 break;
3920 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003921 }
3922 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003923 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003924}
3925
Chris Lattnere13042c2008-07-11 19:10:17 +00003926bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003927 switch (E->getOpcode()) {
3928 default:
3929 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3930 // See C99 6.6p3.
3931 return Error(E);
3932 case UO_Extension:
3933 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3934 // If so, we could clear the diagnostic ID.
3935 return Visit(E->getSubExpr());
3936 case UO_Plus:
3937 // The result is just the value.
3938 return Visit(E->getSubExpr());
3939 case UO_Minus: {
3940 if (!Visit(E->getSubExpr()))
3941 return false;
3942 if (!Result.isInt()) return Error(E);
3943 return Success(-Result.getInt(), E);
3944 }
3945 case UO_Not: {
3946 if (!Visit(E->getSubExpr()))
3947 return false;
3948 if (!Result.isInt()) return Error(E);
3949 return Success(~Result.getInt(), E);
3950 }
3951 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00003952 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00003953 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00003954 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003955 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003956 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003957 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003958}
Mike Stump11289f42009-09-09 15:08:12 +00003959
Chris Lattner477c4be2008-07-12 01:15:53 +00003960/// HandleCast - This is used to evaluate implicit or explicit casts where the
3961/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00003962bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3963 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003964 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00003965 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003966
Eli Friedmanc757de22011-03-25 00:43:55 +00003967 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00003968 case CK_BaseToDerived:
3969 case CK_DerivedToBase:
3970 case CK_UncheckedDerivedToBase:
3971 case CK_Dynamic:
3972 case CK_ToUnion:
3973 case CK_ArrayToPointerDecay:
3974 case CK_FunctionToPointerDecay:
3975 case CK_NullToPointer:
3976 case CK_NullToMemberPointer:
3977 case CK_BaseToDerivedMemberPointer:
3978 case CK_DerivedToBaseMemberPointer:
3979 case CK_ConstructorConversion:
3980 case CK_IntegralToPointer:
3981 case CK_ToVoid:
3982 case CK_VectorSplat:
3983 case CK_IntegralToFloating:
3984 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00003985 case CK_CPointerToObjCPointerCast:
3986 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003987 case CK_AnyPointerToBlockPointerCast:
3988 case CK_ObjCObjectLValueCast:
3989 case CK_FloatingRealToComplex:
3990 case CK_FloatingComplexToReal:
3991 case CK_FloatingComplexCast:
3992 case CK_FloatingComplexToIntegralComplex:
3993 case CK_IntegralRealToComplex:
3994 case CK_IntegralComplexCast:
3995 case CK_IntegralComplexToFloatingComplex:
3996 llvm_unreachable("invalid cast kind for integral value");
3997
Eli Friedman9faf2f92011-03-25 19:07:11 +00003998 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003999 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004000 case CK_LValueBitCast:
4001 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004002 case CK_ARCProduceObject:
4003 case CK_ARCConsumeObject:
4004 case CK_ARCReclaimReturnedObject:
4005 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004006 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004007
4008 case CK_LValueToRValue:
4009 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004010 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004011
4012 case CK_MemberPointerToBoolean:
4013 case CK_PointerToBoolean:
4014 case CK_IntegralToBoolean:
4015 case CK_FloatingToBoolean:
4016 case CK_FloatingComplexToBoolean:
4017 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004018 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004019 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004020 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004021 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004022 }
4023
Eli Friedmanc757de22011-03-25 00:43:55 +00004024 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004025 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004026 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004027
Eli Friedman742421e2009-02-20 01:15:07 +00004028 if (!Result.isInt()) {
4029 // Only allow casts of lvalues if they are lossless.
4030 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4031 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004032
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004033 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004034 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004035 }
Mike Stump11289f42009-09-09 15:08:12 +00004036
Eli Friedmanc757de22011-03-25 00:43:55 +00004037 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004038 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4039
John McCall45d55e42010-05-07 21:00:08 +00004040 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004041 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004042 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004043
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004044 if (LV.getLValueBase()) {
4045 // Only allow based lvalue casts if they are lossless.
4046 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004047 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004048
Richard Smithcf74da72011-11-16 07:18:12 +00004049 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004050 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004051 return true;
4052 }
4053
Ken Dyck02990832010-01-15 12:37:54 +00004054 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4055 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004056 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004057 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004058
Eli Friedmanc757de22011-03-25 00:43:55 +00004059 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004060 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004061 if (!EvaluateComplex(SubExpr, C, Info))
4062 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004063 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004064 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004065
Eli Friedmanc757de22011-03-25 00:43:55 +00004066 case CK_FloatingToIntegral: {
4067 APFloat F(0.0);
4068 if (!EvaluateFloat(SubExpr, F, Info))
4069 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004070
Richard Smith357362d2011-12-13 06:39:58 +00004071 APSInt Value;
4072 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4073 return false;
4074 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004075 }
4076 }
Mike Stump11289f42009-09-09 15:08:12 +00004077
Eli Friedmanc757de22011-03-25 00:43:55 +00004078 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004079 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004080}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004081
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004082bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4083 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004084 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004085 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4086 return false;
4087 if (!LV.isComplexInt())
4088 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004089 return Success(LV.getComplexIntReal(), E);
4090 }
4091
4092 return Visit(E->getSubExpr());
4093}
4094
Eli Friedman4e7a2412009-02-27 04:45:43 +00004095bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004096 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004097 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004098 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4099 return false;
4100 if (!LV.isComplexInt())
4101 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004102 return Success(LV.getComplexIntImag(), E);
4103 }
4104
Richard Smith4a678122011-10-24 18:44:57 +00004105 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004106 return Success(0, E);
4107}
4108
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004109bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4110 return Success(E->getPackLength(), E);
4111}
4112
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004113bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4114 return Success(E->getValue(), E);
4115}
4116
Chris Lattner05706e882008-07-11 18:11:29 +00004117//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004118// Float Evaluation
4119//===----------------------------------------------------------------------===//
4120
4121namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004122class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004123 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004124 APFloat &Result;
4125public:
4126 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004127 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004128
Richard Smith0b0a0b62011-10-29 20:57:55 +00004129 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004130 Result = V.getFloat();
4131 return true;
4132 }
Eli Friedman24c01542008-08-22 00:06:13 +00004133
Richard Smith4ce706a2011-10-11 21:43:33 +00004134 bool ValueInitialization(const Expr *E) {
4135 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4136 return true;
4137 }
4138
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004139 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004140
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004141 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004142 bool VisitBinaryOperator(const BinaryOperator *E);
4143 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004144 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004145
John McCallb1fb0d32010-05-07 22:08:54 +00004146 bool VisitUnaryReal(const UnaryOperator *E);
4147 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004148
John McCallb1fb0d32010-05-07 22:08:54 +00004149 // FIXME: Missing: array subscript of vector, member of vector,
4150 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00004151};
4152} // end anonymous namespace
4153
4154static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004155 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004156 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004157}
4158
Jay Foad39c79802011-01-12 09:06:06 +00004159static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004160 QualType ResultTy,
4161 const Expr *Arg,
4162 bool SNaN,
4163 llvm::APFloat &Result) {
4164 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4165 if (!S) return false;
4166
4167 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4168
4169 llvm::APInt fill;
4170
4171 // Treat empty strings as if they were zero.
4172 if (S->getString().empty())
4173 fill = llvm::APInt(32, 0);
4174 else if (S->getString().getAsInteger(0, fill))
4175 return false;
4176
4177 if (SNaN)
4178 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4179 else
4180 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4181 return true;
4182}
4183
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004184bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004185 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004186 default:
4187 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4188
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004189 case Builtin::BI__builtin_huge_val:
4190 case Builtin::BI__builtin_huge_valf:
4191 case Builtin::BI__builtin_huge_vall:
4192 case Builtin::BI__builtin_inf:
4193 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004194 case Builtin::BI__builtin_infl: {
4195 const llvm::fltSemantics &Sem =
4196 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004197 Result = llvm::APFloat::getInf(Sem);
4198 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004199 }
Mike Stump11289f42009-09-09 15:08:12 +00004200
John McCall16291492010-02-28 13:00:19 +00004201 case Builtin::BI__builtin_nans:
4202 case Builtin::BI__builtin_nansf:
4203 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004204 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4205 true, Result))
4206 return Error(E);
4207 return true;
John McCall16291492010-02-28 13:00:19 +00004208
Chris Lattner0b7282e2008-10-06 06:31:58 +00004209 case Builtin::BI__builtin_nan:
4210 case Builtin::BI__builtin_nanf:
4211 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004212 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004213 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004214 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4215 false, Result))
4216 return Error(E);
4217 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004218
4219 case Builtin::BI__builtin_fabs:
4220 case Builtin::BI__builtin_fabsf:
4221 case Builtin::BI__builtin_fabsl:
4222 if (!EvaluateFloat(E->getArg(0), Result, Info))
4223 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004224
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004225 if (Result.isNegative())
4226 Result.changeSign();
4227 return true;
4228
Mike Stump11289f42009-09-09 15:08:12 +00004229 case Builtin::BI__builtin_copysign:
4230 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004231 case Builtin::BI__builtin_copysignl: {
4232 APFloat RHS(0.);
4233 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4234 !EvaluateFloat(E->getArg(1), RHS, Info))
4235 return false;
4236 Result.copySign(RHS);
4237 return true;
4238 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004239 }
4240}
4241
John McCallb1fb0d32010-05-07 22:08:54 +00004242bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004243 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4244 ComplexValue CV;
4245 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4246 return false;
4247 Result = CV.FloatReal;
4248 return true;
4249 }
4250
4251 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004252}
4253
4254bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004255 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4256 ComplexValue CV;
4257 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4258 return false;
4259 Result = CV.FloatImag;
4260 return true;
4261 }
4262
Richard Smith4a678122011-10-24 18:44:57 +00004263 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004264 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4265 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004266 return true;
4267}
4268
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004269bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004270 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004271 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004272 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004273 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004274 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004275 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4276 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004277 Result.changeSign();
4278 return true;
4279 }
4280}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004281
Eli Friedman24c01542008-08-22 00:06:13 +00004282bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004283 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4284 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004285
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004286 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004287 if (!EvaluateFloat(E->getLHS(), Result, Info))
4288 return false;
4289 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4290 return false;
4291
4292 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004293 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004294 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004295 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4296 return true;
John McCalle3027922010-08-25 11:45:40 +00004297 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004298 Result.add(RHS, APFloat::rmNearestTiesToEven);
4299 return true;
John McCalle3027922010-08-25 11:45:40 +00004300 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004301 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4302 return true;
John McCalle3027922010-08-25 11:45:40 +00004303 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004304 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4305 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004306 }
4307}
4308
4309bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4310 Result = E->getValue();
4311 return true;
4312}
4313
Peter Collingbournee9200682011-05-13 03:29:01 +00004314bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4315 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004316
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004317 switch (E->getCastKind()) {
4318 default:
Richard Smith11562c52011-10-28 17:51:58 +00004319 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004320
4321 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004322 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004323 return EvaluateInteger(SubExpr, IntResult, Info) &&
4324 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4325 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004326 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004327
4328 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004329 if (!Visit(SubExpr))
4330 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004331 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4332 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004333 }
John McCalld7646252010-11-14 08:17:51 +00004334
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004335 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004336 ComplexValue V;
4337 if (!EvaluateComplex(SubExpr, V, Info))
4338 return false;
4339 Result = V.getComplexFloatReal();
4340 return true;
4341 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004342 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004343
Richard Smithf57d8cb2011-12-09 22:58:01 +00004344 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004345}
4346
Eli Friedman24c01542008-08-22 00:06:13 +00004347//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004348// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004349//===----------------------------------------------------------------------===//
4350
4351namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004352class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004353 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004354 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004355
Anders Carlsson537969c2008-11-16 20:27:53 +00004356public:
John McCall93d91dc2010-05-07 17:22:02 +00004357 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004358 : ExprEvaluatorBaseTy(info), Result(Result) {}
4359
Richard Smith0b0a0b62011-10-29 20:57:55 +00004360 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004361 Result.setFrom(V);
4362 return true;
4363 }
Mike Stump11289f42009-09-09 15:08:12 +00004364
Anders Carlsson537969c2008-11-16 20:27:53 +00004365 //===--------------------------------------------------------------------===//
4366 // Visitor Methods
4367 //===--------------------------------------------------------------------===//
4368
Peter Collingbournee9200682011-05-13 03:29:01 +00004369 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004370
Peter Collingbournee9200682011-05-13 03:29:01 +00004371 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004372
John McCall93d91dc2010-05-07 17:22:02 +00004373 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004374 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004375 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004376};
4377} // end anonymous namespace
4378
John McCall93d91dc2010-05-07 17:22:02 +00004379static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4380 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004381 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004382 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004383}
4384
Peter Collingbournee9200682011-05-13 03:29:01 +00004385bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4386 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004387
4388 if (SubExpr->getType()->isRealFloatingType()) {
4389 Result.makeComplexFloat();
4390 APFloat &Imag = Result.FloatImag;
4391 if (!EvaluateFloat(SubExpr, Imag, Info))
4392 return false;
4393
4394 Result.FloatReal = APFloat(Imag.getSemantics());
4395 return true;
4396 } else {
4397 assert(SubExpr->getType()->isIntegerType() &&
4398 "Unexpected imaginary literal.");
4399
4400 Result.makeComplexInt();
4401 APSInt &Imag = Result.IntImag;
4402 if (!EvaluateInteger(SubExpr, Imag, Info))
4403 return false;
4404
4405 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4406 return true;
4407 }
4408}
4409
Peter Collingbournee9200682011-05-13 03:29:01 +00004410bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004411
John McCallfcef3cf2010-12-14 17:51:41 +00004412 switch (E->getCastKind()) {
4413 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004414 case CK_BaseToDerived:
4415 case CK_DerivedToBase:
4416 case CK_UncheckedDerivedToBase:
4417 case CK_Dynamic:
4418 case CK_ToUnion:
4419 case CK_ArrayToPointerDecay:
4420 case CK_FunctionToPointerDecay:
4421 case CK_NullToPointer:
4422 case CK_NullToMemberPointer:
4423 case CK_BaseToDerivedMemberPointer:
4424 case CK_DerivedToBaseMemberPointer:
4425 case CK_MemberPointerToBoolean:
4426 case CK_ConstructorConversion:
4427 case CK_IntegralToPointer:
4428 case CK_PointerToIntegral:
4429 case CK_PointerToBoolean:
4430 case CK_ToVoid:
4431 case CK_VectorSplat:
4432 case CK_IntegralCast:
4433 case CK_IntegralToBoolean:
4434 case CK_IntegralToFloating:
4435 case CK_FloatingToIntegral:
4436 case CK_FloatingToBoolean:
4437 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004438 case CK_CPointerToObjCPointerCast:
4439 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004440 case CK_AnyPointerToBlockPointerCast:
4441 case CK_ObjCObjectLValueCast:
4442 case CK_FloatingComplexToReal:
4443 case CK_FloatingComplexToBoolean:
4444 case CK_IntegralComplexToReal:
4445 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004446 case CK_ARCProduceObject:
4447 case CK_ARCConsumeObject:
4448 case CK_ARCReclaimReturnedObject:
4449 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004450 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004451
John McCallfcef3cf2010-12-14 17:51:41 +00004452 case CK_LValueToRValue:
4453 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004454 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004455
4456 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004457 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004458 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004459 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004460
4461 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004462 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004463 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004464 return false;
4465
John McCallfcef3cf2010-12-14 17:51:41 +00004466 Result.makeComplexFloat();
4467 Result.FloatImag = APFloat(Real.getSemantics());
4468 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004469 }
4470
John McCallfcef3cf2010-12-14 17:51:41 +00004471 case CK_FloatingComplexCast: {
4472 if (!Visit(E->getSubExpr()))
4473 return false;
4474
4475 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4476 QualType From
4477 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4478
Richard Smith357362d2011-12-13 06:39:58 +00004479 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4480 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004481 }
4482
4483 case CK_FloatingComplexToIntegralComplex: {
4484 if (!Visit(E->getSubExpr()))
4485 return false;
4486
4487 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4488 QualType From
4489 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4490 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004491 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4492 To, Result.IntReal) &&
4493 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4494 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004495 }
4496
4497 case CK_IntegralRealToComplex: {
4498 APSInt &Real = Result.IntReal;
4499 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4500 return false;
4501
4502 Result.makeComplexInt();
4503 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4504 return true;
4505 }
4506
4507 case CK_IntegralComplexCast: {
4508 if (!Visit(E->getSubExpr()))
4509 return false;
4510
4511 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4512 QualType From
4513 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4514
4515 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4516 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4517 return true;
4518 }
4519
4520 case CK_IntegralComplexToFloatingComplex: {
4521 if (!Visit(E->getSubExpr()))
4522 return false;
4523
4524 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4525 QualType From
4526 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4527 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00004528 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4529 To, Result.FloatReal) &&
4530 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4531 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004532 }
4533 }
4534
4535 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004536 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004537}
4538
John McCall93d91dc2010-05-07 17:22:02 +00004539bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004540 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004541 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4542
John McCall93d91dc2010-05-07 17:22:02 +00004543 if (!Visit(E->getLHS()))
4544 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004545
John McCall93d91dc2010-05-07 17:22:02 +00004546 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004547 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004548 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004549
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004550 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4551 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004552 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004553 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004554 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004555 if (Result.isComplexFloat()) {
4556 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4557 APFloat::rmNearestTiesToEven);
4558 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4559 APFloat::rmNearestTiesToEven);
4560 } else {
4561 Result.getComplexIntReal() += RHS.getComplexIntReal();
4562 Result.getComplexIntImag() += RHS.getComplexIntImag();
4563 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004564 break;
John McCalle3027922010-08-25 11:45:40 +00004565 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004566 if (Result.isComplexFloat()) {
4567 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4568 APFloat::rmNearestTiesToEven);
4569 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4570 APFloat::rmNearestTiesToEven);
4571 } else {
4572 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4573 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4574 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004575 break;
John McCalle3027922010-08-25 11:45:40 +00004576 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004577 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004578 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004579 APFloat &LHS_r = LHS.getComplexFloatReal();
4580 APFloat &LHS_i = LHS.getComplexFloatImag();
4581 APFloat &RHS_r = RHS.getComplexFloatReal();
4582 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004583
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004584 APFloat Tmp = LHS_r;
4585 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4586 Result.getComplexFloatReal() = Tmp;
4587 Tmp = LHS_i;
4588 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4589 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4590
4591 Tmp = LHS_r;
4592 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4593 Result.getComplexFloatImag() = Tmp;
4594 Tmp = LHS_i;
4595 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4596 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4597 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004598 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004599 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004600 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4601 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004602 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004603 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4604 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4605 }
4606 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004607 case BO_Div:
4608 if (Result.isComplexFloat()) {
4609 ComplexValue LHS = Result;
4610 APFloat &LHS_r = LHS.getComplexFloatReal();
4611 APFloat &LHS_i = LHS.getComplexFloatImag();
4612 APFloat &RHS_r = RHS.getComplexFloatReal();
4613 APFloat &RHS_i = RHS.getComplexFloatImag();
4614 APFloat &Res_r = Result.getComplexFloatReal();
4615 APFloat &Res_i = Result.getComplexFloatImag();
4616
4617 APFloat Den = RHS_r;
4618 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4619 APFloat Tmp = RHS_i;
4620 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4621 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4622
4623 Res_r = LHS_r;
4624 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4625 Tmp = LHS_i;
4626 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4627 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4628 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4629
4630 Res_i = LHS_i;
4631 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4632 Tmp = LHS_r;
4633 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4634 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4635 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4636 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004637 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4638 return Error(E, diag::note_expr_divide_by_zero);
4639
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004640 ComplexValue LHS = Result;
4641 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4642 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4643 Result.getComplexIntReal() =
4644 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4645 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4646 Result.getComplexIntImag() =
4647 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4648 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4649 }
4650 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004651 }
4652
John McCall93d91dc2010-05-07 17:22:02 +00004653 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004654}
4655
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004656bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4657 // Get the operand value into 'Result'.
4658 if (!Visit(E->getSubExpr()))
4659 return false;
4660
4661 switch (E->getOpcode()) {
4662 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004663 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004664 case UO_Extension:
4665 return true;
4666 case UO_Plus:
4667 // The result is always just the subexpr.
4668 return true;
4669 case UO_Minus:
4670 if (Result.isComplexFloat()) {
4671 Result.getComplexFloatReal().changeSign();
4672 Result.getComplexFloatImag().changeSign();
4673 }
4674 else {
4675 Result.getComplexIntReal() = -Result.getComplexIntReal();
4676 Result.getComplexIntImag() = -Result.getComplexIntImag();
4677 }
4678 return true;
4679 case UO_Not:
4680 if (Result.isComplexFloat())
4681 Result.getComplexFloatImag().changeSign();
4682 else
4683 Result.getComplexIntImag() = -Result.getComplexIntImag();
4684 return true;
4685 }
4686}
4687
Anders Carlsson537969c2008-11-16 20:27:53 +00004688//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00004689// Void expression evaluation, primarily for a cast to void on the LHS of a
4690// comma operator
4691//===----------------------------------------------------------------------===//
4692
4693namespace {
4694class VoidExprEvaluator
4695 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4696public:
4697 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4698
4699 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00004700
4701 bool VisitCastExpr(const CastExpr *E) {
4702 switch (E->getCastKind()) {
4703 default:
4704 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4705 case CK_ToVoid:
4706 VisitIgnoredValue(E->getSubExpr());
4707 return true;
4708 }
4709 }
4710};
4711} // end anonymous namespace
4712
4713static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4714 assert(E->isRValue() && E->getType()->isVoidType());
4715 return VoidExprEvaluator(Info).Visit(E);
4716}
4717
4718//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00004719// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00004720//===----------------------------------------------------------------------===//
4721
Richard Smith0b0a0b62011-10-29 20:57:55 +00004722static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004723 // In C, function designators are not lvalues, but we evaluate them as if they
4724 // are.
4725 if (E->isGLValue() || E->getType()->isFunctionType()) {
4726 LValue LV;
4727 if (!EvaluateLValue(E, LV, Info))
4728 return false;
4729 LV.moveInto(Result);
4730 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004731 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004732 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004733 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004734 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004735 return false;
John McCall45d55e42010-05-07 21:00:08 +00004736 } else if (E->getType()->hasPointerRepresentation()) {
4737 LValue LV;
4738 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004739 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004740 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00004741 } else if (E->getType()->isRealFloatingType()) {
4742 llvm::APFloat F(0.0);
4743 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004744 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004745 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00004746 } else if (E->getType()->isAnyComplexType()) {
4747 ComplexValue C;
4748 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004749 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004750 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004751 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004752 MemberPtr P;
4753 if (!EvaluateMemberPointer(E, P, Info))
4754 return false;
4755 P.moveInto(Result);
4756 return true;
Richard Smithed5165f2011-11-04 05:33:44 +00004757 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004758 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004759 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004760 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00004761 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004762 Result = Info.CurrentCall->Temporaries[E];
Richard Smithed5165f2011-11-04 05:33:44 +00004763 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004764 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004765 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004766 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4767 return false;
4768 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00004769 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00004770 if (Info.getLangOpts().CPlusPlus0x)
4771 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
4772 << E->getType();
4773 else
4774 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00004775 if (!EvaluateVoid(E, Info))
4776 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004777 } else if (Info.getLangOpts().CPlusPlus0x) {
4778 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
4779 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004780 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00004781 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00004782 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004783 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004784
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00004785 return true;
4786}
4787
Richard Smithed5165f2011-11-04 05:33:44 +00004788/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4789/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4790/// since later initializers for an object can indirectly refer to subobjects
4791/// which were initialized earlier.
4792static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00004793 const LValue &This, const Expr *E,
4794 CheckConstantExpressionKind CCEK) {
Richard Smithed5165f2011-11-04 05:33:44 +00004795 if (E->isRValue() && E->getType()->isLiteralType()) {
4796 // Evaluate arrays and record types in-place, so that later initializers can
4797 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00004798 if (E->getType()->isArrayType())
4799 return EvaluateArray(E, This, Result, Info);
4800 else if (E->getType()->isRecordType())
4801 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00004802 }
4803
4804 // For any other type, in-place evaluation is unimportant.
4805 CCValue CoreConstResult;
4806 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00004807 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00004808}
4809
Richard Smithf57d8cb2011-12-09 22:58:01 +00004810/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4811/// lvalue-to-rvalue cast if it is an lvalue.
4812static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4813 CCValue Value;
4814 if (!::Evaluate(Value, Info, E))
4815 return false;
4816
4817 if (E->isGLValue()) {
4818 LValue LV;
4819 LV.setFrom(Value);
4820 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4821 return false;
4822 }
4823
4824 // Check this core constant expression is a constant expression, and if so,
4825 // convert it to one.
4826 return CheckConstantExpression(Info, E, Value, Result);
4827}
Richard Smith11562c52011-10-28 17:51:58 +00004828
Richard Smith7b553f12011-10-29 00:50:52 +00004829/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00004830/// any crazy technique (that has nothing to do with language standards) that
4831/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00004832/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4833/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00004834bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00004835 // Fast-path evaluations of integer literals, since we sometimes see files
4836 // containing vast quantities of these.
4837 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4838 Result.Val = APValue(APSInt(L->getValue(),
4839 L->getType()->isUnsignedIntegerType()));
4840 return true;
4841 }
4842
Richard Smith5686e752011-11-10 03:30:42 +00004843 // FIXME: Evaluating initializers for large arrays can cause performance
4844 // problems, and we don't use such values yet. Once we have a more efficient
4845 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00004846 // The same problem affects large records.
4847 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4848 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00004849 return false;
4850
Richard Smithd62306a2011-11-10 06:34:14 +00004851 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004852 EvalInfo Info(Ctx, Result);
4853 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00004854}
4855
Jay Foad39c79802011-01-12 09:06:06 +00004856bool Expr::EvaluateAsBooleanCondition(bool &Result,
4857 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004858 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00004859 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00004860 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00004861 Result);
John McCall1be1c632010-01-05 23:42:56 +00004862}
4863
Richard Smithcaf33902011-10-10 18:28:20 +00004864bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004865 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004866 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00004867 !ExprResult.Val.isInt())
Richard Smith11562c52011-10-28 17:51:58 +00004868 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004869
Richard Smith11562c52011-10-28 17:51:58 +00004870 Result = ExprResult.Val.getInt();
4871 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00004872}
4873
Jay Foad39c79802011-01-12 09:06:06 +00004874bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00004875 EvalInfo Info(Ctx, Result);
4876
John McCall45d55e42010-05-07 21:00:08 +00004877 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00004878 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00004879 CheckLValueConstantExpression(Info, this, LV, Result.Val,
4880 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00004881}
4882
Richard Smithd0b4dd62011-12-19 06:19:21 +00004883bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
4884 const VarDecl *VD,
4885 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
4886 Expr::EvalStatus EStatus;
4887 EStatus.Diag = &Notes;
4888
4889 EvalInfo InitInfo(Ctx, EStatus);
4890 InitInfo.setEvaluatingDecl(VD, Value);
4891
4892 LValue LVal;
4893 LVal.set(VD);
4894
4895 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
4896 !EStatus.HasSideEffects;
4897}
4898
Richard Smith7b553f12011-10-29 00:50:52 +00004899/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4900/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00004901bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00004902 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00004903 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00004904}
Anders Carlsson59689ed2008-11-22 21:04:56 +00004905
Jay Foad39c79802011-01-12 09:06:06 +00004906bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00004907 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004908}
4909
Richard Smithcaf33902011-10-10 18:28:20 +00004910APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004911 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004912 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00004913 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00004914 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004915 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00004916
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004917 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00004918}
John McCall864e3962010-05-07 05:32:02 +00004919
Abramo Bagnaraf8199452010-05-14 17:07:14 +00004920 bool Expr::EvalResult::isGlobalLValue() const {
4921 assert(Val.isLValue());
4922 return IsGlobalLValue(Val.getLValueBase());
4923 }
4924
4925
John McCall864e3962010-05-07 05:32:02 +00004926/// isIntegerConstantExpr - this recursive routine will test if an expression is
4927/// an integer constant expression.
4928
4929/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4930/// comma, etc
4931///
4932/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4933/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4934/// cast+dereference.
4935
4936// CheckICE - This function does the fundamental ICE checking: the returned
4937// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4938// Note that to reduce code duplication, this helper does no evaluation
4939// itself; the caller checks whether the expression is evaluatable, and
4940// in the rare cases where CheckICE actually cares about the evaluated
4941// value, it calls into Evalute.
4942//
4943// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00004944// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00004945// 1: This expression is not an ICE, but if it isn't evaluated, it's
4946// a legal subexpression for an ICE. This return value is used to handle
4947// the comma operator in C99 mode.
4948// 2: This expression is not an ICE, and is not a legal subexpression for one.
4949
Dan Gohman28ade552010-07-26 21:25:24 +00004950namespace {
4951
John McCall864e3962010-05-07 05:32:02 +00004952struct ICEDiag {
4953 unsigned Val;
4954 SourceLocation Loc;
4955
4956 public:
4957 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4958 ICEDiag() : Val(0) {}
4959};
4960
Dan Gohman28ade552010-07-26 21:25:24 +00004961}
4962
4963static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00004964
4965static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4966 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004967 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00004968 !EVResult.Val.isInt()) {
4969 return ICEDiag(2, E->getLocStart());
4970 }
4971 return NoDiag();
4972}
4973
4974static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4975 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00004976 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00004977 return ICEDiag(2, E->getLocStart());
4978 }
4979
4980 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00004981#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00004982#define STMT(Node, Base) case Expr::Node##Class:
4983#define EXPR(Node, Base)
4984#include "clang/AST/StmtNodes.inc"
4985 case Expr::PredefinedExprClass:
4986 case Expr::FloatingLiteralClass:
4987 case Expr::ImaginaryLiteralClass:
4988 case Expr::StringLiteralClass:
4989 case Expr::ArraySubscriptExprClass:
4990 case Expr::MemberExprClass:
4991 case Expr::CompoundAssignOperatorClass:
4992 case Expr::CompoundLiteralExprClass:
4993 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00004994 case Expr::DesignatedInitExprClass:
4995 case Expr::ImplicitValueInitExprClass:
4996 case Expr::ParenListExprClass:
4997 case Expr::VAArgExprClass:
4998 case Expr::AddrLabelExprClass:
4999 case Expr::StmtExprClass:
5000 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005001 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005002 case Expr::CXXDynamicCastExprClass:
5003 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005004 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005005 case Expr::CXXNullPtrLiteralExprClass:
5006 case Expr::CXXThisExprClass:
5007 case Expr::CXXThrowExprClass:
5008 case Expr::CXXNewExprClass:
5009 case Expr::CXXDeleteExprClass:
5010 case Expr::CXXPseudoDestructorExprClass:
5011 case Expr::UnresolvedLookupExprClass:
5012 case Expr::DependentScopeDeclRefExprClass:
5013 case Expr::CXXConstructExprClass:
5014 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005015 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005016 case Expr::CXXTemporaryObjectExprClass:
5017 case Expr::CXXUnresolvedConstructExprClass:
5018 case Expr::CXXDependentScopeMemberExprClass:
5019 case Expr::UnresolvedMemberExprClass:
5020 case Expr::ObjCStringLiteralClass:
5021 case Expr::ObjCEncodeExprClass:
5022 case Expr::ObjCMessageExprClass:
5023 case Expr::ObjCSelectorExprClass:
5024 case Expr::ObjCProtocolExprClass:
5025 case Expr::ObjCIvarRefExprClass:
5026 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005027 case Expr::ObjCIsaExprClass:
5028 case Expr::ShuffleVectorExprClass:
5029 case Expr::BlockExprClass:
5030 case Expr::BlockDeclRefExprClass:
5031 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005032 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005033 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005034 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005035 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005036 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005037 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005038 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005039 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005040 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005041 return ICEDiag(2, E->getLocStart());
5042
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005043 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005044 case Expr::GNUNullExprClass:
5045 // GCC considers the GNU __null value to be an integral constant expression.
5046 return NoDiag();
5047
John McCall7c454bb2011-07-15 05:09:51 +00005048 case Expr::SubstNonTypeTemplateParmExprClass:
5049 return
5050 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5051
John McCall864e3962010-05-07 05:32:02 +00005052 case Expr::ParenExprClass:
5053 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005054 case Expr::GenericSelectionExprClass:
5055 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005056 case Expr::IntegerLiteralClass:
5057 case Expr::CharacterLiteralClass:
5058 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005059 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005060 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005061 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005062 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005063 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005064 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005065 return NoDiag();
5066 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005067 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005068 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5069 // constant expressions, but they can never be ICEs because an ICE cannot
5070 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005071 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005072 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005073 return CheckEvalInICE(E, Ctx);
5074 return ICEDiag(2, E->getLocStart());
5075 }
5076 case Expr::DeclRefExprClass:
5077 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5078 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005079 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005080 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5081
5082 // Parameter variables are never constants. Without this check,
5083 // getAnyInitializer() can find a default argument, which leads
5084 // to chaos.
5085 if (isa<ParmVarDecl>(D))
5086 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5087
5088 // C++ 7.1.5.1p2
5089 // A variable of non-volatile const-qualified integral or enumeration
5090 // type initialized by an ICE can be used in ICEs.
5091 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005092 if (!Dcl->getType()->isIntegralOrEnumerationType())
5093 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5094
Richard Smithd0b4dd62011-12-19 06:19:21 +00005095 const VarDecl *VD;
5096 // Look for a declaration of this variable that has an initializer, and
5097 // check whether it is an ICE.
5098 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5099 return NoDiag();
5100 else
5101 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005102 }
5103 }
5104 return ICEDiag(2, E->getLocStart());
5105 case Expr::UnaryOperatorClass: {
5106 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5107 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005108 case UO_PostInc:
5109 case UO_PostDec:
5110 case UO_PreInc:
5111 case UO_PreDec:
5112 case UO_AddrOf:
5113 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005114 // C99 6.6/3 allows increment and decrement within unevaluated
5115 // subexpressions of constant expressions, but they can never be ICEs
5116 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005117 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005118 case UO_Extension:
5119 case UO_LNot:
5120 case UO_Plus:
5121 case UO_Minus:
5122 case UO_Not:
5123 case UO_Real:
5124 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005125 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005126 }
5127
5128 // OffsetOf falls through here.
5129 }
5130 case Expr::OffsetOfExprClass: {
5131 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005132 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005133 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005134 // compliance: we should warn earlier for offsetof expressions with
5135 // array subscripts that aren't ICEs, and if the array subscripts
5136 // are ICEs, the value of the offsetof must be an integer constant.
5137 return CheckEvalInICE(E, Ctx);
5138 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005139 case Expr::UnaryExprOrTypeTraitExprClass: {
5140 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5141 if ((Exp->getKind() == UETT_SizeOf) &&
5142 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005143 return ICEDiag(2, E->getLocStart());
5144 return NoDiag();
5145 }
5146 case Expr::BinaryOperatorClass: {
5147 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5148 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005149 case BO_PtrMemD:
5150 case BO_PtrMemI:
5151 case BO_Assign:
5152 case BO_MulAssign:
5153 case BO_DivAssign:
5154 case BO_RemAssign:
5155 case BO_AddAssign:
5156 case BO_SubAssign:
5157 case BO_ShlAssign:
5158 case BO_ShrAssign:
5159 case BO_AndAssign:
5160 case BO_XorAssign:
5161 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005162 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5163 // constant expressions, but they can never be ICEs because an ICE cannot
5164 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005165 return ICEDiag(2, E->getLocStart());
5166
John McCalle3027922010-08-25 11:45:40 +00005167 case BO_Mul:
5168 case BO_Div:
5169 case BO_Rem:
5170 case BO_Add:
5171 case BO_Sub:
5172 case BO_Shl:
5173 case BO_Shr:
5174 case BO_LT:
5175 case BO_GT:
5176 case BO_LE:
5177 case BO_GE:
5178 case BO_EQ:
5179 case BO_NE:
5180 case BO_And:
5181 case BO_Xor:
5182 case BO_Or:
5183 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005184 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5185 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005186 if (Exp->getOpcode() == BO_Div ||
5187 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005188 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005189 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005190 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005191 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005192 if (REval == 0)
5193 return ICEDiag(1, E->getLocStart());
5194 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005195 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005196 if (LEval.isMinSignedValue())
5197 return ICEDiag(1, E->getLocStart());
5198 }
5199 }
5200 }
John McCalle3027922010-08-25 11:45:40 +00005201 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005202 if (Ctx.getLangOptions().C99) {
5203 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5204 // if it isn't evaluated.
5205 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5206 return ICEDiag(1, E->getLocStart());
5207 } else {
5208 // In both C89 and C++, commas in ICEs are illegal.
5209 return ICEDiag(2, E->getLocStart());
5210 }
5211 }
5212 if (LHSResult.Val >= RHSResult.Val)
5213 return LHSResult;
5214 return RHSResult;
5215 }
John McCalle3027922010-08-25 11:45:40 +00005216 case BO_LAnd:
5217 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005218 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5219 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5220 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5221 // Rare case where the RHS has a comma "side-effect"; we need
5222 // to actually check the condition to see whether the side
5223 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005224 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005225 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005226 return RHSResult;
5227 return NoDiag();
5228 }
5229
5230 if (LHSResult.Val >= RHSResult.Val)
5231 return LHSResult;
5232 return RHSResult;
5233 }
5234 }
5235 }
5236 case Expr::ImplicitCastExprClass:
5237 case Expr::CStyleCastExprClass:
5238 case Expr::CXXFunctionalCastExprClass:
5239 case Expr::CXXStaticCastExprClass:
5240 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005241 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005242 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005243 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005244 if (isa<ExplicitCastExpr>(E)) {
5245 if (const FloatingLiteral *FL
5246 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5247 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5248 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5249 APSInt IgnoredVal(DestWidth, !DestSigned);
5250 bool Ignored;
5251 // If the value does not fit in the destination type, the behavior is
5252 // undefined, so we are not required to treat it as a constant
5253 // expression.
5254 if (FL->getValue().convertToInteger(IgnoredVal,
5255 llvm::APFloat::rmTowardZero,
5256 &Ignored) & APFloat::opInvalidOp)
5257 return ICEDiag(2, E->getLocStart());
5258 return NoDiag();
5259 }
5260 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005261 switch (cast<CastExpr>(E)->getCastKind()) {
5262 case CK_LValueToRValue:
5263 case CK_NoOp:
5264 case CK_IntegralToBoolean:
5265 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005266 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005267 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005268 return ICEDiag(2, E->getLocStart());
5269 }
John McCall864e3962010-05-07 05:32:02 +00005270 }
John McCallc07a0c72011-02-17 10:25:35 +00005271 case Expr::BinaryConditionalOperatorClass: {
5272 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5273 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5274 if (CommonResult.Val == 2) return CommonResult;
5275 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5276 if (FalseResult.Val == 2) return FalseResult;
5277 if (CommonResult.Val == 1) return CommonResult;
5278 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005279 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005280 return FalseResult;
5281 }
John McCall864e3962010-05-07 05:32:02 +00005282 case Expr::ConditionalOperatorClass: {
5283 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5284 // If the condition (ignoring parens) is a __builtin_constant_p call,
5285 // then only the true side is actually considered in an integer constant
5286 // expression, and it is fully evaluated. This is an important GNU
5287 // extension. See GCC PR38377 for discussion.
5288 if (const CallExpr *CallCE
5289 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00005290 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00005291 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005292 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005293 !EVResult.Val.isInt()) {
5294 return ICEDiag(2, E->getLocStart());
5295 }
5296 return NoDiag();
5297 }
5298 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005299 if (CondResult.Val == 2)
5300 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005301
Richard Smithf57d8cb2011-12-09 22:58:01 +00005302 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5303 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005304
John McCall864e3962010-05-07 05:32:02 +00005305 if (TrueResult.Val == 2)
5306 return TrueResult;
5307 if (FalseResult.Val == 2)
5308 return FalseResult;
5309 if (CondResult.Val == 1)
5310 return CondResult;
5311 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5312 return NoDiag();
5313 // Rare case where the diagnostics depend on which side is evaluated
5314 // Note that if we get here, CondResult is 0, and at least one of
5315 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005316 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005317 return FalseResult;
5318 }
5319 return TrueResult;
5320 }
5321 case Expr::CXXDefaultArgExprClass:
5322 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5323 case Expr::ChooseExprClass: {
5324 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5325 }
5326 }
5327
5328 // Silence a GCC warning
5329 return ICEDiag(2, E->getLocStart());
5330}
5331
Richard Smithf57d8cb2011-12-09 22:58:01 +00005332/// Evaluate an expression as a C++11 integral constant expression.
5333static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5334 const Expr *E,
5335 llvm::APSInt *Value,
5336 SourceLocation *Loc) {
5337 if (!E->getType()->isIntegralOrEnumerationType()) {
5338 if (Loc) *Loc = E->getExprLoc();
5339 return false;
5340 }
5341
5342 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005343 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5344 Result.Diag = &Diags;
5345 EvalInfo Info(Ctx, Result);
5346
5347 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5348 if (!Diags.empty()) {
5349 IsICE = false;
5350 if (Loc) *Loc = Diags[0].first;
5351 } else if (!IsICE && Loc) {
5352 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005353 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005354
5355 if (!IsICE)
5356 return false;
5357
5358 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5359 if (Value) *Value = Result.Val.getInt();
5360 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005361}
5362
Richard Smith92b1ce02011-12-12 09:28:41 +00005363bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005364 if (Ctx.getLangOptions().CPlusPlus0x)
5365 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5366
John McCall864e3962010-05-07 05:32:02 +00005367 ICEDiag d = CheckICE(this, Ctx);
5368 if (d.Val != 0) {
5369 if (Loc) *Loc = d.Loc;
5370 return false;
5371 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005372 return true;
5373}
5374
5375bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5376 SourceLocation *Loc, bool isEvaluated) const {
5377 if (Ctx.getLangOptions().CPlusPlus0x)
5378 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5379
5380 if (!isIntegerConstantExpr(Ctx, Loc))
5381 return false;
5382 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005383 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005384 return true;
5385}