1//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2//
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 defines the Expr interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXPR_H
15#define LLVM_CLANG_AST_EXPR_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/ASTVector.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/OperationKinds.h"
22#include "clang/AST/Stmt.h"
23#include "clang/AST/TemplateBase.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/CharInfo.h"
26#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/SyncScope.h"
28#include "clang/Basic/TypeTraits.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/APSInt.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/Support/AtomicOrdering.h"
34#include "llvm/Support/Compiler.h"
35
36namespace clang {
37 class APValue;
38 class ASTContext;
39 class BlockDecl;
40 class CXXBaseSpecifier;
41 class CXXMemberCallExpr;
42 class CXXOperatorCallExpr;
43 class CastExpr;
44 class Decl;
45 class IdentifierInfo;
46 class MaterializeTemporaryExpr;
47 class NamedDecl;
48 class ObjCPropertyRefExpr;
49 class OpaqueValueExpr;
50 class ParmVarDecl;
51 class StringLiteral;
52 class TargetInfo;
53 class ValueDecl;
54
55/// A simple array of base specifiers.
56typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
57
58/// An adjustment to be made to the temporary created when emitting a
59/// reference binding, which accesses a particular subobject of that temporary.
60struct SubobjectAdjustment {
61 enum {
62 DerivedToBaseAdjustment,
63 FieldAdjustment,
64 MemberPointerAdjustment
65 } Kind;
66
67 struct DTB {
68 const CastExpr *BasePath;
69 const CXXRecordDecl *DerivedClass;
70 };
71
72 struct P {
73 const MemberPointerType *MPT;
74 Expr *RHS;
75 };
76
77 union {
78 struct DTB DerivedToBase;
79 FieldDecl *Field;
80 struct P Ptr;
81 };
82
83 SubobjectAdjustment(const CastExpr *BasePath,
84 const CXXRecordDecl *DerivedClass)
85 : Kind(DerivedToBaseAdjustment) {
86 DerivedToBase.BasePath = BasePath;
87 DerivedToBase.DerivedClass = DerivedClass;
88 }
89
90 SubobjectAdjustment(FieldDecl *Field)
91 : Kind(FieldAdjustment) {
92 this->Field = Field;
93 }
94
95 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
96 : Kind(MemberPointerAdjustment) {
97 this->Ptr.MPT = MPT;
98 this->Ptr.RHS = RHS;
99 }
100};
101
102/// Expr - This represents one expression. Note that Expr's are subclasses of
103/// Stmt. This allows an expression to be transparently used any place a Stmt
104/// is required.
105///
106class Expr : public Stmt {
107 QualType TR;
108
109protected:
110 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
111 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
112 : Stmt(SC)
113 {
114 ExprBits.TypeDependent = TD;
115 ExprBits.ValueDependent = VD;
116 ExprBits.InstantiationDependent = ID;
117 ExprBits.ValueKind = VK;
118 ExprBits.ObjectKind = OK;
119 assert(ExprBits.ObjectKind == OK && "truncated kind");
120 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
121 setType(T);
122 }
123
124 /// Construct an empty expression.
125 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
126
127public:
128 QualType getType() const { return TR; }
129 void setType(QualType t) {
130 // In C++, the type of an expression is always adjusted so that it
131 // will not have reference type (C++ [expr]p6). Use
132 // QualType::getNonReferenceType() to retrieve the non-reference
133 // type. Additionally, inspect Expr::isLvalue to determine whether
134 // an expression that is adjusted in this manner should be
135 // considered an lvalue.
136 assert((t.isNull() || !t->isReferenceType()) &&
137 "Expressions can't have reference type");
138
139 TR = t;
140 }
141
142 /// isValueDependent - Determines whether this expression is
143 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
144 /// array bound of "Chars" in the following example is
145 /// value-dependent.
146 /// @code
147 /// template<int Size, char (&Chars)[Size]> struct meta_string;
148 /// @endcode
149 bool isValueDependent() const { return ExprBits.ValueDependent; }
150
151 /// Set whether this expression is value-dependent or not.
152 void setValueDependent(bool VD) {
153 ExprBits.ValueDependent = VD;
154 }
155
156 /// isTypeDependent - Determines whether this expression is
157 /// type-dependent (C++ [temp.dep.expr]), which means that its type
158 /// could change from one template instantiation to the next. For
159 /// example, the expressions "x" and "x + y" are type-dependent in
160 /// the following code, but "y" is not type-dependent:
161 /// @code
162 /// template<typename T>
163 /// void add(T x, int y) {
164 /// x + y;
165 /// }
166 /// @endcode
167 bool isTypeDependent() const { return ExprBits.TypeDependent; }
168
169 /// Set whether this expression is type-dependent or not.
170 void setTypeDependent(bool TD) {
171 ExprBits.TypeDependent = TD;
172 }
173
174 /// Whether this expression is instantiation-dependent, meaning that
175 /// it depends in some way on a template parameter, even if neither its type
176 /// nor (constant) value can change due to the template instantiation.
177 ///
178 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
179 /// instantiation-dependent (since it involves a template parameter \c T), but
180 /// is neither type- nor value-dependent, since the type of the inner
181 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
182 /// \c sizeof is known.
183 ///
184 /// \code
185 /// template<typename T>
186 /// void f(T x, T y) {
187 /// sizeof(sizeof(T() + T());
188 /// }
189 /// \endcode
190 ///
191 bool isInstantiationDependent() const {
192 return ExprBits.InstantiationDependent;
193 }
194
195 /// Set whether this expression is instantiation-dependent or not.
196 void setInstantiationDependent(bool ID) {
197 ExprBits.InstantiationDependent = ID;
198 }
199
200 /// Whether this expression contains an unexpanded parameter
201 /// pack (for C++11 variadic templates).
202 ///
203 /// Given the following function template:
204 ///
205 /// \code
206 /// template<typename F, typename ...Types>
207 /// void forward(const F &f, Types &&...args) {
208 /// f(static_cast<Types&&>(args)...);
209 /// }
210 /// \endcode
211 ///
212 /// The expressions \c args and \c static_cast<Types&&>(args) both
213 /// contain parameter packs.
214 bool containsUnexpandedParameterPack() const {
215 return ExprBits.ContainsUnexpandedParameterPack;
216 }
217
218 /// Set the bit that describes whether this expression
219 /// contains an unexpanded parameter pack.
220 void setContainsUnexpandedParameterPack(bool PP = true) {
221 ExprBits.ContainsUnexpandedParameterPack = PP;
222 }
223
224 /// getExprLoc - Return the preferred location for the arrow when diagnosing
225 /// a problem with a generic expression.
226 SourceLocation getExprLoc() const LLVM_READONLY;
227
228 /// isUnusedResultAWarning - Return true if this immediate expression should
229 /// be warned about if the result is unused. If so, fill in expr, location,
230 /// and ranges with expr to warn on and source locations/ranges appropriate
231 /// for a warning.
232 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
233 SourceRange &R1, SourceRange &R2,
234 ASTContext &Ctx) const;
235
236 /// isLValue - True if this expression is an "l-value" according to
237 /// the rules of the current language. C and C++ give somewhat
238 /// different rules for this concept, but in general, the result of
239 /// an l-value expression identifies a specific object whereas the
240 /// result of an r-value expression is a value detached from any
241 /// specific storage.
242 ///
243 /// C++11 divides the concept of "r-value" into pure r-values
244 /// ("pr-values") and so-called expiring values ("x-values"), which
245 /// identify specific objects that can be safely cannibalized for
246 /// their resources. This is an unfortunate abuse of terminology on
247 /// the part of the C++ committee. In Clang, when we say "r-value",
248 /// we generally mean a pr-value.
249 bool isLValue() const { return getValueKind() == VK_LValue; }
250 bool isRValue() const { return getValueKind() == VK_RValue; }
251 bool isXValue() const { return getValueKind() == VK_XValue; }
252 bool isGLValue() const { return getValueKind() != VK_RValue; }
253
254 enum LValueClassification {
255 LV_Valid,
256 LV_NotObjectType,
257 LV_IncompleteVoidType,
258 LV_DuplicateVectorComponents,
259 LV_InvalidExpression,
260 LV_InvalidMessageExpression,
261 LV_MemberFunction,
262 LV_SubObjCPropertySetting,
263 LV_ClassTemporary,
264 LV_ArrayTemporary
265 };
266 /// Reasons why an expression might not be an l-value.
267 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
268
269 enum isModifiableLvalueResult {
270 MLV_Valid,
271 MLV_NotObjectType,
272 MLV_IncompleteVoidType,
273 MLV_DuplicateVectorComponents,
274 MLV_InvalidExpression,
275 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
276 MLV_IncompleteType,
277 MLV_ConstQualified,
278 MLV_ConstQualifiedField,
279 MLV_ConstAddrSpace,
280 MLV_ArrayType,
281 MLV_NoSetterProperty,
282 MLV_MemberFunction,
283 MLV_SubObjCPropertySetting,
284 MLV_InvalidMessageExpression,
285 MLV_ClassTemporary,
286 MLV_ArrayTemporary
287 };
288 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
289 /// does not have an incomplete type, does not have a const-qualified type,
290 /// and if it is a structure or union, does not have any member (including,
291 /// recursively, any member or element of all contained aggregates or unions)
292 /// with a const-qualified type.
293 ///
294 /// \param Loc [in,out] - A source location which *may* be filled
295 /// in with the location of the expression making this a
296 /// non-modifiable lvalue, if specified.
297 isModifiableLvalueResult
298 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
299
300 /// The return type of classify(). Represents the C++11 expression
301 /// taxonomy.
302 class Classification {
303 public:
304 /// The various classification results. Most of these mean prvalue.
305 enum Kinds {
306 CL_LValue,
307 CL_XValue,
308 CL_Function, // Functions cannot be lvalues in C.
309 CL_Void, // Void cannot be an lvalue in C.
310 CL_AddressableVoid, // Void expression whose address can be taken in C.
311 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
312 CL_MemberFunction, // An expression referring to a member function
313 CL_SubObjCPropertySetting,
314 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
315 CL_ArrayTemporary, // A temporary of array type.
316 CL_ObjCMessageRValue, // ObjC message is an rvalue
317 CL_PRValue // A prvalue for any other reason, of any other type
318 };
319 /// The results of modification testing.
320 enum ModifiableType {
321 CM_Untested, // testModifiable was false.
322 CM_Modifiable,
323 CM_RValue, // Not modifiable because it's an rvalue
324 CM_Function, // Not modifiable because it's a function; C++ only
325 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
326 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
327 CM_ConstQualified,
328 CM_ConstQualifiedField,
329 CM_ConstAddrSpace,
330 CM_ArrayType,
331 CM_IncompleteType
332 };
333
334 private:
335 friend class Expr;
336
337 unsigned short Kind;
338 unsigned short Modifiable;
339
340 explicit Classification(Kinds k, ModifiableType m)
341 : Kind(k), Modifiable(m)
342 {}
343
344 public:
345 Classification() {}
346
347 Kinds getKind() const { return static_cast<Kinds>(Kind); }
348 ModifiableType getModifiable() const {
349 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
350 return static_cast<ModifiableType>(Modifiable);
351 }
352 bool isLValue() const { return Kind == CL_LValue; }
353 bool isXValue() const { return Kind == CL_XValue; }
354 bool isGLValue() const { return Kind <= CL_XValue; }
355 bool isPRValue() const { return Kind >= CL_Function; }
356 bool isRValue() const { return Kind >= CL_XValue; }
357 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
358
359 /// Create a simple, modifiably lvalue
360 static Classification makeSimpleLValue() {
361 return Classification(CL_LValue, CM_Modifiable);
362 }
363
364 };
365 /// Classify - Classify this expression according to the C++11
366 /// expression taxonomy.
367 ///
368 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
369 /// old lvalue vs rvalue. This function determines the type of expression this
370 /// is. There are three expression types:
371 /// - lvalues are classical lvalues as in C++03.
372 /// - prvalues are equivalent to rvalues in C++03.
373 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
374 /// function returning an rvalue reference.
375 /// lvalues and xvalues are collectively referred to as glvalues, while
376 /// prvalues and xvalues together form rvalues.
377 Classification Classify(ASTContext &Ctx) const {
378 return ClassifyImpl(Ctx, nullptr);
379 }
380
381 /// ClassifyModifiable - Classify this expression according to the
382 /// C++11 expression taxonomy, and see if it is valid on the left side
383 /// of an assignment.
384 ///
385 /// This function extends classify in that it also tests whether the
386 /// expression is modifiable (C99 6.3.2.1p1).
387 /// \param Loc A source location that might be filled with a relevant location
388 /// if the expression is not modifiable.
389 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
390 return ClassifyImpl(Ctx, &Loc);
391 }
392
393 /// getValueKindForType - Given a formal return or parameter type,
394 /// give its value kind.
395 static ExprValueKind getValueKindForType(QualType T) {
396 if (const ReferenceType *RT = T->getAs<ReferenceType>())
397 return (isa<LValueReferenceType>(RT)
398 ? VK_LValue
399 : (RT->getPointeeType()->isFunctionType()
400 ? VK_LValue : VK_XValue));
401 return VK_RValue;
402 }
403
404 /// getValueKind - The value kind that this expression produces.
405 ExprValueKind getValueKind() const {
406 return static_cast<ExprValueKind>(ExprBits.ValueKind);
407 }
408
409 /// getObjectKind - The object kind that this expression produces.
410 /// Object kinds are meaningful only for expressions that yield an
411 /// l-value or x-value.
412 ExprObjectKind getObjectKind() const {
413 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
414 }
415
416 bool isOrdinaryOrBitFieldObject() const {
417 ExprObjectKind OK = getObjectKind();
418 return (OK == OK_Ordinary || OK == OK_BitField);
419 }
420
421 /// setValueKind - Set the value kind produced by this expression.
422 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
423
424 /// setObjectKind - Set the object kind produced by this expression.
425 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
426
427private:
428 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
429
430public:
431
432 /// Returns true if this expression is a gl-value that
433 /// potentially refers to a bit-field.
434 ///
435 /// In C++, whether a gl-value refers to a bitfield is essentially
436 /// an aspect of the value-kind type system.
437 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
438
439 /// If this expression refers to a bit-field, retrieve the
440 /// declaration of that bit-field.
441 ///
442 /// Note that this returns a non-null pointer in subtly different
443 /// places than refersToBitField returns true. In particular, this can
444 /// return a non-null pointer even for r-values loaded from
445 /// bit-fields, but it will return null for a conditional bit-field.
446 FieldDecl *getSourceBitField();
447
448 const FieldDecl *getSourceBitField() const {
449 return const_cast<Expr*>(this)->getSourceBitField();
450 }
451
452 Decl *getReferencedDeclOfCallee();
453 const Decl *getReferencedDeclOfCallee() const {
454 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
455 }
456
457 /// If this expression is an l-value for an Objective C
458 /// property, find the underlying property reference expression.
459 const ObjCPropertyRefExpr *getObjCProperty() const;
460
461 /// Check if this expression is the ObjC 'self' implicit parameter.
462 bool isObjCSelfExpr() const;
463
464 /// Returns whether this expression refers to a vector element.
465 bool refersToVectorElement() const;
466
467 /// Returns whether this expression refers to a global register
468 /// variable.
469 bool refersToGlobalRegisterVar() const;
470
471 /// Returns whether this expression has a placeholder type.
472 bool hasPlaceholderType() const {
473 return getType()->isPlaceholderType();
474 }
475
476 /// Returns whether this expression has a specific placeholder type.
477 bool hasPlaceholderType(BuiltinType::Kind K) const {
478 assert(BuiltinType::isPlaceholderTypeKind(K));
479 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
480 return BT->getKind() == K;
481 return false;
482 }
483
484 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
485 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
486 /// but also int expressions which are produced by things like comparisons in
487 /// C.
488 bool isKnownToHaveBooleanValue() const;
489
490 /// isIntegerConstantExpr - Return true if this expression is a valid integer
491 /// constant expression, and, if so, return its value in Result. If not a
492 /// valid i-c-e, return false and fill in Loc (if specified) with the location
493 /// of the invalid expression.
494 ///
495 /// Note: This does not perform the implicit conversions required by C++11
496 /// [expr.const]p5.
497 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
498 SourceLocation *Loc = nullptr,
499 bool isEvaluated = true) const;
500 bool isIntegerConstantExpr(const ASTContext &Ctx,
501 SourceLocation *Loc = nullptr) const;
502
503 /// isCXX98IntegralConstantExpr - Return true if this expression is an
504 /// integral constant expression in C++98. Can only be used in C++.
505 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
506
507 /// isCXX11ConstantExpr - Return true if this expression is a constant
508 /// expression in C++11. Can only be used in C++.
509 ///
510 /// Note: This does not perform the implicit conversions required by C++11
511 /// [expr.const]p5.
512 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
513 SourceLocation *Loc = nullptr) const;
514
515 /// isPotentialConstantExpr - Return true if this function's definition
516 /// might be usable in a constant expression in C++11, if it were marked
517 /// constexpr. Return false if the function can never produce a constant
518 /// expression, along with diagnostics describing why not.
519 static bool isPotentialConstantExpr(const FunctionDecl *FD,
520 SmallVectorImpl<
521 PartialDiagnosticAt> &Diags);
522
523 /// isPotentialConstantExprUnevaluted - Return true if this expression might
524 /// be usable in a constant expression in C++11 in an unevaluated context, if
525 /// it were in function FD marked constexpr. Return false if the function can
526 /// never produce a constant expression, along with diagnostics describing
527 /// why not.
528 static bool isPotentialConstantExprUnevaluated(Expr *E,
529 const FunctionDecl *FD,
530 SmallVectorImpl<
531 PartialDiagnosticAt> &Diags);
532
533 /// isConstantInitializer - Returns true if this expression can be emitted to
534 /// IR as a constant, and thus can be used as a constant initializer in C.
535 /// If this expression is not constant and Culprit is non-null,
536 /// it is used to store the address of first non constant expr.
537 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
538 const Expr **Culprit = nullptr) const;
539
540 /// EvalStatus is a struct with detailed info about an evaluation in progress.
541 struct EvalStatus {
542 /// Whether the evaluated expression has side effects.
543 /// For example, (f() && 0) can be folded, but it still has side effects.
544 bool HasSideEffects;
545
546 /// Whether the evaluation hit undefined behavior.
547 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
548 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
549 bool HasUndefinedBehavior;
550
551 /// Diag - If this is non-null, it will be filled in with a stack of notes
552 /// indicating why evaluation failed (or why it failed to produce a constant
553 /// expression).
554 /// If the expression is unfoldable, the notes will indicate why it's not
555 /// foldable. If the expression is foldable, but not a constant expression,
556 /// the notes will describes why it isn't a constant expression. If the
557 /// expression *is* a constant expression, no notes will be produced.
558 SmallVectorImpl<PartialDiagnosticAt> *Diag;
559
560 EvalStatus()
561 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
562
563 // hasSideEffects - Return true if the evaluated expression has
564 // side effects.
565 bool hasSideEffects() const {
566 return HasSideEffects;
567 }
568 };
569
570 /// EvalResult is a struct with detailed info about an evaluated expression.
571 struct EvalResult : EvalStatus {
572 /// Val - This is the value the expression can be folded to.
573 APValue Val;
574
575 // isGlobalLValue - Return true if the evaluated lvalue expression
576 // is global.
577 bool isGlobalLValue() const;
578 };
579
580 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
581 /// an rvalue using any crazy technique (that has nothing to do with language
582 /// standards) that we want to, even if the expression has side-effects. If
583 /// this function returns true, it returns the folded constant in Result. If
584 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
585 /// applied.
586 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
587
588 /// EvaluateAsBooleanCondition - Return true if this is a constant
589 /// which we can fold and convert to a boolean condition using
590 /// any crazy technique that we want to, even if the expression has
591 /// side-effects.
592 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
593
594 enum SideEffectsKind {
595 SE_NoSideEffects, ///< Strictly evaluate the expression.
596 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
597 ///< arbitrary unmodeled side effects.
598 SE_AllowSideEffects ///< Allow any unmodeled side effect.
599 };
600
601 /// EvaluateAsInt - Return true if this is a constant which we can fold and
602 /// convert to an integer, using any crazy technique that we want to.
603 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
604 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
605
606 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
607 /// convert to a floating point value, using any crazy technique that we
608 /// want to.
609 bool
610 EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
611 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
612
613 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
614 /// constant folded without side-effects, but discard the result.
615 bool isEvaluatable(const ASTContext &Ctx,
616 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
617
618 /// HasSideEffects - This routine returns true for all those expressions
619 /// which have any effect other than producing a value. Example is a function
620 /// call, volatile variable read, or throwing an exception. If
621 /// IncludePossibleEffects is false, this call treats certain expressions with
622 /// potential side effects (such as function call-like expressions,
623 /// instantiation-dependent expressions, or invocations from a macro) as not
624 /// having side effects.
625 bool HasSideEffects(const ASTContext &Ctx,
626 bool IncludePossibleEffects = true) const;
627
628 /// Determine whether this expression involves a call to any function
629 /// that is not trivial.
630 bool hasNonTrivialCall(const ASTContext &Ctx) const;
631
632 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
633 /// integer. This must be called on an expression that constant folds to an
634 /// integer.
635 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
636 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
637
638 void EvaluateForOverflow(const ASTContext &Ctx) const;
639
640 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
641 /// lvalue with link time known address, with no side-effects.
642 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
643
644 /// EvaluateAsInitializer - Evaluate an expression as if it were the
645 /// initializer of the given declaration. Returns true if the initializer
646 /// can be folded to a constant, and produces any relevant notes. In C++11,
647 /// notes will be produced if the expression is not a constant expression.
648 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
649 const VarDecl *VD,
650 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
651
652 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
653 /// of a call to the given function with the given arguments, inside an
654 /// unevaluated context. Returns true if the expression could be folded to a
655 /// constant.
656 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
657 const FunctionDecl *Callee,
658 ArrayRef<const Expr*> Args,
659 const Expr *This = nullptr) const;
660
661 /// Indicates how the constant expression will be used.
662 enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling };
663
664 /// Evaluate an expression that is required to be a constant expression.
665 bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
666 const ASTContext &Ctx) const;
667
668 /// If the current Expr is a pointer, this will try to statically
669 /// determine the number of bytes available where the pointer is pointing.
670 /// Returns true if all of the above holds and we were able to figure out the
671 /// size, false otherwise.
672 ///
673 /// \param Type - How to evaluate the size of the Expr, as defined by the
674 /// "type" parameter of __builtin_object_size
675 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
676 unsigned Type) const;
677
678 /// Enumeration used to describe the kind of Null pointer constant
679 /// returned from \c isNullPointerConstant().
680 enum NullPointerConstantKind {
681 /// Expression is not a Null pointer constant.
682 NPCK_NotNull = 0,
683
684 /// Expression is a Null pointer constant built from a zero integer
685 /// expression that is not a simple, possibly parenthesized, zero literal.
686 /// C++ Core Issue 903 will classify these expressions as "not pointers"
687 /// once it is adopted.
688 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
689 NPCK_ZeroExpression,
690
691 /// Expression is a Null pointer constant built from a literal zero.
692 NPCK_ZeroLiteral,
693
694 /// Expression is a C++11 nullptr.
695 NPCK_CXX11_nullptr,
696
697 /// Expression is a GNU-style __null constant.
698 NPCK_GNUNull
699 };
700
701 /// Enumeration used to describe how \c isNullPointerConstant()
702 /// should cope with value-dependent expressions.
703 enum NullPointerConstantValueDependence {
704 /// Specifies that the expression should never be value-dependent.
705 NPC_NeverValueDependent = 0,
706
707 /// Specifies that a value-dependent expression of integral or
708 /// dependent type should be considered a null pointer constant.
709 NPC_ValueDependentIsNull,
710
711 /// Specifies that a value-dependent expression should be considered
712 /// to never be a null pointer constant.
713 NPC_ValueDependentIsNotNull
714 };
715
716 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
717 /// a Null pointer constant. The return value can further distinguish the
718 /// kind of NULL pointer constant that was detected.
719 NullPointerConstantKind isNullPointerConstant(
720 ASTContext &Ctx,
721 NullPointerConstantValueDependence NPC) const;
722
723 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
724 /// write barrier.
725 bool isOBJCGCCandidate(ASTContext &Ctx) const;
726
727 /// Returns true if this expression is a bound member function.
728 bool isBoundMemberFunction(ASTContext &Ctx) const;
729
730 /// Given an expression of bound-member type, find the type
731 /// of the member. Returns null if this is an *overloaded* bound
732 /// member expression.
733 static QualType findBoundMemberType(const Expr *expr);
734
735 /// IgnoreImpCasts - Skip past any implicit casts which might
736 /// surround this expression. Only skips ImplicitCastExprs.
737 Expr *IgnoreImpCasts() LLVM_READONLY;
738
739 /// IgnoreImplicit - Skip past any implicit AST nodes which might
740 /// surround this expression.
741 Expr *IgnoreImplicit() LLVM_READONLY {
742 return cast<Expr>(Stmt::IgnoreImplicit());
743 }
744
745 const Expr *IgnoreImplicit() const LLVM_READONLY {
746 return const_cast<Expr*>(this)->IgnoreImplicit();
747 }
748
749 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
750 /// its subexpression. If that subexpression is also a ParenExpr,
751 /// then this method recursively returns its subexpression, and so forth.
752 /// Otherwise, the method returns the current Expr.
753 Expr *IgnoreParens() LLVM_READONLY;
754
755 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
756 /// or CastExprs, returning their operand.
757 Expr *IgnoreParenCasts() LLVM_READONLY;
758
759 /// Ignore casts. Strip off any CastExprs, returning their operand.
760 Expr *IgnoreCasts() LLVM_READONLY;
761
762 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
763 /// any ParenExpr or ImplicitCastExprs, returning their operand.
764 Expr *IgnoreParenImpCasts() LLVM_READONLY;
765
766 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
767 /// call to a conversion operator, return the argument.
768 Expr *IgnoreConversionOperator() LLVM_READONLY;
769
770 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
771 return const_cast<Expr*>(this)->IgnoreConversionOperator();
772 }
773
774 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
775 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
776 }
777
778 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
779 /// CastExprs that represent lvalue casts, returning their operand.
780 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
781
782 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
783 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
784 }
785
786 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
787 /// value (including ptr->int casts of the same size). Strip off any
788 /// ParenExpr or CastExprs, returning their operand.
789 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
790
791 /// Ignore parentheses and derived-to-base casts.
792 Expr *ignoreParenBaseCasts() LLVM_READONLY;
793
794 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
795 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
796 }
797
798 /// Determine whether this expression is a default function argument.
799 ///
800 /// Default arguments are implicitly generated in the abstract syntax tree
801 /// by semantic analysis for function calls, object constructions, etc. in
802 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
803 /// this routine also looks through any implicit casts to determine whether
804 /// the expression is a default argument.
805 bool isDefaultArgument() const;
806
807 /// Determine whether the result of this expression is a
808 /// temporary object of the given class type.
809 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
810
811 /// Whether this expression is an implicit reference to 'this' in C++.
812 bool isImplicitCXXThis() const;
813
814 const Expr *IgnoreImpCasts() const LLVM_READONLY {
815 return const_cast<Expr*>(this)->IgnoreImpCasts();
816 }
817 const Expr *IgnoreParens() const LLVM_READONLY {
818 return const_cast<Expr*>(this)->IgnoreParens();
819 }
820 const Expr *IgnoreParenCasts() const LLVM_READONLY {
821 return const_cast<Expr*>(this)->IgnoreParenCasts();
822 }
823 /// Strip off casts, but keep parentheses.
824 const Expr *IgnoreCasts() const LLVM_READONLY {
825 return const_cast<Expr*>(this)->IgnoreCasts();
826 }
827
828 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
829 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
830 }
831
832 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
833
834 /// For an expression of class type or pointer to class type,
835 /// return the most derived class decl the expression is known to refer to.
836 ///
837 /// If this expression is a cast, this method looks through it to find the
838 /// most derived decl that can be inferred from the expression.
839 /// This is valid because derived-to-base conversions have undefined
840 /// behavior if the object isn't dynamically of the derived type.
841 const CXXRecordDecl *getBestDynamicClassType() const;
842
843 /// Get the inner expression that determines the best dynamic class.
844 /// If this is a prvalue, we guarantee that it is of the most-derived type
845 /// for the object itself.
846 const Expr *getBestDynamicClassTypeExpr() const;
847
848 /// Walk outwards from an expression we want to bind a reference to and
849 /// find the expression whose lifetime needs to be extended. Record
850 /// the LHSs of comma expressions and adjustments needed along the path.
851 const Expr *skipRValueSubobjectAdjustments(
852 SmallVectorImpl<const Expr *> &CommaLHS,
853 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
854 const Expr *skipRValueSubobjectAdjustments() const {
855 SmallVector<const Expr *, 8> CommaLHSs;
856 SmallVector<SubobjectAdjustment, 8> Adjustments;
857 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
858 }
859
860 static bool classof(const Stmt *T) {
861 return T->getStmtClass() >= firstExprConstant &&
862 T->getStmtClass() <= lastExprConstant;
863 }
864};
865
866//===----------------------------------------------------------------------===//
867// Primary Expressions.
868//===----------------------------------------------------------------------===//
869
870/// OpaqueValueExpr - An expression referring to an opaque object of a
871/// fixed type and value class. These don't correspond to concrete
872/// syntax; instead they're used to express operations (usually copy
873/// operations) on values whose source is generally obvious from
874/// context.
875class OpaqueValueExpr : public Expr {
876 friend class ASTStmtReader;
877 Expr *SourceExpr;
878 SourceLocation Loc;
879
880public:
881 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
882 ExprObjectKind OK = OK_Ordinary,
883 Expr *SourceExpr = nullptr)
884 : Expr(OpaqueValueExprClass, T, VK, OK,
885 T->isDependentType() ||
886 (SourceExpr && SourceExpr->isTypeDependent()),
887 T->isDependentType() ||
888 (SourceExpr && SourceExpr->isValueDependent()),
889 T->isInstantiationDependentType() ||
890 (SourceExpr && SourceExpr->isInstantiationDependent()),
891 false),
892 SourceExpr(SourceExpr), Loc(Loc) {
893 setIsUnique(false);
894 }
895
896 /// Given an expression which invokes a copy constructor --- i.e. a
897 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
898 /// find the OpaqueValueExpr that's the source of the construction.
899 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
900
901 explicit OpaqueValueExpr(EmptyShell Empty)
902 : Expr(OpaqueValueExprClass, Empty) { }
903
904 /// Retrieve the location of this expression.
905 SourceLocation getLocation() const { return Loc; }
906
907 SourceLocation getLocStart() const LLVM_READONLY {
908 return SourceExpr ? SourceExpr->getLocStart() : Loc;
909 }
910 SourceLocation getLocEnd() const LLVM_READONLY {
911 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
912 }
913 SourceLocation getExprLoc() const LLVM_READONLY {
914 if (SourceExpr) return SourceExpr->getExprLoc();
915 return Loc;
916 }
917
918 child_range children() {
919 return child_range(child_iterator(), child_iterator());
920 }
921
922 const_child_range children() const {
923 return const_child_range(const_child_iterator(), const_child_iterator());
924 }
925
926 /// The source expression of an opaque value expression is the
927 /// expression which originally generated the value. This is
928 /// provided as a convenience for analyses that don't wish to
929 /// precisely model the execution behavior of the program.
930 ///
931 /// The source expression is typically set when building the
932 /// expression which binds the opaque value expression in the first
933 /// place.
934 Expr *getSourceExpr() const { return SourceExpr; }
935
936 void setIsUnique(bool V) {
937 assert((!V || SourceExpr) &&
938 "unique OVEs are expected to have source expressions");
939 OpaqueValueExprBits.IsUnique = V;
940 }
941
942 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
943
944 static bool classof(const Stmt *T) {
945 return T->getStmtClass() == OpaqueValueExprClass;
946 }
947};
948
949/// A reference to a declared variable, function, enum, etc.
950/// [C99 6.5.1p2]
951///
952/// This encodes all the information about how a declaration is referenced
953/// within an expression.
954///
955/// There are several optional constructs attached to DeclRefExprs only when
956/// they apply in order to conserve memory. These are laid out past the end of
957/// the object, and flags in the DeclRefExprBitfield track whether they exist:
958///
959/// DeclRefExprBits.HasQualifier:
960/// Specifies when this declaration reference expression has a C++
961/// nested-name-specifier.
962/// DeclRefExprBits.HasFoundDecl:
963/// Specifies when this declaration reference expression has a record of
964/// a NamedDecl (different from the referenced ValueDecl) which was found
965/// during name lookup and/or overload resolution.
966/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
967/// Specifies when this declaration reference expression has an explicit
968/// C++ template keyword and/or template argument list.
969/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
970/// Specifies when this declaration reference expression (validly)
971/// refers to an enclosed local or a captured variable.
972class DeclRefExpr final
973 : public Expr,
974 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
975 NamedDecl *, ASTTemplateKWAndArgsInfo,
976 TemplateArgumentLoc> {
977 /// The declaration that we are referencing.
978 ValueDecl *D;
979
980 /// The location of the declaration name itself.
981 SourceLocation Loc;
982
983 /// Provides source/type location info for the declaration name
984 /// embedded in D.
985 DeclarationNameLoc DNLoc;
986
987 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
988 return hasQualifier() ? 1 : 0;
989 }
990
991 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
992 return hasFoundDecl() ? 1 : 0;
993 }
994
995 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
996 return hasTemplateKWAndArgsInfo() ? 1 : 0;
997 }
998
999 /// Test whether there is a distinct FoundDecl attached to the end of
1000 /// this DRE.
1001 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1002
1003 DeclRefExpr(const ASTContext &Ctx,
1004 NestedNameSpecifierLoc QualifierLoc,
1005 SourceLocation TemplateKWLoc,
1006 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
1007 const DeclarationNameInfo &NameInfo,
1008 NamedDecl *FoundD,
1009 const TemplateArgumentListInfo *TemplateArgs,
1010 QualType T, ExprValueKind VK);
1011
1012 /// Construct an empty declaration reference expression.
1013 explicit DeclRefExpr(EmptyShell Empty)
1014 : Expr(DeclRefExprClass, Empty) { }
1015
1016 /// Computes the type- and value-dependence flags for this
1017 /// declaration reference expression.
1018 void computeDependence(const ASTContext &C);
1019
1020public:
1021 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
1022 ExprValueKind VK, SourceLocation L,
1023 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
1024 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
1025 D(D), Loc(L), DNLoc(LocInfo) {
1026 DeclRefExprBits.HasQualifier = 0;
1027 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
1028 DeclRefExprBits.HasFoundDecl = 0;
1029 DeclRefExprBits.HadMultipleCandidates = 0;
1030 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
1031 RefersToEnclosingVariableOrCapture;
1032 computeDependence(D->getASTContext());
1033 }
1034
1035 static DeclRefExpr *
1036 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1037 SourceLocation TemplateKWLoc, ValueDecl *D,
1038 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1039 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1040 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1041
1042 static DeclRefExpr *
1043 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1044 SourceLocation TemplateKWLoc, ValueDecl *D,
1045 bool RefersToEnclosingVariableOrCapture,
1046 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1047 NamedDecl *FoundD = nullptr,
1048 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1049
1050 /// Construct an empty declaration reference expression.
1051 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1052 bool HasQualifier,
1053 bool HasFoundDecl,
1054 bool HasTemplateKWAndArgsInfo,
1055 unsigned NumTemplateArgs);
1056
1057 ValueDecl *getDecl() { return D; }
1058 const ValueDecl *getDecl() const { return D; }
1059 void setDecl(ValueDecl *NewD) { D = NewD; }
1060
1061 DeclarationNameInfo getNameInfo() const {
1062 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1063 }
1064
1065 SourceLocation getLocation() const { return Loc; }
1066 void setLocation(SourceLocation L) { Loc = L; }
1067 SourceLocation getLocStart() const LLVM_READONLY;
1068 SourceLocation getLocEnd() const LLVM_READONLY;
1069
1070 /// Determine whether this declaration reference was preceded by a
1071 /// C++ nested-name-specifier, e.g., \c N::foo.
1072 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1073
1074 /// If the name was qualified, retrieves the nested-name-specifier
1075 /// that precedes the name, with source-location information.
1076 NestedNameSpecifierLoc getQualifierLoc() const {
1077 if (!hasQualifier())
1078 return NestedNameSpecifierLoc();
1079 return *getTrailingObjects<NestedNameSpecifierLoc>();
1080 }
1081
1082 /// If the name was qualified, retrieves the nested-name-specifier
1083 /// that precedes the name. Otherwise, returns NULL.
1084 NestedNameSpecifier *getQualifier() const {
1085 return getQualifierLoc().getNestedNameSpecifier();
1086 }
1087
1088 /// Get the NamedDecl through which this reference occurred.
1089 ///
1090 /// This Decl may be different from the ValueDecl actually referred to in the
1091 /// presence of using declarations, etc. It always returns non-NULL, and may
1092 /// simple return the ValueDecl when appropriate.
1093
1094 NamedDecl *getFoundDecl() {
1095 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1096 }
1097
1098 /// Get the NamedDecl through which this reference occurred.
1099 /// See non-const variant.
1100 const NamedDecl *getFoundDecl() const {
1101 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1102 }
1103
1104 bool hasTemplateKWAndArgsInfo() const {
1105 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1106 }
1107
1108 /// Retrieve the location of the template keyword preceding
1109 /// this name, if any.
1110 SourceLocation getTemplateKeywordLoc() const {
1111 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1112 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1113 }
1114
1115 /// Retrieve the location of the left angle bracket starting the
1116 /// explicit template argument list following the name, if any.
1117 SourceLocation getLAngleLoc() const {
1118 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1119 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1120 }
1121
1122 /// Retrieve the location of the right angle bracket ending the
1123 /// explicit template argument list following the name, if any.
1124 SourceLocation getRAngleLoc() const {
1125 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1126 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1127 }
1128
1129 /// Determines whether the name in this declaration reference
1130 /// was preceded by the template keyword.
1131 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1132
1133 /// Determines whether this declaration reference was followed by an
1134 /// explicit template argument list.
1135 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1136
1137 /// Copies the template arguments (if present) into the given
1138 /// structure.
1139 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1140 if (hasExplicitTemplateArgs())
1141 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1142 getTrailingObjects<TemplateArgumentLoc>(), List);
1143 }
1144
1145 /// Retrieve the template arguments provided as part of this
1146 /// template-id.
1147 const TemplateArgumentLoc *getTemplateArgs() const {
1148 if (!hasExplicitTemplateArgs())
1149 return nullptr;
1150
1151 return getTrailingObjects<TemplateArgumentLoc>();
1152 }
1153
1154 /// Retrieve the number of template arguments provided as part of this
1155 /// template-id.
1156 unsigned getNumTemplateArgs() const {
1157 if (!hasExplicitTemplateArgs())
1158 return 0;
1159
1160 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1161 }
1162
1163 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1164 return {getTemplateArgs(), getNumTemplateArgs()};
1165 }
1166
1167 /// Returns true if this expression refers to a function that
1168 /// was resolved from an overloaded set having size greater than 1.
1169 bool hadMultipleCandidates() const {
1170 return DeclRefExprBits.HadMultipleCandidates;
1171 }
1172 /// Sets the flag telling whether this expression refers to
1173 /// a function that was resolved from an overloaded set having size
1174 /// greater than 1.
1175 void setHadMultipleCandidates(bool V = true) {
1176 DeclRefExprBits.HadMultipleCandidates = V;
1177 }
1178
1179 /// Does this DeclRefExpr refer to an enclosing local or a captured
1180 /// variable?
1181 bool refersToEnclosingVariableOrCapture() const {
1182 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1183 }
1184
1185 static bool classof(const Stmt *T) {
1186 return T->getStmtClass() == DeclRefExprClass;
1187 }
1188
1189 // Iterators
1190 child_range children() {
1191 return child_range(child_iterator(), child_iterator());
1192 }
1193
1194 const_child_range children() const {
1195 return const_child_range(const_child_iterator(), const_child_iterator());
1196 }
1197
1198 friend TrailingObjects;
1199 friend class ASTStmtReader;
1200 friend class ASTStmtWriter;
1201};
1202
1203/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1204class PredefinedExpr : public Expr {
1205public:
1206 enum IdentType {
1207 Func,
1208 Function,
1209 LFunction, // Same as Function, but as wide string.
1210 FuncDName,
1211 FuncSig,
1212 PrettyFunction,
1213 /// The same as PrettyFunction, except that the
1214 /// 'virtual' keyword is omitted for virtual member functions.
1215 PrettyFunctionNoVirtual
1216 };
1217
1218private:
1219 SourceLocation Loc;
1220 IdentType Type;
1221 Stmt *FnName;
1222
1223public:
1224 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1225 StringLiteral *SL);
1226
1227 /// Construct an empty predefined expression.
1228 explicit PredefinedExpr(EmptyShell Empty)
1229 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1230
1231 IdentType getIdentType() const { return Type; }
1232
1233 SourceLocation getLocation() const { return Loc; }
1234 void setLocation(SourceLocation L) { Loc = L; }
1235
1236 StringLiteral *getFunctionName();
1237 const StringLiteral *getFunctionName() const {
1238 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1239 }
1240
1241 static StringRef getIdentTypeName(IdentType IT);
1242 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1243
1244 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1245 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1246
1247 static bool classof(const Stmt *T) {
1248 return T->getStmtClass() == PredefinedExprClass;
1249 }
1250
1251 // Iterators
1252 child_range children() { return child_range(&FnName, &FnName + 1); }
1253 const_child_range children() const {
1254 return const_child_range(&FnName, &FnName + 1);
1255 }
1256
1257 friend class ASTStmtReader;
1258};
1259
1260/// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1261/// leaking memory.
1262///
1263/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1264/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1265/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1266/// the APFloat/APInt values will never get freed. APNumericStorage uses
1267/// ASTContext's allocator for memory allocation.
1268class APNumericStorage {
1269 union {
1270 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1271 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1272 };
1273 unsigned BitWidth;
1274
1275 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1276
1277 APNumericStorage(const APNumericStorage &) = delete;
1278 void operator=(const APNumericStorage &) = delete;
1279
1280protected:
1281 APNumericStorage() : VAL(0), BitWidth(0) { }
1282
1283 llvm::APInt getIntValue() const {
1284 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1285 if (NumWords > 1)
1286 return llvm::APInt(BitWidth, NumWords, pVal);
1287 else
1288 return llvm::APInt(BitWidth, VAL);
1289 }
1290 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1291};
1292
1293class APIntStorage : private APNumericStorage {
1294public:
1295 llvm::APInt getValue() const { return getIntValue(); }
1296 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1297 setIntValue(C, Val);
1298 }
1299};
1300
1301class APFloatStorage : private APNumericStorage {
1302public:
1303 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1304 return llvm::APFloat(Semantics, getIntValue());
1305 }
1306 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1307 setIntValue(C, Val.bitcastToAPInt());
1308 }
1309};
1310
1311class IntegerLiteral : public Expr, public APIntStorage {
1312 SourceLocation Loc;
1313
1314 /// Construct an empty integer literal.
1315 explicit IntegerLiteral(EmptyShell Empty)
1316 : Expr(IntegerLiteralClass, Empty) { }
1317
1318public:
1319 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1320 // or UnsignedLongLongTy
1321 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1322 SourceLocation l);
1323
1324 /// Returns a new integer literal with value 'V' and type 'type'.
1325 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1326 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1327 /// \param V - the value that the returned integer literal contains.
1328 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1329 QualType type, SourceLocation l);
1330 /// Returns a new empty integer literal.
1331 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1332
1333 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1334 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1335
1336 /// Retrieve the location of the literal.
1337 SourceLocation getLocation() const { return Loc; }
1338
1339 void setLocation(SourceLocation Location) { Loc = Location; }
1340
1341 static bool classof(const Stmt *T) {
1342 return T->getStmtClass() == IntegerLiteralClass;
1343 }
1344
1345 // Iterators
1346 child_range children() {
1347 return child_range(child_iterator(), child_iterator());
1348 }
1349 const_child_range children() const {
1350 return const_child_range(const_child_iterator(), const_child_iterator());
1351 }
1352};
1353
1354class CharacterLiteral : public Expr {
1355public:
1356 enum CharacterKind {
1357 Ascii,
1358 Wide,
1359 UTF8,
1360 UTF16,
1361 UTF32
1362 };
1363
1364private:
1365 unsigned Value;
1366 SourceLocation Loc;
1367public:
1368 // type should be IntTy
1369 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1370 SourceLocation l)
1371 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1372 false, false),
1373 Value(value), Loc(l) {
1374 CharacterLiteralBits.Kind = kind;
1375 }
1376
1377 /// Construct an empty character literal.
1378 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1379
1380 SourceLocation getLocation() const { return Loc; }
1381 CharacterKind getKind() const {
1382 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1383 }
1384
1385 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1386 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1387
1388 unsigned getValue() const { return Value; }
1389
1390 void setLocation(SourceLocation Location) { Loc = Location; }
1391 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1392 void setValue(unsigned Val) { Value = Val; }
1393
1394 static bool classof(const Stmt *T) {
1395 return T->getStmtClass() == CharacterLiteralClass;
1396 }
1397
1398 // Iterators
1399 child_range children() {
1400 return child_range(child_iterator(), child_iterator());
1401 }
1402 const_child_range children() const {
1403 return const_child_range(const_child_iterator(), const_child_iterator());
1404 }
1405};
1406
1407class FloatingLiteral : public Expr, private APFloatStorage {
1408 SourceLocation Loc;
1409
1410 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1411 QualType Type, SourceLocation L);
1412
1413 /// Construct an empty floating-point literal.
1414 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1415
1416public:
1417 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1418 bool isexact, QualType Type, SourceLocation L);
1419 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1420
1421 llvm::APFloat getValue() const {
1422 return APFloatStorage::getValue(getSemantics());
1423 }
1424 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1425 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1426 APFloatStorage::setValue(C, Val);
1427 }
1428
1429 /// Get a raw enumeration value representing the floating-point semantics of
1430 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1431 APFloatSemantics getRawSemantics() const {
1432 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1433 }
1434
1435 /// Set the raw enumeration value representing the floating-point semantics of
1436 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1437 void setRawSemantics(APFloatSemantics Sem) {
1438 FloatingLiteralBits.Semantics = Sem;
1439 }
1440
1441 /// Return the APFloat semantics this literal uses.
1442 const llvm::fltSemantics &getSemantics() const;
1443
1444 /// Set the APFloat semantics this literal uses.
1445 void setSemantics(const llvm::fltSemantics &Sem);
1446
1447 bool isExact() const { return FloatingLiteralBits.IsExact; }
1448 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1449
1450 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1451 /// double. Note that this may cause loss of precision, but is useful for
1452 /// debugging dumps, etc.
1453 double getValueAsApproximateDouble() const;
1454
1455 SourceLocation getLocation() const { return Loc; }
1456 void setLocation(SourceLocation L) { Loc = L; }
1457
1458 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1459 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1460
1461 static bool classof(const Stmt *T) {
1462 return T->getStmtClass() == FloatingLiteralClass;
1463 }
1464
1465 // Iterators
1466 child_range children() {
1467 return child_range(child_iterator(), child_iterator());
1468 }
1469 const_child_range children() const {
1470 return const_child_range(const_child_iterator(), const_child_iterator());
1471 }
1472};
1473
1474/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1475/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1476/// IntegerLiteral classes. Instances of this class always have a Complex type
1477/// whose element type matches the subexpression.
1478///
1479class ImaginaryLiteral : public Expr {
1480 Stmt *Val;
1481public:
1482 ImaginaryLiteral(Expr *val, QualType Ty)
1483 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1484 false, false),
1485 Val(val) {}
1486
1487 /// Build an empty imaginary literal.
1488 explicit ImaginaryLiteral(EmptyShell Empty)
1489 : Expr(ImaginaryLiteralClass, Empty) { }
1490
1491 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1492 Expr *getSubExpr() { return cast<Expr>(Val); }
1493 void setSubExpr(Expr *E) { Val = E; }
1494
1495 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1496 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1497
1498 static bool classof(const Stmt *T) {
1499 return T->getStmtClass() == ImaginaryLiteralClass;
1500 }
1501
1502 // Iterators
1503 child_range children() { return child_range(&Val, &Val+1); }
1504 const_child_range children() const {
1505 return const_child_range(&Val, &Val + 1);
1506 }
1507};
1508
1509/// StringLiteral - This represents a string literal expression, e.g. "foo"
1510/// or L"bar" (wide strings). The actual string is returned by getBytes()
1511/// is NOT null-terminated, and the length of the string is determined by
1512/// calling getByteLength(). The C type for a string is always a
1513/// ConstantArrayType. In C++, the char type is const qualified, in C it is
1514/// not.
1515///
1516/// Note that strings in C can be formed by concatenation of multiple string
1517/// literal pptokens in translation phase #6. This keeps track of the locations
1518/// of each of these pieces.
1519///
1520/// Strings in C can also be truncated and extended by assigning into arrays,
1521/// e.g. with constructs like:
1522/// char X[2] = "foobar";
1523/// In this case, getByteLength() will return 6, but the string literal will
1524/// have type "char[2]".
1525class StringLiteral : public Expr {
1526public:
1527 enum StringKind {
1528 Ascii,
1529 Wide,
1530 UTF8,
1531 UTF16,
1532 UTF32
1533 };
1534
1535private:
1536 friend class ASTStmtReader;
1537
1538 union {
1539 const char *asChar;
1540 const uint16_t *asUInt16;
1541 const uint32_t *asUInt32;
1542 } StrData;
1543 unsigned Length;
1544 unsigned CharByteWidth : 4;
1545 unsigned Kind : 3;
1546 unsigned IsPascal : 1;
1547 unsigned NumConcatenated;
1548 SourceLocation TokLocs[1];
1549
1550 StringLiteral(QualType Ty) :
1551 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1552 false) {}
1553
1554 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1555
1556public:
1557 /// This is the "fully general" constructor that allows representation of
1558 /// strings formed from multiple concatenated tokens.
1559 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1560 StringKind Kind, bool Pascal, QualType Ty,
1561 const SourceLocation *Loc, unsigned NumStrs);
1562
1563 /// Simple constructor for string literals made from one token.
1564 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1565 StringKind Kind, bool Pascal, QualType Ty,
1566 SourceLocation Loc) {
1567 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1568 }
1569
1570 /// Construct an empty string literal.
1571 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1572
1573 StringRef getString() const {
1574 assert(CharByteWidth==1
1575 && "This function is used in places that assume strings use char");
1576 return StringRef(StrData.asChar, getByteLength());
1577 }
1578
1579 /// Allow access to clients that need the byte representation, such as
1580 /// ASTWriterStmt::VisitStringLiteral().
1581 StringRef getBytes() const {
1582 // FIXME: StringRef may not be the right type to use as a result for this.
1583 if (CharByteWidth == 1)
1584 return StringRef(StrData.asChar, getByteLength());
1585 if (CharByteWidth == 4)
1586 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1587 getByteLength());
1588 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1589 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1590 getByteLength());
1591 }
1592
1593 void outputString(raw_ostream &OS) const;
1594
1595 uint32_t getCodeUnit(size_t i) const {
1596 assert(i < Length && "out of bounds access");
1597 if (CharByteWidth == 1)
1598 return static_cast<unsigned char>(StrData.asChar[i]);
1599 if (CharByteWidth == 4)
1600 return StrData.asUInt32[i];
1601 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1602 return StrData.asUInt16[i];
1603 }
1604
1605 unsigned getByteLength() const { return CharByteWidth*Length; }
1606 unsigned getLength() const { return Length; }
1607 unsigned getCharByteWidth() const { return CharByteWidth; }
1608
1609 /// Sets the string data to the given string data.
1610 void setString(const ASTContext &C, StringRef Str,
1611 StringKind Kind, bool IsPascal);
1612
1613 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1614
1615
1616 bool isAscii() const { return Kind == Ascii; }
1617 bool isWide() const { return Kind == Wide; }
1618 bool isUTF8() const { return Kind == UTF8; }
1619 bool isUTF16() const { return Kind == UTF16; }
1620 bool isUTF32() const { return Kind == UTF32; }
1621 bool isPascal() const { return IsPascal; }
1622
1623 bool containsNonAscii() const {
1624 StringRef Str = getString();
1625 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1626 if (!isASCII(Str[i]))
1627 return true;
1628 return false;
1629 }
1630
1631 bool containsNonAsciiOrNull() const {
1632 StringRef Str = getString();
1633 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1634 if (!isASCII(Str[i]) || !Str[i])
1635 return true;
1636 return false;
1637 }
1638
1639 /// getNumConcatenated - Get the number of string literal tokens that were
1640 /// concatenated in translation phase #6 to form this string literal.
1641 unsigned getNumConcatenated() const { return NumConcatenated; }
1642
1643 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1644 assert(TokNum < NumConcatenated && "Invalid tok number");
1645 return TokLocs[TokNum];
1646 }
1647 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1648 assert(TokNum < NumConcatenated && "Invalid tok number");
1649 TokLocs[TokNum] = L;
1650 }
1651
1652 /// getLocationOfByte - Return a source location that points to the specified
1653 /// byte of this string literal.
1654 ///
1655 /// Strings are amazingly complex. They can be formed from multiple tokens
1656 /// and can have escape sequences in them in addition to the usual trigraph
1657 /// and escaped newline business. This routine handles this complexity.
1658 ///
1659 SourceLocation
1660 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1661 const LangOptions &Features, const TargetInfo &Target,
1662 unsigned *StartToken = nullptr,
1663 unsigned *StartTokenByteOffset = nullptr) const;
1664
1665 typedef const SourceLocation *tokloc_iterator;
1666 tokloc_iterator tokloc_begin() const { return TokLocs; }
1667 tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1668
1669 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1670 SourceLocation getLocEnd() const LLVM_READONLY {
1671 return TokLocs[NumConcatenated - 1];
1672 }
1673
1674 static bool classof(const Stmt *T) {
1675 return T->getStmtClass() == StringLiteralClass;
1676 }
1677
1678 // Iterators
1679 child_range children() {
1680 return child_range(child_iterator(), child_iterator());
1681 }
1682 const_child_range children() const {
1683 return const_child_range(const_child_iterator(), const_child_iterator());
1684 }
1685};
1686
1687/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1688/// AST node is only formed if full location information is requested.
1689class ParenExpr : public Expr {
1690 SourceLocation L, R;
1691 Stmt *Val;
1692public:
1693 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1694 : Expr(ParenExprClass, val->getType(),
1695 val->getValueKind(), val->getObjectKind(),
1696 val->isTypeDependent(), val->isValueDependent(),
1697 val->isInstantiationDependent(),
1698 val->containsUnexpandedParameterPack()),
1699 L(l), R(r), Val(val) {}
1700
1701 /// Construct an empty parenthesized expression.
1702 explicit ParenExpr(EmptyShell Empty)
1703 : Expr(ParenExprClass, Empty) { }
1704
1705 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1706 Expr *getSubExpr() { return cast<Expr>(Val); }
1707 void setSubExpr(Expr *E) { Val = E; }
1708
1709 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1710 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1711
1712 /// Get the location of the left parentheses '('.
1713 SourceLocation getLParen() const { return L; }
1714 void setLParen(SourceLocation Loc) { L = Loc; }
1715
1716 /// Get the location of the right parentheses ')'.
1717 SourceLocation getRParen() const { return R; }
1718 void setRParen(SourceLocation Loc) { R = Loc; }
1719
1720 static bool classof(const Stmt *T) {
1721 return T->getStmtClass() == ParenExprClass;
1722 }
1723
1724 // Iterators
1725 child_range children() { return child_range(&Val, &Val+1); }
1726 const_child_range children() const {
1727 return const_child_range(&Val, &Val + 1);
1728 }
1729};
1730
1731/// UnaryOperator - This represents the unary-expression's (except sizeof and
1732/// alignof), the postinc/postdec operators from postfix-expression, and various
1733/// extensions.
1734///
1735/// Notes on various nodes:
1736///
1737/// Real/Imag - These return the real/imag part of a complex operand. If
1738/// applied to a non-complex value, the former returns its operand and the
1739/// later returns zero in the type of the operand.
1740///
1741class UnaryOperator : public Expr {
1742public:
1743 typedef UnaryOperatorKind Opcode;
1744
1745private:
1746 unsigned Opc : 5;
1747 unsigned CanOverflow : 1;
1748 SourceLocation Loc;
1749 Stmt *Val;
1750public:
1751 UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK,
1752 ExprObjectKind OK, SourceLocation l, bool CanOverflow)
1753 : Expr(UnaryOperatorClass, type, VK, OK,
1754 input->isTypeDependent() || type->isDependentType(),
1755 input->isValueDependent(),
1756 (input->isInstantiationDependent() ||
1757 type->isInstantiationDependentType()),
1758 input->containsUnexpandedParameterPack()),
1759 Opc(opc), CanOverflow(CanOverflow), Loc(l), Val(input) {}
1760
1761 /// Build an empty unary operator.
1762 explicit UnaryOperator(EmptyShell Empty)
1763 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1764
1765 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1766 void setOpcode(Opcode O) { Opc = O; }
1767
1768 Expr *getSubExpr() const { return cast<Expr>(Val); }
1769 void setSubExpr(Expr *E) { Val = E; }
1770
1771 /// getOperatorLoc - Return the location of the operator.
1772 SourceLocation getOperatorLoc() const { return Loc; }
1773 void setOperatorLoc(SourceLocation L) { Loc = L; }
1774
1775 /// Returns true if the unary operator can cause an overflow. For instance,
1776 /// signed int i = INT_MAX; i++;
1777 /// signed char c = CHAR_MAX; c++;
1778 /// Due to integer promotions, c++ is promoted to an int before the postfix
1779 /// increment, and the result is an int that cannot overflow. However, i++
1780 /// can overflow.
1781 bool canOverflow() const { return CanOverflow; }
1782 void setCanOverflow(bool C) { CanOverflow = C; }
1783
1784 /// isPostfix - Return true if this is a postfix operation, like x++.
1785 static bool isPostfix(Opcode Op) {
1786 return Op == UO_PostInc || Op == UO_PostDec;
1787 }
1788
1789 /// isPrefix - Return true if this is a prefix operation, like --x.
1790 static bool isPrefix(Opcode Op) {
1791 return Op == UO_PreInc || Op == UO_PreDec;
1792 }
1793
1794 bool isPrefix() const { return isPrefix(getOpcode()); }
1795 bool isPostfix() const { return isPostfix(getOpcode()); }
1796
1797 static bool isIncrementOp(Opcode Op) {
1798 return Op == UO_PreInc || Op == UO_PostInc;
1799 }
1800 bool isIncrementOp() const {
1801 return isIncrementOp(getOpcode());
1802 }
1803
1804 static bool isDecrementOp(Opcode Op) {
1805 return Op == UO_PreDec || Op == UO_PostDec;
1806 }
1807 bool isDecrementOp() const {
1808 return isDecrementOp(getOpcode());
1809 }
1810
1811 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1812 bool isIncrementDecrementOp() const {
1813 return isIncrementDecrementOp(getOpcode());
1814 }
1815
1816 static bool isArithmeticOp(Opcode Op) {
1817 return Op >= UO_Plus && Op <= UO_LNot;
1818 }
1819 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1820
1821 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1822 /// corresponds to, e.g. "sizeof" or "[pre]++"
1823 static StringRef getOpcodeStr(Opcode Op);
1824
1825 /// Retrieve the unary opcode that corresponds to the given
1826 /// overloaded operator.
1827 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1828
1829 /// Retrieve the overloaded operator kind that corresponds to
1830 /// the given unary opcode.
1831 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1832
1833 SourceLocation getLocStart() const LLVM_READONLY {
1834 return isPostfix() ? Val->getLocStart() : Loc;
1835 }
1836 SourceLocation getLocEnd() const LLVM_READONLY {
1837 return isPostfix() ? Loc : Val->getLocEnd();
1838 }
1839 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1840
1841 static bool classof(const Stmt *T) {
1842 return T->getStmtClass() == UnaryOperatorClass;
1843 }
1844
1845 // Iterators
1846 child_range children() { return child_range(&Val, &Val+1); }
1847 const_child_range children() const {
1848 return const_child_range(&Val, &Val + 1);
1849 }
1850};
1851
1852/// Helper class for OffsetOfExpr.
1853
1854// __builtin_offsetof(type, identifier(.identifier|[expr])*)
1855class OffsetOfNode {
1856public:
1857 /// The kind of offsetof node we have.
1858 enum Kind {
1859 /// An index into an array.
1860 Array = 0x00,
1861 /// A field.
1862 Field = 0x01,
1863 /// A field in a dependent type, known only by its name.
1864 Identifier = 0x02,
1865 /// An implicit indirection through a C++ base class, when the
1866 /// field found is in a base class.
1867 Base = 0x03
1868 };
1869
1870private:
1871 enum { MaskBits = 2, Mask = 0x03 };
1872
1873 /// The source range that covers this part of the designator.
1874 SourceRange Range;
1875
1876 /// The data describing the designator, which comes in three
1877 /// different forms, depending on the lower two bits.
1878 /// - An unsigned index into the array of Expr*'s stored after this node
1879 /// in memory, for [constant-expression] designators.
1880 /// - A FieldDecl*, for references to a known field.
1881 /// - An IdentifierInfo*, for references to a field with a given name
1882 /// when the class type is dependent.
1883 /// - A CXXBaseSpecifier*, for references that look at a field in a
1884 /// base class.
1885 uintptr_t Data;
1886
1887public:
1888 /// Create an offsetof node that refers to an array element.
1889 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1890 SourceLocation RBracketLoc)
1891 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1892
1893 /// Create an offsetof node that refers to a field.
1894 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
1895 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1896 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1897
1898 /// Create an offsetof node that refers to an identifier.
1899 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1900 SourceLocation NameLoc)
1901 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1902 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1903
1904 /// Create an offsetof node that refers into a C++ base class.
1905 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1906 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1907
1908 /// Determine what kind of offsetof node this is.
1909 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1910
1911 /// For an array element node, returns the index into the array
1912 /// of expressions.
1913 unsigned getArrayExprIndex() const {
1914 assert(getKind() == Array);
1915 return Data >> 2;
1916 }
1917
1918 /// For a field offsetof node, returns the field.
1919 FieldDecl *getField() const {
1920 assert(getKind() == Field);
1921 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1922 }
1923
1924 /// For a field or identifier offsetof node, returns the name of
1925 /// the field.
1926 IdentifierInfo *getFieldName() const;
1927
1928 /// For a base class node, returns the base specifier.
1929 CXXBaseSpecifier *getBase() const {
1930 assert(getKind() == Base);
1931 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1932 }
1933
1934 /// Retrieve the source range that covers this offsetof node.
1935 ///
1936 /// For an array element node, the source range contains the locations of
1937 /// the square brackets. For a field or identifier node, the source range
1938 /// contains the location of the period (if there is one) and the
1939 /// identifier.
1940 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1941 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1942 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1943};
1944
1945/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1946/// offsetof(record-type, member-designator). For example, given:
1947/// @code
1948/// struct S {
1949/// float f;
1950/// double d;
1951/// };
1952/// struct T {
1953/// int i;
1954/// struct S s[10];
1955/// };
1956/// @endcode
1957/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1958
1959class OffsetOfExpr final
1960 : public Expr,
1961 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
1962 SourceLocation OperatorLoc, RParenLoc;
1963 // Base type;
1964 TypeSourceInfo *TSInfo;
1965 // Number of sub-components (i.e. instances of OffsetOfNode).
1966 unsigned NumComps;
1967 // Number of sub-expressions (i.e. array subscript expressions).
1968 unsigned NumExprs;
1969
1970 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
1971 return NumComps;
1972 }
1973
1974 OffsetOfExpr(const ASTContext &C, QualType type,
1975 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1976 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1977 SourceLocation RParenLoc);
1978
1979 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1980 : Expr(OffsetOfExprClass, EmptyShell()),
1981 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1982
1983public:
1984
1985 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1986 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1987 ArrayRef<OffsetOfNode> comps,
1988 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1989
1990 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1991 unsigned NumComps, unsigned NumExprs);
1992
1993 /// getOperatorLoc - Return the location of the operator.
1994 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1995 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1996
1997 /// Return the location of the right parentheses.
1998 SourceLocation getRParenLoc() const { return RParenLoc; }
1999 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2000
2001 TypeSourceInfo *getTypeSourceInfo() const {
2002 return TSInfo;
2003 }
2004 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2005 TSInfo = tsi;
2006 }
2007
2008 const OffsetOfNode &getComponent(unsigned Idx) const {
2009 assert(Idx < NumComps && "Subscript out of range");
2010 return getTrailingObjects<OffsetOfNode>()[Idx];
2011 }
2012
2013 void setComponent(unsigned Idx, OffsetOfNode ON) {
2014 assert(Idx < NumComps && "Subscript out of range");
2015 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2016 }
2017
2018 unsigned getNumComponents() const {
2019 return NumComps;
2020 }
2021
2022 Expr* getIndexExpr(unsigned Idx) {
2023 assert(Idx < NumExprs && "Subscript out of range");
2024 return getTrailingObjects<Expr *>()[Idx];
2025 }
2026
2027 const Expr *getIndexExpr(unsigned Idx) const {
2028 assert(Idx < NumExprs && "Subscript out of range");
2029 return getTrailingObjects<Expr *>()[Idx];
2030 }
2031
2032 void setIndexExpr(unsigned Idx, Expr* E) {
2033 assert(Idx < NumComps && "Subscript out of range");
2034 getTrailingObjects<Expr *>()[Idx] = E;
2035 }
2036
2037 unsigned getNumExpressions() const {
2038 return NumExprs;
2039 }
2040
2041 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
2042 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2043
2044 static bool classof(const Stmt *T) {
2045 return T->getStmtClass() == OffsetOfExprClass;
2046 }
2047
2048 // Iterators
2049 child_range children() {
2050 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2051 return child_range(begin, begin + NumExprs);
2052 }
2053 const_child_range children() const {
2054 Stmt *const *begin =
2055 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2056 return const_child_range(begin, begin + NumExprs);
2057 }
2058 friend TrailingObjects;
2059};
2060
2061/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2062/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2063/// vec_step (OpenCL 1.1 6.11.12).
2064class UnaryExprOrTypeTraitExpr : public Expr {
2065 union {
2066 TypeSourceInfo *Ty;
2067 Stmt *Ex;
2068 } Argument;
2069 SourceLocation OpLoc, RParenLoc;
2070
2071public:
2072 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2073 QualType resultType, SourceLocation op,
2074 SourceLocation rp) :
2075 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2076 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2077 // Value-dependent if the argument is type-dependent.
2078 TInfo->getType()->isDependentType(),
2079 TInfo->getType()->isInstantiationDependentType(),
2080 TInfo->getType()->containsUnexpandedParameterPack()),
2081 OpLoc(op), RParenLoc(rp) {
2082 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2083 UnaryExprOrTypeTraitExprBits.IsType = true;
2084 Argument.Ty = TInfo;
2085 }
2086
2087 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2088 QualType resultType, SourceLocation op,
2089 SourceLocation rp);
2090
2091 /// Construct an empty sizeof/alignof expression.
2092 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2093 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2094
2095 UnaryExprOrTypeTrait getKind() const {
2096 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2097 }
2098 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2099
2100 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2101 QualType getArgumentType() const {
2102 return getArgumentTypeInfo()->getType();
2103 }
2104 TypeSourceInfo *getArgumentTypeInfo() const {
2105 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2106 return Argument.Ty;
2107 }
2108 Expr *getArgumentExpr() {
2109 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2110 return static_cast<Expr*>(Argument.Ex);
2111 }
2112 const Expr *getArgumentExpr() const {
2113 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2114 }
2115
2116 void setArgument(Expr *E) {
2117 Argument.Ex = E;
2118 UnaryExprOrTypeTraitExprBits.IsType = false;
2119 }
2120 void setArgument(TypeSourceInfo *TInfo) {
2121 Argument.Ty = TInfo;
2122 UnaryExprOrTypeTraitExprBits.IsType = true;
2123 }
2124
2125 /// Gets the argument type, or the type of the argument expression, whichever
2126 /// is appropriate.
2127 QualType getTypeOfArgument() const {
2128 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2129 }
2130
2131 SourceLocation getOperatorLoc() const { return OpLoc; }
2132 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2133
2134 SourceLocation getRParenLoc() const { return RParenLoc; }
2135 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2136
2137 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2138 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2139
2140 static bool classof(const Stmt *T) {
2141 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2142 }
2143
2144 // Iterators
2145 child_range children();
2146 const_child_range children() const;
2147};
2148
2149//===----------------------------------------------------------------------===//
2150// Postfix Operators.
2151//===----------------------------------------------------------------------===//
2152
2153/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2154class ArraySubscriptExpr : public Expr {
2155 enum { LHS, RHS, END_EXPR=2 };
2156 Stmt* SubExprs[END_EXPR];
2157 SourceLocation RBracketLoc;
2158public:
2159 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2160 ExprValueKind VK, ExprObjectKind OK,
2161 SourceLocation rbracketloc)
2162 : Expr(ArraySubscriptExprClass, t, VK, OK,
2163 lhs->isTypeDependent() || rhs->isTypeDependent(),
2164 lhs->isValueDependent() || rhs->isValueDependent(),
2165 (lhs->isInstantiationDependent() ||
2166 rhs->isInstantiationDependent()),
2167 (lhs->containsUnexpandedParameterPack() ||
2168 rhs->containsUnexpandedParameterPack())),
2169 RBracketLoc(rbracketloc) {
2170 SubExprs[LHS] = lhs;
2171 SubExprs[RHS] = rhs;
2172 }
2173
2174 /// Create an empty array subscript expression.
2175 explicit ArraySubscriptExpr(EmptyShell Shell)
2176 : Expr(ArraySubscriptExprClass, Shell) { }
2177
2178 /// An array access can be written A[4] or 4[A] (both are equivalent).
2179 /// - getBase() and getIdx() always present the normalized view: A[4].
2180 /// In this case getBase() returns "A" and getIdx() returns "4".
2181 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2182 /// 4[A] getLHS() returns "4".
2183 /// Note: Because vector element access is also written A[4] we must
2184 /// predicate the format conversion in getBase and getIdx only on the
2185 /// the type of the RHS, as it is possible for the LHS to be a vector of
2186 /// integer type
2187 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2188 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2189 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2190
2191 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2192 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2193 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2194
2195 Expr *getBase() {
2196 return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS();
2197 }
2198
2199 const Expr *getBase() const {
2200 return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS();
2201 }
2202
2203 Expr *getIdx() {
2204 return getRHS()->getType()->isIntegerType() ? getRHS() : getLHS();
2205 }
2206
2207 const Expr *getIdx() const {
2208 return getRHS()->getType()->isIntegerType() ? getRHS() : getLHS();
2209 }
2210
2211 SourceLocation getLocStart() const LLVM_READONLY {
2212 return getLHS()->getLocStart();
2213 }
2214 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2215
2216 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2217 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2218
2219 SourceLocation getExprLoc() const LLVM_READONLY {
2220 return getBase()->getExprLoc();
2221 }
2222
2223 static bool classof(const Stmt *T) {
2224 return T->getStmtClass() == ArraySubscriptExprClass;
2225 }
2226
2227 // Iterators
2228 child_range children() {
2229 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2230 }
2231 const_child_range children() const {
2232 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2233 }
2234};
2235
2236/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2237/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2238/// while its subclasses may represent alternative syntax that (semantically)
2239/// results in a function call. For example, CXXOperatorCallExpr is
2240/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2241/// "str1 + str2" to resolve to a function call.
2242class CallExpr : public Expr {
2243 enum { FN=0, PREARGS_START=1 };
2244 Stmt **SubExprs;
2245 unsigned NumArgs;
2246 SourceLocation RParenLoc;
2247
2248 void updateDependenciesFromArg(Expr *Arg);
2249
2250protected:
2251 // These versions of the constructor are for derived classes.
2252 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
2253 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
2254 ExprValueKind VK, SourceLocation rparenloc);
2255 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef<Expr *> args,
2256 QualType t, ExprValueKind VK, SourceLocation rparenloc);
2257 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2258 EmptyShell Empty);
2259
2260 Stmt *getPreArg(unsigned i) {
2261 assert(i < getNumPreArgs() && "Prearg access out of range!");
2262 return SubExprs[PREARGS_START+i];
2263 }
2264 const Stmt *getPreArg(unsigned i) const {
2265 assert(i < getNumPreArgs() && "Prearg access out of range!");
2266 return SubExprs[PREARGS_START+i];
2267 }
2268 void setPreArg(unsigned i, Stmt *PreArg) {
2269 assert(i < getNumPreArgs() && "Prearg access out of range!");
2270 SubExprs[PREARGS_START+i] = PreArg;
2271 }
2272
2273 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2274
2275public:
2276 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2277 ExprValueKind VK, SourceLocation rparenloc);
2278
2279 /// Build an empty call expression.
2280 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2281
2282 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2283 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2284 void setCallee(Expr *F) { SubExprs[FN] = F; }
2285
2286 Decl *getCalleeDecl();
2287 const Decl *getCalleeDecl() const {
2288 return const_cast<CallExpr*>(this)->getCalleeDecl();
2289 }
2290
2291 /// If the callee is a FunctionDecl, return it. Otherwise return 0.
2292 FunctionDecl *getDirectCallee();
2293 const FunctionDecl *getDirectCallee() const {
2294 return const_cast<CallExpr*>(this)->getDirectCallee();
2295 }
2296
2297 /// getNumArgs - Return the number of actual arguments to this call.
2298 ///
2299 unsigned getNumArgs() const { return NumArgs; }
2300
2301 /// Retrieve the call arguments.
2302 Expr **getArgs() {
2303 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2304 }
2305 const Expr *const *getArgs() const {
2306 return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2307 PREARGS_START);
2308 }
2309
2310 /// getArg - Return the specified argument.
2311 Expr *getArg(unsigned Arg) {
2312 assert(Arg < NumArgs && "Arg access out of range!");
2313 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2314 }
2315 const Expr *getArg(unsigned Arg) const {
2316 assert(Arg < NumArgs && "Arg access out of range!");
2317 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2318 }
2319
2320 /// setArg - Set the specified argument.
2321 void setArg(unsigned Arg, Expr *ArgExpr) {
2322 assert(Arg < NumArgs && "Arg access out of range!");
2323 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2324 }
2325
2326 /// setNumArgs - This changes the number of arguments present in this call.
2327 /// Any orphaned expressions are deleted by this, and any new operands are set
2328 /// to null.
2329 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2330
2331 typedef ExprIterator arg_iterator;
2332 typedef ConstExprIterator const_arg_iterator;
2333 typedef llvm::iterator_range<arg_iterator> arg_range;
2334 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2335
2336 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2337 arg_const_range arguments() const {
2338 return arg_const_range(arg_begin(), arg_end());
2339 }
2340
2341 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2342 arg_iterator arg_end() {
2343 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2344 }
2345 const_arg_iterator arg_begin() const {
2346 return SubExprs+PREARGS_START+getNumPreArgs();
2347 }
2348 const_arg_iterator arg_end() const {
2349 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2350 }
2351
2352 /// This method provides fast access to all the subexpressions of
2353 /// a CallExpr without going through the slower virtual child_iterator
2354 /// interface. This provides efficient reverse iteration of the
2355 /// subexpressions. This is currently used for CFG construction.
2356 ArrayRef<Stmt*> getRawSubExprs() {
2357 return llvm::makeArrayRef(SubExprs,
2358 getNumPreArgs() + PREARGS_START + getNumArgs());
2359 }
2360
2361 /// getNumCommas - Return the number of commas that must have been present in
2362 /// this function call.
2363 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2364
2365 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2366 /// of the callee. If not, return 0.
2367 unsigned getBuiltinCallee() const;
2368
2369 /// Returns \c true if this is a call to a builtin which does not
2370 /// evaluate side-effects within its arguments.
2371 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2372
2373 /// getCallReturnType - Get the return type of the call expr. This is not
2374 /// always the type of the expr itself, if the return type is a reference
2375 /// type.
2376 QualType getCallReturnType(const ASTContext &Ctx) const;
2377
2378 SourceLocation getRParenLoc() const { return RParenLoc; }
2379 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2380
2381 SourceLocation getLocStart() const LLVM_READONLY;
2382 SourceLocation getLocEnd() const LLVM_READONLY;
2383
2384 /// Return true if this is a call to __assume() or __builtin_assume() with
2385 /// a non-value-dependent constant parameter evaluating as false.
2386 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
2387
2388 bool isCallToStdMove() const {
2389 const FunctionDecl* FD = getDirectCallee();
2390 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
2391 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
2392 }
2393
2394 static bool classof(const Stmt *T) {
2395 return T->getStmtClass() >= firstCallExprConstant &&
2396 T->getStmtClass() <= lastCallExprConstant;
2397 }
2398
2399 // Iterators
2400 child_range children() {
2401 return child_range(&SubExprs[0],
2402 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2403 }
2404
2405 const_child_range children() const {
2406 return const_child_range(&SubExprs[0], &SubExprs[0] + NumArgs +
2407 getNumPreArgs() + PREARGS_START);
2408 }
2409};
2410
2411/// Extra data stored in some MemberExpr objects.
2412struct MemberExprNameQualifier {
2413 /// The nested-name-specifier that qualifies the name, including
2414 /// source-location information.
2415 NestedNameSpecifierLoc QualifierLoc;
2416
2417 /// The DeclAccessPair through which the MemberDecl was found due to
2418 /// name qualifiers.
2419 DeclAccessPair FoundDecl;
2420};
2421
2422/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2423///
2424class MemberExpr final
2425 : public Expr,
2426 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2427 ASTTemplateKWAndArgsInfo,
2428 TemplateArgumentLoc> {
2429 /// Base - the expression for the base pointer or structure references. In
2430 /// X.F, this is "X".
2431 Stmt *Base;
2432
2433 /// MemberDecl - This is the decl being referenced by the field/member name.
2434 /// In X.F, this is the decl referenced by F.
2435 ValueDecl *MemberDecl;
2436
2437 /// MemberDNLoc - Provides source/type location info for the
2438 /// declaration name embedded in MemberDecl.
2439 DeclarationNameLoc MemberDNLoc;
2440
2441 /// MemberLoc - This is the location of the member name.
2442 SourceLocation MemberLoc;
2443
2444 /// This is the location of the -> or . in the expression.
2445 SourceLocation OperatorLoc;
2446
2447 /// IsArrow - True if this is "X->F", false if this is "X.F".
2448 bool IsArrow : 1;
2449
2450 /// True if this member expression used a nested-name-specifier to
2451 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2452 /// declaration. When true, a MemberExprNameQualifier
2453 /// structure is allocated immediately after the MemberExpr.
2454 bool HasQualifierOrFoundDecl : 1;
2455
2456 /// True if this member expression specified a template keyword
2457 /// and/or a template argument list explicitly, e.g., x->f<int>,
2458 /// x->template f, x->template f<int>.
2459 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2460 /// TemplateArguments (if any) are present.
2461 bool HasTemplateKWAndArgsInfo : 1;
2462
2463 /// True if this member expression refers to a method that
2464 /// was resolved from an overloaded set having size greater than 1.
2465 bool HadMultipleCandidates : 1;
2466
2467 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2468 return HasQualifierOrFoundDecl ? 1 : 0;
2469 }
2470
2471 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2472 return HasTemplateKWAndArgsInfo ? 1 : 0;
2473 }
2474
2475public:
2476 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2477 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2478 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2479 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2480 base->isValueDependent(), base->isInstantiationDependent(),
2481 base->containsUnexpandedParameterPack()),
2482 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2483 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2484 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2485 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2486 assert(memberdecl->getDeclName() == NameInfo.getName());
2487 }
2488
2489 // NOTE: this constructor should be used only when it is known that
2490 // the member name can not provide additional syntactic info
2491 // (i.e., source locations for C++ operator names or type source info
2492 // for constructors, destructors and conversion operators).
2493 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2494 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2495 ExprValueKind VK, ExprObjectKind OK)
2496 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2497 base->isValueDependent(), base->isInstantiationDependent(),
2498 base->containsUnexpandedParameterPack()),
2499 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2500 OperatorLoc(operatorloc), IsArrow(isarrow),
2501 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2502 HadMultipleCandidates(false) {}
2503
2504 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2505 SourceLocation OperatorLoc,
2506 NestedNameSpecifierLoc QualifierLoc,
2507 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2508 DeclAccessPair founddecl,
2509 DeclarationNameInfo MemberNameInfo,
2510 const TemplateArgumentListInfo *targs, QualType ty,
2511 ExprValueKind VK, ExprObjectKind OK);
2512
2513 void setBase(Expr *E) { Base = E; }
2514 Expr *getBase() const { return cast<Expr>(Base); }
2515
2516 /// Retrieve the member declaration to which this expression refers.
2517 ///
2518 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2519 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2520 ValueDecl *getMemberDecl() const { return MemberDecl; }
2521 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2522
2523 /// Retrieves the declaration found by lookup.
2524 DeclAccessPair getFoundDecl() const {
2525 if (!HasQualifierOrFoundDecl)
2526 return DeclAccessPair::make(getMemberDecl(),
2527 getMemberDecl()->getAccess());
2528 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2529 }
2530
2531 /// Determines whether this member expression actually had
2532 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2533 /// x->Base::foo.
2534 bool hasQualifier() const { return getQualifier() != nullptr; }
2535
2536 /// If the member name was qualified, retrieves the
2537 /// nested-name-specifier that precedes the member name, with source-location
2538 /// information.
2539 NestedNameSpecifierLoc getQualifierLoc() const {
2540 if (!HasQualifierOrFoundDecl)
2541 return NestedNameSpecifierLoc();
2542
2543 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2544 }
2545
2546 /// If the member name was qualified, retrieves the
2547 /// nested-name-specifier that precedes the member name. Otherwise, returns
2548 /// NULL.
2549 NestedNameSpecifier *getQualifier() const {
2550 return getQualifierLoc().getNestedNameSpecifier();
2551 }
2552
2553 /// Retrieve the location of the template keyword preceding
2554 /// the member name, if any.
2555 SourceLocation getTemplateKeywordLoc() const {
2556 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2557 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2558 }
2559
2560 /// Retrieve the location of the left angle bracket starting the
2561 /// explicit template argument list following the member name, if any.
2562 SourceLocation getLAngleLoc() const {
2563 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2564 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2565 }
2566
2567 /// Retrieve the location of the right angle bracket ending the
2568 /// explicit template argument list following the member name, if any.
2569 SourceLocation getRAngleLoc() const {
2570 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2571 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2572 }
2573
2574 /// Determines whether the member name was preceded by the template keyword.
2575 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2576
2577 /// Determines whether the member name was followed by an
2578 /// explicit template argument list.
2579 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2580
2581 /// Copies the template arguments (if present) into the given
2582 /// structure.
2583 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2584 if (hasExplicitTemplateArgs())
2585 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2586 getTrailingObjects<TemplateArgumentLoc>(), List);
2587 }
2588
2589 /// Retrieve the template arguments provided as part of this
2590 /// template-id.
2591 const TemplateArgumentLoc *getTemplateArgs() const {
2592 if (!hasExplicitTemplateArgs())
2593 return nullptr;
2594
2595 return getTrailingObjects<TemplateArgumentLoc>();
2596 }
2597
2598 /// Retrieve the number of template arguments provided as part of this
2599 /// template-id.
2600 unsigned getNumTemplateArgs() const {
2601 if (!hasExplicitTemplateArgs())
2602 return 0;
2603
2604 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2605 }
2606
2607 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2608 return {getTemplateArgs(), getNumTemplateArgs()};
2609 }
2610
2611 /// Retrieve the member declaration name info.
2612 DeclarationNameInfo getMemberNameInfo() const {
2613 return DeclarationNameInfo(MemberDecl->getDeclName(),
2614 MemberLoc, MemberDNLoc);
2615 }
2616
2617 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2618
2619 bool isArrow() const { return IsArrow; }
2620 void setArrow(bool A) { IsArrow = A; }
2621
2622 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2623 /// location of 'F'.
2624 SourceLocation getMemberLoc() const { return MemberLoc; }
2625 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2626
2627 SourceLocation getLocStart() const LLVM_READONLY;
2628 SourceLocation getLocEnd() const LLVM_READONLY;
2629
2630 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2631
2632 /// Determine whether the base of this explicit is implicit.
2633 bool isImplicitAccess() const {
2634 return getBase() && getBase()->isImplicitCXXThis();
2635 }
2636
2637 /// Returns true if this member expression refers to a method that
2638 /// was resolved from an overloaded set having size greater than 1.
2639 bool hadMultipleCandidates() const {
2640 return HadMultipleCandidates;
2641 }
2642 /// Sets the flag telling whether this expression refers to
2643 /// a method that was resolved from an overloaded set having size
2644 /// greater than 1.
2645 void setHadMultipleCandidates(bool V = true) {
2646 HadMultipleCandidates = V;
2647 }
2648
2649 /// Returns true if virtual dispatch is performed.
2650 /// If the member access is fully qualified, (i.e. X::f()), virtual
2651 /// dispatching is not performed. In -fapple-kext mode qualified
2652 /// calls to virtual method will still go through the vtable.
2653 bool performsVirtualDispatch(const LangOptions &LO) const {
2654 return LO.AppleKext || !hasQualifier();
2655 }
2656
2657 static bool classof(const Stmt *T) {
2658 return T->getStmtClass() == MemberExprClass;
2659 }
2660
2661 // Iterators
2662 child_range children() { return child_range(&Base, &Base+1); }
2663 const_child_range children() const {
2664 return const_child_range(&Base, &Base + 1);
2665 }
2666
2667 friend TrailingObjects;
2668 friend class ASTReader;
2669 friend class ASTStmtWriter;
2670};
2671
2672/// CompoundLiteralExpr - [C99 6.5.2.5]
2673///
2674class CompoundLiteralExpr : public Expr {
2675 /// LParenLoc - If non-null, this is the location of the left paren in a
2676 /// compound literal like "(int){4}". This can be null if this is a
2677 /// synthesized compound expression.
2678 SourceLocation LParenLoc;
2679
2680 /// The type as written. This can be an incomplete array type, in
2681 /// which case the actual expression type will be different.
2682 /// The int part of the pair stores whether this expr is file scope.
2683 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2684 Stmt *Init;
2685public:
2686 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2687 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2688 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2689 tinfo->getType()->isDependentType(),
2690 init->isValueDependent(),
2691 (init->isInstantiationDependent() ||
2692 tinfo->getType()->isInstantiationDependentType()),
2693 init->containsUnexpandedParameterPack()),
2694 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2695
2696 /// Construct an empty compound literal.
2697 explicit CompoundLiteralExpr(EmptyShell Empty)
2698 : Expr(CompoundLiteralExprClass, Empty) { }
2699
2700 const Expr *getInitializer() const { return cast<Expr>(Init); }
2701 Expr *getInitializer() { return cast<Expr>(Init); }
2702 void setInitializer(Expr *E) { Init = E; }
2703
2704 bool isFileScope() const { return TInfoAndScope.getInt(); }
2705 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2706
2707 SourceLocation getLParenLoc() const { return LParenLoc; }
2708 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2709
2710 TypeSourceInfo *getTypeSourceInfo() const {
2711 return TInfoAndScope.getPointer();
2712 }
2713 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2714 TInfoAndScope.setPointer(tinfo);
2715 }
2716
2717 SourceLocation getLocStart() const LLVM_READONLY {
2718 // FIXME: Init should never be null.
2719 if (!Init)
2720 return SourceLocation();
2721 if (LParenLoc.isInvalid())
2722 return Init->getLocStart();
2723 return LParenLoc;
2724 }
2725 SourceLocation getLocEnd() const LLVM_READONLY {
2726 // FIXME: Init should never be null.
2727 if (!Init)
2728 return SourceLocation();
2729 return Init->getLocEnd();
2730 }
2731
2732 static bool classof(const Stmt *T) {
2733 return T->getStmtClass() == CompoundLiteralExprClass;
2734 }
2735
2736 // Iterators
2737 child_range children() { return child_range(&Init, &Init+1); }
2738 const_child_range children() const {
2739 return const_child_range(&Init, &Init + 1);
2740 }
2741};
2742
2743/// CastExpr - Base class for type casts, including both implicit
2744/// casts (ImplicitCastExpr) and explicit casts that have some
2745/// representation in the source code (ExplicitCastExpr's derived
2746/// classes).
2747class CastExpr : public Expr {
2748private:
2749 Stmt *Op;
2750
2751 bool CastConsistency() const;
2752
2753 const CXXBaseSpecifier * const *path_buffer() const {
2754 return const_cast<CastExpr*>(this)->path_buffer();
2755 }
2756 CXXBaseSpecifier **path_buffer();
2757
2758 void setBasePathSize(unsigned basePathSize) {
2759 CastExprBits.BasePathSize = basePathSize;
2760 assert(CastExprBits.BasePathSize == basePathSize &&
2761 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2762 }
2763
2764protected:
2765 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2766 Expr *op, unsigned BasePathSize)
2767 : Expr(SC, ty, VK, OK_Ordinary,
2768 // Cast expressions are type-dependent if the type is
2769 // dependent (C++ [temp.dep.expr]p3).
2770 ty->isDependentType(),
2771 // Cast expressions are value-dependent if the type is
2772 // dependent or if the subexpression is value-dependent.
2773 ty->isDependentType() || (op && op->isValueDependent()),
2774 (ty->isInstantiationDependentType() ||
2775 (op && op->isInstantiationDependent())),
2776 // An implicit cast expression doesn't (lexically) contain an
2777 // unexpanded pack, even if its target type does.
2778 ((SC != ImplicitCastExprClass &&
2779 ty->containsUnexpandedParameterPack()) ||
2780 (op && op->containsUnexpandedParameterPack()))),
2781 Op(op) {
2782 CastExprBits.Kind = kind;
2783 setBasePathSize(BasePathSize);
2784 assert(CastConsistency());
2785 }
2786
2787 /// Construct an empty cast.
2788 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2789 : Expr(SC, Empty) {
2790 setBasePathSize(BasePathSize);
2791 }
2792
2793public:
2794 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2795 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2796
2797 static const char *getCastKindName(CastKind CK);
2798 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
2799
2800 Expr *getSubExpr() { return cast<Expr>(Op); }
2801 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2802 void setSubExpr(Expr *E) { Op = E; }
2803
2804 /// Retrieve the cast subexpression as it was written in the source
2805 /// code, looking through any implicit casts or other intermediate nodes
2806 /// introduced by semantic analysis.
2807 Expr *getSubExprAsWritten();
2808 const Expr *getSubExprAsWritten() const {
2809 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2810 }
2811
2812 typedef CXXBaseSpecifier **path_iterator;
2813 typedef const CXXBaseSpecifier * const *path_const_iterator;
2814 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2815 unsigned path_size() const { return CastExprBits.BasePathSize; }
2816 path_iterator path_begin() { return path_buffer(); }
2817 path_iterator path_end() { return path_buffer() + path_size(); }
2818 path_const_iterator path_begin() const { return path_buffer(); }
2819 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2820
2821 const FieldDecl *getTargetUnionField() const {
2822 assert(getCastKind() == CK_ToUnion);
2823 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
2824 }
2825
2826 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
2827 QualType opType);
2828 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
2829 QualType opType);
2830
2831 static bool classof(const Stmt *T) {
2832 return T->getStmtClass() >= firstCastExprConstant &&
2833 T->getStmtClass() <= lastCastExprConstant;
2834 }
2835
2836 // Iterators
2837 child_range children() { return child_range(&Op, &Op+1); }
2838 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
2839};
2840
2841/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2842/// conversions, which have no direct representation in the original
2843/// source code. For example: converting T[]->T*, void f()->void
2844/// (*f)(), float->double, short->int, etc.
2845///
2846/// In C, implicit casts always produce rvalues. However, in C++, an
2847/// implicit cast whose result is being bound to a reference will be
2848/// an lvalue or xvalue. For example:
2849///
2850/// @code
2851/// class Base { };
2852/// class Derived : public Base { };
2853/// Derived &&ref();
2854/// void f(Derived d) {
2855/// Base& b = d; // initializer is an ImplicitCastExpr
2856/// // to an lvalue of type Base
2857/// Base&& r = ref(); // initializer is an ImplicitCastExpr
2858/// // to an xvalue of type Base
2859/// }
2860/// @endcode
2861class ImplicitCastExpr final
2862 : public CastExpr,
2863 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
2864private:
2865 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2866 unsigned BasePathLength, ExprValueKind VK)
2867 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2868 }
2869
2870 /// Construct an empty implicit cast.
2871 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2872 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2873
2874public:
2875 enum OnStack_t { OnStack };
2876 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2877 ExprValueKind VK)
2878 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2879 }
2880
2881 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2882 CastKind Kind, Expr *Operand,
2883 const CXXCastPath *BasePath,
2884 ExprValueKind Cat);
2885
2886 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2887 unsigned PathSize);
2888
2889 SourceLocation getLocStart() const LLVM_READONLY {
2890 return getSubExpr()->getLocStart();
2891 }
2892 SourceLocation getLocEnd() const LLVM_READONLY {
2893 return getSubExpr()->getLocEnd();
2894 }
2895
2896 static bool classof(const Stmt *T) {
2897 return T->getStmtClass() == ImplicitCastExprClass;
2898 }
2899
2900 friend TrailingObjects;
2901 friend class CastExpr;
2902};
2903
2904inline Expr *Expr::IgnoreImpCasts() {
2905 Expr *e = this;
2906 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2907 e = ice->getSubExpr();
2908 return e;
2909}
2910
2911/// ExplicitCastExpr - An explicit cast written in the source
2912/// code.
2913///
2914/// This class is effectively an abstract class, because it provides
2915/// the basic representation of an explicitly-written cast without
2916/// specifying which kind of cast (C cast, functional cast, static
2917/// cast, etc.) was written; specific derived classes represent the
2918/// particular style of cast and its location information.
2919///
2920/// Unlike implicit casts, explicit cast nodes have two different
2921/// types: the type that was written into the source code, and the
2922/// actual type of the expression as determined by semantic
2923/// analysis. These types may differ slightly. For example, in C++ one
2924/// can cast to a reference type, which indicates that the resulting
2925/// expression will be an lvalue or xvalue. The reference type, however,
2926/// will not be used as the type of the expression.
2927class ExplicitCastExpr : public CastExpr {
2928 /// TInfo - Source type info for the (written) type
2929 /// this expression is casting to.
2930 TypeSourceInfo *TInfo;
2931
2932protected:
2933 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2934 CastKind kind, Expr *op, unsigned PathSize,
2935 TypeSourceInfo *writtenTy)
2936 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2937
2938 /// Construct an empty explicit cast.
2939 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2940 : CastExpr(SC, Shell, PathSize) { }
2941
2942public:
2943 /// getTypeInfoAsWritten - Returns the type source info for the type
2944 /// that this expression is casting to.
2945 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2946 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2947
2948 /// getTypeAsWritten - Returns the type that this expression is
2949 /// casting to, as written in the source code.
2950 QualType getTypeAsWritten() const { return TInfo->getType(); }
2951
2952 static bool classof(const Stmt *T) {
2953 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2954 T->getStmtClass() <= lastExplicitCastExprConstant;
2955 }
2956};
2957
2958/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2959/// cast in C++ (C++ [expr.cast]), which uses the syntax
2960/// (Type)expr. For example: @c (int)f.
2961class CStyleCastExpr final
2962 : public ExplicitCastExpr,
2963 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
2964 SourceLocation LPLoc; // the location of the left paren
2965 SourceLocation RPLoc; // the location of the right paren
2966
2967 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2968 unsigned PathSize, TypeSourceInfo *writtenTy,
2969 SourceLocation l, SourceLocation r)
2970 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2971 writtenTy), LPLoc(l), RPLoc(r) {}
2972
2973 /// Construct an empty C-style explicit cast.
2974 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2975 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2976
2977public:
2978 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2979 ExprValueKind VK, CastKind K,
2980 Expr *Op, const CXXCastPath *BasePath,
2981 TypeSourceInfo *WrittenTy, SourceLocation L,
2982 SourceLocation R);
2983
2984 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2985 unsigned PathSize);
2986
2987 SourceLocation getLParenLoc() const { return LPLoc; }
2988 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2989
2990 SourceLocation getRParenLoc() const { return RPLoc; }
2991 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2992
2993 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2994 SourceLocation getLocEnd() const LLVM_READONLY {
2995 return getSubExpr()->getLocEnd();
2996 }
2997
2998 static bool classof(const Stmt *T) {
2999 return T->getStmtClass() == CStyleCastExprClass;
3000 }
3001
3002 friend TrailingObjects;
3003 friend class CastExpr;
3004};
3005
3006/// A builtin binary operation expression such as "x + y" or "x <= y".
3007///
3008/// This expression node kind describes a builtin binary operation,
3009/// such as "x + y" for integer values "x" and "y". The operands will
3010/// already have been converted to appropriate types (e.g., by
3011/// performing promotions or conversions).
3012///
3013/// In C++, where operators may be overloaded, a different kind of
3014/// expression node (CXXOperatorCallExpr) is used to express the
3015/// invocation of an overloaded operator with operator syntax. Within
3016/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3017/// used to store an expression "x + y" depends on the subexpressions
3018/// for x and y. If neither x or y is type-dependent, and the "+"
3019/// operator resolves to a built-in operation, BinaryOperator will be
3020/// used to express the computation (x and y may still be
3021/// value-dependent). If either x or y is type-dependent, or if the
3022/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3023/// be used to express the computation.
3024class BinaryOperator : public Expr {
3025public:
3026 typedef BinaryOperatorKind Opcode;
3027
3028private:
3029 unsigned Opc : 6;
3030
3031 // This is only meaningful for operations on floating point types and 0
3032 // otherwise.
3033 unsigned FPFeatures : 2;
3034 SourceLocation OpLoc;
3035
3036 enum { LHS, RHS, END_EXPR };
3037 Stmt* SubExprs[END_EXPR];
3038public:
3039
3040 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3041 ExprValueKind VK, ExprObjectKind OK,
3042 SourceLocation opLoc, FPOptions FPFeatures)
3043 : Expr(BinaryOperatorClass, ResTy, VK, OK,
3044 lhs->isTypeDependent() || rhs->isTypeDependent(),
3045 lhs->isValueDependent() || rhs->isValueDependent(),
3046 (lhs->isInstantiationDependent() ||
3047 rhs->isInstantiationDependent()),
3048 (lhs->containsUnexpandedParameterPack() ||
3049 rhs->containsUnexpandedParameterPack())),
3050 Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3051 SubExprs[LHS] = lhs;
3052 SubExprs[RHS] = rhs;
3053 assert(!isCompoundAssignmentOp() &&
3054 "Use CompoundAssignOperator for compound assignments");
3055 }
3056
3057 /// Construct an empty binary operator.
3058 explicit BinaryOperator(EmptyShell Empty)
3059 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
3060
3061 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
3062 SourceLocation getOperatorLoc() const { return OpLoc; }
3063 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
3064
3065 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
3066 void setOpcode(Opcode O) { Opc = O; }
3067
3068 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3069 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3070 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3071 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3072
3073 SourceLocation getLocStart() const LLVM_READONLY {
3074 return getLHS()->getLocStart();
3075 }
3076 SourceLocation getLocEnd() const LLVM_READONLY {
3077 return getRHS()->getLocEnd();
3078 }
3079
3080 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3081 /// corresponds to, e.g. "<<=".
3082 static StringRef getOpcodeStr(Opcode Op);
3083
3084 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3085
3086 /// Retrieve the binary opcode that corresponds to the given
3087 /// overloaded operator.
3088 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3089
3090 /// Retrieve the overloaded operator kind that corresponds to
3091 /// the given binary opcode.
3092 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3093
3094 /// predicates to categorize the respective opcodes.
3095 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
3096 static bool isMultiplicativeOp(Opcode Opc) {
3097 return Opc >= BO_Mul && Opc <= BO_Rem;
3098 }
3099 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3100 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3101 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3102 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3103 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3104
3105 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3106 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3107
3108 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3109 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3110
3111 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3112 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3113
3114 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3115 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3116
3117 static Opcode negateComparisonOp(Opcode Opc) {
3118 switch (Opc) {
3119 default:
3120 llvm_unreachable("Not a comparison operator.");
3121 case BO_LT: return BO_GE;
3122 case BO_GT: return BO_LE;
3123 case BO_LE: return BO_GT;
3124 case BO_GE: return BO_LT;
3125 case BO_EQ: return BO_NE;
3126 case BO_NE: return BO_EQ;
3127 }
3128 }
3129
3130 static Opcode reverseComparisonOp(Opcode Opc) {
3131 switch (Opc) {
3132 default:
3133 llvm_unreachable("Not a comparison operator.");
3134 case BO_LT: return BO_GT;
3135 case BO_GT: return BO_LT;
3136 case BO_LE: return BO_GE;
3137 case BO_GE: return BO_LE;
3138 case BO_EQ:
3139 case BO_NE:
3140 return Opc;
3141 }
3142 }
3143
3144 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3145 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3146
3147 static bool isAssignmentOp(Opcode Opc) {
3148 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3149 }
3150 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3151
3152 static bool isCompoundAssignmentOp(Opcode Opc) {
3153 return Opc > BO_Assign && Opc <= BO_OrAssign;
3154 }
3155 bool isCompoundAssignmentOp() const {
3156 return isCompoundAssignmentOp(getOpcode());
3157 }
3158 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3159 assert(isCompoundAssignmentOp(Opc));
3160 if (Opc >= BO_AndAssign)
3161 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3162 else
3163 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3164 }
3165
3166 static bool isShiftAssignOp(Opcode Opc) {
3167 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3168 }
3169 bool isShiftAssignOp() const {
3170 return isShiftAssignOp(getOpcode());
3171 }
3172
3173 // Return true if a binary operator using the specified opcode and operands
3174 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3175 // integer to a pointer.
3176 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3177 Expr *LHS, Expr *RHS);
3178
3179 static bool classof(const Stmt *S) {
3180 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3181 S->getStmtClass() <= lastBinaryOperatorConstant;
3182 }
3183
3184 // Iterators
3185 child_range children() {
3186 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3187 }
3188 const_child_range children() const {
3189 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3190 }
3191
3192 // Set the FP contractability status of this operator. Only meaningful for
3193 // operations on floating point types.
3194 void setFPFeatures(FPOptions F) { FPFeatures = F.getInt(); }
3195
3196 FPOptions getFPFeatures() const { return FPOptions(FPFeatures); }
3197
3198 // Get the FP contractability status of this operator. Only meaningful for
3199 // operations on floating point types.
3200 bool isFPContractableWithinStatement() const {
3201 return FPOptions(FPFeatures).allowFPContractWithinStatement();
3202 }
3203
3204protected:
3205 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3206 ExprValueKind VK, ExprObjectKind OK,
3207 SourceLocation opLoc, FPOptions FPFeatures, bool dead2)
3208 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3209 lhs->isTypeDependent() || rhs->isTypeDependent(),
3210 lhs->isValueDependent() || rhs->isValueDependent(),
3211 (lhs->isInstantiationDependent() ||
3212 rhs->isInstantiationDependent()),
3213 (lhs->containsUnexpandedParameterPack() ||
3214 rhs->containsUnexpandedParameterPack())),
3215 Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3216 SubExprs[LHS] = lhs;
3217 SubExprs[RHS] = rhs;
3218 }
3219
3220 BinaryOperator(StmtClass SC, EmptyShell Empty)
3221 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3222};
3223
3224/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3225/// track of the type the operation is performed in. Due to the semantics of
3226/// these operators, the operands are promoted, the arithmetic performed, an
3227/// implicit conversion back to the result type done, then the assignment takes
3228/// place. This captures the intermediate type which the computation is done
3229/// in.
3230class CompoundAssignOperator : public BinaryOperator {
3231 QualType ComputationLHSType;
3232 QualType ComputationResultType;
3233public:
3234 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3235 ExprValueKind VK, ExprObjectKind OK,
3236 QualType CompLHSType, QualType CompResultType,
3237 SourceLocation OpLoc, FPOptions FPFeatures)
3238 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3239 true),
3240 ComputationLHSType(CompLHSType),
3241 ComputationResultType(CompResultType) {
3242 assert(isCompoundAssignmentOp() &&
3243 "Only should be used for compound assignments");
3244 }
3245
3246 /// Build an empty compound assignment operator expression.
3247 explicit CompoundAssignOperator(EmptyShell Empty)
3248 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3249
3250 // The two computation types are the type the LHS is converted
3251 // to for the computation and the type of the result; the two are
3252 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3253 QualType getComputationLHSType() const { return ComputationLHSType; }
3254 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3255
3256 QualType getComputationResultType() const { return ComputationResultType; }
3257 void setComputationResultType(QualType T) { ComputationResultType = T; }
3258
3259 static bool classof(const Stmt *S) {
3260 return S->getStmtClass() == CompoundAssignOperatorClass;
3261 }
3262};
3263
3264/// AbstractConditionalOperator - An abstract base class for
3265/// ConditionalOperator and BinaryConditionalOperator.
3266class AbstractConditionalOperator : public Expr {
3267 SourceLocation QuestionLoc, ColonLoc;
3268 friend class ASTStmtReader;
3269
3270protected:
3271 AbstractConditionalOperator(StmtClass SC, QualType T,
3272 ExprValueKind VK, ExprObjectKind OK,
3273 bool TD, bool VD, bool ID,
3274 bool ContainsUnexpandedParameterPack,
3275 SourceLocation qloc,
3276 SourceLocation cloc)
3277 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3278 QuestionLoc(qloc), ColonLoc(cloc) {}
3279
3280 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3281 : Expr(SC, Empty) { }
3282
3283public:
3284 // getCond - Return the expression representing the condition for
3285 // the ?: operator.
3286 Expr *getCond() const;
3287
3288 // getTrueExpr - Return the subexpression representing the value of
3289 // the expression if the condition evaluates to true.
3290 Expr *getTrueExpr() const;
3291
3292 // getFalseExpr - Return the subexpression representing the value of
3293 // the expression if the condition evaluates to false. This is
3294 // the same as getRHS.
3295 Expr *getFalseExpr() const;
3296
3297 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3298 SourceLocation getColonLoc() const { return ColonLoc; }
3299
3300 static bool classof(const Stmt *T) {
3301 return T->getStmtClass() == ConditionalOperatorClass ||
3302 T->getStmtClass() == BinaryConditionalOperatorClass;
3303 }
3304};
3305
3306/// ConditionalOperator - The ?: ternary operator. The GNU "missing
3307/// middle" extension is a BinaryConditionalOperator.
3308class ConditionalOperator : public AbstractConditionalOperator {
3309 enum { COND, LHS, RHS, END_EXPR };
3310 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3311
3312 friend class ASTStmtReader;
3313public:
3314 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3315 SourceLocation CLoc, Expr *rhs,
3316 QualType t, ExprValueKind VK, ExprObjectKind OK)
3317 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3318 // FIXME: the type of the conditional operator doesn't
3319 // depend on the type of the conditional, but the standard
3320 // seems to imply that it could. File a bug!
3321 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3322 (cond->isValueDependent() || lhs->isValueDependent() ||
3323 rhs->isValueDependent()),
3324 (cond->isInstantiationDependent() ||
3325 lhs->isInstantiationDependent() ||
3326 rhs->isInstantiationDependent()),
3327 (cond->containsUnexpandedParameterPack() ||
3328 lhs->containsUnexpandedParameterPack() ||
3329 rhs->containsUnexpandedParameterPack()),
3330 QLoc, CLoc) {
3331 SubExprs[COND] = cond;
3332 SubExprs[LHS] = lhs;
3333 SubExprs[RHS] = rhs;
3334 }
3335
3336 /// Build an empty conditional operator.
3337 explicit ConditionalOperator(EmptyShell Empty)
3338 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3339
3340 // getCond - Return the expression representing the condition for
3341 // the ?: operator.
3342 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3343
3344 // getTrueExpr - Return the subexpression representing the value of
3345 // the expression if the condition evaluates to true.
3346 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3347
3348 // getFalseExpr - Return the subexpression representing the value of
3349 // the expression if the condition evaluates to false. This is
3350 // the same as getRHS.
3351 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3352
3353 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3354 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3355
3356 SourceLocation getLocStart() const LLVM_READONLY {
3357 return getCond()->getLocStart();
3358 }
3359 SourceLocation getLocEnd() const LLVM_READONLY {
3360 return getRHS()->getLocEnd();
3361 }
3362
3363 static bool classof(const Stmt *T) {
3364 return T->getStmtClass() == ConditionalOperatorClass;
3365 }
3366
3367 // Iterators
3368 child_range children() {
3369 return child_range(