blob: fa5cb8cd732e6325a1b14f716454bd41be5dbc51 [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//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it.
80 if (Inner != Temp)
81 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
George Burgess IVa51c4072015-10-16 01:49:01 +0000117 uint64_t &ArraySize, QualType &Type,
118 bool &IsArray) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000119 unsigned MostDerivedLength = 0;
120 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000121 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000122 if (Type->isArrayType()) {
123 const ConstantArrayType *CAT =
124 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
125 Type = CAT->getElementType();
126 ArraySize = CAT->getSize().getZExtValue();
127 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000128 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000129 } else if (Type->isAnyComplexType()) {
130 const ComplexType *CT = Type->castAs<ComplexType>();
131 Type = CT->getElementType();
132 ArraySize = 2;
133 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000134 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000135 } else if (const FieldDecl *FD = getAsField(Path[I])) {
136 Type = FD->getType();
137 ArraySize = 0;
138 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000139 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000140 } else {
Richard Smith80815602011-11-07 05:07:52 +0000141 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000143 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 }
Richard Smith80815602011-11-07 05:07:52 +0000145 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000146 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000147 }
148
Richard Smitha8105bc2012-01-06 16:39:00 +0000149 // The order of this enum is important for diagnostics.
150 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000151 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000152 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000153 };
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// A path from a glvalue to a subobject of that glvalue.
156 struct SubobjectDesignator {
157 /// True if the subobject was named in a manner not supported by C++11. Such
158 /// lvalues can still be folded, but they are not core constant expressions
159 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000160 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000161
Richard Smitha8105bc2012-01-06 16:39:00 +0000162 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000163 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000164
George Burgess IVa51c4072015-10-16 01:49:01 +0000165 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000166 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000167
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 /// The length of the path to the most-derived object of which this is a
169 /// subobject.
George Burgess IVa51c4072015-10-16 01:49:01 +0000170 unsigned MostDerivedPathLength : 29;
Richard Smitha8105bc2012-01-06 16:39:00 +0000171
George Burgess IVa51c4072015-10-16 01:49:01 +0000172 /// The size of the array of which the most-derived object is an element.
173 /// This will always be 0 if the most-derived object is not an array
174 /// element. 0 is not an indicator of whether or not the most-derived object
175 /// is an array, however, because 0-length arrays are allowed.
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 uint64_t MostDerivedArraySize;
177
178 /// The type of the most derived object referred to by this address.
179 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000180
Richard Smith80815602011-11-07 05:07:52 +0000181 typedef APValue::LValuePathEntry PathEntry;
182
Richard Smith96e0c102011-11-04 02:25:55 +0000183 /// The entries on the path from the glvalue to the designated subobject.
184 SmallVector<PathEntry, 8> Entries;
185
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000187
Richard Smitha8105bc2012-01-06 16:39:00 +0000188 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000189 : Invalid(false), IsOnePastTheEnd(false),
190 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
191 MostDerivedArraySize(0), MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000192
193 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000194 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
195 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
196 MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000197 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000198 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000199 ArrayRef<PathEntry> VEntries = V.getLValuePath();
200 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000201 if (V.getLValueBase()) {
202 bool IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000203 MostDerivedPathLength =
204 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
205 V.getLValuePath(), MostDerivedArraySize,
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 MostDerivedType, IsArray);
207 MostDerivedIsArrayElement = IsArray;
208 }
Richard Smith80815602011-11-07 05:07:52 +0000209 }
210 }
211
Richard Smith96e0c102011-11-04 02:25:55 +0000212 void setInvalid() {
213 Invalid = true;
214 Entries.clear();
215 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000216
217 /// Determine whether this is a one-past-the-end pointer.
218 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000219 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 if (IsOnePastTheEnd)
221 return true;
George Burgess IVa51c4072015-10-16 01:49:01 +0000222 if (MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000223 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
224 return true;
225 return false;
226 }
227
228 /// Check that this refers to a valid subobject.
229 bool isValidSubobject() const {
230 if (Invalid)
231 return false;
232 return !isOnePastTheEnd();
233 }
234 /// Check that this refers to a valid subobject, and if not, produce a
235 /// relevant diagnostic and set the designator as invalid.
236 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
237
238 /// Update this designator to refer to the first element within this array.
239 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000240 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000241 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000242 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000243
244 // This is a most-derived object.
245 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247 MostDerivedArraySize = CAT->getSize().getZExtValue();
248 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000249 }
250 /// Update this designator to refer to the given base or member of this
251 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000252 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000253 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000254 APValue::BaseOrMemberType Value(D, Virtual);
255 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000256 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000257
258 // If this isn't a base class, it's a new most-derived object.
259 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
260 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000261 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 MostDerivedArraySize = 0;
263 MostDerivedPathLength = Entries.size();
264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
Richard Smith66c96992012-02-18 22:04:06 +0000266 /// Update this designator to refer to the given complex component.
267 void addComplexUnchecked(QualType EltTy, bool Imag) {
268 PathEntry Entry;
269 Entry.ArrayIndex = Imag;
270 Entries.push_back(Entry);
271
272 // This is technically a most-derived object, though in practice this
273 // is unlikely to matter.
274 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000275 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000276 MostDerivedArraySize = 2;
277 MostDerivedPathLength = Entries.size();
278 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000280 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000281 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000282 if (Invalid) return;
George Burgess IVa51c4072015-10-16 01:49:01 +0000283 if (MostDerivedPathLength == Entries.size() &&
284 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000285 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000286 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
287 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
288 setInvalid();
289 }
Richard Smith96e0c102011-11-04 02:25:55 +0000290 return;
291 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000292 // [expr.add]p4: For the purposes of these operators, a pointer to a
293 // nonarray object behaves the same as a pointer to the first element of
294 // an array of length one with the type of the object as its element type.
295 if (IsOnePastTheEnd && N == (uint64_t)-1)
296 IsOnePastTheEnd = false;
297 else if (!IsOnePastTheEnd && N == 1)
298 IsOnePastTheEnd = true;
299 else if (N != 0) {
300 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000301 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000302 }
Richard Smith96e0c102011-11-04 02:25:55 +0000303 }
304 };
305
Richard Smith254a73d2011-10-28 22:34:42 +0000306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
308 EvalInfo &Info;
309
310 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000311 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000312
Richard Smithf6f003a2011-12-16 19:06:07 +0000313 /// Callee - The function which was called.
314 const FunctionDecl *Callee;
315
Richard Smithd62306a2011-11-10 06:34:14 +0000316 /// This - The binding for the this pointer in this call, if any.
317 const LValue *This;
318
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000319 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000320 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000321 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000322
Eli Friedman4830ec82012-06-25 21:21:08 +0000323 // Note that we intentionally use std::map here so that references to
324 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000325 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000326 typedef MapTy::const_iterator temp_iterator;
327 /// Temporaries - Temporary lvalues materialized within this stack frame.
328 MapTy Temporaries;
329
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000330 /// CallLoc - The location of the call expression for this call.
331 SourceLocation CallLoc;
332
333 /// Index - The call index of this call.
334 unsigned Index;
335
Richard Smithf6f003a2011-12-16 19:06:07 +0000336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000338 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000339 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000340
341 APValue *getTemporary(const void *Key) {
342 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000343 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000344 }
345 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000346 };
347
Richard Smith852c9db2013-04-20 22:23:05 +0000348 /// Temporarily override 'this'.
349 class ThisOverrideRAII {
350 public:
351 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
352 : Frame(Frame), OldThis(Frame.This) {
353 if (Enable)
354 Frame.This = NewThis;
355 }
356 ~ThisOverrideRAII() {
357 Frame.This = OldThis;
358 }
359 private:
360 CallStackFrame &Frame;
361 const LValue *OldThis;
362 };
363
Richard Smith92b1ce02011-12-12 09:28:41 +0000364 /// A partial diagnostic which we might know in advance that we are not going
365 /// to emit.
366 class OptionalDiagnostic {
367 PartialDiagnostic *Diag;
368
369 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000370 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
371 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000372
373 template<typename T>
374 OptionalDiagnostic &operator<<(const T &v) {
375 if (Diag)
376 *Diag << v;
377 return *this;
378 }
Richard Smithfe800032012-01-31 04:08:20 +0000379
380 OptionalDiagnostic &operator<<(const APSInt &I) {
381 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000382 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000383 I.toString(Buffer);
384 *Diag << StringRef(Buffer.data(), Buffer.size());
385 }
386 return *this;
387 }
388
389 OptionalDiagnostic &operator<<(const APFloat &F) {
390 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000391 // FIXME: Force the precision of the source value down so we don't
392 // print digits which are usually useless (we don't really care here if
393 // we truncate a digit by accident in edge cases). Ideally,
394 // APFloat::toString would automatically print the shortest
395 // representation which rounds to the correct value, but it's a bit
396 // tricky to implement.
397 unsigned precision =
398 llvm::APFloat::semanticsPrecision(F.getSemantics());
399 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000400 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000401 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000402 *Diag << StringRef(Buffer.data(), Buffer.size());
403 }
404 return *this;
405 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000406 };
407
Richard Smith08d6a2c2013-07-24 07:11:57 +0000408 /// A cleanup, and a flag indicating whether it is lifetime-extended.
409 class Cleanup {
410 llvm::PointerIntPair<APValue*, 1, bool> Value;
411
412 public:
413 Cleanup(APValue *Val, bool IsLifetimeExtended)
414 : Value(Val, IsLifetimeExtended) {}
415
416 bool isLifetimeExtended() const { return Value.getInt(); }
417 void endLifetime() {
418 *Value.getPointer() = APValue();
419 }
420 };
421
Richard Smithb228a862012-02-15 02:18:13 +0000422 /// EvalInfo - This is a private struct used by the evaluator to capture
423 /// information about a subexpression as it is folded. It retains information
424 /// about the AST context, but also maintains information about the folded
425 /// expression.
426 ///
427 /// If an expression could be evaluated, it is still possible it is not a C
428 /// "integer constant expression" or constant expression. If not, this struct
429 /// captures information about how and why not.
430 ///
431 /// One bit of information passed *into* the request for constant folding
432 /// indicates whether the subexpression is "evaluated" or not according to C
433 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
434 /// evaluate the expression regardless of what the RHS is, but C only allows
435 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000436 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000437 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000438
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 /// EvalStatus - Contains information about the evaluation.
440 Expr::EvalStatus &EvalStatus;
441
442 /// CurrentCall - The top of the constexpr call stack.
443 CallStackFrame *CurrentCall;
444
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000445 /// CallStackDepth - The number of calls in the call stack right now.
446 unsigned CallStackDepth;
447
Richard Smithb228a862012-02-15 02:18:13 +0000448 /// NextCallIndex - The next call index to assign.
449 unsigned NextCallIndex;
450
Richard Smitha3d3bd22013-05-08 02:12:03 +0000451 /// StepsLeft - The remaining number of evaluation steps we're permitted
452 /// to perform. This is essentially a limit for the number of statements
453 /// we will evaluate.
454 unsigned StepsLeft;
455
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000456 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000457 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000458 CallStackFrame BottomFrame;
459
Richard Smith08d6a2c2013-07-24 07:11:57 +0000460 /// A stack of values whose lifetimes end at the end of some surrounding
461 /// evaluation frame.
462 llvm::SmallVector<Cleanup, 16> CleanupStack;
463
Richard Smithd62306a2011-11-10 06:34:14 +0000464 /// EvaluatingDecl - This is the declaration whose initializer is being
465 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000466 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000467
468 /// EvaluatingDeclValue - This is the value being constructed for the
469 /// declaration whose initializer is being evaluated, if any.
470 APValue *EvaluatingDeclValue;
471
Richard Smith357362d2011-12-13 06:39:58 +0000472 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
473 /// notes attached to it will also be stored, otherwise they will not be.
474 bool HasActiveDiagnostic;
475
Richard Smith0c6124b2015-12-03 01:36:22 +0000476 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
477 /// fold (not just why it's not strictly a constant expression)?
478 bool HasFoldFailureDiagnostic;
479
George Burgess IV8c892b52016-05-25 22:31:54 +0000480 /// \brief Whether or not we're currently speculatively evaluating.
481 bool IsSpeculativelyEvaluating;
482
Richard Smith6d4c6582013-11-05 22:18:15 +0000483 enum EvaluationMode {
484 /// Evaluate as a constant expression. Stop if we find that the expression
485 /// is not a constant expression.
486 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000487
Richard Smith6d4c6582013-11-05 22:18:15 +0000488 /// Evaluate as a potential constant expression. Keep going if we hit a
489 /// construct that we can't evaluate yet (because we don't yet know the
490 /// value of something) but stop if we hit something that could never be
491 /// a constant expression.
492 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000493
Richard Smith6d4c6582013-11-05 22:18:15 +0000494 /// Fold the expression to a constant. Stop if we hit a side-effect that
495 /// we can't model.
496 EM_ConstantFold,
497
498 /// Evaluate the expression looking for integer overflow and similar
499 /// issues. Don't worry about side-effects, and try to visit all
500 /// subexpressions.
501 EM_EvaluateForOverflow,
502
503 /// Evaluate in any way we know how. Don't worry about side-effects that
504 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000505 EM_IgnoreSideEffects,
506
507 /// Evaluate as a constant expression. Stop if we find that the expression
508 /// is not a constant expression. Some expressions can be retried in the
509 /// optimizer if we don't constant fold them here, but in an unevaluated
510 /// context we try to fold them immediately since the optimizer never
511 /// gets a chance to look at it.
512 EM_ConstantExpressionUnevaluated,
513
514 /// Evaluate as a potential constant expression. Keep going if we hit a
515 /// construct that we can't evaluate yet (because we don't yet know the
516 /// value of something) but stop if we hit something that could never be
517 /// a constant expression. Some expressions can be retried in the
518 /// optimizer if we don't constant fold them here, but in an unevaluated
519 /// context we try to fold them immediately since the optimizer never
520 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000521 EM_PotentialConstantExpressionUnevaluated,
522
523 /// Evaluate as a constant expression. Continue evaluating if we find a
524 /// MemberExpr with a base that can't be evaluated.
525 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000526 } EvalMode;
527
528 /// Are we checking whether the expression is a potential constant
529 /// expression?
530 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000531 return EvalMode == EM_PotentialConstantExpression ||
532 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000533 }
534
535 /// Are we checking an expression for overflow?
536 // FIXME: We should check for any kind of undefined or suspicious behavior
537 // in such constructs, not just overflow.
538 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
539
540 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000541 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000542 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000543 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000544 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
545 EvaluatingDecl((const ValueDecl *)nullptr),
546 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000547 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
548 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000549
Richard Smith7525ff62013-05-09 07:14:00 +0000550 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
551 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000552 EvaluatingDeclValue = &Value;
553 }
554
David Blaikiebbafb8a2012-03-11 07:00:24 +0000555 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000556
Richard Smith357362d2011-12-13 06:39:58 +0000557 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000558 // Don't perform any constexpr calls (other than the call we're checking)
559 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000560 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000561 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000562 if (NextCallIndex == 0) {
563 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000564 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000565 return false;
566 }
Richard Smith357362d2011-12-13 06:39:58 +0000567 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
568 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000569 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000570 << getLangOpts().ConstexprCallDepth;
571 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000572 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000573
Richard Smithb228a862012-02-15 02:18:13 +0000574 CallStackFrame *getCallFrame(unsigned CallIndex) {
575 assert(CallIndex && "no call index in getCallFrame");
576 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
577 // be null in this loop.
578 CallStackFrame *Frame = CurrentCall;
579 while (Frame->Index > CallIndex)
580 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000581 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000582 }
583
Richard Smitha3d3bd22013-05-08 02:12:03 +0000584 bool nextStep(const Stmt *S) {
585 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000586 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000587 return false;
588 }
589 --StepsLeft;
590 return true;
591 }
592
Richard Smith357362d2011-12-13 06:39:58 +0000593 private:
594 /// Add a diagnostic to the diagnostics list.
595 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
596 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
597 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
598 return EvalStatus.Diag->back().second;
599 }
600
Richard Smithf6f003a2011-12-16 19:06:07 +0000601 /// Add notes containing a call stack to the current point of evaluation.
602 void addCallStack(unsigned Limit);
603
Faisal Valie690b7a2016-07-02 22:34:24 +0000604 private:
605 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
606 unsigned ExtraNotes, bool IsCCEDiag) {
607
Richard Smith92b1ce02011-12-12 09:28:41 +0000608 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000609 // If we have a prior diagnostic, it will be noting that the expression
610 // isn't a constant expression. This diagnostic is more important,
611 // unless we require this evaluation to produce a constant expression.
612 //
613 // FIXME: We might want to show both diagnostics to the user in
614 // EM_ConstantFold mode.
615 if (!EvalStatus.Diag->empty()) {
616 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000617 case EM_ConstantFold:
618 case EM_IgnoreSideEffects:
619 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000620 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000621 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000622 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000623 case EM_ConstantExpression:
624 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000625 case EM_ConstantExpressionUnevaluated:
626 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000627 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000628 HasActiveDiagnostic = false;
629 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000630 }
631 }
632
Richard Smithf6f003a2011-12-16 19:06:07 +0000633 unsigned CallStackNotes = CallStackDepth - 1;
634 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
635 if (Limit)
636 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000637 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000638 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000639
Richard Smith357362d2011-12-13 06:39:58 +0000640 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000641 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000642 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000643 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
644 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000645 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000646 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000647 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000648 }
Richard Smith357362d2011-12-13 06:39:58 +0000649 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000650 return OptionalDiagnostic();
651 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000652 public:
653 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
654 OptionalDiagnostic
655 FFDiag(SourceLocation Loc,
656 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
657 unsigned ExtraNotes = 0) {
658 return Diag(Loc, DiagId, ExtraNotes, false);
659 }
660
661 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000662 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000663 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000664 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000665 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000666 HasActiveDiagnostic = false;
667 return OptionalDiagnostic();
668 }
669
Richard Smith92b1ce02011-12-12 09:28:41 +0000670 /// Diagnose that the evaluation does not produce a C++11 core constant
671 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000672 ///
673 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
674 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000675 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000676 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000677 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000678 // Don't override a previous diagnostic. Don't bother collecting
679 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000680 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000681 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000682 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000683 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000684 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000685 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000686 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
687 = diag::note_invalid_subexpr_in_const_expr,
688 unsigned ExtraNotes = 0) {
689 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
690 }
Richard Smith357362d2011-12-13 06:39:58 +0000691 /// Add a note to a prior diagnostic.
692 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
693 if (!HasActiveDiagnostic)
694 return OptionalDiagnostic();
695 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000696 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000697
698 /// Add a stack of notes to a prior diagnostic.
699 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
700 if (HasActiveDiagnostic) {
701 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
702 Diags.begin(), Diags.end());
703 }
704 }
Richard Smith253c2a32012-01-27 01:14:48 +0000705
Richard Smith6d4c6582013-11-05 22:18:15 +0000706 /// Should we continue evaluation after encountering a side-effect that we
707 /// couldn't model?
708 bool keepEvaluatingAfterSideEffect() {
709 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000710 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000711 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000712 case EM_EvaluateForOverflow:
713 case EM_IgnoreSideEffects:
714 return true;
715
Richard Smith6d4c6582013-11-05 22:18:15 +0000716 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000717 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000718 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000719 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000720 return false;
721 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000722 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000723 }
724
725 /// Note that we have had a side-effect, and determine whether we should
726 /// keep evaluating.
727 bool noteSideEffect() {
728 EvalStatus.HasSideEffects = true;
729 return keepEvaluatingAfterSideEffect();
730 }
731
Richard Smithce8eca52015-12-08 03:21:47 +0000732 /// Should we continue evaluation after encountering undefined behavior?
733 bool keepEvaluatingAfterUndefinedBehavior() {
734 switch (EvalMode) {
735 case EM_EvaluateForOverflow:
736 case EM_IgnoreSideEffects:
737 case EM_ConstantFold:
738 case EM_DesignatorFold:
739 return true;
740
741 case EM_PotentialConstantExpression:
742 case EM_PotentialConstantExpressionUnevaluated:
743 case EM_ConstantExpression:
744 case EM_ConstantExpressionUnevaluated:
745 return false;
746 }
747 llvm_unreachable("Missed EvalMode case");
748 }
749
750 /// Note that we hit something that was technically undefined behavior, but
751 /// that we can evaluate past it (such as signed overflow or floating-point
752 /// division by zero.)
753 bool noteUndefinedBehavior() {
754 EvalStatus.HasUndefinedBehavior = true;
755 return keepEvaluatingAfterUndefinedBehavior();
756 }
757
Richard Smith253c2a32012-01-27 01:14:48 +0000758 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000759 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000760 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000761 if (!StepsLeft)
762 return false;
763
764 switch (EvalMode) {
765 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000766 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000767 case EM_EvaluateForOverflow:
768 return true;
769
770 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000771 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000772 case EM_ConstantFold:
773 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000774 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000775 return false;
776 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000777 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000778 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000779
George Burgess IV8c892b52016-05-25 22:31:54 +0000780 /// Notes that we failed to evaluate an expression that other expressions
781 /// directly depend on, and determine if we should keep evaluating. This
782 /// should only be called if we actually intend to keep evaluating.
783 ///
784 /// Call noteSideEffect() instead if we may be able to ignore the value that
785 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
786 ///
787 /// (Foo(), 1) // use noteSideEffect
788 /// (Foo() || true) // use noteSideEffect
789 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000790 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000791 // Failure when evaluating some expression often means there is some
792 // subexpression whose evaluation was skipped. Therefore, (because we
793 // don't track whether we skipped an expression when unwinding after an
794 // evaluation failure) every evaluation failure that bubbles up from a
795 // subexpression implies that a side-effect has potentially happened. We
796 // skip setting the HasSideEffects flag to true until we decide to
797 // continue evaluating after that point, which happens here.
798 bool KeepGoing = keepEvaluatingAfterFailure();
799 EvalStatus.HasSideEffects |= KeepGoing;
800 return KeepGoing;
801 }
802
George Burgess IV3a03fab2015-09-04 21:28:13 +0000803 bool allowInvalidBaseExpr() const {
804 return EvalMode == EM_DesignatorFold;
805 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000806 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000807
808 /// Object used to treat all foldable expressions as constant expressions.
809 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000810 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000811 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000812 bool HadNoPriorDiags;
813 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000814
Richard Smith6d4c6582013-11-05 22:18:15 +0000815 explicit FoldConstant(EvalInfo &Info, bool Enabled)
816 : Info(Info),
817 Enabled(Enabled),
818 HadNoPriorDiags(Info.EvalStatus.Diag &&
819 Info.EvalStatus.Diag->empty() &&
820 !Info.EvalStatus.HasSideEffects),
821 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000822 if (Enabled &&
823 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
824 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000825 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000826 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000827 void keepDiagnostics() { Enabled = false; }
828 ~FoldConstant() {
829 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000830 !Info.EvalStatus.HasSideEffects)
831 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000832 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000833 }
834 };
Richard Smith17100ba2012-02-16 02:46:34 +0000835
George Burgess IV3a03fab2015-09-04 21:28:13 +0000836 /// RAII object used to treat the current evaluation as the correct pointer
837 /// offset fold for the current EvalMode
838 struct FoldOffsetRAII {
839 EvalInfo &Info;
840 EvalInfo::EvaluationMode OldMode;
841 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
842 : Info(Info), OldMode(Info.EvalMode) {
843 if (!Info.checkingPotentialConstantExpression())
844 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
845 : EvalInfo::EM_ConstantFold;
846 }
847
848 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
849 };
850
George Burgess IV8c892b52016-05-25 22:31:54 +0000851 /// RAII object used to optionally suppress diagnostics and side-effects from
852 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000853 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000854 /// Pair of EvalInfo, and a bit that stores whether or not we were
855 /// speculatively evaluating when we created this RAII.
856 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000857 Expr::EvalStatus Old;
858
George Burgess IV8c892b52016-05-25 22:31:54 +0000859 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
860 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
861 Old = Other.Old;
862 Other.InfoAndOldSpecEval.setPointer(nullptr);
863 }
864
865 void maybeRestoreState() {
866 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
867 if (!Info)
868 return;
869
870 Info->EvalStatus = Old;
871 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
872 }
873
Richard Smith17100ba2012-02-16 02:46:34 +0000874 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000875 SpeculativeEvaluationRAII() = default;
876
877 SpeculativeEvaluationRAII(
878 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
879 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
880 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000881 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000882 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000883 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000884
885 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
886 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
887 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000888 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000889
890 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
891 maybeRestoreState();
892 moveFromAndCancel(std::move(Other));
893 return *this;
894 }
895
896 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +0000897 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000898
899 /// RAII object wrapping a full-expression or block scope, and handling
900 /// the ending of the lifetime of temporaries created within it.
901 template<bool IsFullExpression>
902 class ScopeRAII {
903 EvalInfo &Info;
904 unsigned OldStackSize;
905 public:
906 ScopeRAII(EvalInfo &Info)
907 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
908 ~ScopeRAII() {
909 // Body moved to a static method to encourage the compiler to inline away
910 // instances of this class.
911 cleanup(Info, OldStackSize);
912 }
913 private:
914 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
915 unsigned NewEnd = OldStackSize;
916 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
917 I != N; ++I) {
918 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
919 // Full-expression cleanup of a lifetime-extended temporary: nothing
920 // to do, just move this cleanup to the right place in the stack.
921 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
922 ++NewEnd;
923 } else {
924 // End the lifetime of the object.
925 Info.CleanupStack[I].endLifetime();
926 }
927 }
928 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
929 Info.CleanupStack.end());
930 }
931 };
932 typedef ScopeRAII<false> BlockScopeRAII;
933 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000934}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000935
Richard Smitha8105bc2012-01-06 16:39:00 +0000936bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
937 CheckSubobjectKind CSK) {
938 if (Invalid)
939 return false;
940 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000941 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000942 << CSK;
943 setInvalid();
944 return false;
945 }
946 return true;
947}
948
949void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
950 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000951 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000952 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000953 << static_cast<int>(N) << /*array*/ 0
954 << static_cast<unsigned>(MostDerivedArraySize);
955 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000956 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000957 << static_cast<int>(N) << /*non-array*/ 1;
958 setInvalid();
959}
960
Richard Smithf6f003a2011-12-16 19:06:07 +0000961CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
962 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000963 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +0000964 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
965 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000966 Info.CurrentCall = this;
967 ++Info.CallStackDepth;
968}
969
970CallStackFrame::~CallStackFrame() {
971 assert(Info.CurrentCall == this && "calls retired out of order");
972 --Info.CallStackDepth;
973 Info.CurrentCall = Caller;
974}
975
Richard Smith08d6a2c2013-07-24 07:11:57 +0000976APValue &CallStackFrame::createTemporary(const void *Key,
977 bool IsLifetimeExtended) {
978 APValue &Result = Temporaries[Key];
979 assert(Result.isUninit() && "temporary created multiple times");
980 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
981 return Result;
982}
983
Richard Smith84401042013-06-03 05:03:02 +0000984static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000985
986void EvalInfo::addCallStack(unsigned Limit) {
987 // Determine which calls to skip, if any.
988 unsigned ActiveCalls = CallStackDepth - 1;
989 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
990 if (Limit && Limit < ActiveCalls) {
991 SkipStart = Limit / 2 + Limit % 2;
992 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000993 }
994
Richard Smithf6f003a2011-12-16 19:06:07 +0000995 // Walk the call stack and add the diagnostics.
996 unsigned CallIdx = 0;
997 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
998 Frame = Frame->Caller, ++CallIdx) {
999 // Skip this call?
1000 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1001 if (CallIdx == SkipStart) {
1002 // Note that we're skipping calls.
1003 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1004 << unsigned(ActiveCalls - Limit);
1005 }
1006 continue;
1007 }
1008
Richard Smith5179eb72016-06-28 19:03:57 +00001009 // Use a different note for an inheriting constructor, because from the
1010 // user's perspective it's not really a function at all.
1011 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1012 if (CD->isInheritingConstructor()) {
1013 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1014 << CD->getParent();
1015 continue;
1016 }
1017 }
1018
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001019 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001020 llvm::raw_svector_ostream Out(Buffer);
1021 describeCall(Frame, Out);
1022 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1023 }
1024}
1025
1026namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001027 struct ComplexValue {
1028 private:
1029 bool IsInt;
1030
1031 public:
1032 APSInt IntReal, IntImag;
1033 APFloat FloatReal, FloatImag;
1034
1035 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
1036
1037 void makeComplexFloat() { IsInt = false; }
1038 bool isComplexFloat() const { return !IsInt; }
1039 APFloat &getComplexFloatReal() { return FloatReal; }
1040 APFloat &getComplexFloatImag() { return FloatImag; }
1041
1042 void makeComplexInt() { IsInt = true; }
1043 bool isComplexInt() const { return IsInt; }
1044 APSInt &getComplexIntReal() { return IntReal; }
1045 APSInt &getComplexIntImag() { return IntImag; }
1046
Richard Smith2e312c82012-03-03 22:46:17 +00001047 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001048 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001049 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001050 else
Richard Smith2e312c82012-03-03 22:46:17 +00001051 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001052 }
Richard Smith2e312c82012-03-03 22:46:17 +00001053 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001054 assert(v.isComplexFloat() || v.isComplexInt());
1055 if (v.isComplexFloat()) {
1056 makeComplexFloat();
1057 FloatReal = v.getComplexFloatReal();
1058 FloatImag = v.getComplexFloatImag();
1059 } else {
1060 makeComplexInt();
1061 IntReal = v.getComplexIntReal();
1062 IntImag = v.getComplexIntImag();
1063 }
1064 }
John McCall93d91dc2010-05-07 17:22:02 +00001065 };
John McCall45d55e42010-05-07 21:00:08 +00001066
1067 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001068 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001069 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001070 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001071 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001072 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +00001073
Richard Smithce40ad62011-11-12 22:28:03 +00001074 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001075 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001076 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001077 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001078 SubobjectDesignator &getLValueDesignator() { return Designator; }
1079 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +00001080
Richard Smith2e312c82012-03-03 22:46:17 +00001081 void moveInto(APValue &V) const {
1082 if (Designator.Invalid)
1083 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
1084 else
1085 V = APValue(Base, Offset, Designator.Entries,
1086 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +00001087 }
Richard Smith2e312c82012-03-03 22:46:17 +00001088 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001089 assert(V.isLValue());
1090 Base = V.getLValueBase();
1091 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001092 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001093 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001094 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +00001095 }
1096
George Burgess IV3a03fab2015-09-04 21:28:13 +00001097 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +00001098 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +00001099 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001100 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001101 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001102 Designator = SubobjectDesignator(getType(B));
1103 }
1104
George Burgess IV3a03fab2015-09-04 21:28:13 +00001105 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1106 set(B, I, true);
1107 }
1108
Richard Smitha8105bc2012-01-06 16:39:00 +00001109 // Check that this LValue is not based on a null pointer. If it is, produce
1110 // a diagnostic and mark the designator as invalid.
1111 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1112 CheckSubobjectKind CSK) {
1113 if (Designator.Invalid)
1114 return false;
1115 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001116 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001117 << CSK;
1118 Designator.setInvalid();
1119 return false;
1120 }
1121 return true;
1122 }
1123
1124 // Check this LValue refers to an object. If not, set the designator to be
1125 // invalid and emit a diagnostic.
1126 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001127 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001128 Designator.checkSubobject(Info, E, CSK);
1129 }
1130
1131 void addDecl(EvalInfo &Info, const Expr *E,
1132 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001133 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1134 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001135 }
1136 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001137 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1138 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001139 }
Richard Smith66c96992012-02-18 22:04:06 +00001140 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001141 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1142 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001143 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001144 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001145 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001146 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001147 }
John McCall45d55e42010-05-07 21:00:08 +00001148 };
Richard Smith027bf112011-11-17 22:56:20 +00001149
1150 struct MemberPtr {
1151 MemberPtr() {}
1152 explicit MemberPtr(const ValueDecl *Decl) :
1153 DeclAndIsDerivedMember(Decl, false), Path() {}
1154
1155 /// The member or (direct or indirect) field referred to by this member
1156 /// pointer, or 0 if this is a null member pointer.
1157 const ValueDecl *getDecl() const {
1158 return DeclAndIsDerivedMember.getPointer();
1159 }
1160 /// Is this actually a member of some type derived from the relevant class?
1161 bool isDerivedMember() const {
1162 return DeclAndIsDerivedMember.getInt();
1163 }
1164 /// Get the class which the declaration actually lives in.
1165 const CXXRecordDecl *getContainingRecord() const {
1166 return cast<CXXRecordDecl>(
1167 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1168 }
1169
Richard Smith2e312c82012-03-03 22:46:17 +00001170 void moveInto(APValue &V) const {
1171 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001172 }
Richard Smith2e312c82012-03-03 22:46:17 +00001173 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001174 assert(V.isMemberPointer());
1175 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1176 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1177 Path.clear();
1178 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1179 Path.insert(Path.end(), P.begin(), P.end());
1180 }
1181
1182 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1183 /// whether the member is a member of some class derived from the class type
1184 /// of the member pointer.
1185 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1186 /// Path - The path of base/derived classes from the member declaration's
1187 /// class (exclusive) to the class type of the member pointer (inclusive).
1188 SmallVector<const CXXRecordDecl*, 4> Path;
1189
1190 /// Perform a cast towards the class of the Decl (either up or down the
1191 /// hierarchy).
1192 bool castBack(const CXXRecordDecl *Class) {
1193 assert(!Path.empty());
1194 const CXXRecordDecl *Expected;
1195 if (Path.size() >= 2)
1196 Expected = Path[Path.size() - 2];
1197 else
1198 Expected = getContainingRecord();
1199 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1200 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1201 // if B does not contain the original member and is not a base or
1202 // derived class of the class containing the original member, the result
1203 // of the cast is undefined.
1204 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1205 // (D::*). We consider that to be a language defect.
1206 return false;
1207 }
1208 Path.pop_back();
1209 return true;
1210 }
1211 /// Perform a base-to-derived member pointer cast.
1212 bool castToDerived(const CXXRecordDecl *Derived) {
1213 if (!getDecl())
1214 return true;
1215 if (!isDerivedMember()) {
1216 Path.push_back(Derived);
1217 return true;
1218 }
1219 if (!castBack(Derived))
1220 return false;
1221 if (Path.empty())
1222 DeclAndIsDerivedMember.setInt(false);
1223 return true;
1224 }
1225 /// Perform a derived-to-base member pointer cast.
1226 bool castToBase(const CXXRecordDecl *Base) {
1227 if (!getDecl())
1228 return true;
1229 if (Path.empty())
1230 DeclAndIsDerivedMember.setInt(true);
1231 if (isDerivedMember()) {
1232 Path.push_back(Base);
1233 return true;
1234 }
1235 return castBack(Base);
1236 }
1237 };
Richard Smith357362d2011-12-13 06:39:58 +00001238
Richard Smith7bb00672012-02-01 01:42:44 +00001239 /// Compare two member pointers, which are assumed to be of the same type.
1240 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1241 if (!LHS.getDecl() || !RHS.getDecl())
1242 return !LHS.getDecl() && !RHS.getDecl();
1243 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1244 return false;
1245 return LHS.Path == RHS.Path;
1246 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001247}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001248
Richard Smith2e312c82012-03-03 22:46:17 +00001249static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001250static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1251 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001252 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001253static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1254static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001255static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1256 EvalInfo &Info);
1257static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001258static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001259static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001260 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001261static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001262static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001263static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001264static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001265
1266//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001267// Misc utilities
1268//===----------------------------------------------------------------------===//
1269
Richard Smith84401042013-06-03 05:03:02 +00001270/// Produce a string describing the given constexpr call.
1271static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1272 unsigned ArgIndex = 0;
1273 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1274 !isa<CXXConstructorDecl>(Frame->Callee) &&
1275 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1276
1277 if (!IsMemberCall)
1278 Out << *Frame->Callee << '(';
1279
1280 if (Frame->This && IsMemberCall) {
1281 APValue Val;
1282 Frame->This->moveInto(Val);
1283 Val.printPretty(Out, Frame->Info.Ctx,
1284 Frame->This->Designator.MostDerivedType);
1285 // FIXME: Add parens around Val if needed.
1286 Out << "->" << *Frame->Callee << '(';
1287 IsMemberCall = false;
1288 }
1289
1290 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1291 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1292 if (ArgIndex > (unsigned)IsMemberCall)
1293 Out << ", ";
1294
1295 const ParmVarDecl *Param = *I;
1296 const APValue &Arg = Frame->Arguments[ArgIndex];
1297 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1298
1299 if (ArgIndex == 0 && IsMemberCall)
1300 Out << "->" << *Frame->Callee << '(';
1301 }
1302
1303 Out << ')';
1304}
1305
Richard Smithd9f663b2013-04-22 15:31:51 +00001306/// Evaluate an expression to see if it had side-effects, and discard its
1307/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001308/// \return \c true if the caller should keep evaluating.
1309static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001310 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001311 if (!Evaluate(Scratch, Info, E))
1312 // We don't need the value, but we might have skipped a side effect here.
1313 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001314 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001315}
1316
Richard Smith861b5b52013-05-07 23:34:45 +00001317/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1318/// return its existing value.
1319static int64_t getExtValue(const APSInt &Value) {
1320 return Value.isSigned() ? Value.getSExtValue()
1321 : static_cast<int64_t>(Value.getZExtValue());
1322}
1323
Richard Smithd62306a2011-11-10 06:34:14 +00001324/// Should this call expression be treated as a string literal?
1325static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001326 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001327 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1328 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1329}
1330
Richard Smithce40ad62011-11-12 22:28:03 +00001331static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001332 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1333 // constant expression of pointer type that evaluates to...
1334
1335 // ... a null pointer value, or a prvalue core constant expression of type
1336 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001337 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001338
Richard Smithce40ad62011-11-12 22:28:03 +00001339 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1340 // ... the address of an object with static storage duration,
1341 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1342 return VD->hasGlobalStorage();
1343 // ... the address of a function,
1344 return isa<FunctionDecl>(D);
1345 }
1346
1347 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001348 switch (E->getStmtClass()) {
1349 default:
1350 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001351 case Expr::CompoundLiteralExprClass: {
1352 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1353 return CLE->isFileScope() && CLE->isLValue();
1354 }
Richard Smithe6c01442013-06-05 00:46:14 +00001355 case Expr::MaterializeTemporaryExprClass:
1356 // A materialized temporary might have been lifetime-extended to static
1357 // storage duration.
1358 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001359 // A string literal has static storage duration.
1360 case Expr::StringLiteralClass:
1361 case Expr::PredefinedExprClass:
1362 case Expr::ObjCStringLiteralClass:
1363 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001364 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001365 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001366 return true;
1367 case Expr::CallExprClass:
1368 return IsStringLiteralCall(cast<CallExpr>(E));
1369 // For GCC compatibility, &&label has static storage duration.
1370 case Expr::AddrLabelExprClass:
1371 return true;
1372 // A Block literal expression may be used as the initialization value for
1373 // Block variables at global or local static scope.
1374 case Expr::BlockExprClass:
1375 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001376 case Expr::ImplicitValueInitExprClass:
1377 // FIXME:
1378 // We can never form an lvalue with an implicit value initialization as its
1379 // base through expression evaluation, so these only appear in one case: the
1380 // implicit variable declaration we invent when checking whether a constexpr
1381 // constructor can produce a constant expression. We must assume that such
1382 // an expression might be a global lvalue.
1383 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001384 }
John McCall95007602010-05-10 23:27:23 +00001385}
1386
Richard Smithb228a862012-02-15 02:18:13 +00001387static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1388 assert(Base && "no location for a null lvalue");
1389 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1390 if (VD)
1391 Info.Note(VD->getLocation(), diag::note_declared_at);
1392 else
Ted Kremenek28831752012-08-23 20:46:57 +00001393 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001394 diag::note_constexpr_temporary_here);
1395}
1396
Richard Smith80815602011-11-07 05:07:52 +00001397/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001398/// value for an address or reference constant expression. Return true if we
1399/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001400static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1401 QualType Type, const LValue &LVal) {
1402 bool IsReferenceType = Type->isReferenceType();
1403
Richard Smith357362d2011-12-13 06:39:58 +00001404 APValue::LValueBase Base = LVal.getLValueBase();
1405 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1406
Richard Smith0dea49e2012-02-18 04:58:18 +00001407 // Check that the object is a global. Note that the fake 'this' object we
1408 // manufacture when checking potential constant expressions is conservatively
1409 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001410 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001411 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001412 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001413 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001414 << IsReferenceType << !Designator.Entries.empty()
1415 << !!VD << VD;
1416 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001417 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001418 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001419 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001420 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001421 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001422 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001423 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001424 LVal.getLValueCallIndex() == 0) &&
1425 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001426
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001427 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1428 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001429 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001430 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001431 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001432
Hans Wennborg82dd8772014-06-25 22:19:48 +00001433 // A dllimport variable never acts like a constant.
1434 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001435 return false;
1436 }
1437 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1438 // __declspec(dllimport) must be handled very carefully:
1439 // We must never initialize an expression with the thunk in C++.
1440 // Doing otherwise would allow the same id-expression to yield
1441 // different addresses for the same function in different translation
1442 // units. However, this means that we must dynamically initialize the
1443 // expression with the contents of the import address table at runtime.
1444 //
1445 // The C language has no notion of ODR; furthermore, it has no notion of
1446 // dynamic initialization. This means that we are permitted to
1447 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001448 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001449 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001450 }
1451 }
1452
Richard Smitha8105bc2012-01-06 16:39:00 +00001453 // Allow address constant expressions to be past-the-end pointers. This is
1454 // an extension: the standard requires them to point to an object.
1455 if (!IsReferenceType)
1456 return true;
1457
1458 // A reference constant expression must refer to an object.
1459 if (!Base) {
1460 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001461 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001462 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001463 }
1464
Richard Smith357362d2011-12-13 06:39:58 +00001465 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001466 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001467 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001468 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001469 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001470 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001471 }
1472
Richard Smith80815602011-11-07 05:07:52 +00001473 return true;
1474}
1475
Richard Smithfddd3842011-12-30 21:15:51 +00001476/// Check that this core constant expression is of literal type, and if not,
1477/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001478static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001479 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001480 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001481 return true;
1482
Richard Smith7525ff62013-05-09 07:14:00 +00001483 // C++1y: A constant initializer for an object o [...] may also invoke
1484 // constexpr constructors for o and its subobjects even if those objects
1485 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001486 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001487 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001488 return true;
1489
Richard Smithfddd3842011-12-30 21:15:51 +00001490 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001491 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001492 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001493 << E->getType();
1494 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001495 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001496 return false;
1497}
1498
Richard Smith0b0a0b62011-10-29 20:57:55 +00001499/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001500/// constant expression. If not, report an appropriate diagnostic. Does not
1501/// check that the expression is of literal type.
1502static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1503 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001504 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001505 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001506 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001507 return false;
1508 }
1509
Richard Smith77be48a2014-07-31 06:31:19 +00001510 // We allow _Atomic(T) to be initialized from anything that T can be
1511 // initialized from.
1512 if (const AtomicType *AT = Type->getAs<AtomicType>())
1513 Type = AT->getValueType();
1514
Richard Smithb228a862012-02-15 02:18:13 +00001515 // Core issue 1454: For a literal constant expression of array or class type,
1516 // each subobject of its value shall have been initialized by a constant
1517 // expression.
1518 if (Value.isArray()) {
1519 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1520 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1521 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1522 Value.getArrayInitializedElt(I)))
1523 return false;
1524 }
1525 if (!Value.hasArrayFiller())
1526 return true;
1527 return CheckConstantExpression(Info, DiagLoc, EltTy,
1528 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001529 }
Richard Smithb228a862012-02-15 02:18:13 +00001530 if (Value.isUnion() && Value.getUnionField()) {
1531 return CheckConstantExpression(Info, DiagLoc,
1532 Value.getUnionField()->getType(),
1533 Value.getUnionValue());
1534 }
1535 if (Value.isStruct()) {
1536 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1537 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1538 unsigned BaseIndex = 0;
1539 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1540 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1541 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1542 Value.getStructBase(BaseIndex)))
1543 return false;
1544 }
1545 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001546 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001547 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1548 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001549 return false;
1550 }
1551 }
1552
1553 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001554 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001555 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001556 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1557 }
1558
1559 // Everything else is fine.
1560 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001561}
1562
Benjamin Kramer8407df72015-03-09 16:47:52 +00001563static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001564 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001565}
1566
1567static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001568 if (Value.CallIndex)
1569 return false;
1570 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1571 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001572}
1573
Richard Smithcecf1842011-11-01 21:06:14 +00001574static bool IsWeakLValue(const LValue &Value) {
1575 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001576 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001577}
1578
David Majnemerb5116032014-12-09 23:32:34 +00001579static bool isZeroSized(const LValue &Value) {
1580 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001581 if (Decl && isa<VarDecl>(Decl)) {
1582 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001583 if (Ty->isArrayType())
1584 return Ty->isIncompleteType() ||
1585 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001586 }
1587 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001588}
1589
Richard Smith2e312c82012-03-03 22:46:17 +00001590static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001591 // A null base expression indicates a null pointer. These are always
1592 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001593 if (!Value.getLValueBase()) {
1594 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001595 return true;
1596 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001597
Richard Smith027bf112011-11-17 22:56:20 +00001598 // We have a non-null base. These are generally known to be true, but if it's
1599 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001600 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001601 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001602 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001603}
1604
Richard Smith2e312c82012-03-03 22:46:17 +00001605static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001606 switch (Val.getKind()) {
1607 case APValue::Uninitialized:
1608 return false;
1609 case APValue::Int:
1610 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001611 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001612 case APValue::Float:
1613 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001614 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001615 case APValue::ComplexInt:
1616 Result = Val.getComplexIntReal().getBoolValue() ||
1617 Val.getComplexIntImag().getBoolValue();
1618 return true;
1619 case APValue::ComplexFloat:
1620 Result = !Val.getComplexFloatReal().isZero() ||
1621 !Val.getComplexFloatImag().isZero();
1622 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001623 case APValue::LValue:
1624 return EvalPointerValueAsBool(Val, Result);
1625 case APValue::MemberPointer:
1626 Result = Val.getMemberPointerDecl();
1627 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001628 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001629 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001630 case APValue::Struct:
1631 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001632 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001633 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001634 }
1635
Richard Smith11562c52011-10-28 17:51:58 +00001636 llvm_unreachable("unknown APValue kind");
1637}
1638
1639static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1640 EvalInfo &Info) {
1641 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001642 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001643 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001644 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001645 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001646}
1647
Richard Smith357362d2011-12-13 06:39:58 +00001648template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001649static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001650 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001651 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001652 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001653 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001654}
1655
1656static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1657 QualType SrcType, const APFloat &Value,
1658 QualType DestType, APSInt &Result) {
1659 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001660 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001661 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001662
Richard Smith357362d2011-12-13 06:39:58 +00001663 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001664 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001665 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1666 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001667 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001668 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001669}
1670
Richard Smith357362d2011-12-13 06:39:58 +00001671static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1672 QualType SrcType, QualType DestType,
1673 APFloat &Result) {
1674 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001675 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001676 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1677 APFloat::rmNearestTiesToEven, &ignored)
1678 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001679 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001680 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001681}
1682
Richard Smith911e1422012-01-30 22:27:01 +00001683static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1684 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001685 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001686 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001687 APSInt Result = Value;
1688 // Figure out if this is a truncate, extend or noop cast.
1689 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001690 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001691 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001692 return Result;
1693}
1694
Richard Smith357362d2011-12-13 06:39:58 +00001695static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1696 QualType SrcType, const APSInt &Value,
1697 QualType DestType, APFloat &Result) {
1698 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1699 if (Result.convertFromAPInt(Value, Value.isSigned(),
1700 APFloat::rmNearestTiesToEven)
1701 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001702 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001703 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001704}
1705
Richard Smith49ca8aa2013-08-06 07:09:20 +00001706static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1707 APValue &Value, const FieldDecl *FD) {
1708 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1709
1710 if (!Value.isInt()) {
1711 // Trying to store a pointer-cast-to-integer into a bitfield.
1712 // FIXME: In this case, we should provide the diagnostic for casting
1713 // a pointer to an integer.
1714 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001715 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001716 return false;
1717 }
1718
1719 APSInt &Int = Value.getInt();
1720 unsigned OldBitWidth = Int.getBitWidth();
1721 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1722 if (NewBitWidth < OldBitWidth)
1723 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1724 return true;
1725}
1726
Eli Friedman803acb32011-12-22 03:51:45 +00001727static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1728 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001729 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001730 if (!Evaluate(SVal, Info, E))
1731 return false;
1732 if (SVal.isInt()) {
1733 Res = SVal.getInt();
1734 return true;
1735 }
1736 if (SVal.isFloat()) {
1737 Res = SVal.getFloat().bitcastToAPInt();
1738 return true;
1739 }
1740 if (SVal.isVector()) {
1741 QualType VecTy = E->getType();
1742 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1743 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1744 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1745 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1746 Res = llvm::APInt::getNullValue(VecSize);
1747 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1748 APValue &Elt = SVal.getVectorElt(i);
1749 llvm::APInt EltAsInt;
1750 if (Elt.isInt()) {
1751 EltAsInt = Elt.getInt();
1752 } else if (Elt.isFloat()) {
1753 EltAsInt = Elt.getFloat().bitcastToAPInt();
1754 } else {
1755 // Don't try to handle vectors of anything other than int or float
1756 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001757 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001758 return false;
1759 }
1760 unsigned BaseEltSize = EltAsInt.getBitWidth();
1761 if (BigEndian)
1762 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1763 else
1764 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1765 }
1766 return true;
1767 }
1768 // Give up if the input isn't an int, float, or vector. For example, we
1769 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001770 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001771 return false;
1772}
1773
Richard Smith43e77732013-05-07 04:50:00 +00001774/// Perform the given integer operation, which is known to need at most BitWidth
1775/// bits, and check for overflow in the original type (if that type was not an
1776/// unsigned type).
1777template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001778static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1779 const APSInt &LHS, const APSInt &RHS,
1780 unsigned BitWidth, Operation Op,
1781 APSInt &Result) {
1782 if (LHS.isUnsigned()) {
1783 Result = Op(LHS, RHS);
1784 return true;
1785 }
Richard Smith43e77732013-05-07 04:50:00 +00001786
1787 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001788 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001789 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001790 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001791 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001792 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001793 << Result.toString(10) << E->getType();
1794 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001795 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001796 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001797 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001798}
1799
1800/// Perform the given binary integer operation.
1801static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1802 BinaryOperatorKind Opcode, APSInt RHS,
1803 APSInt &Result) {
1804 switch (Opcode) {
1805 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001806 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001807 return false;
1808 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001809 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1810 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001811 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001812 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1813 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001814 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001815 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1816 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001817 case BO_And: Result = LHS & RHS; return true;
1818 case BO_Xor: Result = LHS ^ RHS; return true;
1819 case BO_Or: Result = LHS | RHS; return true;
1820 case BO_Div:
1821 case BO_Rem:
1822 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001823 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00001824 return false;
1825 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001826 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1827 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1828 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001829 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1830 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001831 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1832 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001833 return true;
1834 case BO_Shl: {
1835 if (Info.getLangOpts().OpenCL)
1836 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1837 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1838 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1839 RHS.isUnsigned());
1840 else if (RHS.isSigned() && RHS.isNegative()) {
1841 // During constant-folding, a negative shift is an opposite shift. Such
1842 // a shift is not a constant expression.
1843 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1844 RHS = -RHS;
1845 goto shift_right;
1846 }
1847 shift_left:
1848 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1849 // the shifted type.
1850 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1851 if (SA != RHS) {
1852 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1853 << RHS << E->getType() << LHS.getBitWidth();
1854 } else if (LHS.isSigned()) {
1855 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1856 // operand, and must not overflow the corresponding unsigned type.
1857 if (LHS.isNegative())
1858 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1859 else if (LHS.countLeadingZeros() < SA)
1860 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1861 }
1862 Result = LHS << SA;
1863 return true;
1864 }
1865 case BO_Shr: {
1866 if (Info.getLangOpts().OpenCL)
1867 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1868 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1869 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1870 RHS.isUnsigned());
1871 else if (RHS.isSigned() && RHS.isNegative()) {
1872 // During constant-folding, a negative shift is an opposite shift. Such a
1873 // shift is not a constant expression.
1874 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1875 RHS = -RHS;
1876 goto shift_left;
1877 }
1878 shift_right:
1879 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1880 // shifted type.
1881 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1882 if (SA != RHS)
1883 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1884 << RHS << E->getType() << LHS.getBitWidth();
1885 Result = LHS >> SA;
1886 return true;
1887 }
1888
1889 case BO_LT: Result = LHS < RHS; return true;
1890 case BO_GT: Result = LHS > RHS; return true;
1891 case BO_LE: Result = LHS <= RHS; return true;
1892 case BO_GE: Result = LHS >= RHS; return true;
1893 case BO_EQ: Result = LHS == RHS; return true;
1894 case BO_NE: Result = LHS != RHS; return true;
1895 }
1896}
1897
Richard Smith861b5b52013-05-07 23:34:45 +00001898/// Perform the given binary floating-point operation, in-place, on LHS.
1899static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1900 APFloat &LHS, BinaryOperatorKind Opcode,
1901 const APFloat &RHS) {
1902 switch (Opcode) {
1903 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001904 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00001905 return false;
1906 case BO_Mul:
1907 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1908 break;
1909 case BO_Add:
1910 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1911 break;
1912 case BO_Sub:
1913 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1914 break;
1915 case BO_Div:
1916 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1917 break;
1918 }
1919
Richard Smith0c6124b2015-12-03 01:36:22 +00001920 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001921 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001922 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001923 }
Richard Smith861b5b52013-05-07 23:34:45 +00001924 return true;
1925}
1926
Richard Smitha8105bc2012-01-06 16:39:00 +00001927/// Cast an lvalue referring to a base subobject to a derived class, by
1928/// truncating the lvalue's path to the given length.
1929static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1930 const RecordDecl *TruncatedType,
1931 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001932 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001933
1934 // Check we actually point to a derived class object.
1935 if (TruncatedElements == D.Entries.size())
1936 return true;
1937 assert(TruncatedElements >= D.MostDerivedPathLength &&
1938 "not casting to a derived class");
1939 if (!Result.checkSubobject(Info, E, CSK_Derived))
1940 return false;
1941
1942 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001943 const RecordDecl *RD = TruncatedType;
1944 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001945 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001946 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1947 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001948 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001949 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001950 else
Richard Smithd62306a2011-11-10 06:34:14 +00001951 Result.Offset -= Layout.getBaseClassOffset(Base);
1952 RD = Base;
1953 }
Richard Smith027bf112011-11-17 22:56:20 +00001954 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001955 return true;
1956}
1957
John McCalld7bca762012-05-01 00:38:49 +00001958static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001959 const CXXRecordDecl *Derived,
1960 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001961 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001962 if (!RL) {
1963 if (Derived->isInvalidDecl()) return false;
1964 RL = &Info.Ctx.getASTRecordLayout(Derived);
1965 }
1966
Richard Smithd62306a2011-11-10 06:34:14 +00001967 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001968 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001969 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001970}
1971
Richard Smitha8105bc2012-01-06 16:39:00 +00001972static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001973 const CXXRecordDecl *DerivedDecl,
1974 const CXXBaseSpecifier *Base) {
1975 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1976
John McCalld7bca762012-05-01 00:38:49 +00001977 if (!Base->isVirtual())
1978 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001979
Richard Smitha8105bc2012-01-06 16:39:00 +00001980 SubobjectDesignator &D = Obj.Designator;
1981 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001982 return false;
1983
Richard Smitha8105bc2012-01-06 16:39:00 +00001984 // Extract most-derived object and corresponding type.
1985 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1986 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1987 return false;
1988
1989 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001990 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001991 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1992 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001993 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001994 return true;
1995}
1996
Richard Smith84401042013-06-03 05:03:02 +00001997static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1998 QualType Type, LValue &Result) {
1999 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2000 PathE = E->path_end();
2001 PathI != PathE; ++PathI) {
2002 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2003 *PathI))
2004 return false;
2005 Type = (*PathI)->getType();
2006 }
2007 return true;
2008}
2009
Richard Smithd62306a2011-11-10 06:34:14 +00002010/// Update LVal to refer to the given field, which must be a member of the type
2011/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002012static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002013 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002014 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002015 if (!RL) {
2016 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002017 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002018 }
Richard Smithd62306a2011-11-10 06:34:14 +00002019
2020 unsigned I = FD->getFieldIndex();
2021 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00002022 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002023 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002024}
2025
Richard Smith1b78b3d2012-01-25 22:15:11 +00002026/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002027static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002028 LValue &LVal,
2029 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002030 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002031 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002032 return false;
2033 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002034}
2035
Richard Smithd62306a2011-11-10 06:34:14 +00002036/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002037static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2038 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002039 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2040 // extension.
2041 if (Type->isVoidType() || Type->isFunctionType()) {
2042 Size = CharUnits::One();
2043 return true;
2044 }
2045
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002046 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002047 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002048 return false;
2049 }
2050
Richard Smithd62306a2011-11-10 06:34:14 +00002051 if (!Type->isConstantSizeType()) {
2052 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002053 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002054 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002055 return false;
2056 }
2057
2058 Size = Info.Ctx.getTypeSizeInChars(Type);
2059 return true;
2060}
2061
2062/// Update a pointer value to model pointer arithmetic.
2063/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002064/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002065/// \param LVal - The pointer value to be updated.
2066/// \param EltTy - The pointee type represented by LVal.
2067/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002068static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2069 LValue &LVal, QualType EltTy,
2070 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002071 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002072 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002073 return false;
2074
2075 // Compute the new offset in the appropriate width.
2076 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00002077 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00002078 return true;
2079}
2080
Richard Smith66c96992012-02-18 22:04:06 +00002081/// Update an lvalue to refer to a component of a complex number.
2082/// \param Info - Information about the ongoing evaluation.
2083/// \param LVal - The lvalue to be updated.
2084/// \param EltTy - The complex number's component type.
2085/// \param Imag - False for the real component, true for the imaginary.
2086static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2087 LValue &LVal, QualType EltTy,
2088 bool Imag) {
2089 if (Imag) {
2090 CharUnits SizeOfComponent;
2091 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2092 return false;
2093 LVal.Offset += SizeOfComponent;
2094 }
2095 LVal.addComplex(Info, E, EltTy, Imag);
2096 return true;
2097}
2098
Richard Smith27908702011-10-24 17:54:18 +00002099/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002100///
2101/// \param Info Information about the ongoing evaluation.
2102/// \param E An expression to be used when printing diagnostics.
2103/// \param VD The variable whose initializer should be obtained.
2104/// \param Frame The frame in which the variable was created. Must be null
2105/// if this variable is not local to the evaluation.
2106/// \param Result Filled in with a pointer to the value of the variable.
2107static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2108 const VarDecl *VD, CallStackFrame *Frame,
2109 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002110 // If this is a parameter to an active constexpr function call, perform
2111 // argument substitution.
2112 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002113 // Assume arguments of a potential constant expression are unknown
2114 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002115 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002116 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002117 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002118 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002119 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002120 }
Richard Smith3229b742013-05-05 21:17:10 +00002121 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002122 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002123 }
Richard Smith27908702011-10-24 17:54:18 +00002124
Richard Smithd9f663b2013-04-22 15:31:51 +00002125 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002126 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002127 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002128 if (!Result) {
2129 // Assume variables referenced within a lambda's call operator that were
2130 // not declared within the call operator are captures and during checking
2131 // of a potential constant expression, assume they are unknown constant
2132 // expressions.
2133 assert(isLambdaCallOperator(Frame->Callee) &&
2134 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2135 "missing value for local variable");
2136 if (Info.checkingPotentialConstantExpression())
2137 return false;
2138 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002139 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002140 diag::note_unimplemented_constexpr_lambda_feature_ast)
2141 << "captures not currently allowed";
2142 return false;
2143 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002144 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002145 }
2146
Richard Smithd0b4dd62011-12-19 06:19:21 +00002147 // Dig out the initializer, and use the declaration which it's attached to.
2148 const Expr *Init = VD->getAnyInitializer(VD);
2149 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002150 // If we're checking a potential constant expression, the variable could be
2151 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002152 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002153 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002154 return false;
2155 }
2156
Richard Smithd62306a2011-11-10 06:34:14 +00002157 // If we're currently evaluating the initializer of this declaration, use that
2158 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002159 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002160 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002161 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002162 }
2163
Richard Smithcecf1842011-11-01 21:06:14 +00002164 // Never evaluate the initializer of a weak variable. We can't be sure that
2165 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002166 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002167 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002168 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002169 }
Richard Smithcecf1842011-11-01 21:06:14 +00002170
Richard Smithd0b4dd62011-12-19 06:19:21 +00002171 // Check that we can fold the initializer. In C++, we will have already done
2172 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002173 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002174 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002175 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002176 Notes.size() + 1) << VD;
2177 Info.Note(VD->getLocation(), diag::note_declared_at);
2178 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002179 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002180 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002181 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002182 Notes.size() + 1) << VD;
2183 Info.Note(VD->getLocation(), diag::note_declared_at);
2184 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002185 }
Richard Smith27908702011-10-24 17:54:18 +00002186
Richard Smith3229b742013-05-05 21:17:10 +00002187 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002188 return true;
Richard Smith27908702011-10-24 17:54:18 +00002189}
2190
Richard Smith11562c52011-10-28 17:51:58 +00002191static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002192 Qualifiers Quals = T.getQualifiers();
2193 return Quals.hasConst() && !Quals.hasVolatile();
2194}
2195
Richard Smithe97cbd72011-11-11 04:05:33 +00002196/// Get the base index of the given base class within an APValue representing
2197/// the given derived class.
2198static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2199 const CXXRecordDecl *Base) {
2200 Base = Base->getCanonicalDecl();
2201 unsigned Index = 0;
2202 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2203 E = Derived->bases_end(); I != E; ++I, ++Index) {
2204 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2205 return Index;
2206 }
2207
2208 llvm_unreachable("base class missing from derived class's bases list");
2209}
2210
Richard Smith3da88fa2013-04-26 14:36:30 +00002211/// Extract the value of a character from a string literal.
2212static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2213 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002214 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2215 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2216 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002217 const StringLiteral *S = cast<StringLiteral>(Lit);
2218 const ConstantArrayType *CAT =
2219 Info.Ctx.getAsConstantArrayType(S->getType());
2220 assert(CAT && "string literal isn't an array");
2221 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002222 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002223
2224 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002225 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002226 if (Index < S->getLength())
2227 Value = S->getCodeUnit(Index);
2228 return Value;
2229}
2230
Richard Smith3da88fa2013-04-26 14:36:30 +00002231// Expand a string literal into an array of characters.
2232static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2233 APValue &Result) {
2234 const StringLiteral *S = cast<StringLiteral>(Lit);
2235 const ConstantArrayType *CAT =
2236 Info.Ctx.getAsConstantArrayType(S->getType());
2237 assert(CAT && "string literal isn't an array");
2238 QualType CharType = CAT->getElementType();
2239 assert(CharType->isIntegerType() && "unexpected character type");
2240
2241 unsigned Elts = CAT->getSize().getZExtValue();
2242 Result = APValue(APValue::UninitArray(),
2243 std::min(S->getLength(), Elts), Elts);
2244 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2245 CharType->isUnsignedIntegerType());
2246 if (Result.hasArrayFiller())
2247 Result.getArrayFiller() = APValue(Value);
2248 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2249 Value = S->getCodeUnit(I);
2250 Result.getArrayInitializedElt(I) = APValue(Value);
2251 }
2252}
2253
2254// Expand an array so that it has more than Index filled elements.
2255static void expandArray(APValue &Array, unsigned Index) {
2256 unsigned Size = Array.getArraySize();
2257 assert(Index < Size);
2258
2259 // Always at least double the number of elements for which we store a value.
2260 unsigned OldElts = Array.getArrayInitializedElts();
2261 unsigned NewElts = std::max(Index+1, OldElts * 2);
2262 NewElts = std::min(Size, std::max(NewElts, 8u));
2263
2264 // Copy the data across.
2265 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2266 for (unsigned I = 0; I != OldElts; ++I)
2267 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2268 for (unsigned I = OldElts; I != NewElts; ++I)
2269 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2270 if (NewValue.hasArrayFiller())
2271 NewValue.getArrayFiller() = Array.getArrayFiller();
2272 Array.swap(NewValue);
2273}
2274
Richard Smithb01fe402014-09-16 01:24:02 +00002275/// Determine whether a type would actually be read by an lvalue-to-rvalue
2276/// conversion. If it's of class type, we may assume that the copy operation
2277/// is trivial. Note that this is never true for a union type with fields
2278/// (because the copy always "reads" the active member) and always true for
2279/// a non-class type.
2280static bool isReadByLvalueToRvalueConversion(QualType T) {
2281 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2282 if (!RD || (RD->isUnion() && !RD->field_empty()))
2283 return true;
2284 if (RD->isEmpty())
2285 return false;
2286
2287 for (auto *Field : RD->fields())
2288 if (isReadByLvalueToRvalueConversion(Field->getType()))
2289 return true;
2290
2291 for (auto &BaseSpec : RD->bases())
2292 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2293 return true;
2294
2295 return false;
2296}
2297
2298/// Diagnose an attempt to read from any unreadable field within the specified
2299/// type, which might be a class type.
2300static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2301 QualType T) {
2302 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2303 if (!RD)
2304 return false;
2305
2306 if (!RD->hasMutableFields())
2307 return false;
2308
2309 for (auto *Field : RD->fields()) {
2310 // If we're actually going to read this field in some way, then it can't
2311 // be mutable. If we're in a union, then assigning to a mutable field
2312 // (even an empty one) can change the active member, so that's not OK.
2313 // FIXME: Add core issue number for the union case.
2314 if (Field->isMutable() &&
2315 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002316 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002317 Info.Note(Field->getLocation(), diag::note_declared_at);
2318 return true;
2319 }
2320
2321 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2322 return true;
2323 }
2324
2325 for (auto &BaseSpec : RD->bases())
2326 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2327 return true;
2328
2329 // All mutable fields were empty, and thus not actually read.
2330 return false;
2331}
2332
Richard Smith861b5b52013-05-07 23:34:45 +00002333/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002334enum AccessKinds {
2335 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002336 AK_Assign,
2337 AK_Increment,
2338 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002339};
2340
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002341namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002342/// A handle to a complete object (an object that is not a subobject of
2343/// another object).
2344struct CompleteObject {
2345 /// The value of the complete object.
2346 APValue *Value;
2347 /// The type of the complete object.
2348 QualType Type;
2349
Craig Topper36250ad2014-05-12 05:36:57 +00002350 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002351 CompleteObject(APValue *Value, QualType Type)
2352 : Value(Value), Type(Type) {
2353 assert(Value && "missing value for complete object");
2354 }
2355
Aaron Ballman67347662015-02-15 22:00:28 +00002356 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002357};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002358} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002359
Richard Smith3da88fa2013-04-26 14:36:30 +00002360/// Find the designated sub-object of an rvalue.
2361template<typename SubobjectHandler>
2362typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002363findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002364 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002365 if (Sub.Invalid)
2366 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002367 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002368 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002369 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002370 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002371 << handler.AccessKind;
2372 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002373 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002374 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002375 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002376
Richard Smith3229b742013-05-05 21:17:10 +00002377 APValue *O = Obj.Value;
2378 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002379 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002380
Richard Smithd62306a2011-11-10 06:34:14 +00002381 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002382 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2383 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002384 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002385 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002386 return handler.failed();
2387 }
2388
Richard Smith49ca8aa2013-08-06 07:09:20 +00002389 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002390 // If we are reading an object of class type, there may still be more
2391 // things we need to check: if there are any mutable subobjects, we
2392 // cannot perform this read. (This only happens when performing a trivial
2393 // copy or assignment.)
2394 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2395 diagnoseUnreadableFields(Info, E, ObjType))
2396 return handler.failed();
2397
Richard Smith49ca8aa2013-08-06 07:09:20 +00002398 if (!handler.found(*O, ObjType))
2399 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002400
Richard Smith49ca8aa2013-08-06 07:09:20 +00002401 // If we modified a bit-field, truncate it to the right width.
2402 if (handler.AccessKind != AK_Read &&
2403 LastField && LastField->isBitField() &&
2404 !truncateBitfieldValue(Info, E, *O, LastField))
2405 return false;
2406
2407 return true;
2408 }
2409
Craig Topper36250ad2014-05-12 05:36:57 +00002410 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002411 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002412 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002413 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002414 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002415 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002416 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002417 // Note, it should not be possible to form a pointer with a valid
2418 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002419 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002420 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002421 << handler.AccessKind;
2422 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002423 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002424 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002425 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002426
2427 ObjType = CAT->getElementType();
2428
Richard Smith14a94132012-02-17 03:35:37 +00002429 // An array object is represented as either an Array APValue or as an
2430 // LValue which refers to a string literal.
2431 if (O->isLValue()) {
2432 assert(I == N - 1 && "extracting subobject of character?");
2433 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002434 if (handler.AccessKind != AK_Read)
2435 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2436 *O);
2437 else
2438 return handler.foundString(*O, ObjType, Index);
2439 }
2440
2441 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002442 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002443 else if (handler.AccessKind != AK_Read) {
2444 expandArray(*O, Index);
2445 O = &O->getArrayInitializedElt(Index);
2446 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002447 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002448 } else if (ObjType->isAnyComplexType()) {
2449 // Next subobject is a complex number.
2450 uint64_t Index = Sub.Entries[I].ArrayIndex;
2451 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002452 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002453 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002454 << handler.AccessKind;
2455 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002456 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002457 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002458 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002459
2460 bool WasConstQualified = ObjType.isConstQualified();
2461 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2462 if (WasConstQualified)
2463 ObjType.addConst();
2464
Richard Smith66c96992012-02-18 22:04:06 +00002465 assert(I == N - 1 && "extracting subobject of scalar?");
2466 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002467 return handler.found(Index ? O->getComplexIntImag()
2468 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002469 } else {
2470 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002471 return handler.found(Index ? O->getComplexFloatImag()
2472 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002473 }
Richard Smithd62306a2011-11-10 06:34:14 +00002474 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002475 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002476 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002477 << Field;
2478 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002479 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002480 }
2481
Richard Smithd62306a2011-11-10 06:34:14 +00002482 // Next subobject is a class, struct or union field.
2483 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2484 if (RD->isUnion()) {
2485 const FieldDecl *UnionField = O->getUnionField();
2486 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002487 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002488 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002489 << handler.AccessKind << Field << !UnionField << UnionField;
2490 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002491 }
Richard Smithd62306a2011-11-10 06:34:14 +00002492 O = &O->getUnionValue();
2493 } else
2494 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002495
2496 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002497 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002498 if (WasConstQualified && !Field->isMutable())
2499 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002500
2501 if (ObjType.isVolatileQualified()) {
2502 if (Info.getLangOpts().CPlusPlus) {
2503 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002504 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002505 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002506 Info.Note(Field->getLocation(), diag::note_declared_at);
2507 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002508 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002509 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002510 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002511 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002512
2513 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002514 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002515 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002516 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2517 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2518 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002519
2520 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002521 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002522 if (WasConstQualified)
2523 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002524 }
2525 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002526}
2527
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002528namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002529struct ExtractSubobjectHandler {
2530 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002531 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002532
2533 static const AccessKinds AccessKind = AK_Read;
2534
2535 typedef bool result_type;
2536 bool failed() { return false; }
2537 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002538 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002539 return true;
2540 }
2541 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002542 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002543 return true;
2544 }
2545 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002546 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002547 return true;
2548 }
2549 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002550 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002551 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2552 return true;
2553 }
2554};
Richard Smith3229b742013-05-05 21:17:10 +00002555} // end anonymous namespace
2556
Richard Smith3da88fa2013-04-26 14:36:30 +00002557const AccessKinds ExtractSubobjectHandler::AccessKind;
2558
2559/// Extract the designated sub-object of an rvalue.
2560static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002561 const CompleteObject &Obj,
2562 const SubobjectDesignator &Sub,
2563 APValue &Result) {
2564 ExtractSubobjectHandler Handler = { Info, Result };
2565 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002566}
2567
Richard Smith3229b742013-05-05 21:17:10 +00002568namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002569struct ModifySubobjectHandler {
2570 EvalInfo &Info;
2571 APValue &NewVal;
2572 const Expr *E;
2573
2574 typedef bool result_type;
2575 static const AccessKinds AccessKind = AK_Assign;
2576
2577 bool checkConst(QualType QT) {
2578 // Assigning to a const object has undefined behavior.
2579 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002580 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002581 return false;
2582 }
2583 return true;
2584 }
2585
2586 bool failed() { return false; }
2587 bool found(APValue &Subobj, QualType SubobjType) {
2588 if (!checkConst(SubobjType))
2589 return false;
2590 // We've been given ownership of NewVal, so just swap it in.
2591 Subobj.swap(NewVal);
2592 return true;
2593 }
2594 bool found(APSInt &Value, QualType SubobjType) {
2595 if (!checkConst(SubobjType))
2596 return false;
2597 if (!NewVal.isInt()) {
2598 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002599 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002600 return false;
2601 }
2602 Value = NewVal.getInt();
2603 return true;
2604 }
2605 bool found(APFloat &Value, QualType SubobjType) {
2606 if (!checkConst(SubobjType))
2607 return false;
2608 Value = NewVal.getFloat();
2609 return true;
2610 }
2611 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2612 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2613 }
2614};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002615} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002616
Richard Smith3229b742013-05-05 21:17:10 +00002617const AccessKinds ModifySubobjectHandler::AccessKind;
2618
Richard Smith3da88fa2013-04-26 14:36:30 +00002619/// Update the designated sub-object of an rvalue to the given value.
2620static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002621 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002622 const SubobjectDesignator &Sub,
2623 APValue &NewVal) {
2624 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002625 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002626}
2627
Richard Smith84f6dcf2012-02-02 01:16:57 +00002628/// Find the position where two subobject designators diverge, or equivalently
2629/// the length of the common initial subsequence.
2630static unsigned FindDesignatorMismatch(QualType ObjType,
2631 const SubobjectDesignator &A,
2632 const SubobjectDesignator &B,
2633 bool &WasArrayIndex) {
2634 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2635 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002636 if (!ObjType.isNull() &&
2637 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002638 // Next subobject is an array element.
2639 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2640 WasArrayIndex = true;
2641 return I;
2642 }
Richard Smith66c96992012-02-18 22:04:06 +00002643 if (ObjType->isAnyComplexType())
2644 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2645 else
2646 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002647 } else {
2648 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2649 WasArrayIndex = false;
2650 return I;
2651 }
2652 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2653 // Next subobject is a field.
2654 ObjType = FD->getType();
2655 else
2656 // Next subobject is a base class.
2657 ObjType = QualType();
2658 }
2659 }
2660 WasArrayIndex = false;
2661 return I;
2662}
2663
2664/// Determine whether the given subobject designators refer to elements of the
2665/// same array object.
2666static bool AreElementsOfSameArray(QualType ObjType,
2667 const SubobjectDesignator &A,
2668 const SubobjectDesignator &B) {
2669 if (A.Entries.size() != B.Entries.size())
2670 return false;
2671
George Burgess IVa51c4072015-10-16 01:49:01 +00002672 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002673 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2674 // A is a subobject of the array element.
2675 return false;
2676
2677 // If A (and B) designates an array element, the last entry will be the array
2678 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2679 // of length 1' case, and the entire path must match.
2680 bool WasArrayIndex;
2681 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2682 return CommonLength >= A.Entries.size() - IsArray;
2683}
2684
Richard Smith3229b742013-05-05 21:17:10 +00002685/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002686static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2687 AccessKinds AK, const LValue &LVal,
2688 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002689 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002690 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002691 return CompleteObject();
2692 }
2693
Craig Topper36250ad2014-05-12 05:36:57 +00002694 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002695 if (LVal.CallIndex) {
2696 Frame = Info.getCallFrame(LVal.CallIndex);
2697 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002698 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002699 << AK << LVal.Base.is<const ValueDecl*>();
2700 NoteLValueLocation(Info, LVal.Base);
2701 return CompleteObject();
2702 }
Richard Smith3229b742013-05-05 21:17:10 +00002703 }
2704
2705 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2706 // is not a constant expression (even if the object is non-volatile). We also
2707 // apply this rule to C++98, in order to conform to the expected 'volatile'
2708 // semantics.
2709 if (LValType.isVolatileQualified()) {
2710 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002711 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002712 << AK << LValType;
2713 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002714 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002715 return CompleteObject();
2716 }
2717
2718 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002719 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002720 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002721
2722 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2723 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2724 // In C++11, constexpr, non-volatile variables initialized with constant
2725 // expressions are constant expressions too. Inside constexpr functions,
2726 // parameters are constant expressions even if they're non-const.
2727 // In C++1y, objects local to a constant expression (those with a Frame) are
2728 // both readable and writable inside constant expressions.
2729 // In C, such things can also be folded, although they are not ICEs.
2730 const VarDecl *VD = dyn_cast<VarDecl>(D);
2731 if (VD) {
2732 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2733 VD = VDef;
2734 }
2735 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002736 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002737 return CompleteObject();
2738 }
2739
2740 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002741 if (BaseType.isVolatileQualified()) {
2742 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002743 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002744 << AK << 1 << VD;
2745 Info.Note(VD->getLocation(), diag::note_declared_at);
2746 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002747 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002748 }
2749 return CompleteObject();
2750 }
2751
2752 // Unless we're looking at a local variable or argument in a constexpr call,
2753 // the variable we're reading must be const.
2754 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002755 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002756 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2757 // OK, we can read and modify an object if we're in the process of
2758 // evaluating its initializer, because its lifetime began in this
2759 // evaluation.
2760 } else if (AK != AK_Read) {
2761 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002762 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002763 return CompleteObject();
2764 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002765 // OK, we can read this variable.
2766 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002767 // In OpenCL if a variable is in constant address space it is a const value.
2768 if (!(BaseType.isConstQualified() ||
2769 (Info.getLangOpts().OpenCL &&
2770 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002771 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002772 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002773 Info.Note(VD->getLocation(), diag::note_declared_at);
2774 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002775 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002776 }
2777 return CompleteObject();
2778 }
2779 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2780 // We support folding of const floating-point types, in order to make
2781 // static const data members of such types (supported as an extension)
2782 // more useful.
2783 if (Info.getLangOpts().CPlusPlus11) {
2784 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2785 Info.Note(VD->getLocation(), diag::note_declared_at);
2786 } else {
2787 Info.CCEDiag(E);
2788 }
2789 } else {
2790 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002791 if (Info.checkingPotentialConstantExpression() &&
2792 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2793 // The definition of this variable could be constexpr. We can't
2794 // access it right now, but may be able to in future.
2795 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002796 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002797 Info.Note(VD->getLocation(), diag::note_declared_at);
2798 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002799 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002800 }
2801 return CompleteObject();
2802 }
2803 }
2804
2805 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2806 return CompleteObject();
2807 } else {
2808 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2809
2810 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002811 if (const MaterializeTemporaryExpr *MTE =
2812 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2813 assert(MTE->getStorageDuration() == SD_Static &&
2814 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002815
Richard Smithe6c01442013-06-05 00:46:14 +00002816 // Per C++1y [expr.const]p2:
2817 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2818 // - a [...] glvalue of integral or enumeration type that refers to
2819 // a non-volatile const object [...]
2820 // [...]
2821 // - a [...] glvalue of literal type that refers to a non-volatile
2822 // object whose lifetime began within the evaluation of e.
2823 //
2824 // C++11 misses the 'began within the evaluation of e' check and
2825 // instead allows all temporaries, including things like:
2826 // int &&r = 1;
2827 // int x = ++r;
2828 // constexpr int k = r;
2829 // Therefore we use the C++1y rules in C++11 too.
2830 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2831 const ValueDecl *ED = MTE->getExtendingDecl();
2832 if (!(BaseType.isConstQualified() &&
2833 BaseType->isIntegralOrEnumerationType()) &&
2834 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002835 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00002836 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2837 return CompleteObject();
2838 }
2839
2840 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2841 assert(BaseVal && "got reference to unevaluated temporary");
2842 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002843 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00002844 return CompleteObject();
2845 }
2846 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002847 BaseVal = Frame->getTemporary(Base);
2848 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002849 }
Richard Smith3229b742013-05-05 21:17:10 +00002850
2851 // Volatile temporary objects cannot be accessed in constant expressions.
2852 if (BaseType.isVolatileQualified()) {
2853 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002854 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002855 << AK << 0;
2856 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2857 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002858 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002859 }
2860 return CompleteObject();
2861 }
2862 }
2863
Richard Smith7525ff62013-05-09 07:14:00 +00002864 // During the construction of an object, it is not yet 'const'.
2865 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2866 // and this doesn't do quite the right thing for const subobjects of the
2867 // object under construction.
2868 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2869 BaseType = Info.Ctx.getCanonicalType(BaseType);
2870 BaseType.removeLocalConst();
2871 }
2872
Richard Smith6d4c6582013-11-05 22:18:15 +00002873 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00002874 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00002875 //
2876 // FIXME: Not all local state is mutable. Allow local constant subobjects
2877 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00002878 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2879 Info.EvalStatus.HasSideEffects) ||
2880 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00002881 return CompleteObject();
2882
2883 return CompleteObject(BaseVal, BaseType);
2884}
2885
Richard Smith243ef902013-05-05 23:31:59 +00002886/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2887/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2888/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002889///
2890/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002891/// \param Conv - The expression for which we are performing the conversion.
2892/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002893/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2894/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002895/// \param LVal - The glvalue on which we are attempting to perform this action.
2896/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002897static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002898 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002899 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002900 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002901 return false;
2902
Richard Smith3229b742013-05-05 21:17:10 +00002903 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002904 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002905 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002906 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2907 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2908 // initializer until now for such expressions. Such an expression can't be
2909 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00002910 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002911 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002912 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002913 }
Richard Smith3229b742013-05-05 21:17:10 +00002914 APValue Lit;
2915 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2916 return false;
2917 CompleteObject LitObj(&Lit, Base->getType());
2918 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002919 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002920 // We represent a string literal array as an lvalue pointing at the
2921 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002922 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002923 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2924 CompleteObject StrObj(&Str, Base->getType());
2925 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002926 }
Richard Smith11562c52011-10-28 17:51:58 +00002927 }
2928
Richard Smith3229b742013-05-05 21:17:10 +00002929 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2930 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002931}
2932
2933/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002934static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002935 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002936 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002937 return false;
2938
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002939 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002940 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002941 return false;
2942 }
2943
Richard Smith3229b742013-05-05 21:17:10 +00002944 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2945 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002946}
2947
Richard Smith243ef902013-05-05 23:31:59 +00002948static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2949 return T->isSignedIntegerType() &&
2950 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2951}
2952
2953namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002954struct CompoundAssignSubobjectHandler {
2955 EvalInfo &Info;
2956 const Expr *E;
2957 QualType PromotedLHSType;
2958 BinaryOperatorKind Opcode;
2959 const APValue &RHS;
2960
2961 static const AccessKinds AccessKind = AK_Assign;
2962
2963 typedef bool result_type;
2964
2965 bool checkConst(QualType QT) {
2966 // Assigning to a const object has undefined behavior.
2967 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002968 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00002969 return false;
2970 }
2971 return true;
2972 }
2973
2974 bool failed() { return false; }
2975 bool found(APValue &Subobj, QualType SubobjType) {
2976 switch (Subobj.getKind()) {
2977 case APValue::Int:
2978 return found(Subobj.getInt(), SubobjType);
2979 case APValue::Float:
2980 return found(Subobj.getFloat(), SubobjType);
2981 case APValue::ComplexInt:
2982 case APValue::ComplexFloat:
2983 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00002984 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002985 return false;
2986 case APValue::LValue:
2987 return foundPointer(Subobj, SubobjType);
2988 default:
2989 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00002990 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002991 return false;
2992 }
2993 }
2994 bool found(APSInt &Value, QualType SubobjType) {
2995 if (!checkConst(SubobjType))
2996 return false;
2997
2998 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2999 // We don't support compound assignment on integer-cast-to-pointer
3000 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003001 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003002 return false;
3003 }
3004
3005 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3006 SubobjType, Value);
3007 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3008 return false;
3009 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3010 return true;
3011 }
3012 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003013 return checkConst(SubobjType) &&
3014 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3015 Value) &&
3016 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3017 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003018 }
3019 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3020 if (!checkConst(SubobjType))
3021 return false;
3022
3023 QualType PointeeType;
3024 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3025 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003026
3027 if (PointeeType.isNull() || !RHS.isInt() ||
3028 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003029 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003030 return false;
3031 }
3032
Richard Smith861b5b52013-05-07 23:34:45 +00003033 int64_t Offset = getExtValue(RHS.getInt());
3034 if (Opcode == BO_Sub)
3035 Offset = -Offset;
3036
3037 LValue LVal;
3038 LVal.setFrom(Info.Ctx, Subobj);
3039 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3040 return false;
3041 LVal.moveInto(Subobj);
3042 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003043 }
3044 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3045 llvm_unreachable("shouldn't encounter string elements here");
3046 }
3047};
3048} // end anonymous namespace
3049
3050const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3051
3052/// Perform a compound assignment of LVal <op>= RVal.
3053static bool handleCompoundAssignment(
3054 EvalInfo &Info, const Expr *E,
3055 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3056 BinaryOperatorKind Opcode, const APValue &RVal) {
3057 if (LVal.Designator.Invalid)
3058 return false;
3059
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003060 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003061 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003062 return false;
3063 }
3064
3065 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3066 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3067 RVal };
3068 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3069}
3070
3071namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003072struct IncDecSubobjectHandler {
3073 EvalInfo &Info;
3074 const Expr *E;
3075 AccessKinds AccessKind;
3076 APValue *Old;
3077
3078 typedef bool result_type;
3079
3080 bool checkConst(QualType QT) {
3081 // Assigning to a const object has undefined behavior.
3082 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003083 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003084 return false;
3085 }
3086 return true;
3087 }
3088
3089 bool failed() { return false; }
3090 bool found(APValue &Subobj, QualType SubobjType) {
3091 // Stash the old value. Also clear Old, so we don't clobber it later
3092 // if we're post-incrementing a complex.
3093 if (Old) {
3094 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003095 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003096 }
3097
3098 switch (Subobj.getKind()) {
3099 case APValue::Int:
3100 return found(Subobj.getInt(), SubobjType);
3101 case APValue::Float:
3102 return found(Subobj.getFloat(), SubobjType);
3103 case APValue::ComplexInt:
3104 return found(Subobj.getComplexIntReal(),
3105 SubobjType->castAs<ComplexType>()->getElementType()
3106 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3107 case APValue::ComplexFloat:
3108 return found(Subobj.getComplexFloatReal(),
3109 SubobjType->castAs<ComplexType>()->getElementType()
3110 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3111 case APValue::LValue:
3112 return foundPointer(Subobj, SubobjType);
3113 default:
3114 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003115 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003116 return false;
3117 }
3118 }
3119 bool found(APSInt &Value, QualType SubobjType) {
3120 if (!checkConst(SubobjType))
3121 return false;
3122
3123 if (!SubobjType->isIntegerType()) {
3124 // We don't support increment / decrement on integer-cast-to-pointer
3125 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003126 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003127 return false;
3128 }
3129
3130 if (Old) *Old = APValue(Value);
3131
3132 // bool arithmetic promotes to int, and the conversion back to bool
3133 // doesn't reduce mod 2^n, so special-case it.
3134 if (SubobjType->isBooleanType()) {
3135 if (AccessKind == AK_Increment)
3136 Value = 1;
3137 else
3138 Value = !Value;
3139 return true;
3140 }
3141
3142 bool WasNegative = Value.isNegative();
3143 if (AccessKind == AK_Increment) {
3144 ++Value;
3145
3146 if (!WasNegative && Value.isNegative() &&
3147 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3148 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003149 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003150 }
3151 } else {
3152 --Value;
3153
3154 if (WasNegative && !Value.isNegative() &&
3155 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3156 unsigned BitWidth = Value.getBitWidth();
3157 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3158 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003159 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003160 }
3161 }
3162 return true;
3163 }
3164 bool found(APFloat &Value, QualType SubobjType) {
3165 if (!checkConst(SubobjType))
3166 return false;
3167
3168 if (Old) *Old = APValue(Value);
3169
3170 APFloat One(Value.getSemantics(), 1);
3171 if (AccessKind == AK_Increment)
3172 Value.add(One, APFloat::rmNearestTiesToEven);
3173 else
3174 Value.subtract(One, APFloat::rmNearestTiesToEven);
3175 return true;
3176 }
3177 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3178 if (!checkConst(SubobjType))
3179 return false;
3180
3181 QualType PointeeType;
3182 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3183 PointeeType = PT->getPointeeType();
3184 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003185 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003186 return false;
3187 }
3188
3189 LValue LVal;
3190 LVal.setFrom(Info.Ctx, Subobj);
3191 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3192 AccessKind == AK_Increment ? 1 : -1))
3193 return false;
3194 LVal.moveInto(Subobj);
3195 return true;
3196 }
3197 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3198 llvm_unreachable("shouldn't encounter string elements here");
3199 }
3200};
3201} // end anonymous namespace
3202
3203/// Perform an increment or decrement on LVal.
3204static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3205 QualType LValType, bool IsIncrement, APValue *Old) {
3206 if (LVal.Designator.Invalid)
3207 return false;
3208
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003209 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003210 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003211 return false;
3212 }
3213
3214 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3215 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3216 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3217 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3218}
3219
Richard Smithe97cbd72011-11-11 04:05:33 +00003220/// Build an lvalue for the object argument of a member function call.
3221static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3222 LValue &This) {
3223 if (Object->getType()->isPointerType())
3224 return EvaluatePointer(Object, This, Info);
3225
3226 if (Object->isGLValue())
3227 return EvaluateLValue(Object, This, Info);
3228
Richard Smithd9f663b2013-04-22 15:31:51 +00003229 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003230 return EvaluateTemporary(Object, This, Info);
3231
Faisal Valie690b7a2016-07-02 22:34:24 +00003232 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003233 return false;
3234}
3235
3236/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3237/// lvalue referring to the result.
3238///
3239/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003240/// \param LV - An lvalue referring to the base of the member pointer.
3241/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003242/// \param IncludeMember - Specifies whether the member itself is included in
3243/// the resulting LValue subobject designator. This is not possible when
3244/// creating a bound member function.
3245/// \return The field or method declaration to which the member pointer refers,
3246/// or 0 if evaluation fails.
3247static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003248 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003249 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003250 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003251 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003252 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003253 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003254 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003255
3256 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3257 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003258 if (!MemPtr.getDecl()) {
3259 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003260 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003261 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003262 }
Richard Smith253c2a32012-01-27 01:14:48 +00003263
Richard Smith027bf112011-11-17 22:56:20 +00003264 if (MemPtr.isDerivedMember()) {
3265 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003266 // The end of the derived-to-base path for the base object must match the
3267 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003268 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003269 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003270 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003271 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003272 }
Richard Smith027bf112011-11-17 22:56:20 +00003273 unsigned PathLengthToMember =
3274 LV.Designator.Entries.size() - MemPtr.Path.size();
3275 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3276 const CXXRecordDecl *LVDecl = getAsBaseClass(
3277 LV.Designator.Entries[PathLengthToMember + I]);
3278 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003279 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003280 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003281 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003282 }
Richard Smith027bf112011-11-17 22:56:20 +00003283 }
3284
3285 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003286 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003287 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003288 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003289 } else if (!MemPtr.Path.empty()) {
3290 // Extend the LValue path with the member pointer's path.
3291 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3292 MemPtr.Path.size() + IncludeMember);
3293
3294 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003295 if (const PointerType *PT = LVType->getAs<PointerType>())
3296 LVType = PT->getPointeeType();
3297 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3298 assert(RD && "member pointer access on non-class-type expression");
3299 // The first class in the path is that of the lvalue.
3300 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3301 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003302 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003303 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003304 RD = Base;
3305 }
3306 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003307 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3308 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003309 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003310 }
3311
3312 // Add the member. Note that we cannot build bound member functions here.
3313 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003314 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003315 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003316 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003317 } else if (const IndirectFieldDecl *IFD =
3318 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003319 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003320 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003321 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003322 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003323 }
Richard Smith027bf112011-11-17 22:56:20 +00003324 }
3325
3326 return MemPtr.getDecl();
3327}
3328
Richard Smith84401042013-06-03 05:03:02 +00003329static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3330 const BinaryOperator *BO,
3331 LValue &LV,
3332 bool IncludeMember = true) {
3333 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3334
3335 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003336 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003337 MemberPtr MemPtr;
3338 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3339 }
Craig Topper36250ad2014-05-12 05:36:57 +00003340 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003341 }
3342
3343 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3344 BO->getRHS(), IncludeMember);
3345}
3346
Richard Smith027bf112011-11-17 22:56:20 +00003347/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3348/// the provided lvalue, which currently refers to the base object.
3349static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3350 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003351 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003352 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003353 return false;
3354
Richard Smitha8105bc2012-01-06 16:39:00 +00003355 QualType TargetQT = E->getType();
3356 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3357 TargetQT = PT->getPointeeType();
3358
3359 // Check this cast lands within the final derived-to-base subobject path.
3360 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003361 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003362 << D.MostDerivedType << TargetQT;
3363 return false;
3364 }
3365
Richard Smith027bf112011-11-17 22:56:20 +00003366 // Check the type of the final cast. We don't need to check the path,
3367 // since a cast can only be formed if the path is unique.
3368 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003369 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3370 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003371 if (NewEntriesSize == D.MostDerivedPathLength)
3372 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3373 else
Richard Smith027bf112011-11-17 22:56:20 +00003374 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003375 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003376 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003377 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003378 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003379 }
Richard Smith027bf112011-11-17 22:56:20 +00003380
3381 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003382 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003383}
3384
Mike Stump876387b2009-10-27 22:09:17 +00003385namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003386enum EvalStmtResult {
3387 /// Evaluation failed.
3388 ESR_Failed,
3389 /// Hit a 'return' statement.
3390 ESR_Returned,
3391 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003392 ESR_Succeeded,
3393 /// Hit a 'continue' statement.
3394 ESR_Continue,
3395 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003396 ESR_Break,
3397 /// Still scanning for 'case' or 'default' statement.
3398 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003399};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003400}
Richard Smith254a73d2011-10-28 22:34:42 +00003401
Richard Smith97fcf4b2016-08-14 23:15:52 +00003402static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3403 // We don't need to evaluate the initializer for a static local.
3404 if (!VD->hasLocalStorage())
3405 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003406
Richard Smith97fcf4b2016-08-14 23:15:52 +00003407 LValue Result;
3408 Result.set(VD, Info.CurrentCall->Index);
3409 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003410
Richard Smith97fcf4b2016-08-14 23:15:52 +00003411 const Expr *InitE = VD->getInit();
3412 if (!InitE) {
3413 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3414 << false << VD->getType();
3415 Val = APValue();
3416 return false;
3417 }
Richard Smith51f03172013-06-20 03:00:05 +00003418
Richard Smith97fcf4b2016-08-14 23:15:52 +00003419 if (InitE->isValueDependent())
3420 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003421
Richard Smith97fcf4b2016-08-14 23:15:52 +00003422 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3423 // Wipe out any partially-computed value, to allow tracking that this
3424 // evaluation failed.
3425 Val = APValue();
3426 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003427 }
3428
3429 return true;
3430}
3431
Richard Smith97fcf4b2016-08-14 23:15:52 +00003432static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3433 bool OK = true;
3434
3435 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3436 OK &= EvaluateVarDecl(Info, VD);
3437
3438 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3439 for (auto *BD : DD->bindings())
3440 if (auto *VD = BD->getHoldingVar())
3441 OK &= EvaluateDecl(Info, VD);
3442
3443 return OK;
3444}
3445
3446
Richard Smith4e18ca52013-05-06 05:56:11 +00003447/// Evaluate a condition (either a variable declaration or an expression).
3448static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3449 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003450 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003451 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3452 return false;
3453 return EvaluateAsBooleanCondition(Cond, Result, Info);
3454}
3455
Richard Smith89210072016-04-04 23:29:43 +00003456namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003457/// \brief A location where the result (returned value) of evaluating a
3458/// statement should be stored.
3459struct StmtResult {
3460 /// The APValue that should be filled in with the returned value.
3461 APValue &Value;
3462 /// The location containing the result, if any (used to support RVO).
3463 const LValue *Slot;
3464};
Richard Smith89210072016-04-04 23:29:43 +00003465}
Richard Smith52a980a2015-08-28 02:43:42 +00003466
3467static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003468 const Stmt *S,
3469 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003470
3471/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003472static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003473 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003474 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003475 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003476 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003477 case ESR_Break:
3478 return ESR_Succeeded;
3479 case ESR_Succeeded:
3480 case ESR_Continue:
3481 return ESR_Continue;
3482 case ESR_Failed:
3483 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003484 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003485 return ESR;
3486 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003487 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003488}
3489
Richard Smith496ddcf2013-05-12 17:32:42 +00003490/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003491static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003492 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003493 BlockScopeRAII Scope(Info);
3494
Richard Smith496ddcf2013-05-12 17:32:42 +00003495 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003496 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003497 {
3498 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003499 if (const Stmt *Init = SS->getInit()) {
3500 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3501 if (ESR != ESR_Succeeded)
3502 return ESR;
3503 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003504 if (SS->getConditionVariable() &&
3505 !EvaluateDecl(Info, SS->getConditionVariable()))
3506 return ESR_Failed;
3507 if (!EvaluateInteger(SS->getCond(), Value, Info))
3508 return ESR_Failed;
3509 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003510
3511 // Find the switch case corresponding to the value of the condition.
3512 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003513 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003514 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3515 SC = SC->getNextSwitchCase()) {
3516 if (isa<DefaultStmt>(SC)) {
3517 Found = SC;
3518 continue;
3519 }
3520
3521 const CaseStmt *CS = cast<CaseStmt>(SC);
3522 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3523 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3524 : LHS;
3525 if (LHS <= Value && Value <= RHS) {
3526 Found = SC;
3527 break;
3528 }
3529 }
3530
3531 if (!Found)
3532 return ESR_Succeeded;
3533
3534 // Search the switch body for the switch case and evaluate it from there.
3535 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3536 case ESR_Break:
3537 return ESR_Succeeded;
3538 case ESR_Succeeded:
3539 case ESR_Continue:
3540 case ESR_Failed:
3541 case ESR_Returned:
3542 return ESR;
3543 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003544 // This can only happen if the switch case is nested within a statement
3545 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003546 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003547 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003548 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003549 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003550}
3551
Richard Smith254a73d2011-10-28 22:34:42 +00003552// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003553static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003554 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003555 if (!Info.nextStep(S))
3556 return ESR_Failed;
3557
Richard Smith496ddcf2013-05-12 17:32:42 +00003558 // If we're hunting down a 'case' or 'default' label, recurse through
3559 // substatements until we hit the label.
3560 if (Case) {
3561 // FIXME: We don't start the lifetime of objects whose initialization we
3562 // jump over. However, such objects must be of class type with a trivial
3563 // default constructor that initialize all subobjects, so must be empty,
3564 // so this almost never matters.
3565 switch (S->getStmtClass()) {
3566 case Stmt::CompoundStmtClass:
3567 // FIXME: Precompute which substatement of a compound statement we
3568 // would jump to, and go straight there rather than performing a
3569 // linear scan each time.
3570 case Stmt::LabelStmtClass:
3571 case Stmt::AttributedStmtClass:
3572 case Stmt::DoStmtClass:
3573 break;
3574
3575 case Stmt::CaseStmtClass:
3576 case Stmt::DefaultStmtClass:
3577 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003578 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003579 break;
3580
3581 case Stmt::IfStmtClass: {
3582 // FIXME: Precompute which side of an 'if' we would jump to, and go
3583 // straight there rather than scanning both sides.
3584 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003585
3586 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3587 // preceded by our switch label.
3588 BlockScopeRAII Scope(Info);
3589
Richard Smith496ddcf2013-05-12 17:32:42 +00003590 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3591 if (ESR != ESR_CaseNotFound || !IS->getElse())
3592 return ESR;
3593 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3594 }
3595
3596 case Stmt::WhileStmtClass: {
3597 EvalStmtResult ESR =
3598 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3599 if (ESR != ESR_Continue)
3600 return ESR;
3601 break;
3602 }
3603
3604 case Stmt::ForStmtClass: {
3605 const ForStmt *FS = cast<ForStmt>(S);
3606 EvalStmtResult ESR =
3607 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3608 if (ESR != ESR_Continue)
3609 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003610 if (FS->getInc()) {
3611 FullExpressionRAII IncScope(Info);
3612 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3613 return ESR_Failed;
3614 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003615 break;
3616 }
3617
3618 case Stmt::DeclStmtClass:
3619 // FIXME: If the variable has initialization that can't be jumped over,
3620 // bail out of any immediately-surrounding compound-statement too.
3621 default:
3622 return ESR_CaseNotFound;
3623 }
3624 }
3625
Richard Smith254a73d2011-10-28 22:34:42 +00003626 switch (S->getStmtClass()) {
3627 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003628 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003629 // Don't bother evaluating beyond an expression-statement which couldn't
3630 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003631 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003632 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003633 return ESR_Failed;
3634 return ESR_Succeeded;
3635 }
3636
Faisal Valie690b7a2016-07-02 22:34:24 +00003637 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003638 return ESR_Failed;
3639
3640 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003641 return ESR_Succeeded;
3642
Richard Smithd9f663b2013-04-22 15:31:51 +00003643 case Stmt::DeclStmtClass: {
3644 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003645 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003646 // Each declaration initialization is its own full-expression.
3647 // FIXME: This isn't quite right; if we're performing aggregate
3648 // initialization, each braced subexpression is its own full-expression.
3649 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003650 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003651 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003652 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003653 return ESR_Succeeded;
3654 }
3655
Richard Smith357362d2011-12-13 06:39:58 +00003656 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003657 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003658 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003659 if (RetExpr &&
3660 !(Result.Slot
3661 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3662 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003663 return ESR_Failed;
3664 return ESR_Returned;
3665 }
Richard Smith254a73d2011-10-28 22:34:42 +00003666
3667 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003668 BlockScopeRAII Scope(Info);
3669
Richard Smith254a73d2011-10-28 22:34:42 +00003670 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003671 for (const auto *BI : CS->body()) {
3672 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003673 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003674 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003675 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003676 return ESR;
3677 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003678 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003679 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003680
3681 case Stmt::IfStmtClass: {
3682 const IfStmt *IS = cast<IfStmt>(S);
3683
3684 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003685 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003686 if (const Stmt *Init = IS->getInit()) {
3687 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3688 if (ESR != ESR_Succeeded)
3689 return ESR;
3690 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003691 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003692 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003693 return ESR_Failed;
3694
3695 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3696 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3697 if (ESR != ESR_Succeeded)
3698 return ESR;
3699 }
3700 return ESR_Succeeded;
3701 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003702
3703 case Stmt::WhileStmtClass: {
3704 const WhileStmt *WS = cast<WhileStmt>(S);
3705 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003706 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003707 bool Continue;
3708 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3709 Continue))
3710 return ESR_Failed;
3711 if (!Continue)
3712 break;
3713
3714 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3715 if (ESR != ESR_Continue)
3716 return ESR;
3717 }
3718 return ESR_Succeeded;
3719 }
3720
3721 case Stmt::DoStmtClass: {
3722 const DoStmt *DS = cast<DoStmt>(S);
3723 bool Continue;
3724 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003725 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003726 if (ESR != ESR_Continue)
3727 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003728 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003729
Richard Smith08d6a2c2013-07-24 07:11:57 +00003730 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003731 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3732 return ESR_Failed;
3733 } while (Continue);
3734 return ESR_Succeeded;
3735 }
3736
3737 case Stmt::ForStmtClass: {
3738 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003739 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003740 if (FS->getInit()) {
3741 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3742 if (ESR != ESR_Succeeded)
3743 return ESR;
3744 }
3745 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003746 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003747 bool Continue = true;
3748 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3749 FS->getCond(), Continue))
3750 return ESR_Failed;
3751 if (!Continue)
3752 break;
3753
3754 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3755 if (ESR != ESR_Continue)
3756 return ESR;
3757
Richard Smith08d6a2c2013-07-24 07:11:57 +00003758 if (FS->getInc()) {
3759 FullExpressionRAII IncScope(Info);
3760 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3761 return ESR_Failed;
3762 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003763 }
3764 return ESR_Succeeded;
3765 }
3766
Richard Smith896e0d72013-05-06 06:51:17 +00003767 case Stmt::CXXForRangeStmtClass: {
3768 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003769 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003770
3771 // Initialize the __range variable.
3772 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3773 if (ESR != ESR_Succeeded)
3774 return ESR;
3775
3776 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003777 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3778 if (ESR != ESR_Succeeded)
3779 return ESR;
3780 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003781 if (ESR != ESR_Succeeded)
3782 return ESR;
3783
3784 while (true) {
3785 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003786 {
3787 bool Continue = true;
3788 FullExpressionRAII CondExpr(Info);
3789 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3790 return ESR_Failed;
3791 if (!Continue)
3792 break;
3793 }
Richard Smith896e0d72013-05-06 06:51:17 +00003794
3795 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003796 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003797 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3798 if (ESR != ESR_Succeeded)
3799 return ESR;
3800
3801 // Loop body.
3802 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3803 if (ESR != ESR_Continue)
3804 return ESR;
3805
3806 // Increment: ++__begin
3807 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3808 return ESR_Failed;
3809 }
3810
3811 return ESR_Succeeded;
3812 }
3813
Richard Smith496ddcf2013-05-12 17:32:42 +00003814 case Stmt::SwitchStmtClass:
3815 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3816
Richard Smith4e18ca52013-05-06 05:56:11 +00003817 case Stmt::ContinueStmtClass:
3818 return ESR_Continue;
3819
3820 case Stmt::BreakStmtClass:
3821 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003822
3823 case Stmt::LabelStmtClass:
3824 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3825
3826 case Stmt::AttributedStmtClass:
3827 // As a general principle, C++11 attributes can be ignored without
3828 // any semantic impact.
3829 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3830 Case);
3831
3832 case Stmt::CaseStmtClass:
3833 case Stmt::DefaultStmtClass:
3834 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003835 }
3836}
3837
Richard Smithcc36f692011-12-22 02:22:31 +00003838/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3839/// default constructor. If so, we'll fold it whether or not it's marked as
3840/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3841/// so we need special handling.
3842static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003843 const CXXConstructorDecl *CD,
3844 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003845 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3846 return false;
3847
Richard Smith66e05fe2012-01-18 05:21:49 +00003848 // Value-initialization does not call a trivial default constructor, so such a
3849 // call is a core constant expression whether or not the constructor is
3850 // constexpr.
3851 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003852 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003853 // FIXME: If DiagDecl is an implicitly-declared special member function,
3854 // we should be much more explicit about why it's not constexpr.
3855 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3856 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3857 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003858 } else {
3859 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3860 }
3861 }
3862 return true;
3863}
3864
Richard Smith357362d2011-12-13 06:39:58 +00003865/// CheckConstexprFunction - Check that a function can be called in a constant
3866/// expression.
3867static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3868 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003869 const FunctionDecl *Definition,
3870 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003871 // Potential constant expressions can contain calls to declared, but not yet
3872 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003873 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003874 Declaration->isConstexpr())
3875 return false;
3876
Richard Smith0838f3a2013-05-14 05:18:44 +00003877 // Bail out with no diagnostic if the function declaration itself is invalid.
3878 // We will have produced a relevant diagnostic while parsing it.
3879 if (Declaration->isInvalidDecl())
3880 return false;
3881
Richard Smith357362d2011-12-13 06:39:58 +00003882 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003883 if (Definition && Definition->isConstexpr() &&
3884 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003885 return true;
3886
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003887 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003888 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00003889
Richard Smith5179eb72016-06-28 19:03:57 +00003890 // If this function is not constexpr because it is an inherited
3891 // non-constexpr constructor, diagnose that directly.
3892 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
3893 if (CD && CD->isInheritingConstructor()) {
3894 auto *Inherited = CD->getInheritedConstructor().getConstructor();
3895 if (!Inherited->isConstexpr())
3896 DiagDecl = CD = Inherited;
3897 }
3898
3899 // FIXME: If DiagDecl is an implicitly-declared special member function
3900 // or an inheriting constructor, we should be much more explicit about why
3901 // it's not constexpr.
3902 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00003903 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003904 << CD->getInheritedConstructor().getConstructor()->getParent();
3905 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003906 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003907 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00003908 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3909 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003910 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00003911 }
3912 return false;
3913}
3914
Richard Smithbe6dd812014-11-19 21:27:17 +00003915/// Determine if a class has any fields that might need to be copied by a
3916/// trivial copy or move operation.
3917static bool hasFields(const CXXRecordDecl *RD) {
3918 if (!RD || RD->isEmpty())
3919 return false;
3920 for (auto *FD : RD->fields()) {
3921 if (FD->isUnnamedBitfield())
3922 continue;
3923 return true;
3924 }
3925 for (auto &Base : RD->bases())
3926 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3927 return true;
3928 return false;
3929}
3930
Richard Smithd62306a2011-11-10 06:34:14 +00003931namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003932typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003933}
3934
3935/// EvaluateArgs - Evaluate the arguments to a function call.
3936static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3937 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003938 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003939 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003940 I != E; ++I) {
3941 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3942 // If we're checking for a potential constant expression, evaluate all
3943 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00003944 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00003945 return false;
3946 Success = false;
3947 }
3948 }
3949 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003950}
3951
Richard Smith254a73d2011-10-28 22:34:42 +00003952/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003953static bool HandleFunctionCall(SourceLocation CallLoc,
3954 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003955 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003956 EvalInfo &Info, APValue &Result,
3957 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003958 ArgVector ArgValues(Args.size());
3959 if (!EvaluateArgs(Args, ArgValues, Info))
3960 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003961
Richard Smith253c2a32012-01-27 01:14:48 +00003962 if (!Info.CheckCallLimit(CallLoc))
3963 return false;
3964
3965 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003966
3967 // For a trivial copy or move assignment, perform an APValue copy. This is
3968 // essential for unions, where the operations performed by the assignment
3969 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003970 //
3971 // Skip this for non-union classes with no fields; in that case, the defaulted
3972 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003973 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003974 if (MD && MD->isDefaulted() &&
3975 (MD->getParent()->isUnion() ||
3976 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003977 assert(This &&
3978 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3979 LValue RHS;
3980 RHS.setFrom(Info.Ctx, ArgValues[0]);
3981 APValue RHSValue;
3982 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3983 RHS, RHSValue))
3984 return false;
3985 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3986 RHSValue))
3987 return false;
3988 This->moveInto(Result);
3989 return true;
3990 }
3991
Richard Smith52a980a2015-08-28 02:43:42 +00003992 StmtResult Ret = {Result, ResultSlot};
3993 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003994 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003995 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003996 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00003997 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003998 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003999 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004000}
4001
Richard Smithd62306a2011-11-10 06:34:14 +00004002/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004003static bool HandleConstructorCall(const Expr *E, const LValue &This,
4004 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004005 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004006 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004007 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004008 if (!Info.CheckCallLimit(CallLoc))
4009 return false;
4010
Richard Smith3607ffe2012-02-13 03:54:03 +00004011 const CXXRecordDecl *RD = Definition->getParent();
4012 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004013 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004014 return false;
4015 }
4016
Richard Smith5179eb72016-06-28 19:03:57 +00004017 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004018
Richard Smith52a980a2015-08-28 02:43:42 +00004019 // FIXME: Creating an APValue just to hold a nonexistent return value is
4020 // wasteful.
4021 APValue RetVal;
4022 StmtResult Ret = {RetVal, nullptr};
4023
Richard Smith5179eb72016-06-28 19:03:57 +00004024 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004025 if (Definition->isDelegatingConstructor()) {
4026 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004027 {
4028 FullExpressionRAII InitScope(Info);
4029 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4030 return false;
4031 }
Richard Smith52a980a2015-08-28 02:43:42 +00004032 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004033 }
4034
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004035 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004036 // essential for unions (or classes with anonymous union members), where the
4037 // operations performed by the constructor cannot be represented by
4038 // ctor-initializers.
4039 //
4040 // Skip this for empty non-union classes; we should not perform an
4041 // lvalue-to-rvalue conversion on them because their copy constructor does not
4042 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004043 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004044 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004045 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004046 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004047 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004048 return handleLValueToRValueConversion(
4049 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4050 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004051 }
4052
4053 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004054 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004055 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004056 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004057
John McCalld7bca762012-05-01 00:38:49 +00004058 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004059 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4060
Richard Smith08d6a2c2013-07-24 07:11:57 +00004061 // A scope for temporaries lifetime-extended by reference members.
4062 BlockScopeRAII LifetimeExtendedScope(Info);
4063
Richard Smith253c2a32012-01-27 01:14:48 +00004064 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004065 unsigned BasesSeen = 0;
4066#ifndef NDEBUG
4067 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4068#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004069 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004070 LValue Subobject = This;
4071 APValue *Value = &Result;
4072
4073 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004074 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004075 if (I->isBaseInitializer()) {
4076 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004077#ifndef NDEBUG
4078 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004079 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004080 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4081 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4082 "base class initializers not in expected order");
4083 ++BaseIt;
4084#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004085 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004086 BaseType->getAsCXXRecordDecl(), &Layout))
4087 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004088 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004089 } else if ((FD = I->getMember())) {
4090 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004091 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004092 if (RD->isUnion()) {
4093 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004094 Value = &Result.getUnionValue();
4095 } else {
4096 Value = &Result.getStructField(FD->getFieldIndex());
4097 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004098 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004099 // Walk the indirect field decl's chain to find the object to initialize,
4100 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004101 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004102 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004103 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4104 // Switch the union field if it differs. This happens if we had
4105 // preceding zero-initialization, and we're now initializing a union
4106 // subobject other than the first.
4107 // FIXME: In this case, the values of the other subobjects are
4108 // specified, since zero-initialization sets all padding bits to zero.
4109 if (Value->isUninit() ||
4110 (Value->isUnion() && Value->getUnionField() != FD)) {
4111 if (CD->isUnion())
4112 *Value = APValue(FD);
4113 else
4114 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004115 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004116 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004117 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004118 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004119 if (CD->isUnion())
4120 Value = &Value->getUnionValue();
4121 else
4122 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004123 }
Richard Smithd62306a2011-11-10 06:34:14 +00004124 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004125 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004126 }
Richard Smith253c2a32012-01-27 01:14:48 +00004127
Richard Smith08d6a2c2013-07-24 07:11:57 +00004128 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004129 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4130 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004131 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004132 // If we're checking for a potential constant expression, evaluate all
4133 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004134 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004135 return false;
4136 Success = false;
4137 }
Richard Smithd62306a2011-11-10 06:34:14 +00004138 }
4139
Richard Smithd9f663b2013-04-22 15:31:51 +00004140 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004141 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004142}
4143
Richard Smith5179eb72016-06-28 19:03:57 +00004144static bool HandleConstructorCall(const Expr *E, const LValue &This,
4145 ArrayRef<const Expr*> Args,
4146 const CXXConstructorDecl *Definition,
4147 EvalInfo &Info, APValue &Result) {
4148 ArgVector ArgValues(Args.size());
4149 if (!EvaluateArgs(Args, ArgValues, Info))
4150 return false;
4151
4152 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4153 Info, Result);
4154}
4155
Eli Friedman9a156e52008-11-12 09:44:48 +00004156//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004157// Generic Evaluation
4158//===----------------------------------------------------------------------===//
4159namespace {
4160
Aaron Ballman68af21c2014-01-03 19:26:43 +00004161template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004162class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004163 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004164private:
Richard Smith52a980a2015-08-28 02:43:42 +00004165 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004166 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004167 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004168 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004169 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004170 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004171 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004172
Richard Smith17100ba2012-02-16 02:46:34 +00004173 // Check whether a conditional operator with a non-constant condition is a
4174 // potential constant expression. If neither arm is a potential constant
4175 // expression, then the conditional operator is not either.
4176 template<typename ConditionalOperator>
4177 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004178 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004179
4180 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004181 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004182 {
Richard Smith17100ba2012-02-16 02:46:34 +00004183 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004184 StmtVisitorTy::Visit(E->getFalseExpr());
4185 if (Diag.empty())
4186 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004187 }
Richard Smith17100ba2012-02-16 02:46:34 +00004188
George Burgess IV8c892b52016-05-25 22:31:54 +00004189 {
4190 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004191 Diag.clear();
4192 StmtVisitorTy::Visit(E->getTrueExpr());
4193 if (Diag.empty())
4194 return;
4195 }
4196
4197 Error(E, diag::note_constexpr_conditional_never_const);
4198 }
4199
4200
4201 template<typename ConditionalOperator>
4202 bool HandleConditionalOperator(const ConditionalOperator *E) {
4203 bool BoolResult;
4204 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004205 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004206 CheckPotentialConstantConditional(E);
4207 return false;
4208 }
4209
4210 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4211 return StmtVisitorTy::Visit(EvalExpr);
4212 }
4213
Peter Collingbournee9200682011-05-13 03:29:01 +00004214protected:
4215 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004216 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004217 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4218
Richard Smith92b1ce02011-12-12 09:28:41 +00004219 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004220 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004221 }
4222
Aaron Ballman68af21c2014-01-03 19:26:43 +00004223 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004224
4225public:
4226 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4227
4228 EvalInfo &getEvalInfo() { return Info; }
4229
Richard Smithf57d8cb2011-12-09 22:58:01 +00004230 /// Report an evaluation error. This should only be called when an error is
4231 /// first discovered. When propagating an error, just return false.
4232 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004233 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004234 return false;
4235 }
4236 bool Error(const Expr *E) {
4237 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4238 }
4239
Aaron Ballman68af21c2014-01-03 19:26:43 +00004240 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004241 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004242 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004243 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004244 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004245 }
4246
Aaron Ballman68af21c2014-01-03 19:26:43 +00004247 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004248 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004249 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004250 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004251 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004252 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004253 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004254 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004255 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004256 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004257 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004258 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004259 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004260 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004261 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004262 // The initializer may not have been parsed yet, or might be erroneous.
4263 if (!E->getExpr())
4264 return Error(E);
4265 return StmtVisitorTy::Visit(E->getExpr());
4266 }
Richard Smith5894a912011-12-19 22:12:41 +00004267 // We cannot create any objects for which cleanups are required, so there is
4268 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004269 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004270 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004271
Aaron Ballman68af21c2014-01-03 19:26:43 +00004272 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004273 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4274 return static_cast<Derived*>(this)->VisitCastExpr(E);
4275 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004276 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004277 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4278 return static_cast<Derived*>(this)->VisitCastExpr(E);
4279 }
4280
Aaron Ballman68af21c2014-01-03 19:26:43 +00004281 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004282 switch (E->getOpcode()) {
4283 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004284 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004285
4286 case BO_Comma:
4287 VisitIgnoredValue(E->getLHS());
4288 return StmtVisitorTy::Visit(E->getRHS());
4289
4290 case BO_PtrMemD:
4291 case BO_PtrMemI: {
4292 LValue Obj;
4293 if (!HandleMemberPointerAccess(Info, E, Obj))
4294 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004295 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004296 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004297 return false;
4298 return DerivedSuccess(Result, E);
4299 }
4300 }
4301 }
4302
Aaron Ballman68af21c2014-01-03 19:26:43 +00004303 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004304 // Evaluate and cache the common expression. We treat it as a temporary,
4305 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004306 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004307 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004308 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004309
Richard Smith17100ba2012-02-16 02:46:34 +00004310 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004311 }
4312
Aaron Ballman68af21c2014-01-03 19:26:43 +00004313 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004314 bool IsBcpCall = false;
4315 // If the condition (ignoring parens) is a __builtin_constant_p call,
4316 // the result is a constant expression if it can be folded without
4317 // side-effects. This is an important GNU extension. See GCC PR38377
4318 // for discussion.
4319 if (const CallExpr *CallCE =
4320 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004321 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004322 IsBcpCall = true;
4323
4324 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4325 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004326 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004327 return false;
4328
Richard Smith6d4c6582013-11-05 22:18:15 +00004329 FoldConstant Fold(Info, IsBcpCall);
4330 if (!HandleConditionalOperator(E)) {
4331 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004332 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004333 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004334
4335 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004336 }
4337
Aaron Ballman68af21c2014-01-03 19:26:43 +00004338 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004339 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4340 return DerivedSuccess(*Value, E);
4341
4342 const Expr *Source = E->getSourceExpr();
4343 if (!Source)
4344 return Error(E);
4345 if (Source == E) { // sanity checking.
4346 assert(0 && "OpaqueValueExpr recursively refers to itself");
4347 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004348 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004349 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004350 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004351
Aaron Ballman68af21c2014-01-03 19:26:43 +00004352 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004353 APValue Result;
4354 if (!handleCallExpr(E, Result, nullptr))
4355 return false;
4356 return DerivedSuccess(Result, E);
4357 }
4358
4359 bool handleCallExpr(const CallExpr *E, APValue &Result,
4360 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004361 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004362 QualType CalleeType = Callee->getType();
4363
Craig Topper36250ad2014-05-12 05:36:57 +00004364 const FunctionDecl *FD = nullptr;
4365 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004366 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004367 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004368
Richard Smithe97cbd72011-11-11 04:05:33 +00004369 // Extract function decl and 'this' pointer from the callee.
4370 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004371 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004372 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4373 // Explicit bound member calls, such as x.f() or p->g();
4374 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004375 return false;
4376 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004377 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004378 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004379 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4380 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004381 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4382 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004383 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004384 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004385 return Error(Callee);
4386
4387 FD = dyn_cast<FunctionDecl>(Member);
4388 if (!FD)
4389 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004390 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004391 LValue Call;
4392 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004393 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004394
Richard Smitha8105bc2012-01-06 16:39:00 +00004395 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004396 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004397 FD = dyn_cast_or_null<FunctionDecl>(
4398 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004399 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004400 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004401
4402 // Overloaded operator calls to member functions are represented as normal
4403 // calls with '*this' as the first argument.
4404 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4405 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004406 // FIXME: When selecting an implicit conversion for an overloaded
4407 // operator delete, we sometimes try to evaluate calls to conversion
4408 // operators without a 'this' parameter!
4409 if (Args.empty())
4410 return Error(E);
4411
Richard Smithe97cbd72011-11-11 04:05:33 +00004412 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4413 return false;
4414 This = &ThisVal;
4415 Args = Args.slice(1);
4416 }
4417
4418 // Don't call function pointers which have been cast to some other type.
4419 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004420 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004421 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004422 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004423
Richard Smith47b34932012-02-01 02:39:43 +00004424 if (This && !This->checkSubobject(Info, E, CSK_This))
4425 return false;
4426
Richard Smith3607ffe2012-02-13 03:54:03 +00004427 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4428 // calls to such functions in constant expressions.
4429 if (This && !HasQualifier &&
4430 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4431 return Error(E, diag::note_constexpr_virtual_call);
4432
Craig Topper36250ad2014-05-12 05:36:57 +00004433 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004434 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004435
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004436 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004437 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4438 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004439 return false;
4440
Richard Smith52a980a2015-08-28 02:43:42 +00004441 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004442 }
4443
Aaron Ballman68af21c2014-01-03 19:26:43 +00004444 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004445 return StmtVisitorTy::Visit(E->getInitializer());
4446 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004447 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004448 if (E->getNumInits() == 0)
4449 return DerivedZeroInitialization(E);
4450 if (E->getNumInits() == 1)
4451 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004452 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004453 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004454 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004455 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004456 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004457 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004458 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004459 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004460 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004461 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004462 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004463
Richard Smithd62306a2011-11-10 06:34:14 +00004464 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004465 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004466 assert(!E->isArrow() && "missing call to bound member function?");
4467
Richard Smith2e312c82012-03-03 22:46:17 +00004468 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004469 if (!Evaluate(Val, Info, E->getBase()))
4470 return false;
4471
4472 QualType BaseTy = E->getBase()->getType();
4473
4474 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004475 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004476 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004477 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004478 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4479
Richard Smith3229b742013-05-05 21:17:10 +00004480 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004481 SubobjectDesignator Designator(BaseTy);
4482 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004483
Richard Smith3229b742013-05-05 21:17:10 +00004484 APValue Result;
4485 return extractSubobject(Info, E, Obj, Designator, Result) &&
4486 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004487 }
4488
Aaron Ballman68af21c2014-01-03 19:26:43 +00004489 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004490 switch (E->getCastKind()) {
4491 default:
4492 break;
4493
Richard Smitha23ab512013-05-23 00:30:41 +00004494 case CK_AtomicToNonAtomic: {
4495 APValue AtomicVal;
4496 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4497 return false;
4498 return DerivedSuccess(AtomicVal, E);
4499 }
4500
Richard Smith11562c52011-10-28 17:51:58 +00004501 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004502 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004503 return StmtVisitorTy::Visit(E->getSubExpr());
4504
4505 case CK_LValueToRValue: {
4506 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004507 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4508 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004509 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004510 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004511 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004512 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004513 return false;
4514 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004515 }
4516 }
4517
Richard Smithf57d8cb2011-12-09 22:58:01 +00004518 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004519 }
4520
Aaron Ballman68af21c2014-01-03 19:26:43 +00004521 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004522 return VisitUnaryPostIncDec(UO);
4523 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004524 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004525 return VisitUnaryPostIncDec(UO);
4526 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004527 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004528 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004529 return Error(UO);
4530
4531 LValue LVal;
4532 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4533 return false;
4534 APValue RVal;
4535 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4536 UO->isIncrementOp(), &RVal))
4537 return false;
4538 return DerivedSuccess(RVal, UO);
4539 }
4540
Aaron Ballman68af21c2014-01-03 19:26:43 +00004541 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004542 // We will have checked the full-expressions inside the statement expression
4543 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004544 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004545 return Error(E);
4546
Richard Smith08d6a2c2013-07-24 07:11:57 +00004547 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004548 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004549 if (CS->body_empty())
4550 return true;
4551
Richard Smith51f03172013-06-20 03:00:05 +00004552 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4553 BE = CS->body_end();
4554 /**/; ++BI) {
4555 if (BI + 1 == BE) {
4556 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4557 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004558 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004559 diag::note_constexpr_stmt_expr_unsupported);
4560 return false;
4561 }
4562 return this->Visit(FinalExpr);
4563 }
4564
4565 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004566 StmtResult Result = { ReturnValue, nullptr };
4567 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004568 if (ESR != ESR_Succeeded) {
4569 // FIXME: If the statement-expression terminated due to 'return',
4570 // 'break', or 'continue', it would be nice to propagate that to
4571 // the outer statement evaluation rather than bailing out.
4572 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004573 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004574 diag::note_constexpr_stmt_expr_unsupported);
4575 return false;
4576 }
4577 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004578
4579 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004580 }
4581
Richard Smith4a678122011-10-24 18:44:57 +00004582 /// Visit a value which is evaluated, but whose value is ignored.
4583 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004584 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004585 }
David Majnemere9807b22016-02-26 04:23:19 +00004586
4587 /// Potentially visit a MemberExpr's base expression.
4588 void VisitIgnoredBaseExpression(const Expr *E) {
4589 // While MSVC doesn't evaluate the base expression, it does diagnose the
4590 // presence of side-effecting behavior.
4591 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4592 return;
4593 VisitIgnoredValue(E);
4594 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004595};
4596
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004597}
Peter Collingbournee9200682011-05-13 03:29:01 +00004598
4599//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004600// Common base class for lvalue and temporary evaluation.
4601//===----------------------------------------------------------------------===//
4602namespace {
4603template<class Derived>
4604class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004605 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004606protected:
4607 LValue &Result;
4608 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004609 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004610
4611 bool Success(APValue::LValueBase B) {
4612 Result.set(B);
4613 return true;
4614 }
4615
4616public:
4617 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4618 ExprEvaluatorBaseTy(Info), Result(Result) {}
4619
Richard Smith2e312c82012-03-03 22:46:17 +00004620 bool Success(const APValue &V, const Expr *E) {
4621 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004622 return true;
4623 }
Richard Smith027bf112011-11-17 22:56:20 +00004624
Richard Smith027bf112011-11-17 22:56:20 +00004625 bool VisitMemberExpr(const MemberExpr *E) {
4626 // Handle non-static data members.
4627 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004628 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004629 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004630 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004631 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004632 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004633 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004634 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004635 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004636 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004637 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004638 BaseTy = E->getBase()->getType();
4639 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004640 if (!EvalOK) {
4641 if (!this->Info.allowInvalidBaseExpr())
4642 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004643 Result.setInvalid(E);
4644 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004645 }
Richard Smith027bf112011-11-17 22:56:20 +00004646
Richard Smith1b78b3d2012-01-25 22:15:11 +00004647 const ValueDecl *MD = E->getMemberDecl();
4648 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4649 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4650 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4651 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004652 if (!HandleLValueMember(this->Info, E, Result, FD))
4653 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004654 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004655 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4656 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004657 } else
4658 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004659
Richard Smith1b78b3d2012-01-25 22:15:11 +00004660 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004661 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004662 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004663 RefValue))
4664 return false;
4665 return Success(RefValue, E);
4666 }
4667 return true;
4668 }
4669
4670 bool VisitBinaryOperator(const BinaryOperator *E) {
4671 switch (E->getOpcode()) {
4672 default:
4673 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4674
4675 case BO_PtrMemD:
4676 case BO_PtrMemI:
4677 return HandleMemberPointerAccess(this->Info, E, Result);
4678 }
4679 }
4680
4681 bool VisitCastExpr(const CastExpr *E) {
4682 switch (E->getCastKind()) {
4683 default:
4684 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4685
4686 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004687 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004688 if (!this->Visit(E->getSubExpr()))
4689 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004690
4691 // Now figure out the necessary offset to add to the base LV to get from
4692 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004693 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4694 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004695 }
4696 }
4697};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004698}
Richard Smith027bf112011-11-17 22:56:20 +00004699
4700//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004701// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004702//
4703// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4704// function designators (in C), decl references to void objects (in C), and
4705// temporaries (if building with -Wno-address-of-temporary).
4706//
4707// LValue evaluation produces values comprising a base expression of one of the
4708// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004709// - Declarations
4710// * VarDecl
4711// * FunctionDecl
4712// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004713// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004714// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004715// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004716// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004717// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004718// * ObjCEncodeExpr
4719// * AddrLabelExpr
4720// * BlockExpr
4721// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004722// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004723// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004724// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004725// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4726// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004727// * A MaterializeTemporaryExpr that has static storage duration, with no
4728// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004729// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004730//===----------------------------------------------------------------------===//
4731namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004732class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004733 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004734public:
Richard Smith027bf112011-11-17 22:56:20 +00004735 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4736 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004737
Richard Smith11562c52011-10-28 17:51:58 +00004738 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004739 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004740
Peter Collingbournee9200682011-05-13 03:29:01 +00004741 bool VisitDeclRefExpr(const DeclRefExpr *E);
4742 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004743 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004744 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4745 bool VisitMemberExpr(const MemberExpr *E);
4746 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4747 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004748 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004749 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004750 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4751 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004752 bool VisitUnaryReal(const UnaryOperator *E);
4753 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004754 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4755 return VisitUnaryPreIncDec(UO);
4756 }
4757 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4758 return VisitUnaryPreIncDec(UO);
4759 }
Richard Smith3229b742013-05-05 21:17:10 +00004760 bool VisitBinAssign(const BinaryOperator *BO);
4761 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004762
Peter Collingbournee9200682011-05-13 03:29:01 +00004763 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004764 switch (E->getCastKind()) {
4765 default:
Richard Smith027bf112011-11-17 22:56:20 +00004766 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004767
Eli Friedmance3e02a2011-10-11 00:13:24 +00004768 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004769 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004770 if (!Visit(E->getSubExpr()))
4771 return false;
4772 Result.Designator.setInvalid();
4773 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004774
Richard Smith027bf112011-11-17 22:56:20 +00004775 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004776 if (!Visit(E->getSubExpr()))
4777 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004778 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004779 }
4780 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004781};
4782} // end anonymous namespace
4783
Richard Smith11562c52011-10-28 17:51:58 +00004784/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004785/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004786/// * function designators in C, and
4787/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004788/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004789static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4790 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004791 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004792 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004793}
4794
Peter Collingbournee9200682011-05-13 03:29:01 +00004795bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004796 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004797 return Success(FD);
4798 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004799 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00004800 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00004801 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00004802 return Error(E);
4803}
Richard Smith733237d2011-10-24 23:14:33 +00004804
Faisal Vali0528a312016-11-13 06:09:16 +00004805
Richard Smith11562c52011-10-28 17:51:58 +00004806bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004807 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00004808 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
4809 // Only if a local variable was declared in the function currently being
4810 // evaluated, do we expect to be able to find its value in the current
4811 // frame. (Otherwise it was likely declared in an enclosing context and
4812 // could either have a valid evaluatable value (for e.g. a constexpr
4813 // variable) or be ill-formed (and trigger an appropriate evaluation
4814 // diagnostic)).
4815 if (Info.CurrentCall->Callee &&
4816 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
4817 Frame = Info.CurrentCall;
4818 }
4819 }
Richard Smith3229b742013-05-05 21:17:10 +00004820
Richard Smithfec09922011-11-01 16:57:24 +00004821 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004822 if (Frame) {
4823 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004824 return true;
4825 }
Richard Smithce40ad62011-11-12 22:28:03 +00004826 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004827 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004828
Richard Smith3229b742013-05-05 21:17:10 +00004829 APValue *V;
4830 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004831 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004832 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004833 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00004834 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004835 return false;
4836 }
Richard Smith3229b742013-05-05 21:17:10 +00004837 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004838}
4839
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004840bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4841 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004842 // Walk through the expression to find the materialized temporary itself.
4843 SmallVector<const Expr *, 2> CommaLHSs;
4844 SmallVector<SubobjectAdjustment, 2> Adjustments;
4845 const Expr *Inner = E->GetTemporaryExpr()->
4846 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004847
Richard Smith84401042013-06-03 05:03:02 +00004848 // If we passed any comma operators, evaluate their LHSs.
4849 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4850 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4851 return false;
4852
Richard Smithe6c01442013-06-05 00:46:14 +00004853 // A materialized temporary with static storage duration can appear within the
4854 // result of a constant expression evaluation, so we need to preserve its
4855 // value for use outside this evaluation.
4856 APValue *Value;
4857 if (E->getStorageDuration() == SD_Static) {
4858 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004859 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004860 Result.set(E);
4861 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004862 Value = &Info.CurrentCall->
4863 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004864 Result.set(E, Info.CurrentCall->Index);
4865 }
4866
Richard Smithea4ad5d2013-06-06 08:19:16 +00004867 QualType Type = Inner->getType();
4868
Richard Smith84401042013-06-03 05:03:02 +00004869 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004870 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4871 (E->getStorageDuration() == SD_Static &&
4872 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4873 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004874 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004875 }
Richard Smith84401042013-06-03 05:03:02 +00004876
4877 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004878 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4879 --I;
4880 switch (Adjustments[I].Kind) {
4881 case SubobjectAdjustment::DerivedToBaseAdjustment:
4882 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4883 Type, Result))
4884 return false;
4885 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4886 break;
4887
4888 case SubobjectAdjustment::FieldAdjustment:
4889 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4890 return false;
4891 Type = Adjustments[I].Field->getType();
4892 break;
4893
4894 case SubobjectAdjustment::MemberPointerAdjustment:
4895 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4896 Adjustments[I].Ptr.RHS))
4897 return false;
4898 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4899 break;
4900 }
4901 }
4902
4903 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004904}
4905
Peter Collingbournee9200682011-05-13 03:29:01 +00004906bool
4907LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00004908 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
4909 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00004910 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4911 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004912 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004913}
4914
Richard Smith6e525142011-12-27 12:18:28 +00004915bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004916 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004917 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004918
Faisal Valie690b7a2016-07-02 22:34:24 +00004919 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00004920 << E->getExprOperand()->getType()
4921 << E->getExprOperand()->getSourceRange();
4922 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004923}
4924
Francois Pichet0066db92012-04-16 04:08:35 +00004925bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4926 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004927}
Francois Pichet0066db92012-04-16 04:08:35 +00004928
Peter Collingbournee9200682011-05-13 03:29:01 +00004929bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004930 // Handle static data members.
4931 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004932 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004933 return VisitVarDecl(E, VD);
4934 }
4935
Richard Smith254a73d2011-10-28 22:34:42 +00004936 // Handle static member functions.
4937 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4938 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004939 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004940 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004941 }
4942 }
4943
Richard Smithd62306a2011-11-10 06:34:14 +00004944 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004945 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004946}
4947
Peter Collingbournee9200682011-05-13 03:29:01 +00004948bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004949 // FIXME: Deal with vectors as array subscript bases.
4950 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004951 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004952
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004953 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004954 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004955
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004956 APSInt Index;
4957 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004958 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004959
Richard Smith861b5b52013-05-07 23:34:45 +00004960 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4961 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004962}
Eli Friedman9a156e52008-11-12 09:44:48 +00004963
Peter Collingbournee9200682011-05-13 03:29:01 +00004964bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004965 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004966}
4967
Richard Smith66c96992012-02-18 22:04:06 +00004968bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4969 if (!Visit(E->getSubExpr()))
4970 return false;
4971 // __real is a no-op on scalar lvalues.
4972 if (E->getSubExpr()->getType()->isAnyComplexType())
4973 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4974 return true;
4975}
4976
4977bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4978 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4979 "lvalue __imag__ on scalar?");
4980 if (!Visit(E->getSubExpr()))
4981 return false;
4982 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4983 return true;
4984}
4985
Richard Smith243ef902013-05-05 23:31:59 +00004986bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004987 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004988 return Error(UO);
4989
4990 if (!this->Visit(UO->getSubExpr()))
4991 return false;
4992
Richard Smith243ef902013-05-05 23:31:59 +00004993 return handleIncDec(
4994 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004995 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004996}
4997
4998bool LValueExprEvaluator::VisitCompoundAssignOperator(
4999 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005000 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005001 return Error(CAO);
5002
Richard Smith3229b742013-05-05 21:17:10 +00005003 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005004
5005 // The overall lvalue result is the result of evaluating the LHS.
5006 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005007 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005008 Evaluate(RHS, this->Info, CAO->getRHS());
5009 return false;
5010 }
5011
Richard Smith3229b742013-05-05 21:17:10 +00005012 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5013 return false;
5014
Richard Smith43e77732013-05-07 04:50:00 +00005015 return handleCompoundAssignment(
5016 this->Info, CAO,
5017 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5018 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005019}
5020
5021bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005022 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005023 return Error(E);
5024
Richard Smith3229b742013-05-05 21:17:10 +00005025 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005026
5027 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005028 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005029 Evaluate(NewVal, this->Info, E->getRHS());
5030 return false;
5031 }
5032
Richard Smith3229b742013-05-05 21:17:10 +00005033 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5034 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005035
5036 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005037 NewVal);
5038}
5039
Eli Friedman9a156e52008-11-12 09:44:48 +00005040//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005041// Pointer Evaluation
5042//===----------------------------------------------------------------------===//
5043
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005044namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005045class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005046 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005047 LValue &Result;
5048
Peter Collingbournee9200682011-05-13 03:29:01 +00005049 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005050 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005051 return true;
5052 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005053public:
Mike Stump11289f42009-09-09 15:08:12 +00005054
John McCall45d55e42010-05-07 21:00:08 +00005055 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005056 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005057
Richard Smith2e312c82012-03-03 22:46:17 +00005058 bool Success(const APValue &V, const Expr *E) {
5059 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005060 return true;
5061 }
Richard Smithfddd3842011-12-30 21:15:51 +00005062 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005063 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00005064 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005065
John McCall45d55e42010-05-07 21:00:08 +00005066 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005067 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005068 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005069 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005070 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005071 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005072 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005073 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005074 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005075 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005076 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005077 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005078 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005079 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005080 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005081 }
Richard Smithd62306a2011-11-10 06:34:14 +00005082 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005083 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005084 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005085 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005086 if (!Info.CurrentCall->This) {
5087 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005088 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005089 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005090 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005091 return false;
5092 }
Richard Smithd62306a2011-11-10 06:34:14 +00005093 Result = *Info.CurrentCall->This;
5094 return true;
5095 }
John McCallc07a0c72011-02-17 10:25:35 +00005096
Eli Friedman449fe542009-03-23 04:56:01 +00005097 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005098};
Chris Lattner05706e882008-07-11 18:11:29 +00005099} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005100
John McCall45d55e42010-05-07 21:00:08 +00005101static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005102 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005103 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005104}
5105
John McCall45d55e42010-05-07 21:00:08 +00005106bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005107 if (E->getOpcode() != BO_Add &&
5108 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005109 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005110
Chris Lattner05706e882008-07-11 18:11:29 +00005111 const Expr *PExp = E->getLHS();
5112 const Expr *IExp = E->getRHS();
5113 if (IExp->getType()->isPointerType())
5114 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005115
Richard Smith253c2a32012-01-27 01:14:48 +00005116 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005117 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005118 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005119
John McCall45d55e42010-05-07 21:00:08 +00005120 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005121 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005122 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005123
5124 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005125 if (E->getOpcode() == BO_Sub)
5126 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005127
Ted Kremenek28831752012-08-23 20:46:57 +00005128 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005129 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5130 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005131}
Eli Friedman9a156e52008-11-12 09:44:48 +00005132
John McCall45d55e42010-05-07 21:00:08 +00005133bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5134 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005135}
Mike Stump11289f42009-09-09 15:08:12 +00005136
Peter Collingbournee9200682011-05-13 03:29:01 +00005137bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5138 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005139
Eli Friedman847a2bc2009-12-27 05:43:15 +00005140 switch (E->getCastKind()) {
5141 default:
5142 break;
5143
John McCalle3027922010-08-25 11:45:40 +00005144 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005145 case CK_CPointerToObjCPointerCast:
5146 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005147 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005148 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005149 if (!Visit(SubExpr))
5150 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005151 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5152 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5153 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005154 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005155 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005156 if (SubExpr->getType()->isVoidPointerType())
5157 CCEDiag(E, diag::note_constexpr_invalid_cast)
5158 << 3 << SubExpr->getType();
5159 else
5160 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5161 }
Richard Smith96e0c102011-11-04 02:25:55 +00005162 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005163
Anders Carlsson18275092010-10-31 20:41:46 +00005164 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005165 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005166 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005167 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005168 if (!Result.Base && Result.Offset.isZero())
5169 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005170
Richard Smithd62306a2011-11-10 06:34:14 +00005171 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005172 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005173 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5174 castAs<PointerType>()->getPointeeType(),
5175 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005176
Richard Smith027bf112011-11-17 22:56:20 +00005177 case CK_BaseToDerived:
5178 if (!Visit(E->getSubExpr()))
5179 return false;
5180 if (!Result.Base && Result.Offset.isZero())
5181 return true;
5182 return HandleBaseToDerivedCast(Info, E, Result);
5183
Richard Smith0b0a0b62011-10-29 20:57:55 +00005184 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005185 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005186 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005187
John McCalle3027922010-08-25 11:45:40 +00005188 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005189 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5190
Richard Smith2e312c82012-03-03 22:46:17 +00005191 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005192 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005193 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005194
John McCall45d55e42010-05-07 21:00:08 +00005195 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005196 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5197 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005198 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005199 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005200 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005201 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005202 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005203 return true;
5204 } else {
5205 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005206 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005207 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005208 }
5209 }
John McCalle3027922010-08-25 11:45:40 +00005210 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005211 if (SubExpr->isGLValue()) {
5212 if (!EvaluateLValue(SubExpr, Result, Info))
5213 return false;
5214 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005215 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005216 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005217 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005218 return false;
5219 }
Richard Smith96e0c102011-11-04 02:25:55 +00005220 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005221 if (const ConstantArrayType *CAT
5222 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5223 Result.addArray(Info, E, CAT);
5224 else
5225 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005226 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005227
John McCalle3027922010-08-25 11:45:40 +00005228 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005229 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005230 }
5231
Richard Smith11562c52011-10-28 17:51:58 +00005232 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005233}
Chris Lattner05706e882008-07-11 18:11:29 +00005234
Hal Finkel0dd05d42014-10-03 17:18:37 +00005235static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5236 // C++ [expr.alignof]p3:
5237 // When alignof is applied to a reference type, the result is the
5238 // alignment of the referenced type.
5239 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5240 T = Ref->getPointeeType();
5241
5242 // __alignof is defined to return the preferred alignment.
5243 return Info.Ctx.toCharUnitsFromBits(
5244 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5245}
5246
5247static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5248 E = E->IgnoreParens();
5249
5250 // The kinds of expressions that we have special-case logic here for
5251 // should be kept up to date with the special checks for those
5252 // expressions in Sema.
5253
5254 // alignof decl is always accepted, even if it doesn't make sense: we default
5255 // to 1 in those cases.
5256 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5257 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5258 /*RefAsPointee*/true);
5259
5260 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5261 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5262 /*RefAsPointee*/true);
5263
5264 return GetAlignOfType(Info, E->getType());
5265}
5266
Peter Collingbournee9200682011-05-13 03:29:01 +00005267bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005268 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005269 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005270
Richard Smith6328cbd2016-11-16 00:57:23 +00005271 if (unsigned BuiltinOp = E->getBuiltinCallee())
5272 return VisitBuiltinCallExpr(E, BuiltinOp);
5273
5274 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5275}
5276
5277bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5278 unsigned BuiltinOp) {
5279 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005280 case Builtin::BI__builtin_addressof:
5281 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005282 case Builtin::BI__builtin_assume_aligned: {
5283 // We need to be very careful here because: if the pointer does not have the
5284 // asserted alignment, then the behavior is undefined, and undefined
5285 // behavior is non-constant.
5286 if (!EvaluatePointer(E->getArg(0), Result, Info))
5287 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005288
Hal Finkel0dd05d42014-10-03 17:18:37 +00005289 LValue OffsetResult(Result);
5290 APSInt Alignment;
5291 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5292 return false;
5293 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5294
5295 if (E->getNumArgs() > 2) {
5296 APSInt Offset;
5297 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5298 return false;
5299
5300 int64_t AdditionalOffset = -getExtValue(Offset);
5301 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5302 }
5303
5304 // If there is a base object, then it must have the correct alignment.
5305 if (OffsetResult.Base) {
5306 CharUnits BaseAlignment;
5307 if (const ValueDecl *VD =
5308 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5309 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5310 } else {
5311 BaseAlignment =
5312 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5313 }
5314
5315 if (BaseAlignment < Align) {
5316 Result.Designator.setInvalid();
Yaron Kerene0bcdd42016-10-08 06:45:10 +00005317 // FIXME: Quantities here cast to integers because the plural modifier
5318 // does not work on APSInts yet.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005319 CCEDiag(E->getArg(0),
5320 diag::note_constexpr_baa_insufficient_alignment) << 0
5321 << (int) BaseAlignment.getQuantity()
5322 << (unsigned) getExtValue(Alignment);
5323 return false;
5324 }
5325 }
5326
5327 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005328 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005329 Result.Designator.setInvalid();
5330 APSInt Offset(64, false);
5331 Offset = OffsetResult.Offset.getQuantity();
5332
5333 if (OffsetResult.Base)
5334 CCEDiag(E->getArg(0),
5335 diag::note_constexpr_baa_insufficient_alignment) << 1
5336 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5337 else
5338 CCEDiag(E->getArg(0),
5339 diag::note_constexpr_baa_value_insufficient_alignment)
5340 << Offset << (unsigned) getExtValue(Alignment);
5341
5342 return false;
5343 }
5344
5345 return true;
5346 }
Richard Smithe9507952016-11-12 01:39:56 +00005347
5348 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005349 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005350 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005351 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005352 if (Info.getLangOpts().CPlusPlus11)
5353 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5354 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005355 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005356 else
5357 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5358 // Fall through.
5359 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005360 case Builtin::BI__builtin_wcschr:
5361 case Builtin::BI__builtin_memchr:
5362 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005363 if (!Visit(E->getArg(0)))
5364 return false;
5365 APSInt Desired;
5366 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5367 return false;
5368 uint64_t MaxLength = uint64_t(-1);
5369 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005370 BuiltinOp != Builtin::BIwcschr &&
5371 BuiltinOp != Builtin::BI__builtin_strchr &&
5372 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005373 APSInt N;
5374 if (!EvaluateInteger(E->getArg(2), N, Info))
5375 return false;
5376 MaxLength = N.getExtValue();
5377 }
5378
Richard Smith8110c9d2016-11-29 19:45:17 +00005379 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005380
Richard Smith8110c9d2016-11-29 19:45:17 +00005381 // Figure out what value we're actually looking for (after converting to
5382 // the corresponding unsigned type if necessary).
5383 uint64_t DesiredVal;
5384 bool StopAtNull = false;
5385 switch (BuiltinOp) {
5386 case Builtin::BIstrchr:
5387 case Builtin::BI__builtin_strchr:
5388 // strchr compares directly to the passed integer, and therefore
5389 // always fails if given an int that is not a char.
5390 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5391 E->getArg(1)->getType(),
5392 Desired),
5393 Desired))
5394 return ZeroInitialization(E);
5395 StopAtNull = true;
5396 // Fall through.
5397 case Builtin::BImemchr:
5398 case Builtin::BI__builtin_memchr:
5399 // memchr compares by converting both sides to unsigned char. That's also
5400 // correct for strchr if we get this far (to cope with plain char being
5401 // unsigned in the strchr case).
5402 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5403 break;
Richard Smithe9507952016-11-12 01:39:56 +00005404
Richard Smith8110c9d2016-11-29 19:45:17 +00005405 case Builtin::BIwcschr:
5406 case Builtin::BI__builtin_wcschr:
5407 StopAtNull = true;
5408 // Fall through.
5409 case Builtin::BIwmemchr:
5410 case Builtin::BI__builtin_wmemchr:
5411 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5412 DesiredVal = Desired.getZExtValue();
5413 break;
5414 }
Richard Smithe9507952016-11-12 01:39:56 +00005415
5416 for (; MaxLength; --MaxLength) {
5417 APValue Char;
5418 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5419 !Char.isInt())
5420 return false;
5421 if (Char.getInt().getZExtValue() == DesiredVal)
5422 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005423 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005424 break;
5425 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5426 return false;
5427 }
5428 // Not found: return nullptr.
5429 return ZeroInitialization(E);
5430 }
5431
Richard Smith6cbd65d2013-07-11 02:27:57 +00005432 default:
5433 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5434 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005435}
Chris Lattner05706e882008-07-11 18:11:29 +00005436
5437//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005438// Member Pointer Evaluation
5439//===----------------------------------------------------------------------===//
5440
5441namespace {
5442class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005443 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005444 MemberPtr &Result;
5445
5446 bool Success(const ValueDecl *D) {
5447 Result = MemberPtr(D);
5448 return true;
5449 }
5450public:
5451
5452 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5453 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5454
Richard Smith2e312c82012-03-03 22:46:17 +00005455 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005456 Result.setFrom(V);
5457 return true;
5458 }
Richard Smithfddd3842011-12-30 21:15:51 +00005459 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005460 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005461 }
5462
5463 bool VisitCastExpr(const CastExpr *E);
5464 bool VisitUnaryAddrOf(const UnaryOperator *E);
5465};
5466} // end anonymous namespace
5467
5468static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5469 EvalInfo &Info) {
5470 assert(E->isRValue() && E->getType()->isMemberPointerType());
5471 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5472}
5473
5474bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5475 switch (E->getCastKind()) {
5476 default:
5477 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5478
5479 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005480 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005481 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005482
5483 case CK_BaseToDerivedMemberPointer: {
5484 if (!Visit(E->getSubExpr()))
5485 return false;
5486 if (E->path_empty())
5487 return true;
5488 // Base-to-derived member pointer casts store the path in derived-to-base
5489 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5490 // the wrong end of the derived->base arc, so stagger the path by one class.
5491 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5492 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5493 PathI != PathE; ++PathI) {
5494 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5495 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5496 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005497 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005498 }
5499 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5500 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005501 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005502 return true;
5503 }
5504
5505 case CK_DerivedToBaseMemberPointer:
5506 if (!Visit(E->getSubExpr()))
5507 return false;
5508 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5509 PathE = E->path_end(); PathI != PathE; ++PathI) {
5510 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5511 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5512 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005513 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005514 }
5515 return true;
5516 }
5517}
5518
5519bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5520 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5521 // member can be formed.
5522 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5523}
5524
5525//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005526// Record Evaluation
5527//===----------------------------------------------------------------------===//
5528
5529namespace {
5530 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005531 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005532 const LValue &This;
5533 APValue &Result;
5534 public:
5535
5536 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5537 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5538
Richard Smith2e312c82012-03-03 22:46:17 +00005539 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005540 Result = V;
5541 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005542 }
Richard Smithb8348f52016-05-12 22:16:28 +00005543 bool ZeroInitialization(const Expr *E) {
5544 return ZeroInitialization(E, E->getType());
5545 }
5546 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005547
Richard Smith52a980a2015-08-28 02:43:42 +00005548 bool VisitCallExpr(const CallExpr *E) {
5549 return handleCallExpr(E, Result, &This);
5550 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005551 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005552 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005553 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5554 return VisitCXXConstructExpr(E, E->getType());
5555 }
Richard Smith5179eb72016-06-28 19:03:57 +00005556 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005557 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005558 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005559 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005560}
Richard Smithd62306a2011-11-10 06:34:14 +00005561
Richard Smithfddd3842011-12-30 21:15:51 +00005562/// Perform zero-initialization on an object of non-union class type.
5563/// C++11 [dcl.init]p5:
5564/// To zero-initialize an object or reference of type T means:
5565/// [...]
5566/// -- if T is a (possibly cv-qualified) non-union class type,
5567/// each non-static data member and each base-class subobject is
5568/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005569static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5570 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005571 const LValue &This, APValue &Result) {
5572 assert(!RD->isUnion() && "Expected non-union class type");
5573 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5574 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005575 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005576
John McCalld7bca762012-05-01 00:38:49 +00005577 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005578 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5579
5580 if (CD) {
5581 unsigned Index = 0;
5582 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005583 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005584 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5585 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005586 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5587 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005588 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005589 Result.getStructBase(Index)))
5590 return false;
5591 }
5592 }
5593
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005594 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005595 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005596 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005597 continue;
5598
5599 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005600 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005601 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005602
David Blaikie2d7c57e2012-04-30 02:36:29 +00005603 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005604 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005605 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005606 return false;
5607 }
5608
5609 return true;
5610}
5611
Richard Smithb8348f52016-05-12 22:16:28 +00005612bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5613 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005614 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005615 if (RD->isUnion()) {
5616 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5617 // object's first non-static named data member is zero-initialized
5618 RecordDecl::field_iterator I = RD->field_begin();
5619 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005620 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005621 return true;
5622 }
5623
5624 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005625 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005626 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005627 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005628 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005629 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005630 }
5631
Richard Smith5d108602012-02-17 00:44:16 +00005632 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005633 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005634 return false;
5635 }
5636
Richard Smitha8105bc2012-01-06 16:39:00 +00005637 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005638}
5639
Richard Smithe97cbd72011-11-11 04:05:33 +00005640bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5641 switch (E->getCastKind()) {
5642 default:
5643 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5644
5645 case CK_ConstructorConversion:
5646 return Visit(E->getSubExpr());
5647
5648 case CK_DerivedToBase:
5649 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005650 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005651 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005652 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005653 if (!DerivedObject.isStruct())
5654 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005655
5656 // Derived-to-base rvalue conversion: just slice off the derived part.
5657 APValue *Value = &DerivedObject;
5658 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5659 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5660 PathE = E->path_end(); PathI != PathE; ++PathI) {
5661 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5662 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5663 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5664 RD = Base;
5665 }
5666 Result = *Value;
5667 return true;
5668 }
5669 }
5670}
5671
Richard Smithd62306a2011-11-10 06:34:14 +00005672bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00005673 if (E->isTransparent())
5674 return Visit(E->getInit(0));
5675
Richard Smithd62306a2011-11-10 06:34:14 +00005676 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005677 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005678 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5679
5680 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005681 const FieldDecl *Field = E->getInitializedFieldInUnion();
5682 Result = APValue(Field);
5683 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005684 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005685
5686 // If the initializer list for a union does not contain any elements, the
5687 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005688 // FIXME: The element should be initialized from an initializer list.
5689 // Is this difference ever observable for initializer lists which
5690 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005691 ImplicitValueInitExpr VIE(Field->getType());
5692 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5693
Richard Smithd62306a2011-11-10 06:34:14 +00005694 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005695 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5696 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005697
5698 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5699 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5700 isa<CXXDefaultInitExpr>(InitExpr));
5701
Richard Smithb228a862012-02-15 02:18:13 +00005702 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005703 }
5704
Richard Smith872307e2016-03-08 22:17:41 +00005705 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005706 if (Result.isUninit())
5707 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5708 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005709 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005710 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005711
5712 // Initialize base classes.
5713 if (CXXRD) {
5714 for (const auto &Base : CXXRD->bases()) {
5715 assert(ElementNo < E->getNumInits() && "missing init for base class");
5716 const Expr *Init = E->getInit(ElementNo);
5717
5718 LValue Subobject = This;
5719 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5720 return false;
5721
5722 APValue &FieldVal = Result.getStructBase(ElementNo);
5723 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00005724 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00005725 return false;
5726 Success = false;
5727 }
5728 ++ElementNo;
5729 }
5730 }
5731
5732 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005733 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005734 // Anonymous bit-fields are not considered members of the class for
5735 // purposes of aggregate initialization.
5736 if (Field->isUnnamedBitfield())
5737 continue;
5738
5739 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005740
Richard Smith253c2a32012-01-27 01:14:48 +00005741 bool HaveInit = ElementNo < E->getNumInits();
5742
5743 // FIXME: Diagnostics here should point to the end of the initializer
5744 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005745 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005746 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005747 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005748
5749 // Perform an implicit value-initialization for members beyond the end of
5750 // the initializer list.
5751 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005752 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005753
Richard Smith852c9db2013-04-20 22:23:05 +00005754 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5755 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5756 isa<CXXDefaultInitExpr>(Init));
5757
Richard Smith49ca8aa2013-08-06 07:09:20 +00005758 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5759 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5760 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005761 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00005762 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005763 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005764 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005765 }
5766 }
5767
Richard Smith253c2a32012-01-27 01:14:48 +00005768 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005769}
5770
Richard Smithb8348f52016-05-12 22:16:28 +00005771bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5772 QualType T) {
5773 // Note that E's type is not necessarily the type of our class here; we might
5774 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005775 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005776 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5777
Richard Smithfddd3842011-12-30 21:15:51 +00005778 bool ZeroInit = E->requiresZeroInitialization();
5779 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005780 // If we've already performed zero-initialization, we're already done.
5781 if (!Result.isUninit())
5782 return true;
5783
Richard Smithda3f4fd2014-03-05 23:32:50 +00005784 // We can get here in two different ways:
5785 // 1) We're performing value-initialization, and should zero-initialize
5786 // the object, or
5787 // 2) We're performing default-initialization of an object with a trivial
5788 // constexpr default constructor, in which case we should start the
5789 // lifetimes of all the base subobjects (there can be no data member
5790 // subobjects in this case) per [basic.life]p1.
5791 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005792 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005793 }
5794
Craig Topper36250ad2014-05-12 05:36:57 +00005795 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005796 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005797
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005798 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005799 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005800
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005801 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005802 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005803 if (const MaterializeTemporaryExpr *ME
5804 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5805 return Visit(ME->GetTemporaryExpr());
5806
Richard Smithb8348f52016-05-12 22:16:28 +00005807 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005808 return false;
5809
Craig Topper5fc8fc22014-08-27 06:28:36 +00005810 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00005811 return HandleConstructorCall(E, This, Args,
5812 cast<CXXConstructorDecl>(Definition), Info,
5813 Result);
5814}
5815
5816bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
5817 const CXXInheritedCtorInitExpr *E) {
5818 if (!Info.CurrentCall) {
5819 assert(Info.checkingPotentialConstantExpression());
5820 return false;
5821 }
5822
5823 const CXXConstructorDecl *FD = E->getConstructor();
5824 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
5825 return false;
5826
5827 const FunctionDecl *Definition = nullptr;
5828 auto Body = FD->getBody(Definition);
5829
5830 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5831 return false;
5832
5833 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005834 cast<CXXConstructorDecl>(Definition), Info,
5835 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005836}
5837
Richard Smithcc1b96d2013-06-12 22:31:48 +00005838bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5839 const CXXStdInitializerListExpr *E) {
5840 const ConstantArrayType *ArrayType =
5841 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5842
5843 LValue Array;
5844 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5845 return false;
5846
5847 // Get a pointer to the first element of the array.
5848 Array.addArray(Info, E, ArrayType);
5849
5850 // FIXME: Perform the checks on the field types in SemaInit.
5851 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5852 RecordDecl::field_iterator Field = Record->field_begin();
5853 if (Field == Record->field_end())
5854 return Error(E);
5855
5856 // Start pointer.
5857 if (!Field->getType()->isPointerType() ||
5858 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5859 ArrayType->getElementType()))
5860 return Error(E);
5861
5862 // FIXME: What if the initializer_list type has base classes, etc?
5863 Result = APValue(APValue::UninitStruct(), 0, 2);
5864 Array.moveInto(Result.getStructField(0));
5865
5866 if (++Field == Record->field_end())
5867 return Error(E);
5868
5869 if (Field->getType()->isPointerType() &&
5870 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5871 ArrayType->getElementType())) {
5872 // End pointer.
5873 if (!HandleLValueArrayAdjustment(Info, E, Array,
5874 ArrayType->getElementType(),
5875 ArrayType->getSize().getZExtValue()))
5876 return false;
5877 Array.moveInto(Result.getStructField(1));
5878 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5879 // Length.
5880 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5881 else
5882 return Error(E);
5883
5884 if (++Field != Record->field_end())
5885 return Error(E);
5886
5887 return true;
5888}
5889
Richard Smithd62306a2011-11-10 06:34:14 +00005890static bool EvaluateRecord(const Expr *E, const LValue &This,
5891 APValue &Result, EvalInfo &Info) {
5892 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005893 "can't evaluate expression as a record rvalue");
5894 return RecordExprEvaluator(Info, This, Result).Visit(E);
5895}
5896
5897//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005898// Temporary Evaluation
5899//
5900// Temporaries are represented in the AST as rvalues, but generally behave like
5901// lvalues. The full-object of which the temporary is a subobject is implicitly
5902// materialized so that a reference can bind to it.
5903//===----------------------------------------------------------------------===//
5904namespace {
5905class TemporaryExprEvaluator
5906 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5907public:
5908 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5909 LValueExprEvaluatorBaseTy(Info, Result) {}
5910
5911 /// Visit an expression which constructs the value of this temporary.
5912 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005913 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005914 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5915 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005916 }
5917
5918 bool VisitCastExpr(const CastExpr *E) {
5919 switch (E->getCastKind()) {
5920 default:
5921 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5922
5923 case CK_ConstructorConversion:
5924 return VisitConstructExpr(E->getSubExpr());
5925 }
5926 }
5927 bool VisitInitListExpr(const InitListExpr *E) {
5928 return VisitConstructExpr(E);
5929 }
5930 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5931 return VisitConstructExpr(E);
5932 }
5933 bool VisitCallExpr(const CallExpr *E) {
5934 return VisitConstructExpr(E);
5935 }
Richard Smith513955c2014-12-17 19:24:30 +00005936 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5937 return VisitConstructExpr(E);
5938 }
Richard Smith027bf112011-11-17 22:56:20 +00005939};
5940} // end anonymous namespace
5941
5942/// Evaluate an expression of record type as a temporary.
5943static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005944 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005945 return TemporaryExprEvaluator(Info, Result).Visit(E);
5946}
5947
5948//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005949// Vector Evaluation
5950//===----------------------------------------------------------------------===//
5951
5952namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005953 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005954 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005955 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005956 public:
Mike Stump11289f42009-09-09 15:08:12 +00005957
Richard Smith2d406342011-10-22 21:10:00 +00005958 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5959 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005960
Craig Topper9798b932015-09-29 04:30:05 +00005961 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005962 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5963 // FIXME: remove this APValue copy.
5964 Result = APValue(V.data(), V.size());
5965 return true;
5966 }
Richard Smith2e312c82012-03-03 22:46:17 +00005967 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005968 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005969 Result = V;
5970 return true;
5971 }
Richard Smithfddd3842011-12-30 21:15:51 +00005972 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005973
Richard Smith2d406342011-10-22 21:10:00 +00005974 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005975 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005976 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005977 bool VisitInitListExpr(const InitListExpr *E);
5978 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005979 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005980 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005981 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005982 };
5983} // end anonymous namespace
5984
5985static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005986 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005987 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005988}
5989
George Burgess IV533ff002015-12-11 00:23:35 +00005990bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005991 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005992 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005993
Richard Smith161f09a2011-12-06 22:44:34 +00005994 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005995 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005996
Eli Friedmanc757de22011-03-25 00:43:55 +00005997 switch (E->getCastKind()) {
5998 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005999 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006000 if (SETy->isIntegerType()) {
6001 APSInt IntResult;
6002 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006003 return false;
6004 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006005 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006006 APFloat FloatResult(0.0);
6007 if (!EvaluateFloat(SE, FloatResult, Info))
6008 return false;
6009 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006010 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006011 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006012 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006013
6014 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006015 SmallVector<APValue, 4> Elts(NElts, Val);
6016 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006017 }
Eli Friedman803acb32011-12-22 03:51:45 +00006018 case CK_BitCast: {
6019 // Evaluate the operand into an APInt we can extract from.
6020 llvm::APInt SValInt;
6021 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6022 return false;
6023 // Extract the elements
6024 QualType EltTy = VTy->getElementType();
6025 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6026 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6027 SmallVector<APValue, 4> Elts;
6028 if (EltTy->isRealFloatingType()) {
6029 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006030 unsigned FloatEltSize = EltSize;
6031 if (&Sem == &APFloat::x87DoubleExtended)
6032 FloatEltSize = 80;
6033 for (unsigned i = 0; i < NElts; i++) {
6034 llvm::APInt Elt;
6035 if (BigEndian)
6036 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6037 else
6038 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006039 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006040 }
6041 } else if (EltTy->isIntegerType()) {
6042 for (unsigned i = 0; i < NElts; i++) {
6043 llvm::APInt Elt;
6044 if (BigEndian)
6045 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6046 else
6047 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6048 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6049 }
6050 } else {
6051 return Error(E);
6052 }
6053 return Success(Elts, E);
6054 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006055 default:
Richard Smith11562c52011-10-28 17:51:58 +00006056 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006057 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006058}
6059
Richard Smith2d406342011-10-22 21:10:00 +00006060bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006061VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006062 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006063 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006064 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006065
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006066 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006067 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006068
Eli Friedmanb9c71292012-01-03 23:24:20 +00006069 // The number of initializers can be less than the number of
6070 // vector elements. For OpenCL, this can be due to nested vector
6071 // initialization. For GCC compatibility, missing trailing elements
6072 // should be initialized with zeroes.
6073 unsigned CountInits = 0, CountElts = 0;
6074 while (CountElts < NumElements) {
6075 // Handle nested vector initialization.
6076 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006077 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006078 APValue v;
6079 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6080 return Error(E);
6081 unsigned vlen = v.getVectorLength();
6082 for (unsigned j = 0; j < vlen; j++)
6083 Elements.push_back(v.getVectorElt(j));
6084 CountElts += vlen;
6085 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006086 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006087 if (CountInits < NumInits) {
6088 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006089 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006090 } else // trailing integer zero.
6091 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6092 Elements.push_back(APValue(sInt));
6093 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006094 } else {
6095 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006096 if (CountInits < NumInits) {
6097 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006098 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006099 } else // trailing float zero.
6100 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6101 Elements.push_back(APValue(f));
6102 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006103 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006104 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006105 }
Richard Smith2d406342011-10-22 21:10:00 +00006106 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006107}
6108
Richard Smith2d406342011-10-22 21:10:00 +00006109bool
Richard Smithfddd3842011-12-30 21:15:51 +00006110VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006111 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006112 QualType EltTy = VT->getElementType();
6113 APValue ZeroElement;
6114 if (EltTy->isIntegerType())
6115 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6116 else
6117 ZeroElement =
6118 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6119
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006120 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006121 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006122}
6123
Richard Smith2d406342011-10-22 21:10:00 +00006124bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006125 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006126 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006127}
6128
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006129//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006130// Array Evaluation
6131//===----------------------------------------------------------------------===//
6132
6133namespace {
6134 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006135 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006136 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006137 APValue &Result;
6138 public:
6139
Richard Smithd62306a2011-11-10 06:34:14 +00006140 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6141 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006142
6143 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006144 assert((V.isArray() || V.isLValue()) &&
6145 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006146 Result = V;
6147 return true;
6148 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006149
Richard Smithfddd3842011-12-30 21:15:51 +00006150 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006151 const ConstantArrayType *CAT =
6152 Info.Ctx.getAsConstantArrayType(E->getType());
6153 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006154 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006155
6156 Result = APValue(APValue::UninitArray(), 0,
6157 CAT->getSize().getZExtValue());
6158 if (!Result.hasArrayFiller()) return true;
6159
Richard Smithfddd3842011-12-30 21:15:51 +00006160 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006161 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006162 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006163 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006164 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006165 }
6166
Richard Smith52a980a2015-08-28 02:43:42 +00006167 bool VisitCallExpr(const CallExpr *E) {
6168 return handleCallExpr(E, Result, &This);
6169 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006170 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006171 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006172 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6173 const LValue &Subobject,
6174 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006175 };
6176} // end anonymous namespace
6177
Richard Smithd62306a2011-11-10 06:34:14 +00006178static bool EvaluateArray(const Expr *E, const LValue &This,
6179 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006180 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006181 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006182}
6183
6184bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6185 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6186 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006187 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006188
Richard Smithca2cfbf2011-12-22 01:07:19 +00006189 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6190 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006191 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006192 LValue LV;
6193 if (!EvaluateLValue(E->getInit(0), LV, Info))
6194 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006195 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006196 LV.moveInto(Val);
6197 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006198 }
6199
Richard Smith253c2a32012-01-27 01:14:48 +00006200 bool Success = true;
6201
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006202 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6203 "zero-initialized array shouldn't have any initialized elts");
6204 APValue Filler;
6205 if (Result.isArray() && Result.hasArrayFiller())
6206 Filler = Result.getArrayFiller();
6207
Richard Smith9543c5e2013-04-22 14:44:29 +00006208 unsigned NumEltsToInit = E->getNumInits();
6209 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006210 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006211
6212 // If the initializer might depend on the array index, run it for each
6213 // array element. For now, just whitelist non-class value-initialization.
6214 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6215 NumEltsToInit = NumElts;
6216
6217 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006218
6219 // If the array was previously zero-initialized, preserve the
6220 // zero-initialized values.
6221 if (!Filler.isUninit()) {
6222 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6223 Result.getArrayInitializedElt(I) = Filler;
6224 if (Result.hasArrayFiller())
6225 Result.getArrayFiller() = Filler;
6226 }
6227
Richard Smithd62306a2011-11-10 06:34:14 +00006228 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006229 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006230 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6231 const Expr *Init =
6232 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006233 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006234 Info, Subobject, Init) ||
6235 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006236 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006237 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006238 return false;
6239 Success = false;
6240 }
Richard Smithd62306a2011-11-10 06:34:14 +00006241 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006242
Richard Smith9543c5e2013-04-22 14:44:29 +00006243 if (!Result.hasArrayFiller())
6244 return Success;
6245
6246 // If we get here, we have a trivial filler, which we can just evaluate
6247 // once and splat over the rest of the array elements.
6248 assert(FillerExpr && "no array filler for incomplete init list");
6249 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6250 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006251}
6252
Richard Smith027bf112011-11-17 22:56:20 +00006253bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006254 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6255}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006256
Richard Smith9543c5e2013-04-22 14:44:29 +00006257bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6258 const LValue &Subobject,
6259 APValue *Value,
6260 QualType Type) {
6261 bool HadZeroInit = !Value->isUninit();
6262
6263 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6264 unsigned N = CAT->getSize().getZExtValue();
6265
6266 // Preserve the array filler if we had prior zero-initialization.
6267 APValue Filler =
6268 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6269 : APValue();
6270
6271 *Value = APValue(APValue::UninitArray(), N, N);
6272
6273 if (HadZeroInit)
6274 for (unsigned I = 0; I != N; ++I)
6275 Value->getArrayInitializedElt(I) = Filler;
6276
6277 // Initialize the elements.
6278 LValue ArrayElt = Subobject;
6279 ArrayElt.addArray(Info, E, CAT);
6280 for (unsigned I = 0; I != N; ++I)
6281 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6282 CAT->getElementType()) ||
6283 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6284 CAT->getElementType(), 1))
6285 return false;
6286
6287 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006288 }
Richard Smith027bf112011-11-17 22:56:20 +00006289
Richard Smith9543c5e2013-04-22 14:44:29 +00006290 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006291 return Error(E);
6292
Richard Smithb8348f52016-05-12 22:16:28 +00006293 return RecordExprEvaluator(Info, Subobject, *Value)
6294 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006295}
6296
Richard Smithf3e9e432011-11-07 09:22:26 +00006297//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006298// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006299//
6300// As a GNU extension, we support casting pointers to sufficiently-wide integer
6301// types and back in constant folding. Integer values are thus represented
6302// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006303//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006304
6305namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006306class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006307 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006308 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006309public:
Richard Smith2e312c82012-03-03 22:46:17 +00006310 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006311 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006312
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006313 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006314 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006315 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006316 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006317 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006318 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006319 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006320 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006321 return true;
6322 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006323 bool Success(const llvm::APSInt &SI, const Expr *E) {
6324 return Success(SI, E, Result);
6325 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006326
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006327 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006328 assert(E->getType()->isIntegralOrEnumerationType() &&
6329 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006330 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006331 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006332 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006333 Result.getInt().setIsUnsigned(
6334 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006335 return true;
6336 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006337 bool Success(const llvm::APInt &I, const Expr *E) {
6338 return Success(I, E, Result);
6339 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006340
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006341 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006342 assert(E->getType()->isIntegralOrEnumerationType() &&
6343 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006344 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006345 return true;
6346 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006347 bool Success(uint64_t Value, const Expr *E) {
6348 return Success(Value, E, Result);
6349 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006350
Ken Dyckdbc01912011-03-11 02:13:43 +00006351 bool Success(CharUnits Size, const Expr *E) {
6352 return Success(Size.getQuantity(), E);
6353 }
6354
Richard Smith2e312c82012-03-03 22:46:17 +00006355 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006356 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006357 Result = V;
6358 return true;
6359 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006360 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006361 }
Mike Stump11289f42009-09-09 15:08:12 +00006362
Richard Smithfddd3842011-12-30 21:15:51 +00006363 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006364
Peter Collingbournee9200682011-05-13 03:29:01 +00006365 //===--------------------------------------------------------------------===//
6366 // Visitor Methods
6367 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006368
Chris Lattner7174bf32008-07-12 00:38:25 +00006369 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006370 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006371 }
6372 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006373 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006374 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006375
6376 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6377 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006378 if (CheckReferencedDecl(E, E->getDecl()))
6379 return true;
6380
6381 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006382 }
6383 bool VisitMemberExpr(const MemberExpr *E) {
6384 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006385 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006386 return true;
6387 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006388
6389 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006390 }
6391
Peter Collingbournee9200682011-05-13 03:29:01 +00006392 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006393 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006394 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006395 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006396 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006397
Peter Collingbournee9200682011-05-13 03:29:01 +00006398 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006399 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006400
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006401 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006402 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006403 }
Mike Stump11289f42009-09-09 15:08:12 +00006404
Ted Kremeneke65b0862012-03-06 20:05:56 +00006405 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6406 return Success(E->getValue(), E);
6407 }
6408
Richard Smith4ce706a2011-10-11 21:43:33 +00006409 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006410 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006411 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006412 }
6413
Douglas Gregor29c42f22012-02-24 07:38:34 +00006414 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6415 return Success(E->getValue(), E);
6416 }
6417
John Wiegley6242b6a2011-04-28 00:16:57 +00006418 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6419 return Success(E->getValue(), E);
6420 }
6421
John Wiegleyf9f65842011-04-25 06:54:41 +00006422 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6423 return Success(E->getValue(), E);
6424 }
6425
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006426 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006427 bool VisitUnaryImag(const UnaryOperator *E);
6428
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006429 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006430 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006431
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006432private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006433 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006434 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006435};
Chris Lattner05706e882008-07-11 18:11:29 +00006436} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006437
Richard Smith11562c52011-10-28 17:51:58 +00006438/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6439/// produce either the integer value or a pointer.
6440///
6441/// GCC has a heinous extension which folds casts between pointer types and
6442/// pointer-sized integral types. We support this by allowing the evaluation of
6443/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6444/// Some simple arithmetic on such values is supported (they are treated much
6445/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006446static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006447 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006448 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006449 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006450}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006451
Richard Smithf57d8cb2011-12-09 22:58:01 +00006452static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006453 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006454 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006455 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006456 if (!Val.isInt()) {
6457 // FIXME: It would be better to produce the diagnostic for casting
6458 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006459 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006460 return false;
6461 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006462 Result = Val.getInt();
6463 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006464}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006465
Richard Smithf57d8cb2011-12-09 22:58:01 +00006466/// Check whether the given declaration can be directly converted to an integral
6467/// rvalue. If not, no diagnostic is produced; there are other things we can
6468/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006469bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006470 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006471 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006472 // Check for signedness/width mismatches between E type and ECD value.
6473 bool SameSign = (ECD->getInitVal().isSigned()
6474 == E->getType()->isSignedIntegerOrEnumerationType());
6475 bool SameWidth = (ECD->getInitVal().getBitWidth()
6476 == Info.Ctx.getIntWidth(E->getType()));
6477 if (SameSign && SameWidth)
6478 return Success(ECD->getInitVal(), E);
6479 else {
6480 // Get rid of mismatch (otherwise Success assertions will fail)
6481 // by computing a new value matching the type of E.
6482 llvm::APSInt Val = ECD->getInitVal();
6483 if (!SameSign)
6484 Val.setIsSigned(!ECD->getInitVal().isSigned());
6485 if (!SameWidth)
6486 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6487 return Success(Val, E);
6488 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006489 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006490 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006491}
6492
Chris Lattner86ee2862008-10-06 06:40:35 +00006493/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6494/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006495static int EvaluateBuiltinClassifyType(const CallExpr *E,
6496 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006497 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006498 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006499 enum gcc_type_class {
6500 no_type_class = -1,
6501 void_type_class, integer_type_class, char_type_class,
6502 enumeral_type_class, boolean_type_class,
6503 pointer_type_class, reference_type_class, offset_type_class,
6504 real_type_class, complex_type_class,
6505 function_type_class, method_type_class,
6506 record_type_class, union_type_class,
6507 array_type_class, string_type_class,
6508 lang_type_class
6509 };
Mike Stump11289f42009-09-09 15:08:12 +00006510
6511 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006512 // ideal, however it is what gcc does.
6513 if (E->getNumArgs() == 0)
6514 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006515
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006516 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6517 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6518
6519 switch (CanTy->getTypeClass()) {
6520#define TYPE(ID, BASE)
6521#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6522#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6523#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6524#include "clang/AST/TypeNodes.def"
6525 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6526
6527 case Type::Builtin:
6528 switch (BT->getKind()) {
6529#define BUILTIN_TYPE(ID, SINGLETON_ID)
6530#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6531#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6532#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6533#include "clang/AST/BuiltinTypes.def"
6534 case BuiltinType::Void:
6535 return void_type_class;
6536
6537 case BuiltinType::Bool:
6538 return boolean_type_class;
6539
6540 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6541 case BuiltinType::UChar:
6542 case BuiltinType::UShort:
6543 case BuiltinType::UInt:
6544 case BuiltinType::ULong:
6545 case BuiltinType::ULongLong:
6546 case BuiltinType::UInt128:
6547 return integer_type_class;
6548
6549 case BuiltinType::NullPtr:
6550 return pointer_type_class;
6551
6552 case BuiltinType::WChar_U:
6553 case BuiltinType::Char16:
6554 case BuiltinType::Char32:
6555 case BuiltinType::ObjCId:
6556 case BuiltinType::ObjCClass:
6557 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006558#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6559 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006560#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006561 case BuiltinType::OCLSampler:
6562 case BuiltinType::OCLEvent:
6563 case BuiltinType::OCLClkEvent:
6564 case BuiltinType::OCLQueue:
6565 case BuiltinType::OCLNDRange:
6566 case BuiltinType::OCLReserveID:
6567 case BuiltinType::Dependent:
6568 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6569 };
6570
6571 case Type::Enum:
6572 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6573 break;
6574
6575 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006576 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006577 break;
6578
6579 case Type::MemberPointer:
6580 if (CanTy->isMemberDataPointerType())
6581 return offset_type_class;
6582 else {
6583 // We expect member pointers to be either data or function pointers,
6584 // nothing else.
6585 assert(CanTy->isMemberFunctionPointerType());
6586 return method_type_class;
6587 }
6588
6589 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006590 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006591
6592 case Type::FunctionNoProto:
6593 case Type::FunctionProto:
6594 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6595
6596 case Type::Record:
6597 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6598 switch (RT->getDecl()->getTagKind()) {
6599 case TagTypeKind::TTK_Struct:
6600 case TagTypeKind::TTK_Class:
6601 case TagTypeKind::TTK_Interface:
6602 return record_type_class;
6603
6604 case TagTypeKind::TTK_Enum:
6605 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6606
6607 case TagTypeKind::TTK_Union:
6608 return union_type_class;
6609 }
6610 }
David Blaikie83d382b2011-09-23 05:06:16 +00006611 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006612
6613 case Type::ConstantArray:
6614 case Type::VariableArray:
6615 case Type::IncompleteArray:
6616 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6617
6618 case Type::BlockPointer:
6619 case Type::LValueReference:
6620 case Type::RValueReference:
6621 case Type::Vector:
6622 case Type::ExtVector:
6623 case Type::Auto:
6624 case Type::ObjCObject:
6625 case Type::ObjCInterface:
6626 case Type::ObjCObjectPointer:
6627 case Type::Pipe:
6628 case Type::Atomic:
6629 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6630 }
6631
6632 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006633}
6634
Richard Smith5fab0c92011-12-28 19:48:30 +00006635/// EvaluateBuiltinConstantPForLValue - Determine the result of
6636/// __builtin_constant_p when applied to the given lvalue.
6637///
6638/// An lvalue is only "constant" if it is a pointer or reference to the first
6639/// character of a string literal.
6640template<typename LValue>
6641static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006642 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006643 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6644}
6645
6646/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6647/// GCC as we can manage.
6648static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6649 QualType ArgType = Arg->getType();
6650
6651 // __builtin_constant_p always has one operand. The rules which gcc follows
6652 // are not precisely documented, but are as follows:
6653 //
6654 // - If the operand is of integral, floating, complex or enumeration type,
6655 // and can be folded to a known value of that type, it returns 1.
6656 // - If the operand and can be folded to a pointer to the first character
6657 // of a string literal (or such a pointer cast to an integral type), it
6658 // returns 1.
6659 //
6660 // Otherwise, it returns 0.
6661 //
6662 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6663 // its support for this does not currently work.
6664 if (ArgType->isIntegralOrEnumerationType()) {
6665 Expr::EvalResult Result;
6666 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6667 return false;
6668
6669 APValue &V = Result.Val;
6670 if (V.getKind() == APValue::Int)
6671 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006672 if (V.getKind() == APValue::LValue)
6673 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006674 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6675 return Arg->isEvaluatable(Ctx);
6676 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6677 LValue LV;
6678 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006679 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006680 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6681 : EvaluatePointer(Arg, LV, Info)) &&
6682 !Status.HasSideEffects)
6683 return EvaluateBuiltinConstantPForLValue(LV);
6684 }
6685
6686 // Anything else isn't considered to be sufficiently constant.
6687 return false;
6688}
6689
John McCall95007602010-05-10 23:27:23 +00006690/// Retrieves the "underlying object type" of the given expression,
6691/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006692static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006693 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6694 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006695 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006696 } else if (const Expr *E = B.get<const Expr*>()) {
6697 if (isa<CompoundLiteralExpr>(E))
6698 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006699 }
6700
6701 return QualType();
6702}
6703
George Burgess IV3a03fab2015-09-04 21:28:13 +00006704/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006705/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6706/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006707/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6708///
6709/// Always returns an RValue with a pointer representation.
6710static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6711 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6712
6713 auto *NoParens = E->IgnoreParens();
6714 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006715 if (Cast == nullptr)
6716 return NoParens;
6717
6718 // We only conservatively allow a few kinds of casts, because this code is
6719 // inherently a simple solution that seeks to support the common case.
6720 auto CastKind = Cast->getCastKind();
6721 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6722 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006723 return NoParens;
6724
6725 auto *SubExpr = Cast->getSubExpr();
6726 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6727 return NoParens;
6728 return ignorePointerCastsAndParens(SubExpr);
6729}
6730
George Burgess IVa51c4072015-10-16 01:49:01 +00006731/// Checks to see if the given LValue's Designator is at the end of the LValue's
6732/// record layout. e.g.
6733/// struct { struct { int a, b; } fst, snd; } obj;
6734/// obj.fst // no
6735/// obj.snd // yes
6736/// obj.fst.a // no
6737/// obj.fst.b // no
6738/// obj.snd.a // no
6739/// obj.snd.b // yes
6740///
6741/// Please note: this function is specialized for how __builtin_object_size
6742/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00006743///
6744/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00006745static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6746 assert(!LVal.Designator.Invalid);
6747
George Burgess IV4168d752016-06-27 19:40:41 +00006748 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
6749 const RecordDecl *Parent = FD->getParent();
6750 Invalid = Parent->isInvalidDecl();
6751 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00006752 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00006753 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00006754 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6755 };
6756
6757 auto &Base = LVal.getLValueBase();
6758 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6759 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006760 bool Invalid;
6761 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6762 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006763 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006764 for (auto *FD : IFD->chain()) {
6765 bool Invalid;
6766 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
6767 return Invalid;
6768 }
George Burgess IVa51c4072015-10-16 01:49:01 +00006769 }
6770 }
6771
6772 QualType BaseType = getType(Base);
6773 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6774 if (BaseType->isArrayType()) {
6775 // Because __builtin_object_size treats arrays as objects, we can ignore
6776 // the index iff this is the last array in the Designator.
6777 if (I + 1 == E)
6778 return true;
6779 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6780 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6781 if (Index + 1 != CAT->getSize())
6782 return false;
6783 BaseType = CAT->getElementType();
6784 } else if (BaseType->isAnyComplexType()) {
6785 auto *CT = BaseType->castAs<ComplexType>();
6786 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6787 if (Index != 1)
6788 return false;
6789 BaseType = CT->getElementType();
6790 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
George Burgess IV4168d752016-06-27 19:40:41 +00006791 bool Invalid;
6792 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6793 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006794 BaseType = FD->getType();
6795 } else {
6796 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6797 "Expecting cast to a base class");
6798 return false;
6799 }
6800 }
6801 return true;
6802}
6803
6804/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6805static bool refersToCompleteObject(const LValue &LVal) {
6806 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6807 return false;
6808
6809 if (!LVal.InvalidBase)
6810 return true;
6811
6812 auto *E = LVal.Base.dyn_cast<const Expr *>();
6813 (void)E;
6814 assert(E != nullptr && isa<MemberExpr>(E));
6815 return false;
6816}
6817
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006818/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6819/// true and stores the result in @p Size.
6820///
6821/// If @p WasError is non-null, this will report whether the failure to evaluate
6822/// is to be treated as an Error in IntExprEvaluator.
6823static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6824 EvalInfo &Info, uint64_t &Size,
6825 bool *WasError = nullptr) {
6826 if (WasError != nullptr)
6827 *WasError = false;
6828
6829 auto Error = [&](const Expr *E) {
6830 if (WasError != nullptr)
6831 *WasError = true;
6832 return false;
6833 };
6834
6835 auto Success = [&](uint64_t S, const Expr *E) {
6836 Size = S;
6837 return true;
6838 };
6839
George Burgess IVbdb5b262015-08-19 02:19:07 +00006840 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006841 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006842 {
6843 // The operand of __builtin_object_size is never evaluated for side-effects.
6844 // If there are any, but we can determine the pointed-to object anyway, then
6845 // ignore the side-effects.
6846 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006847 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006848
6849 if (E->isGLValue()) {
6850 // It's possible for us to be given GLValues if we're called via
6851 // Expr::tryEvaluateObjectSize.
6852 APValue RVal;
6853 if (!EvaluateAsRValue(Info, E, RVal))
6854 return false;
6855 Base.setFrom(Info.Ctx, RVal);
6856 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006857 return false;
6858 }
John McCall95007602010-05-10 23:27:23 +00006859
George Burgess IVbdb5b262015-08-19 02:19:07 +00006860 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006861 // If we point to before the start of the object, there are no accessible
6862 // bytes.
6863 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006864 return Success(0, E);
6865
George Burgess IV3a03fab2015-09-04 21:28:13 +00006866 // In the case where we're not dealing with a subobject, we discard the
6867 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006868 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006869
6870 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6871 // exist. If we can't verify the base, then we can't do that.
6872 //
6873 // As a special case, we produce a valid object size for an unknown object
6874 // with a known designator if Type & 1 is 1. For instance:
6875 //
6876 // extern struct X { char buff[32]; int a, b, c; } *p;
6877 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6878 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6879 //
6880 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006881 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006882 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006883
George Burgess IVa51c4072015-10-16 01:49:01 +00006884 // If we're not examining only the subobject, then we reset to a complete
6885 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006886 //
6887 // If Type is 1 and we've lost track of the subobject, just find the complete
6888 // object instead. (If Type is 3, that's not correct behavior and we should
6889 // return 0 instead.)
6890 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006891 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006892 QualType T = getObjectType(End.getLValueBase());
6893 if (T.isNull())
6894 End.Designator.setInvalid();
6895 else {
6896 End.Designator = SubobjectDesignator(T);
6897 End.Offset = CharUnits::Zero();
6898 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006899 }
John McCall95007602010-05-10 23:27:23 +00006900
George Burgess IVbdb5b262015-08-19 02:19:07 +00006901 // If it is not possible to determine which objects ptr points to at compile
6902 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6903 // and (size_t) 0 for type 2 or 3.
6904 if (End.Designator.Invalid)
6905 return false;
6906
6907 // According to the GCC documentation, we want the size of the subobject
6908 // denoted by the pointer. But that's not quite right -- what we actually
6909 // want is the size of the immediately-enclosing array, if there is one.
6910 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006911 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006912 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6913 // We got a pointer to an array. Step to its end.
6914 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006915 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006916 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006917 // We're already pointing at the end of the object.
6918 AmountToAdd = 0;
6919 }
6920
George Burgess IV3a03fab2015-09-04 21:28:13 +00006921 QualType PointeeType = End.Designator.MostDerivedType;
6922 assert(!PointeeType.isNull());
6923 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006924 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006925
George Burgess IVbdb5b262015-08-19 02:19:07 +00006926 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6927 AmountToAdd))
6928 return false;
John McCall95007602010-05-10 23:27:23 +00006929
George Burgess IVbdb5b262015-08-19 02:19:07 +00006930 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006931
6932 // The following is a moderately common idiom in C:
6933 //
6934 // struct Foo { int a; char c[1]; };
6935 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6936 // strcpy(&F->c[0], Bar);
6937 //
George Burgess IVf8f63242016-09-12 23:50:35 +00006938 // So, if we see that we're examining an array at the end of a struct with an
6939 // unknown base, we give up instead of breaking code that behaves this way.
6940 // Note that we only do this when Type=1, because Type=3 is a lower bound, so
6941 // answering conservatively is fine.
6942 //
6943 // We used to be a bit more aggressive here; we'd only be conservative if the
6944 // array at the end was flexible, or if it had 0 or 1 elements. This broke
6945 // some common standard library extensions (PR30346), but was otherwise
6946 // seemingly fine. It may be useful to reintroduce this behavior with some
6947 // sort of whitelist. OTOH, it seems that GCC is always conservative with the
6948 // last element in structs (if it's an array), so our current behavior is more
6949 // compatible than a whitelisting approach would be.
George Burgess IVa51c4072015-10-16 01:49:01 +00006950 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6951 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6952 End.Designator.MostDerivedIsArrayElement &&
George Burgess IVa51c4072015-10-16 01:49:01 +00006953 isDesignatorAtObjectEnd(Info.Ctx, End))
6954 return false;
6955
George Burgess IVbdb5b262015-08-19 02:19:07 +00006956 if (BaseOffset > EndOffset)
6957 return Success(0, E);
6958
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006959 return Success((EndOffset - BaseOffset).getQuantity(), E);
6960}
6961
6962bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6963 unsigned Type) {
6964 uint64_t Size;
6965 bool WasError;
6966 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6967 return Success(Size, E);
6968 if (WasError)
6969 return Error(E);
6970 return false;
John McCall95007602010-05-10 23:27:23 +00006971}
6972
Peter Collingbournee9200682011-05-13 03:29:01 +00006973bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00006974 if (unsigned BuiltinOp = E->getBuiltinCallee())
6975 return VisitBuiltinCallExpr(E, BuiltinOp);
6976
6977 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6978}
6979
6980bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6981 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00006982 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006983 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006984 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006985
6986 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006987 // The type was checked when we built the expression.
6988 unsigned Type =
6989 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6990 assert(Type <= 3 && "unexpected type");
6991
6992 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006993 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006994
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006995 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00006996 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006997
Richard Smith01ade172012-05-23 04:13:20 +00006998 // Expression had no side effects, but we couldn't statically determine the
6999 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007000 switch (Info.EvalMode) {
7001 case EvalInfo::EM_ConstantExpression:
7002 case EvalInfo::EM_PotentialConstantExpression:
7003 case EvalInfo::EM_ConstantFold:
7004 case EvalInfo::EM_EvaluateForOverflow:
7005 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00007006 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007007 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007008 return Error(E);
7009 case EvalInfo::EM_ConstantExpressionUnevaluated:
7010 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007011 // Reduce it to a constant now.
7012 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007013 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007014
7015 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007016 }
7017
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007018 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007019 case Builtin::BI__builtin_bswap32:
7020 case Builtin::BI__builtin_bswap64: {
7021 APSInt Val;
7022 if (!EvaluateInteger(E->getArg(0), Val, Info))
7023 return false;
7024
7025 return Success(Val.byteSwap(), E);
7026 }
7027
Richard Smith8889a3d2013-06-13 06:26:32 +00007028 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007029 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007030
7031 // FIXME: BI__builtin_clrsb
7032 // FIXME: BI__builtin_clrsbl
7033 // FIXME: BI__builtin_clrsbll
7034
Richard Smith80b3c8e2013-06-13 05:04:16 +00007035 case Builtin::BI__builtin_clz:
7036 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007037 case Builtin::BI__builtin_clzll:
7038 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007039 APSInt Val;
7040 if (!EvaluateInteger(E->getArg(0), Val, Info))
7041 return false;
7042 if (!Val)
7043 return Error(E);
7044
7045 return Success(Val.countLeadingZeros(), E);
7046 }
7047
Richard Smith8889a3d2013-06-13 06:26:32 +00007048 case Builtin::BI__builtin_constant_p:
7049 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7050
Richard Smith80b3c8e2013-06-13 05:04:16 +00007051 case Builtin::BI__builtin_ctz:
7052 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007053 case Builtin::BI__builtin_ctzll:
7054 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007055 APSInt Val;
7056 if (!EvaluateInteger(E->getArg(0), Val, Info))
7057 return false;
7058 if (!Val)
7059 return Error(E);
7060
7061 return Success(Val.countTrailingZeros(), E);
7062 }
7063
Richard Smith8889a3d2013-06-13 06:26:32 +00007064 case Builtin::BI__builtin_eh_return_data_regno: {
7065 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7066 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7067 return Success(Operand, E);
7068 }
7069
7070 case Builtin::BI__builtin_expect:
7071 return Visit(E->getArg(0));
7072
7073 case Builtin::BI__builtin_ffs:
7074 case Builtin::BI__builtin_ffsl:
7075 case Builtin::BI__builtin_ffsll: {
7076 APSInt Val;
7077 if (!EvaluateInteger(E->getArg(0), Val, Info))
7078 return false;
7079
7080 unsigned N = Val.countTrailingZeros();
7081 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7082 }
7083
7084 case Builtin::BI__builtin_fpclassify: {
7085 APFloat Val(0.0);
7086 if (!EvaluateFloat(E->getArg(5), Val, Info))
7087 return false;
7088 unsigned Arg;
7089 switch (Val.getCategory()) {
7090 case APFloat::fcNaN: Arg = 0; break;
7091 case APFloat::fcInfinity: Arg = 1; break;
7092 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7093 case APFloat::fcZero: Arg = 4; break;
7094 }
7095 return Visit(E->getArg(Arg));
7096 }
7097
7098 case Builtin::BI__builtin_isinf_sign: {
7099 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007100 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007101 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7102 }
7103
Richard Smithea3019d2013-10-15 19:07:14 +00007104 case Builtin::BI__builtin_isinf: {
7105 APFloat Val(0.0);
7106 return EvaluateFloat(E->getArg(0), Val, Info) &&
7107 Success(Val.isInfinity() ? 1 : 0, E);
7108 }
7109
7110 case Builtin::BI__builtin_isfinite: {
7111 APFloat Val(0.0);
7112 return EvaluateFloat(E->getArg(0), Val, Info) &&
7113 Success(Val.isFinite() ? 1 : 0, E);
7114 }
7115
7116 case Builtin::BI__builtin_isnan: {
7117 APFloat Val(0.0);
7118 return EvaluateFloat(E->getArg(0), Val, Info) &&
7119 Success(Val.isNaN() ? 1 : 0, E);
7120 }
7121
7122 case Builtin::BI__builtin_isnormal: {
7123 APFloat Val(0.0);
7124 return EvaluateFloat(E->getArg(0), Val, Info) &&
7125 Success(Val.isNormal() ? 1 : 0, E);
7126 }
7127
Richard Smith8889a3d2013-06-13 06:26:32 +00007128 case Builtin::BI__builtin_parity:
7129 case Builtin::BI__builtin_parityl:
7130 case Builtin::BI__builtin_parityll: {
7131 APSInt Val;
7132 if (!EvaluateInteger(E->getArg(0), Val, Info))
7133 return false;
7134
7135 return Success(Val.countPopulation() % 2, E);
7136 }
7137
Richard Smith80b3c8e2013-06-13 05:04:16 +00007138 case Builtin::BI__builtin_popcount:
7139 case Builtin::BI__builtin_popcountl:
7140 case Builtin::BI__builtin_popcountll: {
7141 APSInt Val;
7142 if (!EvaluateInteger(E->getArg(0), Val, Info))
7143 return false;
7144
7145 return Success(Val.countPopulation(), E);
7146 }
7147
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007148 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007149 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007150 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007151 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007152 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007153 << /*isConstexpr*/0 << /*isConstructor*/0
7154 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007155 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007156 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007157 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007158 case Builtin::BI__builtin_strlen:
7159 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007160 // As an extension, we support __builtin_strlen() as a constant expression,
7161 // and support folding strlen() to a constant.
7162 LValue String;
7163 if (!EvaluatePointer(E->getArg(0), String, Info))
7164 return false;
7165
Richard Smith8110c9d2016-11-29 19:45:17 +00007166 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7167
Richard Smithe6c19f22013-11-15 02:10:04 +00007168 // Fast path: if it's a string literal, search the string value.
7169 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7170 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007171 // The string literal may have embedded null characters. Find the first
7172 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007173 StringRef Str = S->getBytes();
7174 int64_t Off = String.Offset.getQuantity();
7175 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007176 S->getCharByteWidth() == 1 &&
7177 // FIXME: Add fast-path for wchar_t too.
7178 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007179 Str = Str.substr(Off);
7180
7181 StringRef::size_type Pos = Str.find(0);
7182 if (Pos != StringRef::npos)
7183 Str = Str.substr(0, Pos);
7184
7185 return Success(Str.size(), E);
7186 }
7187
7188 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007189 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007190
7191 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007192 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7193 APValue Char;
7194 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7195 !Char.isInt())
7196 return false;
7197 if (!Char.getInt())
7198 return Success(Strlen, E);
7199 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7200 return false;
7201 }
7202 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007203
Richard Smithe151bab2016-11-11 23:43:35 +00007204 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007205 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007206 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007207 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007208 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007209 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007210 // A call to strlen is not a constant expression.
7211 if (Info.getLangOpts().CPlusPlus11)
7212 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7213 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007214 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007215 else
7216 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7217 // Fall through.
7218 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007219 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007220 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007221 case Builtin::BI__builtin_wcsncmp:
7222 case Builtin::BI__builtin_memcmp:
7223 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007224 LValue String1, String2;
7225 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7226 !EvaluatePointer(E->getArg(1), String2, Info))
7227 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007228
7229 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7230
Richard Smithe151bab2016-11-11 23:43:35 +00007231 uint64_t MaxLength = uint64_t(-1);
7232 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007233 BuiltinOp != Builtin::BIwcscmp &&
7234 BuiltinOp != Builtin::BI__builtin_strcmp &&
7235 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007236 APSInt N;
7237 if (!EvaluateInteger(E->getArg(2), N, Info))
7238 return false;
7239 MaxLength = N.getExtValue();
7240 }
7241 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007242 BuiltinOp != Builtin::BIwmemcmp &&
7243 BuiltinOp != Builtin::BI__builtin_memcmp &&
7244 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007245 for (; MaxLength; --MaxLength) {
7246 APValue Char1, Char2;
7247 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7248 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7249 !Char1.isInt() || !Char2.isInt())
7250 return false;
7251 if (Char1.getInt() != Char2.getInt())
7252 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7253 if (StopAtNull && !Char1.getInt())
7254 return Success(0, E);
7255 assert(!(StopAtNull && !Char2.getInt()));
7256 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7257 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7258 return false;
7259 }
7260 // We hit the strncmp / memcmp limit.
7261 return Success(0, E);
7262 }
7263
Richard Smith01ba47d2012-04-13 00:45:38 +00007264 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007265 case Builtin::BI__atomic_is_lock_free:
7266 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007267 APSInt SizeVal;
7268 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7269 return false;
7270
7271 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7272 // of two less than the maximum inline atomic width, we know it is
7273 // lock-free. If the size isn't a power of two, or greater than the
7274 // maximum alignment where we promote atomics, we know it is not lock-free
7275 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7276 // the answer can only be determined at runtime; for example, 16-byte
7277 // atomics have lock-free implementations on some, but not all,
7278 // x86-64 processors.
7279
7280 // Check power-of-two.
7281 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007282 if (Size.isPowerOfTwo()) {
7283 // Check against inlining width.
7284 unsigned InlineWidthBits =
7285 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7286 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7287 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7288 Size == CharUnits::One() ||
7289 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7290 Expr::NPC_NeverValueDependent))
7291 // OK, we will inline appropriately-aligned operations of this size,
7292 // and _Atomic(T) is appropriately-aligned.
7293 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007294
Richard Smith01ba47d2012-04-13 00:45:38 +00007295 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7296 castAs<PointerType>()->getPointeeType();
7297 if (!PointeeType->isIncompleteType() &&
7298 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7299 // OK, we will inline operations on this object.
7300 return Success(1, E);
7301 }
7302 }
7303 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007304
Richard Smith01ba47d2012-04-13 00:45:38 +00007305 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7306 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007307 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007308 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007309}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007310
Richard Smith8b3497e2011-10-31 01:37:14 +00007311static bool HasSameBase(const LValue &A, const LValue &B) {
7312 if (!A.getLValueBase())
7313 return !B.getLValueBase();
7314 if (!B.getLValueBase())
7315 return false;
7316
Richard Smithce40ad62011-11-12 22:28:03 +00007317 if (A.getLValueBase().getOpaqueValue() !=
7318 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007319 const Decl *ADecl = GetLValueBaseDecl(A);
7320 if (!ADecl)
7321 return false;
7322 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007323 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007324 return false;
7325 }
7326
7327 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007328 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007329}
7330
Richard Smithd20f1e62014-10-21 23:01:04 +00007331/// \brief Determine whether this is a pointer past the end of the complete
7332/// object referred to by the lvalue.
7333static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7334 const LValue &LV) {
7335 // A null pointer can be viewed as being "past the end" but we don't
7336 // choose to look at it that way here.
7337 if (!LV.getLValueBase())
7338 return false;
7339
7340 // If the designator is valid and refers to a subobject, we're not pointing
7341 // past the end.
7342 if (!LV.getLValueDesignator().Invalid &&
7343 !LV.getLValueDesignator().isOnePastTheEnd())
7344 return false;
7345
David Majnemerc378ca52015-08-29 08:32:55 +00007346 // A pointer to an incomplete type might be past-the-end if the type's size is
7347 // zero. We cannot tell because the type is incomplete.
7348 QualType Ty = getType(LV.getLValueBase());
7349 if (Ty->isIncompleteType())
7350 return true;
7351
Richard Smithd20f1e62014-10-21 23:01:04 +00007352 // We're a past-the-end pointer if we point to the byte after the object,
7353 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007354 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007355 return LV.getLValueOffset() == Size;
7356}
7357
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007358namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007359
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007360/// \brief Data recursive integer evaluator of certain binary operators.
7361///
7362/// We use a data recursive algorithm for binary operators so that we are able
7363/// to handle extreme cases of chained binary operators without causing stack
7364/// overflow.
7365class DataRecursiveIntBinOpEvaluator {
7366 struct EvalResult {
7367 APValue Val;
7368 bool Failed;
7369
7370 EvalResult() : Failed(false) { }
7371
7372 void swap(EvalResult &RHS) {
7373 Val.swap(RHS.Val);
7374 Failed = RHS.Failed;
7375 RHS.Failed = false;
7376 }
7377 };
7378
7379 struct Job {
7380 const Expr *E;
7381 EvalResult LHSResult; // meaningful only for binary operator expression.
7382 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007383
David Blaikie73726062015-08-12 23:09:24 +00007384 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007385 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007386
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007387 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007388 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007389 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007390
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007391 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007392 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007393 };
7394
7395 SmallVector<Job, 16> Queue;
7396
7397 IntExprEvaluator &IntEval;
7398 EvalInfo &Info;
7399 APValue &FinalResult;
7400
7401public:
7402 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7403 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7404
7405 /// \brief True if \param E is a binary operator that we are going to handle
7406 /// data recursively.
7407 /// We handle binary operators that are comma, logical, or that have operands
7408 /// with integral or enumeration type.
7409 static bool shouldEnqueue(const BinaryOperator *E) {
7410 return E->getOpcode() == BO_Comma ||
7411 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007412 (E->isRValue() &&
7413 E->getType()->isIntegralOrEnumerationType() &&
7414 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007415 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007416 }
7417
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007418 bool Traverse(const BinaryOperator *E) {
7419 enqueue(E);
7420 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007421 while (!Queue.empty())
7422 process(PrevResult);
7423
7424 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007425
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007426 FinalResult.swap(PrevResult.Val);
7427 return true;
7428 }
7429
7430private:
7431 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7432 return IntEval.Success(Value, E, Result);
7433 }
7434 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7435 return IntEval.Success(Value, E, Result);
7436 }
7437 bool Error(const Expr *E) {
7438 return IntEval.Error(E);
7439 }
7440 bool Error(const Expr *E, diag::kind D) {
7441 return IntEval.Error(E, D);
7442 }
7443
7444 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7445 return Info.CCEDiag(E, D);
7446 }
7447
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007448 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7449 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007450 bool &SuppressRHSDiags);
7451
7452 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7453 const BinaryOperator *E, APValue &Result);
7454
7455 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7456 Result.Failed = !Evaluate(Result.Val, Info, E);
7457 if (Result.Failed)
7458 Result.Val = APValue();
7459 }
7460
Richard Trieuba4d0872012-03-21 23:30:30 +00007461 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007462
7463 void enqueue(const Expr *E) {
7464 E = E->IgnoreParens();
7465 Queue.resize(Queue.size()+1);
7466 Queue.back().E = E;
7467 Queue.back().Kind = Job::AnyExprKind;
7468 }
7469};
7470
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007471}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007472
7473bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007474 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007475 bool &SuppressRHSDiags) {
7476 if (E->getOpcode() == BO_Comma) {
7477 // Ignore LHS but note if we could not evaluate it.
7478 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007479 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007480 return true;
7481 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007482
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007483 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007484 bool LHSAsBool;
7485 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007486 // We were able to evaluate the LHS, see if we can get away with not
7487 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007488 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7489 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007490 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007491 }
7492 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007493 LHSResult.Failed = true;
7494
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007495 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007496 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007497 if (!Info.noteSideEffect())
7498 return false;
7499
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007500 // We can't evaluate the LHS; however, sometimes the result
7501 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7502 // Don't ignore RHS and suppress diagnostics from this arm.
7503 SuppressRHSDiags = true;
7504 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007505
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007506 return true;
7507 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007508
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007509 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7510 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007511
George Burgess IVa145e252016-05-25 22:38:36 +00007512 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007513 return false; // Ignore RHS;
7514
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007515 return true;
7516}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007517
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007518bool DataRecursiveIntBinOpEvaluator::
7519 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7520 const BinaryOperator *E, APValue &Result) {
7521 if (E->getOpcode() == BO_Comma) {
7522 if (RHSResult.Failed)
7523 return false;
7524 Result = RHSResult.Val;
7525 return true;
7526 }
7527
7528 if (E->isLogicalOp()) {
7529 bool lhsResult, rhsResult;
7530 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7531 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7532
7533 if (LHSIsOK) {
7534 if (RHSIsOK) {
7535 if (E->getOpcode() == BO_LOr)
7536 return Success(lhsResult || rhsResult, E, Result);
7537 else
7538 return Success(lhsResult && rhsResult, E, Result);
7539 }
7540 } else {
7541 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007542 // We can't evaluate the LHS; however, sometimes the result
7543 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7544 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007545 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007546 }
7547 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007548
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007549 return false;
7550 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007551
7552 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7553 E->getRHS()->getType()->isIntegralOrEnumerationType());
7554
7555 if (LHSResult.Failed || RHSResult.Failed)
7556 return false;
7557
7558 const APValue &LHSVal = LHSResult.Val;
7559 const APValue &RHSVal = RHSResult.Val;
7560
7561 // Handle cases like (unsigned long)&a + 4.
7562 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7563 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007564 CharUnits AdditionalOffset =
7565 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007566 if (E->getOpcode() == BO_Add)
7567 Result.getLValueOffset() += AdditionalOffset;
7568 else
7569 Result.getLValueOffset() -= AdditionalOffset;
7570 return true;
7571 }
7572
7573 // Handle cases like 4 + (unsigned long)&a
7574 if (E->getOpcode() == BO_Add &&
7575 RHSVal.isLValue() && LHSVal.isInt()) {
7576 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007577 Result.getLValueOffset() +=
7578 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007579 return true;
7580 }
7581
7582 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7583 // Handle (intptr_t)&&A - (intptr_t)&&B.
7584 if (!LHSVal.getLValueOffset().isZero() ||
7585 !RHSVal.getLValueOffset().isZero())
7586 return false;
7587 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7588 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7589 if (!LHSExpr || !RHSExpr)
7590 return false;
7591 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7592 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7593 if (!LHSAddrExpr || !RHSAddrExpr)
7594 return false;
7595 // Make sure both labels come from the same function.
7596 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7597 RHSAddrExpr->getLabel()->getDeclContext())
7598 return false;
7599 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7600 return true;
7601 }
Richard Smith43e77732013-05-07 04:50:00 +00007602
7603 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007604 if (!LHSVal.isInt() || !RHSVal.isInt())
7605 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007606
7607 // Set up the width and signedness manually, in case it can't be deduced
7608 // from the operation we're performing.
7609 // FIXME: Don't do this in the cases where we can deduce it.
7610 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7611 E->getType()->isUnsignedIntegerOrEnumerationType());
7612 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7613 RHSVal.getInt(), Value))
7614 return false;
7615 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007616}
7617
Richard Trieuba4d0872012-03-21 23:30:30 +00007618void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007619 Job &job = Queue.back();
7620
7621 switch (job.Kind) {
7622 case Job::AnyExprKind: {
7623 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7624 if (shouldEnqueue(Bop)) {
7625 job.Kind = Job::BinOpKind;
7626 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007627 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007628 }
7629 }
7630
7631 EvaluateExpr(job.E, Result);
7632 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007633 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007634 }
7635
7636 case Job::BinOpKind: {
7637 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007638 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007639 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007640 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007641 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007642 }
7643 if (SuppressRHSDiags)
7644 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007645 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007646 job.Kind = Job::BinOpVisitedLHSKind;
7647 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007648 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007649 }
7650
7651 case Job::BinOpVisitedLHSKind: {
7652 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7653 EvalResult RHS;
7654 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007655 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007656 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007657 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007658 }
7659 }
7660
7661 llvm_unreachable("Invalid Job::Kind!");
7662}
7663
George Burgess IV8c892b52016-05-25 22:31:54 +00007664namespace {
7665/// Used when we determine that we should fail, but can keep evaluating prior to
7666/// noting that we had a failure.
7667class DelayedNoteFailureRAII {
7668 EvalInfo &Info;
7669 bool NoteFailure;
7670
7671public:
7672 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7673 : Info(Info), NoteFailure(NoteFailure) {}
7674 ~DelayedNoteFailureRAII() {
7675 if (NoteFailure) {
7676 bool ContinueAfterFailure = Info.noteFailure();
7677 (void)ContinueAfterFailure;
7678 assert(ContinueAfterFailure &&
7679 "Shouldn't have kept evaluating on failure.");
7680 }
7681 }
7682};
7683}
7684
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007685bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007686 // We don't call noteFailure immediately because the assignment happens after
7687 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00007688 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007689 return Error(E);
7690
George Burgess IV8c892b52016-05-25 22:31:54 +00007691 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007692 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7693 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007694
Anders Carlssonacc79812008-11-16 07:17:21 +00007695 QualType LHSTy = E->getLHS()->getType();
7696 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007697
Chandler Carruthb29a7432014-10-11 11:03:30 +00007698 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007699 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007700 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007701 if (E->isAssignmentOp()) {
7702 LValue LV;
7703 EvaluateLValue(E->getLHS(), LV, Info);
7704 LHSOK = false;
7705 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007706 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7707 if (LHSOK) {
7708 LHS.makeComplexFloat();
7709 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7710 }
7711 } else {
7712 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7713 }
George Burgess IVa145e252016-05-25 22:38:36 +00007714 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007715 return false;
7716
Chandler Carruthb29a7432014-10-11 11:03:30 +00007717 if (E->getRHS()->getType()->isRealFloatingType()) {
7718 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7719 return false;
7720 RHS.makeComplexFloat();
7721 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7722 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007723 return false;
7724
7725 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007726 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007727 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007728 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007729 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7730
John McCalle3027922010-08-25 11:45:40 +00007731 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007732 return Success((CR_r == APFloat::cmpEqual &&
7733 CR_i == APFloat::cmpEqual), E);
7734 else {
John McCalle3027922010-08-25 11:45:40 +00007735 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007736 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007737 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007738 CR_r == APFloat::cmpLessThan ||
7739 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007740 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007741 CR_i == APFloat::cmpLessThan ||
7742 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007743 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007744 } else {
John McCalle3027922010-08-25 11:45:40 +00007745 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007746 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7747 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7748 else {
John McCalle3027922010-08-25 11:45:40 +00007749 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007750 "Invalid compex comparison.");
7751 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7752 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7753 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007754 }
7755 }
Mike Stump11289f42009-09-09 15:08:12 +00007756
Anders Carlssonacc79812008-11-16 07:17:21 +00007757 if (LHSTy->isRealFloatingType() &&
7758 RHSTy->isRealFloatingType()) {
7759 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007760
Richard Smith253c2a32012-01-27 01:14:48 +00007761 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007762 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007763 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007764
Richard Smith253c2a32012-01-27 01:14:48 +00007765 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007766 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007767
Anders Carlssonacc79812008-11-16 07:17:21 +00007768 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007769
Anders Carlssonacc79812008-11-16 07:17:21 +00007770 switch (E->getOpcode()) {
7771 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007772 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007773 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007774 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007775 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007776 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007777 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007778 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007779 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007780 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007781 E);
John McCalle3027922010-08-25 11:45:40 +00007782 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007783 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007784 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007785 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007786 || CR == APFloat::cmpLessThan
7787 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007788 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007789 }
Mike Stump11289f42009-09-09 15:08:12 +00007790
Eli Friedmana38da572009-04-28 19:17:36 +00007791 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007792 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007793 LValue LHSValue, RHSValue;
7794
7795 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007796 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007797 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007798
Richard Smith253c2a32012-01-27 01:14:48 +00007799 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007800 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007801
Richard Smith8b3497e2011-10-31 01:37:14 +00007802 // Reject differing bases from the normal codepath; we special-case
7803 // comparisons to null.
7804 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007805 if (E->getOpcode() == BO_Sub) {
7806 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007807 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007808 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007809 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007810 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007811 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007812 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007813 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7814 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7815 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007816 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007817 // Make sure both labels come from the same function.
7818 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7819 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007820 return Error(E);
7821 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007822 }
Richard Smith83c68212011-10-31 05:11:32 +00007823 // Inequalities and subtractions between unrelated pointers have
7824 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007825 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007826 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007827 // A constant address may compare equal to the address of a symbol.
7828 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007829 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007830 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7831 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007832 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007833 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007834 // distinct addresses. In clang, the result of such a comparison is
7835 // unspecified, so it is not a constant expression. However, we do know
7836 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007837 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7838 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007839 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007840 // We can't tell whether weak symbols will end up pointing to the same
7841 // object.
7842 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007843 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007844 // We can't compare the address of the start of one object with the
7845 // past-the-end address of another object, per C++ DR1652.
7846 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7847 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7848 (RHSValue.Base && RHSValue.Offset.isZero() &&
7849 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7850 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007851 // We can't tell whether an object is at the same address as another
7852 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007853 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7854 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007855 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007856 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007857 // (Note that clang defaults to -fmerge-all-constants, which can
7858 // lead to inconsistent results for comparisons involving the address
7859 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007860 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007861 }
Eli Friedman64004332009-03-23 04:38:34 +00007862
Richard Smith1b470412012-02-01 08:10:20 +00007863 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7864 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7865
Richard Smith84f6dcf2012-02-02 01:16:57 +00007866 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7867 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7868
John McCalle3027922010-08-25 11:45:40 +00007869 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007870 // C++11 [expr.add]p6:
7871 // Unless both pointers point to elements of the same array object, or
7872 // one past the last element of the array object, the behavior is
7873 // undefined.
7874 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7875 !AreElementsOfSameArray(getType(LHSValue.Base),
7876 LHSDesignator, RHSDesignator))
7877 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7878
Chris Lattner882bdf22010-04-20 17:13:14 +00007879 QualType Type = E->getLHS()->getType();
7880 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007881
Richard Smithd62306a2011-11-10 06:34:14 +00007882 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007883 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007884 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007885
Richard Smith84c6b3d2013-09-10 21:34:14 +00007886 // As an extension, a type may have zero size (empty struct or union in
7887 // C, array of zero length). Pointer subtraction in such cases has
7888 // undefined behavior, so is not constant.
7889 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007890 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00007891 << ElementType;
7892 return false;
7893 }
7894
Richard Smith1b470412012-02-01 08:10:20 +00007895 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7896 // and produce incorrect results when it overflows. Such behavior
7897 // appears to be non-conforming, but is common, so perhaps we should
7898 // assume the standard intended for such cases to be undefined behavior
7899 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007900
Richard Smith1b470412012-02-01 08:10:20 +00007901 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7902 // overflow in the final conversion to ptrdiff_t.
7903 APSInt LHS(
7904 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7905 APSInt RHS(
7906 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7907 APSInt ElemSize(
7908 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7909 APSInt TrueResult = (LHS - RHS) / ElemSize;
7910 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7911
Richard Smith0c6124b2015-12-03 01:36:22 +00007912 if (Result.extend(65) != TrueResult &&
7913 !HandleOverflow(Info, E, TrueResult, E->getType()))
7914 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007915 return Success(Result, E);
7916 }
Richard Smithde21b242012-01-31 06:41:30 +00007917
7918 // C++11 [expr.rel]p3:
7919 // Pointers to void (after pointer conversions) can be compared, with a
7920 // result defined as follows: If both pointers represent the same
7921 // address or are both the null pointer value, the result is true if the
7922 // operator is <= or >= and false otherwise; otherwise the result is
7923 // unspecified.
7924 // We interpret this as applying to pointers to *cv* void.
7925 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007926 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007927 CCEDiag(E, diag::note_constexpr_void_comparison);
7928
Richard Smith84f6dcf2012-02-02 01:16:57 +00007929 // C++11 [expr.rel]p2:
7930 // - If two pointers point to non-static data members of the same object,
7931 // or to subobjects or array elements fo such members, recursively, the
7932 // pointer to the later declared member compares greater provided the
7933 // two members have the same access control and provided their class is
7934 // not a union.
7935 // [...]
7936 // - Otherwise pointer comparisons are unspecified.
7937 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7938 E->isRelationalOp()) {
7939 bool WasArrayIndex;
7940 unsigned Mismatch =
7941 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7942 RHSDesignator, WasArrayIndex);
7943 // At the point where the designators diverge, the comparison has a
7944 // specified value if:
7945 // - we are comparing array indices
7946 // - we are comparing fields of a union, or fields with the same access
7947 // Otherwise, the result is unspecified and thus the comparison is not a
7948 // constant expression.
7949 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7950 Mismatch < RHSDesignator.Entries.size()) {
7951 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7952 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7953 if (!LF && !RF)
7954 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7955 else if (!LF)
7956 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7957 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7958 << RF->getParent() << RF;
7959 else if (!RF)
7960 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7961 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7962 << LF->getParent() << LF;
7963 else if (!LF->getParent()->isUnion() &&
7964 LF->getAccess() != RF->getAccess())
7965 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7966 << LF << LF->getAccess() << RF << RF->getAccess()
7967 << LF->getParent();
7968 }
7969 }
7970
Eli Friedman6c31cb42012-04-16 04:30:08 +00007971 // The comparison here must be unsigned, and performed with the same
7972 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007973 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7974 uint64_t CompareLHS = LHSOffset.getQuantity();
7975 uint64_t CompareRHS = RHSOffset.getQuantity();
7976 assert(PtrSize <= 64 && "Unexpected pointer width");
7977 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7978 CompareLHS &= Mask;
7979 CompareRHS &= Mask;
7980
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007981 // If there is a base and this is a relational operator, we can only
7982 // compare pointers within the object in question; otherwise, the result
7983 // depends on where the object is located in memory.
7984 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7985 QualType BaseTy = getType(LHSValue.Base);
7986 if (BaseTy->isIncompleteType())
7987 return Error(E);
7988 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7989 uint64_t OffsetLimit = Size.getQuantity();
7990 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7991 return Error(E);
7992 }
7993
Richard Smith8b3497e2011-10-31 01:37:14 +00007994 switch (E->getOpcode()) {
7995 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007996 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7997 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7998 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7999 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8000 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8001 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008002 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008003 }
8004 }
Richard Smith7bb00672012-02-01 01:42:44 +00008005
8006 if (LHSTy->isMemberPointerType()) {
8007 assert(E->isEqualityOp() && "unexpected member pointer operation");
8008 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8009
8010 MemberPtr LHSValue, RHSValue;
8011
8012 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008013 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008014 return false;
8015
8016 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8017 return false;
8018
8019 // C++11 [expr.eq]p2:
8020 // If both operands are null, they compare equal. Otherwise if only one is
8021 // null, they compare unequal.
8022 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8023 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8024 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8025 }
8026
8027 // Otherwise if either is a pointer to a virtual member function, the
8028 // result is unspecified.
8029 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8030 if (MD->isVirtual())
8031 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8032 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8033 if (MD->isVirtual())
8034 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8035
8036 // Otherwise they compare equal if and only if they would refer to the
8037 // same member of the same most derived object or the same subobject if
8038 // they were dereferenced with a hypothetical object of the associated
8039 // class type.
8040 bool Equal = LHSValue == RHSValue;
8041 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8042 }
8043
Richard Smithab44d9b2012-02-14 22:35:28 +00008044 if (LHSTy->isNullPtrType()) {
8045 assert(E->isComparisonOp() && "unexpected nullptr operation");
8046 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8047 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8048 // are compared, the result is true of the operator is <=, >= or ==, and
8049 // false otherwise.
8050 BinaryOperator::Opcode Opcode = E->getOpcode();
8051 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8052 }
8053
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008054 assert((!LHSTy->isIntegralOrEnumerationType() ||
8055 !RHSTy->isIntegralOrEnumerationType()) &&
8056 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8057 // We can't continue from here for non-integral types.
8058 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008059}
8060
Peter Collingbournee190dee2011-03-11 19:24:49 +00008061/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8062/// a result as the expression's type.
8063bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8064 const UnaryExprOrTypeTraitExpr *E) {
8065 switch(E->getKind()) {
8066 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008067 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008068 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008069 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008070 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008071 }
Eli Friedman64004332009-03-23 04:38:34 +00008072
Peter Collingbournee190dee2011-03-11 19:24:49 +00008073 case UETT_VecStep: {
8074 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008075
Peter Collingbournee190dee2011-03-11 19:24:49 +00008076 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008077 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008078
Peter Collingbournee190dee2011-03-11 19:24:49 +00008079 // The vec_step built-in functions that take a 3-component
8080 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8081 if (n == 3)
8082 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008083
Peter Collingbournee190dee2011-03-11 19:24:49 +00008084 return Success(n, E);
8085 } else
8086 return Success(1, E);
8087 }
8088
8089 case UETT_SizeOf: {
8090 QualType SrcTy = E->getTypeOfArgument();
8091 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8092 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008093 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8094 SrcTy = Ref->getPointeeType();
8095
Richard Smithd62306a2011-11-10 06:34:14 +00008096 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008097 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008098 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008099 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008100 }
Alexey Bataev00396512015-07-02 03:40:19 +00008101 case UETT_OpenMPRequiredSimdAlign:
8102 assert(E->isArgumentType());
8103 return Success(
8104 Info.Ctx.toCharUnitsFromBits(
8105 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8106 .getQuantity(),
8107 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008108 }
8109
8110 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008111}
8112
Peter Collingbournee9200682011-05-13 03:29:01 +00008113bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008114 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008115 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008116 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008117 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008118 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008119 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008120 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008121 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008122 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008123 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008124 APSInt IdxResult;
8125 if (!EvaluateInteger(Idx, IdxResult, Info))
8126 return false;
8127 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8128 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008129 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008130 CurrentType = AT->getElementType();
8131 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8132 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008133 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008134 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008135
James Y Knight7281c352015-12-29 22:31:18 +00008136 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008137 FieldDecl *MemberDecl = ON.getField();
8138 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008139 if (!RT)
8140 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008141 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008142 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008143 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008144 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008145 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008146 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008147 CurrentType = MemberDecl->getType().getNonReferenceType();
8148 break;
8149 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008150
James Y Knight7281c352015-12-29 22:31:18 +00008151 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008152 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008153
James Y Knight7281c352015-12-29 22:31:18 +00008154 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008155 CXXBaseSpecifier *BaseSpec = ON.getBase();
8156 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008157 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008158
8159 // Find the layout of the class whose base we are looking into.
8160 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008161 if (!RT)
8162 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008163 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008164 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008165 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8166
8167 // Find the base class itself.
8168 CurrentType = BaseSpec->getType();
8169 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8170 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008171 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008172
8173 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008174 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008175 break;
8176 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008177 }
8178 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008179 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008180}
8181
Chris Lattnere13042c2008-07-11 19:10:17 +00008182bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008183 switch (E->getOpcode()) {
8184 default:
8185 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8186 // See C99 6.6p3.
8187 return Error(E);
8188 case UO_Extension:
8189 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8190 // If so, we could clear the diagnostic ID.
8191 return Visit(E->getSubExpr());
8192 case UO_Plus:
8193 // The result is just the value.
8194 return Visit(E->getSubExpr());
8195 case UO_Minus: {
8196 if (!Visit(E->getSubExpr()))
8197 return false;
8198 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008199 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008200 if (Value.isSigned() && Value.isMinSignedValue() &&
8201 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8202 E->getType()))
8203 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008204 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008205 }
8206 case UO_Not: {
8207 if (!Visit(E->getSubExpr()))
8208 return false;
8209 if (!Result.isInt()) return Error(E);
8210 return Success(~Result.getInt(), E);
8211 }
8212 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008213 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008214 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008215 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008216 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008217 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008218 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008219}
Mike Stump11289f42009-09-09 15:08:12 +00008220
Chris Lattner477c4be2008-07-12 01:15:53 +00008221/// HandleCast - This is used to evaluate implicit or explicit casts where the
8222/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008223bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8224 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008225 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008226 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008227
Eli Friedmanc757de22011-03-25 00:43:55 +00008228 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008229 case CK_BaseToDerived:
8230 case CK_DerivedToBase:
8231 case CK_UncheckedDerivedToBase:
8232 case CK_Dynamic:
8233 case CK_ToUnion:
8234 case CK_ArrayToPointerDecay:
8235 case CK_FunctionToPointerDecay:
8236 case CK_NullToPointer:
8237 case CK_NullToMemberPointer:
8238 case CK_BaseToDerivedMemberPointer:
8239 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008240 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008241 case CK_ConstructorConversion:
8242 case CK_IntegralToPointer:
8243 case CK_ToVoid:
8244 case CK_VectorSplat:
8245 case CK_IntegralToFloating:
8246 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008247 case CK_CPointerToObjCPointerCast:
8248 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008249 case CK_AnyPointerToBlockPointerCast:
8250 case CK_ObjCObjectLValueCast:
8251 case CK_FloatingRealToComplex:
8252 case CK_FloatingComplexToReal:
8253 case CK_FloatingComplexCast:
8254 case CK_FloatingComplexToIntegralComplex:
8255 case CK_IntegralRealToComplex:
8256 case CK_IntegralComplexCast:
8257 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008258 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008259 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008260 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008261 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008262 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008263 llvm_unreachable("invalid cast kind for integral value");
8264
Eli Friedman9faf2f92011-03-25 19:07:11 +00008265 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008266 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008267 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008268 case CK_ARCProduceObject:
8269 case CK_ARCConsumeObject:
8270 case CK_ARCReclaimReturnedObject:
8271 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008272 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008273 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008274
Richard Smith4ef685b2012-01-17 21:17:26 +00008275 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008276 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008277 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008278 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008279 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008280
8281 case CK_MemberPointerToBoolean:
8282 case CK_PointerToBoolean:
8283 case CK_IntegralToBoolean:
8284 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008285 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008286 case CK_FloatingComplexToBoolean:
8287 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008288 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008289 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008290 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008291 uint64_t IntResult = BoolResult;
8292 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8293 IntResult = (uint64_t)-1;
8294 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008295 }
8296
Eli Friedmanc757de22011-03-25 00:43:55 +00008297 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008298 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008299 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008300
Eli Friedman742421e2009-02-20 01:15:07 +00008301 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008302 // Allow casts of address-of-label differences if they are no-ops
8303 // or narrowing. (The narrowing case isn't actually guaranteed to
8304 // be constant-evaluatable except in some narrow cases which are hard
8305 // to detect here. We let it through on the assumption the user knows
8306 // what they are doing.)
8307 if (Result.isAddrLabelDiff())
8308 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008309 // Only allow casts of lvalues if they are lossless.
8310 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8311 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008312
Richard Smith911e1422012-01-30 22:27:01 +00008313 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8314 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008315 }
Mike Stump11289f42009-09-09 15:08:12 +00008316
Eli Friedmanc757de22011-03-25 00:43:55 +00008317 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008318 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8319
John McCall45d55e42010-05-07 21:00:08 +00008320 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008321 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008322 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008323
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008324 if (LV.getLValueBase()) {
8325 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008326 // FIXME: Allow a larger integer size than the pointer size, and allow
8327 // narrowing back down to pointer width in subsequent integral casts.
8328 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008329 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008330 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008331
Richard Smithcf74da72011-11-16 07:18:12 +00008332 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008333 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008334 return true;
8335 }
8336
Ken Dyck02990832010-01-15 12:37:54 +00008337 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
8338 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008339 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008340 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008341
Eli Friedmanc757de22011-03-25 00:43:55 +00008342 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008343 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008344 if (!EvaluateComplex(SubExpr, C, Info))
8345 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008346 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008347 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008348
Eli Friedmanc757de22011-03-25 00:43:55 +00008349 case CK_FloatingToIntegral: {
8350 APFloat F(0.0);
8351 if (!EvaluateFloat(SubExpr, F, Info))
8352 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008353
Richard Smith357362d2011-12-13 06:39:58 +00008354 APSInt Value;
8355 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8356 return false;
8357 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008358 }
8359 }
Mike Stump11289f42009-09-09 15:08:12 +00008360
Eli Friedmanc757de22011-03-25 00:43:55 +00008361 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008362}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008363
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008364bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8365 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008366 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008367 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8368 return false;
8369 if (!LV.isComplexInt())
8370 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008371 return Success(LV.getComplexIntReal(), E);
8372 }
8373
8374 return Visit(E->getSubExpr());
8375}
8376
Eli Friedman4e7a2412009-02-27 04:45:43 +00008377bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008378 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008379 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008380 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8381 return false;
8382 if (!LV.isComplexInt())
8383 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008384 return Success(LV.getComplexIntImag(), E);
8385 }
8386
Richard Smith4a678122011-10-24 18:44:57 +00008387 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008388 return Success(0, E);
8389}
8390
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008391bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8392 return Success(E->getPackLength(), E);
8393}
8394
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008395bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8396 return Success(E->getValue(), E);
8397}
8398
Chris Lattner05706e882008-07-11 18:11:29 +00008399//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008400// Float Evaluation
8401//===----------------------------------------------------------------------===//
8402
8403namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008404class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008405 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008406 APFloat &Result;
8407public:
8408 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008409 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008410
Richard Smith2e312c82012-03-03 22:46:17 +00008411 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008412 Result = V.getFloat();
8413 return true;
8414 }
Eli Friedman24c01542008-08-22 00:06:13 +00008415
Richard Smithfddd3842011-12-30 21:15:51 +00008416 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008417 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8418 return true;
8419 }
8420
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008421 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008422
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008423 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008424 bool VisitBinaryOperator(const BinaryOperator *E);
8425 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008426 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008427
John McCallb1fb0d32010-05-07 22:08:54 +00008428 bool VisitUnaryReal(const UnaryOperator *E);
8429 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008430
Richard Smithfddd3842011-12-30 21:15:51 +00008431 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008432};
8433} // end anonymous namespace
8434
8435static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008436 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008437 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008438}
8439
Jay Foad39c79802011-01-12 09:06:06 +00008440static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008441 QualType ResultTy,
8442 const Expr *Arg,
8443 bool SNaN,
8444 llvm::APFloat &Result) {
8445 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8446 if (!S) return false;
8447
8448 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8449
8450 llvm::APInt fill;
8451
8452 // Treat empty strings as if they were zero.
8453 if (S->getString().empty())
8454 fill = llvm::APInt(32, 0);
8455 else if (S->getString().getAsInteger(0, fill))
8456 return false;
8457
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008458 if (Context.getTargetInfo().isNan2008()) {
8459 if (SNaN)
8460 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8461 else
8462 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8463 } else {
8464 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8465 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8466 // a different encoding to what became a standard in 2008, and for pre-
8467 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8468 // sNaN. This is now known as "legacy NaN" encoding.
8469 if (SNaN)
8470 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8471 else
8472 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8473 }
8474
John McCall16291492010-02-28 13:00:19 +00008475 return true;
8476}
8477
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008478bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008479 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008480 default:
8481 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8482
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008483 case Builtin::BI__builtin_huge_val:
8484 case Builtin::BI__builtin_huge_valf:
8485 case Builtin::BI__builtin_huge_vall:
8486 case Builtin::BI__builtin_inf:
8487 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008488 case Builtin::BI__builtin_infl: {
8489 const llvm::fltSemantics &Sem =
8490 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008491 Result = llvm::APFloat::getInf(Sem);
8492 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008493 }
Mike Stump11289f42009-09-09 15:08:12 +00008494
John McCall16291492010-02-28 13:00:19 +00008495 case Builtin::BI__builtin_nans:
8496 case Builtin::BI__builtin_nansf:
8497 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008498 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8499 true, Result))
8500 return Error(E);
8501 return true;
John McCall16291492010-02-28 13:00:19 +00008502
Chris Lattner0b7282e2008-10-06 06:31:58 +00008503 case Builtin::BI__builtin_nan:
8504 case Builtin::BI__builtin_nanf:
8505 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008506 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008507 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008508 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8509 false, Result))
8510 return Error(E);
8511 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008512
8513 case Builtin::BI__builtin_fabs:
8514 case Builtin::BI__builtin_fabsf:
8515 case Builtin::BI__builtin_fabsl:
8516 if (!EvaluateFloat(E->getArg(0), Result, Info))
8517 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008518
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008519 if (Result.isNegative())
8520 Result.changeSign();
8521 return true;
8522
Richard Smith8889a3d2013-06-13 06:26:32 +00008523 // FIXME: Builtin::BI__builtin_powi
8524 // FIXME: Builtin::BI__builtin_powif
8525 // FIXME: Builtin::BI__builtin_powil
8526
Mike Stump11289f42009-09-09 15:08:12 +00008527 case Builtin::BI__builtin_copysign:
8528 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008529 case Builtin::BI__builtin_copysignl: {
8530 APFloat RHS(0.);
8531 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8532 !EvaluateFloat(E->getArg(1), RHS, Info))
8533 return false;
8534 Result.copySign(RHS);
8535 return true;
8536 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008537 }
8538}
8539
John McCallb1fb0d32010-05-07 22:08:54 +00008540bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008541 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8542 ComplexValue CV;
8543 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8544 return false;
8545 Result = CV.FloatReal;
8546 return true;
8547 }
8548
8549 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008550}
8551
8552bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008553 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8554 ComplexValue CV;
8555 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8556 return false;
8557 Result = CV.FloatImag;
8558 return true;
8559 }
8560
Richard Smith4a678122011-10-24 18:44:57 +00008561 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008562 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8563 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008564 return true;
8565}
8566
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008567bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008568 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008569 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008570 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008571 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008572 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008573 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8574 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008575 Result.changeSign();
8576 return true;
8577 }
8578}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008579
Eli Friedman24c01542008-08-22 00:06:13 +00008580bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008581 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8582 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008583
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008584 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008585 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008586 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008587 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008588 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8589 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008590}
8591
8592bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8593 Result = E->getValue();
8594 return true;
8595}
8596
Peter Collingbournee9200682011-05-13 03:29:01 +00008597bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8598 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008599
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008600 switch (E->getCastKind()) {
8601 default:
Richard Smith11562c52011-10-28 17:51:58 +00008602 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008603
8604 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008605 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008606 return EvaluateInteger(SubExpr, IntResult, Info) &&
8607 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8608 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008609 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008610
8611 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008612 if (!Visit(SubExpr))
8613 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008614 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8615 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008616 }
John McCalld7646252010-11-14 08:17:51 +00008617
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008618 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008619 ComplexValue V;
8620 if (!EvaluateComplex(SubExpr, V, Info))
8621 return false;
8622 Result = V.getComplexFloatReal();
8623 return true;
8624 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008625 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008626}
8627
Eli Friedman24c01542008-08-22 00:06:13 +00008628//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008629// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008630//===----------------------------------------------------------------------===//
8631
8632namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008633class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008634 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008635 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008636
Anders Carlsson537969c2008-11-16 20:27:53 +00008637public:
John McCall93d91dc2010-05-07 17:22:02 +00008638 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008639 : ExprEvaluatorBaseTy(info), Result(Result) {}
8640
Richard Smith2e312c82012-03-03 22:46:17 +00008641 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008642 Result.setFrom(V);
8643 return true;
8644 }
Mike Stump11289f42009-09-09 15:08:12 +00008645
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008646 bool ZeroInitialization(const Expr *E);
8647
Anders Carlsson537969c2008-11-16 20:27:53 +00008648 //===--------------------------------------------------------------------===//
8649 // Visitor Methods
8650 //===--------------------------------------------------------------------===//
8651
Peter Collingbournee9200682011-05-13 03:29:01 +00008652 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008653 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008654 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008655 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008656 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008657};
8658} // end anonymous namespace
8659
John McCall93d91dc2010-05-07 17:22:02 +00008660static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8661 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008662 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008663 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008664}
8665
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008666bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008667 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008668 if (ElemTy->isRealFloatingType()) {
8669 Result.makeComplexFloat();
8670 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8671 Result.FloatReal = Zero;
8672 Result.FloatImag = Zero;
8673 } else {
8674 Result.makeComplexInt();
8675 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8676 Result.IntReal = Zero;
8677 Result.IntImag = Zero;
8678 }
8679 return true;
8680}
8681
Peter Collingbournee9200682011-05-13 03:29:01 +00008682bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8683 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008684
8685 if (SubExpr->getType()->isRealFloatingType()) {
8686 Result.makeComplexFloat();
8687 APFloat &Imag = Result.FloatImag;
8688 if (!EvaluateFloat(SubExpr, Imag, Info))
8689 return false;
8690
8691 Result.FloatReal = APFloat(Imag.getSemantics());
8692 return true;
8693 } else {
8694 assert(SubExpr->getType()->isIntegerType() &&
8695 "Unexpected imaginary literal.");
8696
8697 Result.makeComplexInt();
8698 APSInt &Imag = Result.IntImag;
8699 if (!EvaluateInteger(SubExpr, Imag, Info))
8700 return false;
8701
8702 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8703 return true;
8704 }
8705}
8706
Peter Collingbournee9200682011-05-13 03:29:01 +00008707bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008708
John McCallfcef3cf2010-12-14 17:51:41 +00008709 switch (E->getCastKind()) {
8710 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008711 case CK_BaseToDerived:
8712 case CK_DerivedToBase:
8713 case CK_UncheckedDerivedToBase:
8714 case CK_Dynamic:
8715 case CK_ToUnion:
8716 case CK_ArrayToPointerDecay:
8717 case CK_FunctionToPointerDecay:
8718 case CK_NullToPointer:
8719 case CK_NullToMemberPointer:
8720 case CK_BaseToDerivedMemberPointer:
8721 case CK_DerivedToBaseMemberPointer:
8722 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008723 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008724 case CK_ConstructorConversion:
8725 case CK_IntegralToPointer:
8726 case CK_PointerToIntegral:
8727 case CK_PointerToBoolean:
8728 case CK_ToVoid:
8729 case CK_VectorSplat:
8730 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008731 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008732 case CK_IntegralToBoolean:
8733 case CK_IntegralToFloating:
8734 case CK_FloatingToIntegral:
8735 case CK_FloatingToBoolean:
8736 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008737 case CK_CPointerToObjCPointerCast:
8738 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008739 case CK_AnyPointerToBlockPointerCast:
8740 case CK_ObjCObjectLValueCast:
8741 case CK_FloatingComplexToReal:
8742 case CK_FloatingComplexToBoolean:
8743 case CK_IntegralComplexToReal:
8744 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008745 case CK_ARCProduceObject:
8746 case CK_ARCConsumeObject:
8747 case CK_ARCReclaimReturnedObject:
8748 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008749 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008750 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008751 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008752 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008753 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008754 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00008755 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008756
John McCallfcef3cf2010-12-14 17:51:41 +00008757 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008758 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008759 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008760 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008761
8762 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008763 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008764 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008765 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008766
8767 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008768 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008769 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008770 return false;
8771
John McCallfcef3cf2010-12-14 17:51:41 +00008772 Result.makeComplexFloat();
8773 Result.FloatImag = APFloat(Real.getSemantics());
8774 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008775 }
8776
John McCallfcef3cf2010-12-14 17:51:41 +00008777 case CK_FloatingComplexCast: {
8778 if (!Visit(E->getSubExpr()))
8779 return false;
8780
8781 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8782 QualType From
8783 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8784
Richard Smith357362d2011-12-13 06:39:58 +00008785 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8786 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008787 }
8788
8789 case CK_FloatingComplexToIntegralComplex: {
8790 if (!Visit(E->getSubExpr()))
8791 return false;
8792
8793 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8794 QualType From
8795 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8796 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008797 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8798 To, Result.IntReal) &&
8799 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8800 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008801 }
8802
8803 case CK_IntegralRealToComplex: {
8804 APSInt &Real = Result.IntReal;
8805 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8806 return false;
8807
8808 Result.makeComplexInt();
8809 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8810 return true;
8811 }
8812
8813 case CK_IntegralComplexCast: {
8814 if (!Visit(E->getSubExpr()))
8815 return false;
8816
8817 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8818 QualType From
8819 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8820
Richard Smith911e1422012-01-30 22:27:01 +00008821 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8822 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008823 return true;
8824 }
8825
8826 case CK_IntegralComplexToFloatingComplex: {
8827 if (!Visit(E->getSubExpr()))
8828 return false;
8829
Ted Kremenek28831752012-08-23 20:46:57 +00008830 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008831 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008832 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008833 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008834 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8835 To, Result.FloatReal) &&
8836 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8837 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008838 }
8839 }
8840
8841 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008842}
8843
John McCall93d91dc2010-05-07 17:22:02 +00008844bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008845 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008846 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8847
Chandler Carrutha216cad2014-10-11 00:57:18 +00008848 // Track whether the LHS or RHS is real at the type system level. When this is
8849 // the case we can simplify our evaluation strategy.
8850 bool LHSReal = false, RHSReal = false;
8851
8852 bool LHSOK;
8853 if (E->getLHS()->getType()->isRealFloatingType()) {
8854 LHSReal = true;
8855 APFloat &Real = Result.FloatReal;
8856 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8857 if (LHSOK) {
8858 Result.makeComplexFloat();
8859 Result.FloatImag = APFloat(Real.getSemantics());
8860 }
8861 } else {
8862 LHSOK = Visit(E->getLHS());
8863 }
George Burgess IVa145e252016-05-25 22:38:36 +00008864 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008865 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008866
John McCall93d91dc2010-05-07 17:22:02 +00008867 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008868 if (E->getRHS()->getType()->isRealFloatingType()) {
8869 RHSReal = true;
8870 APFloat &Real = RHS.FloatReal;
8871 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8872 return false;
8873 RHS.makeComplexFloat();
8874 RHS.FloatImag = APFloat(Real.getSemantics());
8875 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008876 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008877
Chandler Carrutha216cad2014-10-11 00:57:18 +00008878 assert(!(LHSReal && RHSReal) &&
8879 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008880 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008881 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008882 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008883 if (Result.isComplexFloat()) {
8884 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8885 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008886 if (LHSReal)
8887 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8888 else if (!RHSReal)
8889 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8890 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008891 } else {
8892 Result.getComplexIntReal() += RHS.getComplexIntReal();
8893 Result.getComplexIntImag() += RHS.getComplexIntImag();
8894 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008895 break;
John McCalle3027922010-08-25 11:45:40 +00008896 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008897 if (Result.isComplexFloat()) {
8898 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8899 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008900 if (LHSReal) {
8901 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8902 Result.getComplexFloatImag().changeSign();
8903 } else if (!RHSReal) {
8904 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8905 APFloat::rmNearestTiesToEven);
8906 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008907 } else {
8908 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8909 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8910 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008911 break;
John McCalle3027922010-08-25 11:45:40 +00008912 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008913 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008914 // This is an implementation of complex multiplication according to the
8915 // constraints laid out in C11 Annex G. The implemantion uses the
8916 // following naming scheme:
8917 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008918 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008919 APFloat &A = LHS.getComplexFloatReal();
8920 APFloat &B = LHS.getComplexFloatImag();
8921 APFloat &C = RHS.getComplexFloatReal();
8922 APFloat &D = RHS.getComplexFloatImag();
8923 APFloat &ResR = Result.getComplexFloatReal();
8924 APFloat &ResI = Result.getComplexFloatImag();
8925 if (LHSReal) {
8926 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8927 ResR = A * C;
8928 ResI = A * D;
8929 } else if (RHSReal) {
8930 ResR = C * A;
8931 ResI = C * B;
8932 } else {
8933 // In the fully general case, we need to handle NaNs and infinities
8934 // robustly.
8935 APFloat AC = A * C;
8936 APFloat BD = B * D;
8937 APFloat AD = A * D;
8938 APFloat BC = B * C;
8939 ResR = AC - BD;
8940 ResI = AD + BC;
8941 if (ResR.isNaN() && ResI.isNaN()) {
8942 bool Recalc = false;
8943 if (A.isInfinity() || B.isInfinity()) {
8944 A = APFloat::copySign(
8945 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8946 B = APFloat::copySign(
8947 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8948 if (C.isNaN())
8949 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8950 if (D.isNaN())
8951 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8952 Recalc = true;
8953 }
8954 if (C.isInfinity() || D.isInfinity()) {
8955 C = APFloat::copySign(
8956 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8957 D = APFloat::copySign(
8958 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8959 if (A.isNaN())
8960 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8961 if (B.isNaN())
8962 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8963 Recalc = true;
8964 }
8965 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8966 AD.isInfinity() || BC.isInfinity())) {
8967 if (A.isNaN())
8968 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8969 if (B.isNaN())
8970 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8971 if (C.isNaN())
8972 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8973 if (D.isNaN())
8974 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8975 Recalc = true;
8976 }
8977 if (Recalc) {
8978 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8979 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8980 }
8981 }
8982 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008983 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008984 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008985 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008986 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8987 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008988 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008989 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8990 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8991 }
8992 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008993 case BO_Div:
8994 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008995 // This is an implementation of complex division according to the
8996 // constraints laid out in C11 Annex G. The implemantion uses the
8997 // following naming scheme:
8998 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008999 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009000 APFloat &A = LHS.getComplexFloatReal();
9001 APFloat &B = LHS.getComplexFloatImag();
9002 APFloat &C = RHS.getComplexFloatReal();
9003 APFloat &D = RHS.getComplexFloatImag();
9004 APFloat &ResR = Result.getComplexFloatReal();
9005 APFloat &ResI = Result.getComplexFloatImag();
9006 if (RHSReal) {
9007 ResR = A / C;
9008 ResI = B / C;
9009 } else {
9010 if (LHSReal) {
9011 // No real optimizations we can do here, stub out with zero.
9012 B = APFloat::getZero(A.getSemantics());
9013 }
9014 int DenomLogB = 0;
9015 APFloat MaxCD = maxnum(abs(C), abs(D));
9016 if (MaxCD.isFinite()) {
9017 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009018 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9019 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009020 }
9021 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009022 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9023 APFloat::rmNearestTiesToEven);
9024 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9025 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009026 if (ResR.isNaN() && ResI.isNaN()) {
9027 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9028 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9029 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9030 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9031 D.isFinite()) {
9032 A = APFloat::copySign(
9033 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9034 B = APFloat::copySign(
9035 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9036 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9037 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9038 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9039 C = APFloat::copySign(
9040 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9041 D = APFloat::copySign(
9042 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9043 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9044 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9045 }
9046 }
9047 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009048 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009049 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9050 return Error(E, diag::note_expr_divide_by_zero);
9051
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009052 ComplexValue LHS = Result;
9053 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9054 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9055 Result.getComplexIntReal() =
9056 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9057 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9058 Result.getComplexIntImag() =
9059 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9060 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9061 }
9062 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009063 }
9064
John McCall93d91dc2010-05-07 17:22:02 +00009065 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009066}
9067
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009068bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9069 // Get the operand value into 'Result'.
9070 if (!Visit(E->getSubExpr()))
9071 return false;
9072
9073 switch (E->getOpcode()) {
9074 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009075 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009076 case UO_Extension:
9077 return true;
9078 case UO_Plus:
9079 // The result is always just the subexpr.
9080 return true;
9081 case UO_Minus:
9082 if (Result.isComplexFloat()) {
9083 Result.getComplexFloatReal().changeSign();
9084 Result.getComplexFloatImag().changeSign();
9085 }
9086 else {
9087 Result.getComplexIntReal() = -Result.getComplexIntReal();
9088 Result.getComplexIntImag() = -Result.getComplexIntImag();
9089 }
9090 return true;
9091 case UO_Not:
9092 if (Result.isComplexFloat())
9093 Result.getComplexFloatImag().changeSign();
9094 else
9095 Result.getComplexIntImag() = -Result.getComplexIntImag();
9096 return true;
9097 }
9098}
9099
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009100bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9101 if (E->getNumInits() == 2) {
9102 if (E->getType()->isComplexType()) {
9103 Result.makeComplexFloat();
9104 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9105 return false;
9106 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9107 return false;
9108 } else {
9109 Result.makeComplexInt();
9110 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9111 return false;
9112 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9113 return false;
9114 }
9115 return true;
9116 }
9117 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9118}
9119
Anders Carlsson537969c2008-11-16 20:27:53 +00009120//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009121// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9122// implicit conversion.
9123//===----------------------------------------------------------------------===//
9124
9125namespace {
9126class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009127 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009128 APValue &Result;
9129public:
9130 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9131 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9132
9133 bool Success(const APValue &V, const Expr *E) {
9134 Result = V;
9135 return true;
9136 }
9137
9138 bool ZeroInitialization(const Expr *E) {
9139 ImplicitValueInitExpr VIE(
9140 E->getType()->castAs<AtomicType>()->getValueType());
9141 return Evaluate(Result, Info, &VIE);
9142 }
9143
9144 bool VisitCastExpr(const CastExpr *E) {
9145 switch (E->getCastKind()) {
9146 default:
9147 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9148 case CK_NonAtomicToAtomic:
9149 return Evaluate(Result, Info, E->getSubExpr());
9150 }
9151 }
9152};
9153} // end anonymous namespace
9154
9155static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9156 assert(E->isRValue() && E->getType()->isAtomicType());
9157 return AtomicExprEvaluator(Info, Result).Visit(E);
9158}
9159
9160//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009161// Void expression evaluation, primarily for a cast to void on the LHS of a
9162// comma operator
9163//===----------------------------------------------------------------------===//
9164
9165namespace {
9166class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009167 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009168public:
9169 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9170
Richard Smith2e312c82012-03-03 22:46:17 +00009171 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009172
9173 bool VisitCastExpr(const CastExpr *E) {
9174 switch (E->getCastKind()) {
9175 default:
9176 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9177 case CK_ToVoid:
9178 VisitIgnoredValue(E->getSubExpr());
9179 return true;
9180 }
9181 }
Hal Finkela8443c32014-07-17 14:49:58 +00009182
9183 bool VisitCallExpr(const CallExpr *E) {
9184 switch (E->getBuiltinCallee()) {
9185 default:
9186 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9187 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009188 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009189 // The argument is not evaluated!
9190 return true;
9191 }
9192 }
Richard Smith42d3af92011-12-07 00:43:50 +00009193};
9194} // end anonymous namespace
9195
9196static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9197 assert(E->isRValue() && E->getType()->isVoidType());
9198 return VoidExprEvaluator(Info).Visit(E);
9199}
9200
9201//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009202// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009203//===----------------------------------------------------------------------===//
9204
Richard Smith2e312c82012-03-03 22:46:17 +00009205static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009206 // In C, function designators are not lvalues, but we evaluate them as if they
9207 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009208 QualType T = E->getType();
9209 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009210 LValue LV;
9211 if (!EvaluateLValue(E, LV, Info))
9212 return false;
9213 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009214 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009215 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009216 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009217 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009218 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009219 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009220 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009221 LValue LV;
9222 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009223 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009224 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009225 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009226 llvm::APFloat F(0.0);
9227 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009228 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009229 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009230 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009231 ComplexValue C;
9232 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009233 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009234 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009235 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009236 MemberPtr P;
9237 if (!EvaluateMemberPointer(E, P, Info))
9238 return false;
9239 P.moveInto(Result);
9240 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009241 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009242 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009243 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009244 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9245 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009246 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009247 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009248 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009249 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009250 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009251 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9252 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009253 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009254 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009255 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009256 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009257 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009258 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009259 if (!EvaluateVoid(E, Info))
9260 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009261 } else if (T->isAtomicType()) {
9262 if (!EvaluateAtomic(E, Result, Info))
9263 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009264 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009265 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009266 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009267 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009268 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009269 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009270 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009271
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009272 return true;
9273}
9274
Richard Smithb228a862012-02-15 02:18:13 +00009275/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9276/// cases, the in-place evaluation is essential, since later initializers for
9277/// an object can indirectly refer to subobjects which were initialized earlier.
9278static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009279 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009280 assert(!E->isValueDependent());
9281
Richard Smith7525ff62013-05-09 07:14:00 +00009282 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009283 return false;
9284
9285 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009286 // Evaluate arrays and record types in-place, so that later initializers can
9287 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009288 if (E->getType()->isArrayType())
9289 return EvaluateArray(E, This, Result, Info);
9290 else if (E->getType()->isRecordType())
9291 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009292 }
9293
9294 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009295 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009296}
9297
Richard Smithf57d8cb2011-12-09 22:58:01 +00009298/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9299/// lvalue-to-rvalue cast if it is an lvalue.
9300static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009301 if (E->getType().isNull())
9302 return false;
9303
Richard Smithfddd3842011-12-30 21:15:51 +00009304 if (!CheckLiteralType(Info, E))
9305 return false;
9306
Richard Smith2e312c82012-03-03 22:46:17 +00009307 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009308 return false;
9309
9310 if (E->isGLValue()) {
9311 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009312 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009313 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009314 return false;
9315 }
9316
Richard Smith2e312c82012-03-03 22:46:17 +00009317 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009318 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009319}
Richard Smith11562c52011-10-28 17:51:58 +00009320
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009321static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9322 const ASTContext &Ctx, bool &IsConst) {
9323 // Fast-path evaluations of integer literals, since we sometimes see files
9324 // containing vast quantities of these.
9325 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9326 Result.Val = APValue(APSInt(L->getValue(),
9327 L->getType()->isUnsignedIntegerType()));
9328 IsConst = true;
9329 return true;
9330 }
James Dennett0492ef02014-03-14 17:44:10 +00009331
9332 // This case should be rare, but we need to check it before we check on
9333 // the type below.
9334 if (Exp->getType().isNull()) {
9335 IsConst = false;
9336 return true;
9337 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009338
9339 // FIXME: Evaluating values of large array and record types can cause
9340 // performance problems. Only do so in C++11 for now.
9341 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9342 Exp->getType()->isRecordType()) &&
9343 !Ctx.getLangOpts().CPlusPlus11) {
9344 IsConst = false;
9345 return true;
9346 }
9347 return false;
9348}
9349
9350
Richard Smith7b553f12011-10-29 00:50:52 +00009351/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009352/// any crazy technique (that has nothing to do with language standards) that
9353/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009354/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9355/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009356bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009357 bool IsConst;
9358 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9359 return IsConst;
9360
Richard Smith6d4c6582013-11-05 22:18:15 +00009361 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009362 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009363}
9364
Jay Foad39c79802011-01-12 09:06:06 +00009365bool Expr::EvaluateAsBooleanCondition(bool &Result,
9366 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009367 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009368 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009369 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009370}
9371
Richard Smithce8eca52015-12-08 03:21:47 +00009372static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9373 Expr::SideEffectsKind SEK) {
9374 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9375 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9376}
9377
Richard Smith5fab0c92011-12-28 19:48:30 +00009378bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9379 SideEffectsKind AllowSideEffects) const {
9380 if (!getType()->isIntegralOrEnumerationType())
9381 return false;
9382
Richard Smith11562c52011-10-28 17:51:58 +00009383 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009384 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009385 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009386 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009387
Richard Smith11562c52011-10-28 17:51:58 +00009388 Result = ExprResult.Val.getInt();
9389 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009390}
9391
Richard Trieube234c32016-04-21 21:04:55 +00009392bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9393 SideEffectsKind AllowSideEffects) const {
9394 if (!getType()->isRealFloatingType())
9395 return false;
9396
9397 EvalResult ExprResult;
9398 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9399 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9400 return false;
9401
9402 Result = ExprResult.Val.getFloat();
9403 return true;
9404}
9405
Jay Foad39c79802011-01-12 09:06:06 +00009406bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009407 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009408
John McCall45d55e42010-05-07 21:00:08 +00009409 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009410 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9411 !CheckLValueConstantExpression(Info, getExprLoc(),
9412 Ctx.getLValueReferenceType(getType()), LV))
9413 return false;
9414
Richard Smith2e312c82012-03-03 22:46:17 +00009415 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009416 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009417}
9418
Richard Smithd0b4dd62011-12-19 06:19:21 +00009419bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9420 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009421 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009422 // FIXME: Evaluating initializers for large array and record types can cause
9423 // performance problems. Only do so in C++11 for now.
9424 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009425 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009426 return false;
9427
Richard Smithd0b4dd62011-12-19 06:19:21 +00009428 Expr::EvalStatus EStatus;
9429 EStatus.Diag = &Notes;
9430
Richard Smith0c6124b2015-12-03 01:36:22 +00009431 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9432 ? EvalInfo::EM_ConstantExpression
9433 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009434 InitInfo.setEvaluatingDecl(VD, Value);
9435
9436 LValue LVal;
9437 LVal.set(VD);
9438
Richard Smithfddd3842011-12-30 21:15:51 +00009439 // C++11 [basic.start.init]p2:
9440 // Variables with static storage duration or thread storage duration shall be
9441 // zero-initialized before any other initialization takes place.
9442 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009443 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009444 !VD->getType()->isReferenceType()) {
9445 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009446 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009447 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009448 return false;
9449 }
9450
Richard Smith7525ff62013-05-09 07:14:00 +00009451 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9452 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009453 EStatus.HasSideEffects)
9454 return false;
9455
9456 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9457 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009458}
9459
Richard Smith7b553f12011-10-29 00:50:52 +00009460/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9461/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009462bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009463 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009464 return EvaluateAsRValue(Result, Ctx) &&
9465 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009466}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009467
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009468APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009469 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009470 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009471 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009472 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009473 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009474 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009475 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009476
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009477 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009478}
John McCall864e3962010-05-07 05:32:02 +00009479
Richard Smithe9ff7702013-11-05 22:23:30 +00009480void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009481 bool IsConst;
9482 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009483 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009484 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009485 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9486 }
9487}
9488
Richard Smithe6c01442013-06-05 00:46:14 +00009489bool Expr::EvalResult::isGlobalLValue() const {
9490 assert(Val.isLValue());
9491 return IsGlobalLValue(Val.getLValueBase());
9492}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009493
9494
John McCall864e3962010-05-07 05:32:02 +00009495/// isIntegerConstantExpr - this recursive routine will test if an expression is
9496/// an integer constant expression.
9497
9498/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9499/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009500
9501// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009502// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9503// and a (possibly null) SourceLocation indicating the location of the problem.
9504//
John McCall864e3962010-05-07 05:32:02 +00009505// Note that to reduce code duplication, this helper does no evaluation
9506// itself; the caller checks whether the expression is evaluatable, and
9507// in the rare cases where CheckICE actually cares about the evaluated
9508// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009509
Dan Gohman28ade552010-07-26 21:25:24 +00009510namespace {
9511
Richard Smith9e575da2012-12-28 13:25:52 +00009512enum ICEKind {
9513 /// This expression is an ICE.
9514 IK_ICE,
9515 /// This expression is not an ICE, but if it isn't evaluated, it's
9516 /// a legal subexpression for an ICE. This return value is used to handle
9517 /// the comma operator in C99 mode, and non-constant subexpressions.
9518 IK_ICEIfUnevaluated,
9519 /// This expression is not an ICE, and is not a legal subexpression for one.
9520 IK_NotICE
9521};
9522
John McCall864e3962010-05-07 05:32:02 +00009523struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009524 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009525 SourceLocation Loc;
9526
Richard Smith9e575da2012-12-28 13:25:52 +00009527 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009528};
9529
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009530}
Dan Gohman28ade552010-07-26 21:25:24 +00009531
Richard Smith9e575da2012-12-28 13:25:52 +00009532static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9533
9534static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009535
Craig Toppera31a8822013-08-22 07:09:37 +00009536static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009537 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009538 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009539 !EVResult.Val.isInt())
9540 return ICEDiag(IK_NotICE, E->getLocStart());
9541
John McCall864e3962010-05-07 05:32:02 +00009542 return NoDiag();
9543}
9544
Craig Toppera31a8822013-08-22 07:09:37 +00009545static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009546 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009547 if (!E->getType()->isIntegralOrEnumerationType())
9548 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009549
9550 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009551#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009552#define STMT(Node, Base) case Expr::Node##Class:
9553#define EXPR(Node, Base)
9554#include "clang/AST/StmtNodes.inc"
9555 case Expr::PredefinedExprClass:
9556 case Expr::FloatingLiteralClass:
9557 case Expr::ImaginaryLiteralClass:
9558 case Expr::StringLiteralClass:
9559 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009560 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009561 case Expr::MemberExprClass:
9562 case Expr::CompoundAssignOperatorClass:
9563 case Expr::CompoundLiteralExprClass:
9564 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009565 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009566 case Expr::NoInitExprClass:
9567 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009568 case Expr::ImplicitValueInitExprClass:
9569 case Expr::ParenListExprClass:
9570 case Expr::VAArgExprClass:
9571 case Expr::AddrLabelExprClass:
9572 case Expr::StmtExprClass:
9573 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009574 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009575 case Expr::CXXDynamicCastExprClass:
9576 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009577 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009578 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009579 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009580 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009581 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009582 case Expr::CXXThisExprClass:
9583 case Expr::CXXThrowExprClass:
9584 case Expr::CXXNewExprClass:
9585 case Expr::CXXDeleteExprClass:
9586 case Expr::CXXPseudoDestructorExprClass:
9587 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009588 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009589 case Expr::DependentScopeDeclRefExprClass:
9590 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00009591 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009592 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009593 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009594 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009595 case Expr::CXXTemporaryObjectExprClass:
9596 case Expr::CXXUnresolvedConstructExprClass:
9597 case Expr::CXXDependentScopeMemberExprClass:
9598 case Expr::UnresolvedMemberExprClass:
9599 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009600 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009601 case Expr::ObjCArrayLiteralClass:
9602 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009603 case Expr::ObjCEncodeExprClass:
9604 case Expr::ObjCMessageExprClass:
9605 case Expr::ObjCSelectorExprClass:
9606 case Expr::ObjCProtocolExprClass:
9607 case Expr::ObjCIvarRefExprClass:
9608 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009609 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009610 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00009611 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +00009612 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009613 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009614 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009615 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009616 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009617 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009618 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009619 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009620 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009621 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009622 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009623 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009624 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009625 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009626 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009627 case Expr::CoawaitExprClass:
9628 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009629 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009630
Richard Smithf137f932014-01-25 20:50:08 +00009631 case Expr::InitListExprClass: {
9632 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9633 // form "T x = { a };" is equivalent to "T x = a;".
9634 // Unless we're initializing a reference, T is a scalar as it is known to be
9635 // of integral or enumeration type.
9636 if (E->isRValue())
9637 if (cast<InitListExpr>(E)->getNumInits() == 1)
9638 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9639 return ICEDiag(IK_NotICE, E->getLocStart());
9640 }
9641
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009642 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009643 case Expr::GNUNullExprClass:
9644 // GCC considers the GNU __null value to be an integral constant expression.
9645 return NoDiag();
9646
John McCall7c454bb2011-07-15 05:09:51 +00009647 case Expr::SubstNonTypeTemplateParmExprClass:
9648 return
9649 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9650
John McCall864e3962010-05-07 05:32:02 +00009651 case Expr::ParenExprClass:
9652 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009653 case Expr::GenericSelectionExprClass:
9654 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009655 case Expr::IntegerLiteralClass:
9656 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009657 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009658 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009659 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009660 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009661 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009662 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009663 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009664 return NoDiag();
9665 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009666 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009667 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9668 // constant expressions, but they can never be ICEs because an ICE cannot
9669 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009670 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009671 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009672 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009673 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009674 }
Richard Smith6365c912012-02-24 22:12:32 +00009675 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009676 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9677 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009678 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009679 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009680 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009681 // Parameter variables are never constants. Without this check,
9682 // getAnyInitializer() can find a default argument, which leads
9683 // to chaos.
9684 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009685 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009686
9687 // C++ 7.1.5.1p2
9688 // A variable of non-volatile const-qualified integral or enumeration
9689 // type initialized by an ICE can be used in ICEs.
9690 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009691 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009692 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009693
Richard Smithd0b4dd62011-12-19 06:19:21 +00009694 const VarDecl *VD;
9695 // Look for a declaration of this variable that has an initializer, and
9696 // check whether it is an ICE.
9697 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9698 return NoDiag();
9699 else
Richard Smith9e575da2012-12-28 13:25:52 +00009700 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009701 }
9702 }
Richard Smith9e575da2012-12-28 13:25:52 +00009703 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009704 }
John McCall864e3962010-05-07 05:32:02 +00009705 case Expr::UnaryOperatorClass: {
9706 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9707 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009708 case UO_PostInc:
9709 case UO_PostDec:
9710 case UO_PreInc:
9711 case UO_PreDec:
9712 case UO_AddrOf:
9713 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009714 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009715 // C99 6.6/3 allows increment and decrement within unevaluated
9716 // subexpressions of constant expressions, but they can never be ICEs
9717 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009718 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009719 case UO_Extension:
9720 case UO_LNot:
9721 case UO_Plus:
9722 case UO_Minus:
9723 case UO_Not:
9724 case UO_Real:
9725 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009726 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009727 }
Richard Smith9e575da2012-12-28 13:25:52 +00009728
John McCall864e3962010-05-07 05:32:02 +00009729 // OffsetOf falls through here.
9730 }
9731 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009732 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9733 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9734 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9735 // compliance: we should warn earlier for offsetof expressions with
9736 // array subscripts that aren't ICEs, and if the array subscripts
9737 // are ICEs, the value of the offsetof must be an integer constant.
9738 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009739 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009740 case Expr::UnaryExprOrTypeTraitExprClass: {
9741 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9742 if ((Exp->getKind() == UETT_SizeOf) &&
9743 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009744 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009745 return NoDiag();
9746 }
9747 case Expr::BinaryOperatorClass: {
9748 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9749 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009750 case BO_PtrMemD:
9751 case BO_PtrMemI:
9752 case BO_Assign:
9753 case BO_MulAssign:
9754 case BO_DivAssign:
9755 case BO_RemAssign:
9756 case BO_AddAssign:
9757 case BO_SubAssign:
9758 case BO_ShlAssign:
9759 case BO_ShrAssign:
9760 case BO_AndAssign:
9761 case BO_XorAssign:
9762 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009763 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9764 // constant expressions, but they can never be ICEs because an ICE cannot
9765 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009766 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009767
John McCalle3027922010-08-25 11:45:40 +00009768 case BO_Mul:
9769 case BO_Div:
9770 case BO_Rem:
9771 case BO_Add:
9772 case BO_Sub:
9773 case BO_Shl:
9774 case BO_Shr:
9775 case BO_LT:
9776 case BO_GT:
9777 case BO_LE:
9778 case BO_GE:
9779 case BO_EQ:
9780 case BO_NE:
9781 case BO_And:
9782 case BO_Xor:
9783 case BO_Or:
9784 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009785 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9786 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009787 if (Exp->getOpcode() == BO_Div ||
9788 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009789 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009790 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009791 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009792 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009793 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009794 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009795 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009796 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009797 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009798 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009799 }
9800 }
9801 }
John McCalle3027922010-08-25 11:45:40 +00009802 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009803 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009804 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9805 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009806 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9807 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009808 } else {
9809 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009810 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009811 }
9812 }
Richard Smith9e575da2012-12-28 13:25:52 +00009813 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009814 }
John McCalle3027922010-08-25 11:45:40 +00009815 case BO_LAnd:
9816 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009817 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9818 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009819 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009820 // Rare case where the RHS has a comma "side-effect"; we need
9821 // to actually check the condition to see whether the side
9822 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009823 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009824 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009825 return RHSResult;
9826 return NoDiag();
9827 }
9828
Richard Smith9e575da2012-12-28 13:25:52 +00009829 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009830 }
9831 }
9832 }
9833 case Expr::ImplicitCastExprClass:
9834 case Expr::CStyleCastExprClass:
9835 case Expr::CXXFunctionalCastExprClass:
9836 case Expr::CXXStaticCastExprClass:
9837 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009838 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009839 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009840 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009841 if (isa<ExplicitCastExpr>(E)) {
9842 if (const FloatingLiteral *FL
9843 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9844 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9845 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9846 APSInt IgnoredVal(DestWidth, !DestSigned);
9847 bool Ignored;
9848 // If the value does not fit in the destination type, the behavior is
9849 // undefined, so we are not required to treat it as a constant
9850 // expression.
9851 if (FL->getValue().convertToInteger(IgnoredVal,
9852 llvm::APFloat::rmTowardZero,
9853 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009854 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009855 return NoDiag();
9856 }
9857 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009858 switch (cast<CastExpr>(E)->getCastKind()) {
9859 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009860 case CK_AtomicToNonAtomic:
9861 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009862 case CK_NoOp:
9863 case CK_IntegralToBoolean:
9864 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009865 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009866 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009867 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009868 }
John McCall864e3962010-05-07 05:32:02 +00009869 }
John McCallc07a0c72011-02-17 10:25:35 +00009870 case Expr::BinaryConditionalOperatorClass: {
9871 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9872 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009873 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009874 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009875 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9876 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9877 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009878 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009879 return FalseResult;
9880 }
John McCall864e3962010-05-07 05:32:02 +00009881 case Expr::ConditionalOperatorClass: {
9882 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9883 // If the condition (ignoring parens) is a __builtin_constant_p call,
9884 // then only the true side is actually considered in an integer constant
9885 // expression, and it is fully evaluated. This is an important GNU
9886 // extension. See GCC PR38377 for discussion.
9887 if (const CallExpr *CallCE
9888 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009889 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009890 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009891 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009892 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009893 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009894
Richard Smithf57d8cb2011-12-09 22:58:01 +00009895 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9896 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009897
Richard Smith9e575da2012-12-28 13:25:52 +00009898 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009899 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009900 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009901 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009902 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009903 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009904 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009905 return NoDiag();
9906 // Rare case where the diagnostics depend on which side is evaluated
9907 // Note that if we get here, CondResult is 0, and at least one of
9908 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009909 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009910 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009911 return TrueResult;
9912 }
9913 case Expr::CXXDefaultArgExprClass:
9914 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009915 case Expr::CXXDefaultInitExprClass:
9916 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009917 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009918 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009919 }
9920 }
9921
David Blaikiee4d798f2012-01-20 21:50:17 +00009922 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009923}
9924
Richard Smithf57d8cb2011-12-09 22:58:01 +00009925/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009926static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009927 const Expr *E,
9928 llvm::APSInt *Value,
9929 SourceLocation *Loc) {
9930 if (!E->getType()->isIntegralOrEnumerationType()) {
9931 if (Loc) *Loc = E->getExprLoc();
9932 return false;
9933 }
9934
Richard Smith66e05fe2012-01-18 05:21:49 +00009935 APValue Result;
9936 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009937 return false;
9938
Richard Smith98710fc2014-11-13 23:03:19 +00009939 if (!Result.isInt()) {
9940 if (Loc) *Loc = E->getExprLoc();
9941 return false;
9942 }
9943
Richard Smith66e05fe2012-01-18 05:21:49 +00009944 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009945 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009946}
9947
Craig Toppera31a8822013-08-22 07:09:37 +00009948bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9949 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009950 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009951 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009952
Richard Smith9e575da2012-12-28 13:25:52 +00009953 ICEDiag D = CheckICE(this, Ctx);
9954 if (D.Kind != IK_ICE) {
9955 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009956 return false;
9957 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009958 return true;
9959}
9960
Craig Toppera31a8822013-08-22 07:09:37 +00009961bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009962 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009963 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009964 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9965
9966 if (!isIntegerConstantExpr(Ctx, Loc))
9967 return false;
Richard Smith5c40f092015-12-04 03:00:44 +00009968 // The only possible side-effects here are due to UB discovered in the
9969 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9970 // required to treat the expression as an ICE, so we produce the folded
9971 // value.
9972 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +00009973 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009974 return true;
9975}
Richard Smith66e05fe2012-01-18 05:21:49 +00009976
Craig Toppera31a8822013-08-22 07:09:37 +00009977bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009978 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009979}
9980
Craig Toppera31a8822013-08-22 07:09:37 +00009981bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009982 SourceLocation *Loc) const {
9983 // We support this checking in C++98 mode in order to diagnose compatibility
9984 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009985 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009986
Richard Smith98a0a492012-02-14 21:38:30 +00009987 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009988 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009989 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009990 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009991 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009992
9993 APValue Scratch;
9994 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9995
9996 if (!Diags.empty()) {
9997 IsConstExpr = false;
9998 if (Loc) *Loc = Diags[0].first;
9999 } else if (!IsConstExpr) {
10000 // FIXME: This shouldn't happen.
10001 if (Loc) *Loc = getExprLoc();
10002 }
10003
10004 return IsConstExpr;
10005}
Richard Smith253c2a32012-01-27 01:14:48 +000010006
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010007bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10008 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +000010009 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010010 Expr::EvalStatus Status;
10011 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10012
10013 ArgVector ArgValues(Args.size());
10014 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10015 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010016 if ((*I)->isValueDependent() ||
10017 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010018 // If evaluation fails, throw away the argument entirely.
10019 ArgValues[I - Args.begin()] = APValue();
10020 if (Info.EvalStatus.HasSideEffects)
10021 return false;
10022 }
10023
10024 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +000010025 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010026 ArgValues.data());
10027 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10028}
10029
Richard Smith253c2a32012-01-27 01:14:48 +000010030bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010031 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010032 PartialDiagnosticAt> &Diags) {
10033 // FIXME: It would be useful to check constexpr function templates, but at the
10034 // moment the constant expression evaluator cannot cope with the non-rigorous
10035 // ASTs which we build for dependent expressions.
10036 if (FD->isDependentContext())
10037 return true;
10038
10039 Expr::EvalStatus Status;
10040 Status.Diag = &Diags;
10041
Richard Smith6d4c6582013-11-05 22:18:15 +000010042 EvalInfo Info(FD->getASTContext(), Status,
10043 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010044
10045 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010046 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010047
Richard Smith7525ff62013-05-09 07:14:00 +000010048 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010049 // is a temporary being used as the 'this' pointer.
10050 LValue This;
10051 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010052 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010053
Richard Smith253c2a32012-01-27 01:14:48 +000010054 ArrayRef<const Expr*> Args;
10055
Richard Smith2e312c82012-03-03 22:46:17 +000010056 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010057 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10058 // Evaluate the call as a constant initializer, to allow the construction
10059 // of objects of non-literal types.
10060 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010061 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10062 } else {
10063 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010064 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010065 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010066 }
Richard Smith253c2a32012-01-27 01:14:48 +000010067
10068 return Diags.empty();
10069}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010070
10071bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10072 const FunctionDecl *FD,
10073 SmallVectorImpl<
10074 PartialDiagnosticAt> &Diags) {
10075 Expr::EvalStatus Status;
10076 Status.Diag = &Diags;
10077
10078 EvalInfo Info(FD->getASTContext(), Status,
10079 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10080
10081 // Fabricate a call stack frame to give the arguments a plausible cover story.
10082 ArrayRef<const Expr*> Args;
10083 ArgVector ArgValues(0);
10084 bool Success = EvaluateArgs(Args, ArgValues, Info);
10085 (void)Success;
10086 assert(Success &&
10087 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010088 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010089
10090 APValue ResultScratch;
10091 Evaluate(ResultScratch, Info, E);
10092 return Diags.empty();
10093}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010094
10095bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10096 unsigned Type) const {
10097 if (!getType()->isPointerType())
10098 return false;
10099
10100 Expr::EvalStatus Status;
10101 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10102 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
10103}