1//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Expr interface and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_EXPR_H
14#define LLVM_CLANG_AST_EXPR_H
15
16#include "clang/AST/APNumericStorage.h"
17#include "clang/AST/APValue.h"
18#include "clang/AST/ASTVector.h"
19#include "clang/AST/ComputeDependence.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclAccessPair.h"
22#include "clang/AST/DependenceFlags.h"
23#include "clang/AST/OperationKinds.h"
24#include "clang/AST/Stmt.h"
25#include "clang/AST/TemplateBase.h"
26#include "clang/AST/Type.h"
27#include "clang/Basic/CharInfo.h"
28#include "clang/Basic/LangOptions.h"
29#include "clang/Basic/SyncScope.h"
30#include "clang/Basic/TypeTraits.h"
31#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APSInt.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/ADT/iterator.h"
36#include "llvm/ADT/iterator_range.h"
37#include "llvm/Support/AtomicOrdering.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/TrailingObjects.h"
40#include <optional>
41
42namespace clang {
43 class APValue;
44 class ASTContext;
45 class BlockDecl;
46 class CXXBaseSpecifier;
47 class CXXMemberCallExpr;
48 class CXXOperatorCallExpr;
49 class CastExpr;
50 class Decl;
51 class IdentifierInfo;
52 class MaterializeTemporaryExpr;
53 class NamedDecl;
54 class ObjCPropertyRefExpr;
55 class OpaqueValueExpr;
56 class ParmVarDecl;
57 class StringLiteral;
58 class TargetInfo;
59 class ValueDecl;
60
61/// A simple array of base specifiers.
62typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
63
64/// An adjustment to be made to the temporary created when emitting a
65/// reference binding, which accesses a particular subobject of that temporary.
66struct SubobjectAdjustment {
67 enum {
68 DerivedToBaseAdjustment,
69 FieldAdjustment,
70 MemberPointerAdjustment
71 } Kind;
72
73 struct DTB {
74 const CastExpr *BasePath;
75 const CXXRecordDecl *DerivedClass;
76 };
77
78 struct P {
79 const MemberPointerType *MPT;
80 Expr *RHS;
81 };
82
83 union {
84 struct DTB DerivedToBase;
85 const FieldDecl *Field;
86 struct P Ptr;
87 };
88
89 SubobjectAdjustment(const CastExpr *BasePath,
90 const CXXRecordDecl *DerivedClass)
91 : Kind(DerivedToBaseAdjustment) {
92 DerivedToBase.BasePath = BasePath;
93 DerivedToBase.DerivedClass = DerivedClass;
94 }
95
96 SubobjectAdjustment(const FieldDecl *Field) : Kind(FieldAdjustment) {
97 this->Field = Field;
98 }
99
100 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
101 : Kind(MemberPointerAdjustment) {
102 this->Ptr.MPT = MPT;
103 this->Ptr.RHS = RHS;
104 }
105};
106
107/// This represents one expression. Note that Expr's are subclasses of Stmt.
108/// This allows an expression to be transparently used any place a Stmt is
109/// required.
110class Expr : public ValueStmt {
111 QualType TR;
112
113public:
114 Expr() = delete;
115 Expr(const Expr&) = delete;
116 Expr(Expr &&) = delete;
117 Expr &operator=(const Expr&) = delete;
118 Expr &operator=(Expr&&) = delete;
119
120protected:
121 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK)
122 : ValueStmt(SC) {
123 ExprBits.Dependent = 0;
124 ExprBits.ValueKind = VK;
125 ExprBits.ObjectKind = OK;
126 assert(ExprBits.ObjectKind == OK && "truncated kind");
127 setType(T);
128 }
129
130 /// Construct an empty expression.
131 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
132
133 /// Each concrete expr subclass is expected to compute its dependence and call
134 /// this in the constructor.
135 void setDependence(ExprDependence Deps) {
136 ExprBits.Dependent = static_cast<unsigned>(Deps);
137 }
138 friend class ASTImporter; // Sets dependence directly.
139 friend class ASTStmtReader; // Sets dependence directly.
140
141public:
142 QualType getType() const { return TR; }
143 void setType(QualType t) {
144 // In C++, the type of an expression is always adjusted so that it
145 // will not have reference type (C++ [expr]p6). Use
146 // QualType::getNonReferenceType() to retrieve the non-reference
147 // type. Additionally, inspect Expr::isLvalue to determine whether
148 // an expression that is adjusted in this manner should be
149 // considered an lvalue.
150 assert((t.isNull() || !t->isReferenceType()) &&
151 "Expressions can't have reference type");
152
153 TR = t;
154 }
155
156 ExprDependence getDependence() const {
157 return static_cast<ExprDependence>(ExprBits.Dependent);
158 }
159
160 /// Determines whether the value of this expression depends on
161 /// - a template parameter (C++ [temp.dep.constexpr])
162 /// - or an error, whose resolution is unknown
163 ///
164 /// For example, the array bound of "Chars" in the following example is
165 /// value-dependent.
166 /// @code
167 /// template<int Size, char (&Chars)[Size]> struct meta_string;
168 /// @endcode
169 bool isValueDependent() const {
170 return static_cast<bool>(getDependence() & ExprDependence::Value);
171 }
172
173 /// Determines whether the type of this expression depends on
174 /// - a template parameter (C++ [temp.dep.expr], which means that its type
175 /// could change from one template instantiation to the next)
176 /// - or an error
177 ///
178 /// For example, the expressions "x" and "x + y" are type-dependent in
179 /// the following code, but "y" is not type-dependent:
180 /// @code
181 /// template<typename T>
182 /// void add(T x, int y) {
183 /// x + y;
184 /// }
185 /// @endcode
186 bool isTypeDependent() const {
187 return static_cast<bool>(getDependence() & ExprDependence::Type);
188 }
189
190 /// Whether this expression is instantiation-dependent, meaning that
191 /// it depends in some way on
192 /// - a template parameter (even if neither its type nor (constant) value
193 /// can change due to the template instantiation)
194 /// - or an error
195 ///
196 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
197 /// instantiation-dependent (since it involves a template parameter \c T), but
198 /// is neither type- nor value-dependent, since the type of the inner
199 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
200 /// \c sizeof is known.
201 ///
202 /// \code
203 /// template<typename T>
204 /// void f(T x, T y) {
205 /// sizeof(sizeof(T() + T());
206 /// }
207 /// \endcode
208 ///
209 /// \code
210 /// void func(int) {
211 /// func(); // the expression is instantiation-dependent, because it depends
212 /// // on an error.
213 /// }
214 /// \endcode
215 bool isInstantiationDependent() const {
216 return static_cast<bool>(getDependence() & ExprDependence::Instantiation);
217 }
218
219 /// Whether this expression contains an unexpanded parameter
220 /// pack (for C++11 variadic templates).
221 ///
222 /// Given the following function template:
223 ///
224 /// \code
225 /// template<typename F, typename ...Types>
226 /// void forward(const F &f, Types &&...args) {
227 /// f(static_cast<Types&&>(args)...);
228 /// }
229 /// \endcode
230 ///
231 /// The expressions \c args and \c static_cast<Types&&>(args) both
232 /// contain parameter packs.
233 bool containsUnexpandedParameterPack() const {
234 return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
235 }
236
237 /// Whether this expression contains subexpressions which had errors, e.g. a
238 /// TypoExpr.
239 bool containsErrors() const {
240 return static_cast<bool>(getDependence() & ExprDependence::Error);
241 }
242
243 /// getExprLoc - Return the preferred location for the arrow when diagnosing
244 /// a problem with a generic expression.
245 SourceLocation getExprLoc() const LLVM_READONLY;
246
247 /// Determine whether an lvalue-to-rvalue conversion should implicitly be
248 /// applied to this expression if it appears as a discarded-value expression
249 /// in C++11 onwards. This applies to certain forms of volatile glvalues.
250 bool isReadIfDiscardedInCPlusPlus11() const;
251
252 /// isUnusedResultAWarning - Return true if this immediate expression should
253 /// be warned about if the result is unused. If so, fill in expr, location,
254 /// and ranges with expr to warn on and source locations/ranges appropriate
255 /// for a warning.
256 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
257 SourceRange &R1, SourceRange &R2,
258 ASTContext &Ctx) const;
259
260 /// isLValue - True if this expression is an "l-value" according to
261 /// the rules of the current language. C and C++ give somewhat
262 /// different rules for this concept, but in general, the result of
263 /// an l-value expression identifies a specific object whereas the
264 /// result of an r-value expression is a value detached from any
265 /// specific storage.
266 ///
267 /// C++11 divides the concept of "r-value" into pure r-values
268 /// ("pr-values") and so-called expiring values ("x-values"), which
269 /// identify specific objects that can be safely cannibalized for
270 /// their resources.
271 bool isLValue() const { return getValueKind() == VK_LValue; }
272 bool isPRValue() const { return getValueKind() == VK_PRValue; }
273 bool isXValue() const { return getValueKind() == VK_XValue; }
274 bool isGLValue() const { return getValueKind() != VK_PRValue; }
275
276 enum LValueClassification {
277 LV_Valid,
278 LV_NotObjectType,
279 LV_IncompleteVoidType,
280 LV_DuplicateVectorComponents,
281 LV_InvalidExpression,
282 LV_InvalidMessageExpression,
283 LV_MemberFunction,
284 LV_SubObjCPropertySetting,
285 LV_ClassTemporary,
286 LV_ArrayTemporary
287 };
288 /// Reasons why an expression might not be an l-value.
289 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
290
291 enum isModifiableLvalueResult {
292 MLV_Valid,
293 MLV_NotObjectType,
294 MLV_IncompleteVoidType,
295 MLV_DuplicateVectorComponents,
296 MLV_InvalidExpression,
297 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
298 MLV_IncompleteType,
299 MLV_ConstQualified,
300 MLV_ConstQualifiedField,
301 MLV_ConstAddrSpace,
302 MLV_ArrayType,
303 MLV_NoSetterProperty,
304 MLV_MemberFunction,
305 MLV_SubObjCPropertySetting,
306 MLV_InvalidMessageExpression,
307 MLV_ClassTemporary,
308 MLV_ArrayTemporary
309 };
310 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
311 /// does not have an incomplete type, does not have a const-qualified type,
312 /// and if it is a structure or union, does not have any member (including,
313 /// recursively, any member or element of all contained aggregates or unions)
314 /// with a const-qualified type.
315 ///
316 /// \param Loc [in,out] - A source location which *may* be filled
317 /// in with the location of the expression making this a
318 /// non-modifiable lvalue, if specified.
319 isModifiableLvalueResult
320 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
321
322 /// The return type of classify(). Represents the C++11 expression
323 /// taxonomy.
324 class Classification {
325 public:
326 /// The various classification results. Most of these mean prvalue.
327 enum Kinds {
328 CL_LValue,
329 CL_XValue,
330 CL_Function, // Functions cannot be lvalues in C.
331 CL_Void, // Void cannot be an lvalue in C.
332 CL_AddressableVoid, // Void expression whose address can be taken in C.
333 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
334 CL_MemberFunction, // An expression referring to a member function
335 CL_SubObjCPropertySetting,
336 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
337 CL_ArrayTemporary, // A temporary of array type.
338 CL_ObjCMessageRValue, // ObjC message is an rvalue
339 CL_PRValue // A prvalue for any other reason, of any other type
340 };
341 /// The results of modification testing.
342 enum ModifiableType {
343 CM_Untested, // testModifiable was false.
344 CM_Modifiable,
345 CM_RValue, // Not modifiable because it's an rvalue
346 CM_Function, // Not modifiable because it's a function; C++ only
347 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
348 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
349 CM_ConstQualified,
350 CM_ConstQualifiedField,
351 CM_ConstAddrSpace,
352 CM_ArrayType,
353 CM_IncompleteType
354 };
355
356 private:
357 friend class Expr;
358
359 unsigned short Kind;
360 unsigned short Modifiable;
361
362 explicit Classification(Kinds k, ModifiableType m)
363 : Kind(k), Modifiable(m)
364 {}
365
366 public:
367 Classification() {}
368
369 Kinds getKind() const { return static_cast<Kinds>(Kind); }
370 ModifiableType getModifiable() const {
371 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
372 return static_cast<ModifiableType>(Modifiable);
373 }
374 bool isLValue() const { return Kind == CL_LValue; }
375 bool isXValue() const { return Kind == CL_XValue; }
376 bool isGLValue() const { return Kind <= CL_XValue; }
377 bool isPRValue() const { return Kind >= CL_Function; }
378 bool isRValue() const { return Kind >= CL_XValue; }
379 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
380
381 /// Create a simple, modifiably lvalue
382 static Classification makeSimpleLValue() {
383 return Classification(CL_LValue, CM_Modifiable);
384 }
385
386 };
387 /// Classify - Classify this expression according to the C++11
388 /// expression taxonomy.
389 ///
390 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
391 /// old lvalue vs rvalue. This function determines the type of expression this
392 /// is. There are three expression types:
393 /// - lvalues are classical lvalues as in C++03.
394 /// - prvalues are equivalent to rvalues in C++03.
395 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
396 /// function returning an rvalue reference.
397 /// lvalues and xvalues are collectively referred to as glvalues, while
398 /// prvalues and xvalues together form rvalues.
399 Classification Classify(ASTContext &Ctx) const {
400 return ClassifyImpl(Ctx, Loc: nullptr);
401 }
402
403 /// ClassifyModifiable - Classify this expression according to the
404 /// C++11 expression taxonomy, and see if it is valid on the left side
405 /// of an assignment.
406 ///
407 /// This function extends classify in that it also tests whether the
408 /// expression is modifiable (C99 6.3.2.1p1).
409 /// \param Loc A source location that might be filled with a relevant location
410 /// if the expression is not modifiable.
411 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
412 return ClassifyImpl(Ctx, Loc: &Loc);
413 }
414
415 /// Returns the set of floating point options that apply to this expression.
416 /// Only meaningful for operations on floating point values.
417 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const;
418
419 /// getValueKindForType - Given a formal return or parameter type,
420 /// give its value kind.
421 static ExprValueKind getValueKindForType(QualType T) {
422 if (const ReferenceType *RT = T->getAs<ReferenceType>())
423 return (isa<LValueReferenceType>(Val: RT)
424 ? VK_LValue
425 : (RT->getPointeeType()->isFunctionType()
426 ? VK_LValue : VK_XValue));
427 return VK_PRValue;
428 }
429
430 /// getValueKind - The value kind that this expression produces.
431 ExprValueKind getValueKind() const {
432 return static_cast<ExprValueKind>(ExprBits.ValueKind);
433 }
434
435 /// getObjectKind - The object kind that this expression produces.
436 /// Object kinds are meaningful only for expressions that yield an
437 /// l-value or x-value.
438 ExprObjectKind getObjectKind() const {
439 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
440 }
441
442 bool isOrdinaryOrBitFieldObject() const {
443 ExprObjectKind OK = getObjectKind();
444 return (OK == OK_Ordinary || OK == OK_BitField);
445 }
446
447 /// setValueKind - Set the value kind produced by this expression.
448 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
449
450 /// setObjectKind - Set the object kind produced by this expression.
451 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
452
453private:
454 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
455
456public:
457
458 /// Returns true if this expression is a gl-value that
459 /// potentially refers to a bit-field.
460 ///
461 /// In C++, whether a gl-value refers to a bitfield is essentially
462 /// an aspect of the value-kind type system.
463 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
464
465 /// If this expression refers to a bit-field, retrieve the
466 /// declaration of that bit-field.
467 ///
468 /// Note that this returns a non-null pointer in subtly different
469 /// places than refersToBitField returns true. In particular, this can
470 /// return a non-null pointer even for r-values loaded from
471 /// bit-fields, but it will return null for a conditional bit-field.
472 FieldDecl *getSourceBitField();
473
474 const FieldDecl *getSourceBitField() const {
475 return const_cast<Expr*>(this)->getSourceBitField();
476 }
477
478 Decl *getReferencedDeclOfCallee();
479 const Decl *getReferencedDeclOfCallee() const {
480 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
481 }
482
483 /// If this expression is an l-value for an Objective C
484 /// property, find the underlying property reference expression.
485 const ObjCPropertyRefExpr *getObjCProperty() const;
486
487 /// Check if this expression is the ObjC 'self' implicit parameter.
488 bool isObjCSelfExpr() const;
489
490 /// Returns whether this expression refers to a vector element.
491 bool refersToVectorElement() const;
492
493 /// Returns whether this expression refers to a matrix element.
494 bool refersToMatrixElement() const {
495 return getObjectKind() == OK_MatrixComponent;
496 }
497
498 /// Returns whether this expression refers to a global register
499 /// variable.
500 bool refersToGlobalRegisterVar() const;
501
502 /// Returns whether this expression has a placeholder type.
503 bool hasPlaceholderType() const {
504 return getType()->isPlaceholderType();
505 }
506
507 /// Returns whether this expression has a specific placeholder type.
508 bool hasPlaceholderType(BuiltinType::Kind K) const {
509 assert(BuiltinType::isPlaceholderTypeKind(K));
510 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Val: getType()))
511 return BT->getKind() == K;
512 return false;
513 }
514
515 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
516 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
517 /// but also int expressions which are produced by things like comparisons in
518 /// C.
519 ///
520 /// \param Semantic If true, only return true for expressions that are known
521 /// to be semantically boolean, which might not be true even for expressions
522 /// that are known to evaluate to 0/1. For instance, reading an unsigned
523 /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
524 /// semantically correspond to a bool.
525 bool isKnownToHaveBooleanValue(bool Semantic = true) const;
526
527 /// Check whether this array fits the idiom of a flexible array member,
528 /// depending on the value of -fstrict-flex-array.
529 /// When IgnoreTemplateOrMacroSubstitution is set, it doesn't consider sizes
530 /// resulting from the substitution of a macro or a template as special sizes.
531 bool isFlexibleArrayMemberLike(
532 ASTContext &Context,
533 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
534 bool IgnoreTemplateOrMacroSubstitution = false) const;
535
536 /// isIntegerConstantExpr - Return the value if this expression is a valid
537 /// integer constant expression. If not a valid i-c-e, return std::nullopt
538 /// and fill in Loc (if specified) with the location of the invalid
539 /// expression.
540 ///
541 /// Note: This does not perform the implicit conversions required by C++11
542 /// [expr.const]p5.
543 std::optional<llvm::APSInt>
544 getIntegerConstantExpr(const ASTContext &Ctx,
545 SourceLocation *Loc = nullptr) const;
546 bool isIntegerConstantExpr(const ASTContext &Ctx,
547 SourceLocation *Loc = nullptr) const;
548
549 /// isCXX98IntegralConstantExpr - Return true if this expression is an
550 /// integral constant expression in C++98. Can only be used in C++.
551 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
552
553 /// isCXX11ConstantExpr - Return true if this expression is a constant
554 /// expression in C++11. Can only be used in C++.
555 ///
556 /// Note: This does not perform the implicit conversions required by C++11
557 /// [expr.const]p5.
558 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
559 SourceLocation *Loc = nullptr) const;
560
561 /// isPotentialConstantExpr - Return true if this function's definition
562 /// might be usable in a constant expression in C++11, if it were marked
563 /// constexpr. Return false if the function can never produce a constant
564 /// expression, along with diagnostics describing why not.
565 static bool isPotentialConstantExpr(const FunctionDecl *FD,
566 SmallVectorImpl<
567 PartialDiagnosticAt> &Diags);
568
569 /// isPotentialConstantExprUnevaluated - Return true if this expression might
570 /// be usable in a constant expression in C++11 in an unevaluated context, if
571 /// it were in function FD marked constexpr. Return false if the function can
572 /// never produce a constant expression, along with diagnostics describing
573 /// why not.
574 static bool isPotentialConstantExprUnevaluated(Expr *E,
575 const FunctionDecl *FD,
576 SmallVectorImpl<
577 PartialDiagnosticAt> &Diags);
578
579 /// isConstantInitializer - Returns true if this expression can be emitted to
580 /// IR as a constant, and thus can be used as a constant initializer in C.
581 /// If this expression is not constant and Culprit is non-null,
582 /// it is used to store the address of first non constant expr.
583 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
584 const Expr **Culprit = nullptr) const;
585
586 /// If this expression is an unambiguous reference to a single declaration,
587 /// in the style of __builtin_function_start, return that declaration. Note
588 /// that this may return a non-static member function or field in C++ if this
589 /// expression is a member pointer constant.
590 const ValueDecl *getAsBuiltinConstantDeclRef(const ASTContext &Context) const;
591
592 /// EvalStatus is a struct with detailed info about an evaluation in progress.
593 struct EvalStatus {
594 /// Whether the evaluated expression has side effects.
595 /// For example, (f() && 0) can be folded, but it still has side effects.
596 bool HasSideEffects = false;
597
598 /// Whether the evaluation hit undefined behavior.
599 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
600 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
601 bool HasUndefinedBehavior = false;
602
603 /// Diag - If this is non-null, it will be filled in with a stack of notes
604 /// indicating why evaluation failed (or why it failed to produce a constant
605 /// expression).
606 /// If the expression is unfoldable, the notes will indicate why it's not
607 /// foldable. If the expression is foldable, but not a constant expression,
608 /// the notes will describes why it isn't a constant expression. If the
609 /// expression *is* a constant expression, no notes will be produced.
610 ///
611 /// FIXME: this causes significant performance concerns and should be
612 /// refactored at some point. Not all evaluations of the constant
613 /// expression interpreter will display the given diagnostics, this means
614 /// those kinds of uses are paying the expense of generating a diagnostic
615 /// (which may include expensive operations like converting APValue objects
616 /// to a string representation).
617 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr;
618
619 EvalStatus() = default;
620
621 // hasSideEffects - Return true if the evaluated expression has
622 // side effects.
623 bool hasSideEffects() const {
624 return HasSideEffects;
625 }
626 };
627
628 /// EvalResult is a struct with detailed info about an evaluated expression.
629 struct EvalResult : EvalStatus {
630 /// Val - This is the value the expression can be folded to.
631 APValue Val;
632
633 // isGlobalLValue - Return true if the evaluated lvalue expression
634 // is global.
635 bool isGlobalLValue() const;
636 };
637
638 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
639 /// an rvalue using any crazy technique (that has nothing to do with language
640 /// standards) that we want to, even if the expression has side-effects. If
641 /// this function returns true, it returns the folded constant in Result. If
642 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
643 /// applied.
644 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
645 bool InConstantContext = false) const;
646
647 /// EvaluateAsBooleanCondition - Return true if this is a constant
648 /// which we can fold and convert to a boolean condition using
649 /// any crazy technique that we want to, even if the expression has
650 /// side-effects.
651 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
652 bool InConstantContext = false) const;
653
654 enum SideEffectsKind {
655 SE_NoSideEffects, ///< Strictly evaluate the expression.
656 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
657 ///< arbitrary unmodeled side effects.
658 SE_AllowSideEffects ///< Allow any unmodeled side effect.
659 };
660
661 /// EvaluateAsInt - Return true if this is a constant which we can fold and
662 /// convert to an integer, using any crazy technique that we want to.
663 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
664 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
665 bool InConstantContext = false) const;
666
667 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
668 /// convert to a floating point value, using any crazy technique that we
669 /// want to.
670 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
671 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
672 bool InConstantContext = false) const;
673
674 /// EvaluateAsFixedPoint - Return true if this is a constant which we can fold
675 /// and convert to a fixed point value.
676 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
677 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
678 bool InConstantContext = false) const;
679
680 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
681 /// constant folded without side-effects, but discard the result.
682 bool isEvaluatable(const ASTContext &Ctx,
683 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
684
685 /// HasSideEffects - This routine returns true for all those expressions
686 /// which have any effect other than producing a value. Example is a function
687 /// call, volatile variable read, or throwing an exception. If
688 /// IncludePossibleEffects is false, this call treats certain expressions with
689 /// potential side effects (such as function call-like expressions,
690 /// instantiation-dependent expressions, or invocations from a macro) as not
691 /// having side effects.
692 bool HasSideEffects(const ASTContext &Ctx,
693 bool IncludePossibleEffects = true) const;
694
695 /// Determine whether this expression involves a call to any function
696 /// that is not trivial.
697 bool hasNonTrivialCall(const ASTContext &Ctx) const;
698
699 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
700 /// integer. This must be called on an expression that constant folds to an
701 /// integer.
702 llvm::APSInt EvaluateKnownConstInt(
703 const ASTContext &Ctx,
704 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
705
706 llvm::APSInt EvaluateKnownConstIntCheckOverflow(
707 const ASTContext &Ctx,
708 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
709
710 void EvaluateForOverflow(const ASTContext &Ctx) const;
711
712 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
713 /// lvalue with link time known address, with no side-effects.
714 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
715 bool InConstantContext = false) const;
716
717 /// EvaluateAsInitializer - Evaluate an expression as if it were the
718 /// initializer of the given declaration. Returns true if the initializer
719 /// can be folded to a constant, and produces any relevant notes. In C++11,
720 /// notes will be produced if the expression is not a constant expression.
721 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
722 const VarDecl *VD,
723 SmallVectorImpl<PartialDiagnosticAt> &Notes,
724 bool IsConstantInitializer) const;
725
726 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
727 /// of a call to the given function with the given arguments, inside an
728 /// unevaluated context. Returns true if the expression could be folded to a
729 /// constant.
730 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
731 const FunctionDecl *Callee,
732 ArrayRef<const Expr*> Args,
733 const Expr *This = nullptr) const;
734
735 enum class ConstantExprKind {
736 /// An integer constant expression (an array bound, enumerator, case value,
737 /// bit-field width, or similar) or similar.
738 Normal,
739 /// A non-class template argument. Such a value is only used for mangling,
740 /// not for code generation, so can refer to dllimported functions.
741 NonClassTemplateArgument,
742 /// A class template argument. Such a value is used for code generation.
743 ClassTemplateArgument,
744 /// An immediate invocation. The destruction of the end result of this
745 /// evaluation is not part of the evaluation, but all other temporaries
746 /// are destroyed.
747 ImmediateInvocation,
748 };
749
750 /// Evaluate an expression that is required to be a constant expression. Does
751 /// not check the syntactic constraints for C and C++98 constant expressions.
752 bool EvaluateAsConstantExpr(
753 EvalResult &Result, const ASTContext &Ctx,
754 ConstantExprKind Kind = ConstantExprKind::Normal) const;
755
756 /// If the current Expr is a pointer, this will try to statically
757 /// determine the number of bytes available where the pointer is pointing.
758 /// Returns true if all of the above holds and we were able to figure out the
759 /// size, false otherwise.
760 ///
761 /// \param Type - How to evaluate the size of the Expr, as defined by the
762 /// "type" parameter of __builtin_object_size
763 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
764 unsigned Type) const;
765
766 /// If the current Expr is a pointer, this will try to statically
767 /// determine the strlen of the string pointed to.
768 /// Returns true if all of the above holds and we were able to figure out the
769 /// strlen, false otherwise.
770 bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const;
771
772 bool EvaluateCharRangeAsString(std::string &Result,
773 const Expr *SizeExpression,
774 const Expr *PtrExpression, ASTContext &Ctx,
775 EvalResult &Status) const;
776
777 /// Enumeration used to describe the kind of Null pointer constant
778 /// returned from \c isNullPointerConstant().
779 enum NullPointerConstantKind {
780 /// Expression is not a Null pointer constant.
781 NPCK_NotNull = 0,
782
783 /// Expression is a Null pointer constant built from a zero integer
784 /// expression that is not a simple, possibly parenthesized, zero literal.
785 /// C++ Core Issue 903 will classify these expressions as "not pointers"
786 /// once it is adopted.
787 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
788 NPCK_ZeroExpression,
789
790 /// Expression is a Null pointer constant built from a literal zero.
791 NPCK_ZeroLiteral,
792
793 /// Expression is a C++11 nullptr.
794 NPCK_CXX11_nullptr,
795
796 /// Expression is a GNU-style __null constant.
797 NPCK_GNUNull
798 };
799
800 /// Enumeration used to describe how \c isNullPointerConstant()
801 /// should cope with value-dependent expressions.
802 enum NullPointerConstantValueDependence {
803 /// Specifies that the expression should never be value-dependent.
804 NPC_NeverValueDependent = 0,
805
806 /// Specifies that a value-dependent expression of integral or
807 /// dependent type should be considered a null pointer constant.
808 NPC_ValueDependentIsNull,
809
810 /// Specifies that a value-dependent expression should be considered
811 /// to never be a null pointer constant.
812 NPC_ValueDependentIsNotNull
813 };
814
815 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
816 /// a Null pointer constant. The return value can further distinguish the
817 /// kind of NULL pointer constant that was detected.
818 NullPointerConstantKind isNullPointerConstant(
819 ASTContext &Ctx,
820 NullPointerConstantValueDependence NPC) const;
821
822 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
823 /// write barrier.
824 bool isOBJCGCCandidate(ASTContext &Ctx) const;
825
826 /// Returns true if this expression is a bound member function.
827 bool isBoundMemberFunction(ASTContext &Ctx) const;
828
829 /// Given an expression of bound-member type, find the type
830 /// of the member. Returns null if this is an *overloaded* bound
831 /// member expression.
832 static QualType findBoundMemberType(const Expr *expr);
833
834 /// Skip past any invisible AST nodes which might surround this
835 /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
836 /// but also injected CXXMemberExpr and CXXConstructExpr which represent
837 /// implicit conversions.
838 Expr *IgnoreUnlessSpelledInSource();
839 const Expr *IgnoreUnlessSpelledInSource() const {
840 return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
841 }
842
843 /// Skip past any implicit casts which might surround this expression until
844 /// reaching a fixed point. Skips:
845 /// * ImplicitCastExpr
846 /// * FullExpr
847 Expr *IgnoreImpCasts() LLVM_READONLY;
848 const Expr *IgnoreImpCasts() const {
849 return const_cast<Expr *>(this)->IgnoreImpCasts();
850 }
851
852 /// Skip past any casts which might surround this expression until reaching
853 /// a fixed point. Skips:
854 /// * CastExpr
855 /// * FullExpr
856 /// * MaterializeTemporaryExpr
857 /// * SubstNonTypeTemplateParmExpr
858 Expr *IgnoreCasts() LLVM_READONLY;
859 const Expr *IgnoreCasts() const {
860 return const_cast<Expr *>(this)->IgnoreCasts();
861 }
862
863 /// Skip past any implicit AST nodes which might surround this expression
864 /// until reaching a fixed point. Skips:
865 /// * What IgnoreImpCasts() skips
866 /// * MaterializeTemporaryExpr
867 /// * CXXBindTemporaryExpr
868 Expr *IgnoreImplicit() LLVM_READONLY;
869 const Expr *IgnoreImplicit() const {
870 return const_cast<Expr *>(this)->IgnoreImplicit();
871 }
872
873 /// Skip past any implicit AST nodes which might surround this expression
874 /// until reaching a fixed point. Same as IgnoreImplicit, except that it
875 /// also skips over implicit calls to constructors and conversion functions.
876 ///
877 /// FIXME: Should IgnoreImplicit do this?
878 Expr *IgnoreImplicitAsWritten() LLVM_READONLY;
879 const Expr *IgnoreImplicitAsWritten() const {
880 return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
881 }
882
883 /// Skip past any parentheses which might surround this expression until
884 /// reaching a fixed point. Skips:
885 /// * ParenExpr
886 /// * UnaryOperator if `UO_Extension`
887 /// * GenericSelectionExpr if `!isResultDependent()`
888 /// * ChooseExpr if `!isConditionDependent()`
889 /// * ConstantExpr
890 Expr *IgnoreParens() LLVM_READONLY;
891 const Expr *IgnoreParens() const {
892 return const_cast<Expr *>(this)->IgnoreParens();
893 }
894
895 /// Skip past any parentheses and implicit casts which might surround this
896 /// expression until reaching a fixed point.
897 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
898 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
899 /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
900 /// * What IgnoreParens() skips
901 /// * What IgnoreImpCasts() skips
902 /// * MaterializeTemporaryExpr
903 /// * SubstNonTypeTemplateParmExpr
904 Expr *IgnoreParenImpCasts() LLVM_READONLY;
905 const Expr *IgnoreParenImpCasts() const {
906 return const_cast<Expr *>(this)->IgnoreParenImpCasts();
907 }
908
909 /// Skip past any parentheses and casts which might surround this expression
910 /// until reaching a fixed point. Skips:
911 /// * What IgnoreParens() skips
912 /// * What IgnoreCasts() skips
913 Expr *IgnoreParenCasts() LLVM_READONLY;
914 const Expr *IgnoreParenCasts() const {
915 return const_cast<Expr *>(this)->IgnoreParenCasts();
916 }
917
918 /// Skip conversion operators. If this Expr is a call to a conversion
919 /// operator, return the argument.
920 Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY;
921 const Expr *IgnoreConversionOperatorSingleStep() const {
922 return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
923 }
924
925 /// Skip past any parentheses and lvalue casts which might surround this
926 /// expression until reaching a fixed point. Skips:
927 /// * What IgnoreParens() skips
928 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
929 /// casts are skipped
930 /// FIXME: This is intended purely as a temporary workaround for code
931 /// that hasn't yet been rewritten to do the right thing about those
932 /// casts, and may disappear along with the last internal use.
933 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
934 const Expr *IgnoreParenLValueCasts() const {
935 return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
936 }
937
938 /// Skip past any parentheses and casts which do not change the value
939 /// (including ptr->int casts of the same size) until reaching a fixed point.
940 /// Skips:
941 /// * What IgnoreParens() skips
942 /// * CastExpr which do not change the value
943 /// * SubstNonTypeTemplateParmExpr
944 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
945 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
946 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
947 }
948
949 /// Skip past any parentheses and derived-to-base casts until reaching a
950 /// fixed point. Skips:
951 /// * What IgnoreParens() skips
952 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
953 /// CK_UncheckedDerivedToBase and CK_NoOp)
954 Expr *IgnoreParenBaseCasts() LLVM_READONLY;
955 const Expr *IgnoreParenBaseCasts() const {
956 return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
957 }
958
959 /// Determine whether this expression is a default function argument.
960 ///
961 /// Default arguments are implicitly generated in the abstract syntax tree
962 /// by semantic analysis for function calls, object constructions, etc. in
963 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
964 /// this routine also looks through any implicit casts to determine whether
965 /// the expression is a default argument.
966 bool isDefaultArgument() const;
967
968 /// Determine whether the result of this expression is a
969 /// temporary object of the given class type.
970 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
971
972 /// Whether this expression is an implicit reference to 'this' in C++.
973 bool isImplicitCXXThis() const;
974
975 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
976
977 /// For an expression of class type or pointer to class type,
978 /// return the most derived class decl the expression is known to refer to.
979 ///
980 /// If this expression is a cast, this method looks through it to find the
981 /// most derived decl that can be inferred from the expression.
982 /// This is valid because derived-to-base conversions have undefined
983 /// behavior if the object isn't dynamically of the derived type.
984 const CXXRecordDecl *getBestDynamicClassType() const;
985
986 /// Get the inner expression that determines the best dynamic class.
987 /// If this is a prvalue, we guarantee that it is of the most-derived type
988 /// for the object itself.
989 const Expr *getBestDynamicClassTypeExpr() const;
990
991 /// Walk outwards from an expression we want to bind a reference to and
992 /// find the expression whose lifetime needs to be extended. Record
993 /// the LHSs of comma expressions and adjustments needed along the path.
994 const Expr *skipRValueSubobjectAdjustments(
995 SmallVectorImpl<const Expr *> &CommaLHS,
996 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
997 const Expr *skipRValueSubobjectAdjustments() const {
998 SmallVector<const Expr *, 8> CommaLHSs;
999 SmallVector<SubobjectAdjustment, 8> Adjustments;
1000 return skipRValueSubobjectAdjustments(CommaLHS&: CommaLHSs, Adjustments);
1001 }
1002
1003 /// Checks that the two Expr's will refer to the same value as a comparison
1004 /// operand. The caller must ensure that the values referenced by the Expr's
1005 /// are not modified between E1 and E2 or the result my be invalid.
1006 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
1007
1008 static bool classof(const Stmt *T) {
1009 return T->getStmtClass() >= firstExprConstant &&
1010 T->getStmtClass() <= lastExprConstant;
1011 }
1012};
1013// PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
1014// Expr. Verify that we got it right.
1015static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <=
1016 llvm::detail::ConstantLog2<alignof(Expr)>::value,
1017 "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
1018
1019using ConstantExprKind = Expr::ConstantExprKind;
1020
1021//===----------------------------------------------------------------------===//
1022// Wrapper Expressions.
1023//===----------------------------------------------------------------------===//
1024
1025/// FullExpr - Represents a "full-expression" node.
1026class FullExpr : public Expr {
1027protected:
1028 Stmt *SubExpr;
1029
1030 FullExpr(StmtClass SC, Expr *subexpr)
1031 : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
1032 subexpr->getObjectKind()),
1033 SubExpr(subexpr) {
1034 setDependence(computeDependence(E: this));
1035 }
1036 FullExpr(StmtClass SC, EmptyShell Empty)
1037 : Expr(SC, Empty) {}
1038public:
1039 const Expr *getSubExpr() const { return cast<Expr>(Val: SubExpr); }
1040 Expr *getSubExpr() { return cast<Expr>(Val: SubExpr); }
1041
1042 /// As with any mutator of the AST, be very careful when modifying an
1043 /// existing AST to preserve its invariants.
1044 void setSubExpr(Expr *E) { SubExpr = E; }
1045
1046 static bool classof(const Stmt *T) {
1047 return T->getStmtClass() >= firstFullExprConstant &&
1048 T->getStmtClass() <= lastFullExprConstant;
1049 }
1050};
1051
1052/// Describes the kind of result that can be tail-allocated.
1053enum class ConstantResultStorageKind { None, Int64, APValue };
1054
1055/// ConstantExpr - An expression that occurs in a constant context and
1056/// optionally the result of evaluating the expression.
1057class ConstantExpr final
1058 : public FullExpr,
1059 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
1060 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
1061 "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
1062 "for tail-allocated storage");
1063 friend TrailingObjects;
1064 friend class ASTStmtReader;
1065 friend class ASTStmtWriter;
1066
1067 size_t numTrailingObjects(OverloadToken<APValue>) const {
1068 return getResultStorageKind() == ConstantResultStorageKind::APValue;
1069 }
1070 size_t numTrailingObjects(OverloadToken<uint64_t>) const {
1071 return getResultStorageKind() == ConstantResultStorageKind::Int64;
1072 }
1073
1074 uint64_t &Int64Result() {
1075 assert(getResultStorageKind() == ConstantResultStorageKind::Int64 &&
1076 "invalid accessor");
1077 return *getTrailingObjects<uint64_t>();
1078 }
1079 const uint64_t &Int64Result() const {
1080 return const_cast<ConstantExpr *>(this)->Int64Result();
1081 }
1082 APValue &APValueResult() {
1083 assert(getResultStorageKind() == ConstantResultStorageKind::APValue &&
1084 "invalid accessor");
1085 return *getTrailingObjects<APValue>();
1086 }
1087 APValue &APValueResult() const {
1088 return const_cast<ConstantExpr *>(this)->APValueResult();
1089 }
1090
1091 ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
1092 bool IsImmediateInvocation);
1093 ConstantExpr(EmptyShell Empty, ConstantResultStorageKind StorageKind);
1094
1095public:
1096 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1097 const APValue &Result);
1098 static ConstantExpr *
1099 Create(const ASTContext &Context, Expr *E,
1100 ConstantResultStorageKind Storage = ConstantResultStorageKind::None,
1101 bool IsImmediateInvocation = false);
1102 static ConstantExpr *CreateEmpty(const ASTContext &Context,
1103 ConstantResultStorageKind StorageKind);
1104
1105 static ConstantResultStorageKind getStorageKind(const APValue &Value);
1106 static ConstantResultStorageKind getStorageKind(const Type *T,
1107 const ASTContext &Context);
1108
1109 SourceLocation getBeginLoc() const LLVM_READONLY {
1110 return SubExpr->getBeginLoc();
1111 }
1112 SourceLocation getEndLoc() const LLVM_READONLY {
1113 return SubExpr->getEndLoc();
1114 }
1115
1116 static bool classof(const Stmt *T) {
1117 return T->getStmtClass() == ConstantExprClass;
1118 }
1119
1120 void SetResult(APValue Value, const ASTContext &Context) {
1121 MoveIntoResult(Value, Context);
1122 }
1123 void MoveIntoResult(APValue &Value, const ASTContext &Context);
1124
1125 APValue::ValueKind getResultAPValueKind() const {
1126 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1127 }
1128 ConstantResultStorageKind getResultStorageKind() const {
1129 return static_cast<ConstantResultStorageKind>(ConstantExprBits.ResultKind);
1130 }
1131 bool isImmediateInvocation() const {
1132 return ConstantExprBits.IsImmediateInvocation;
1133 }
1134 bool hasAPValueResult() const {
1135 return ConstantExprBits.APValueKind != APValue::None;
1136 }
1137 APValue getAPValueResult() const;
1138 llvm::APSInt getResultAsAPSInt() const;
1139 // Iterators
1140 child_range children() { return child_range(&SubExpr, &SubExpr+1); }
1141 const_child_range children() const {
1142 return const_child_range(&SubExpr, &SubExpr + 1);
1143 }
1144};
1145
1146//===----------------------------------------------------------------------===//
1147// Primary Expressions.
1148//===----------------------------------------------------------------------===//
1149
1150/// OpaqueValueExpr - An expression referring to an opaque object of a
1151/// fixed type and value class. These don't correspond to concrete
1152/// syntax; instead they're used to express operations (usually copy
1153/// operations) on values whose source is generally obvious from
1154/// context.
1155class OpaqueValueExpr : public Expr {
1156 friend class ASTStmtReader;
1157 Expr *SourceExpr;
1158
1159public:
1160 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
1161 ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
1162 : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
1163 setIsUnique(false);
1164 OpaqueValueExprBits.Loc = Loc;
1165 setDependence(computeDependence(E: this));
1166 }
1167
1168 /// Given an expression which invokes a copy constructor --- i.e. a
1169 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1170 /// find the OpaqueValueExpr that's the source of the construction.
1171 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1172
1173 explicit OpaqueValueExpr(EmptyShell Empty)
1174 : Expr(OpaqueValueExprClass, Empty) {}
1175
1176 /// Retrieve the location of this expression.
1177 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
1178
1179 SourceLocation getBeginLoc() const LLVM_READONLY {
1180 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1181 }
1182 SourceLocation getEndLoc() const LLVM_READONLY {
1183 return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1184 }
1185 SourceLocation getExprLoc() const LLVM_READONLY {
1186 return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1187 }
1188
1189 child_range children() {
1190 return child_range(child_iterator(), child_iterator());
1191 }
1192
1193 const_child_range children() const {
1194 return const_child_range(const_child_iterator(), const_child_iterator());
1195 }
1196
1197 /// The source expression of an opaque value expression is the
1198 /// expression which originally generated the value. This is
1199 /// provided as a convenience for analyses that don't wish to
1200 /// precisely model the execution behavior of the program.
1201 ///
1202 /// The source expression is typically set when building the
1203 /// expression which binds the opaque value expression in the first
1204 /// place.
1205 Expr *getSourceExpr() const { return SourceExpr; }
1206
1207 void setIsUnique(bool V) {
1208 assert((!V || SourceExpr) &&
1209 "unique OVEs are expected to have source expressions");
1210 OpaqueValueExprBits.IsUnique = V;
1211 }
1212
1213 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1214
1215 static bool classof(const Stmt *T) {
1216 return T->getStmtClass() == OpaqueValueExprClass;
1217 }
1218};
1219
1220/// A reference to a declared variable, function, enum, etc.
1221/// [C99 6.5.1p2]
1222///
1223/// This encodes all the information about how a declaration is referenced
1224/// within an expression.
1225///
1226/// There are several optional constructs attached to DeclRefExprs only when
1227/// they apply in order to conserve memory. These are laid out past the end of
1228/// the object, and flags in the DeclRefExprBitfield track whether they exist:
1229///
1230/// DeclRefExprBits.HasQualifier:
1231/// Specifies when this declaration reference expression has a C++
1232/// nested-name-specifier.
1233/// DeclRefExprBits.HasFoundDecl:
1234/// Specifies when this declaration reference expression has a record of
1235/// a NamedDecl (different from the referenced ValueDecl) which was found
1236/// during name lookup and/or overload resolution.
1237/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1238/// Specifies when this declaration reference expression has an explicit
1239/// C++ template keyword and/or template argument list.
1240/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1241/// Specifies when this declaration reference expression (validly)
1242/// refers to an enclosed local or a captured variable.
1243class DeclRefExpr final
1244 : public Expr,
1245 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1246 NamedDecl *, ASTTemplateKWAndArgsInfo,
1247 TemplateArgumentLoc> {
1248 friend class ASTStmtReader;
1249 friend class ASTStmtWriter;
1250 friend TrailingObjects;
1251
1252 /// The declaration that we are referencing.
1253 ValueDecl *D;
1254
1255 /// Provides source/type location info for the declaration name
1256 /// embedded in D.
1257 DeclarationNameLoc DNLoc;
1258
1259 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1260 return hasQualifier();
1261 }
1262
1263 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1264 return hasFoundDecl();
1265 }
1266
1267 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1268 return hasTemplateKWAndArgsInfo();
1269 }
1270
1271 /// Test whether there is a distinct FoundDecl attached to the end of
1272 /// this DRE.
1273 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1274
1275 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1276 SourceLocation TemplateKWLoc, ValueDecl *D,
1277 bool RefersToEnlosingVariableOrCapture,
1278 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1279 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1280 ExprValueKind VK, NonOdrUseReason NOUR);
1281
1282 /// Construct an empty declaration reference expression.
1283 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1284
1285public:
1286 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1287 bool RefersToEnclosingVariableOrCapture, QualType T,
1288 ExprValueKind VK, SourceLocation L,
1289 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1290 NonOdrUseReason NOUR = NOUR_None);
1291
1292 static DeclRefExpr *
1293 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1294 SourceLocation TemplateKWLoc, ValueDecl *D,
1295 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1296 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1297 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1298 NonOdrUseReason NOUR = NOUR_None);
1299
1300 static DeclRefExpr *
1301 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1302 SourceLocation TemplateKWLoc, ValueDecl *D,
1303 bool RefersToEnclosingVariableOrCapture,
1304 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1305 NamedDecl *FoundD = nullptr,
1306 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1307 NonOdrUseReason NOUR = NOUR_None);
1308
1309 /// Construct an empty declaration reference expression.
1310 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1311 bool HasFoundDecl,
1312 bool HasTemplateKWAndArgsInfo,
1313 unsigned NumTemplateArgs);
1314
1315 ValueDecl *getDecl() { return D; }
1316 const ValueDecl *getDecl() const { return D; }
1317 void setDecl(ValueDecl *NewD);
1318
1319 DeclarationNameInfo getNameInfo() const {
1320 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1321 }
1322
1323 SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
1324 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1325 SourceLocation getBeginLoc() const LLVM_READONLY;
1326 SourceLocation getEndLoc() const LLVM_READONLY;
1327
1328 /// Determine whether this declaration reference was preceded by a
1329 /// C++ nested-name-specifier, e.g., \c N::foo.
1330 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1331
1332 /// If the name was qualified, retrieves the nested-name-specifier
1333 /// that precedes the name, with source-location information.
1334 NestedNameSpecifierLoc getQualifierLoc() const {
1335 if (!hasQualifier())
1336 return NestedNameSpecifierLoc();
1337 return *getTrailingObjects<NestedNameSpecifierLoc>();
1338 }
1339
1340 /// If the name was qualified, retrieves the nested-name-specifier
1341 /// that precedes the name. Otherwise, returns NULL.
1342 NestedNameSpecifier *getQualifier() const {
1343 return getQualifierLoc().getNestedNameSpecifier();
1344 }
1345
1346 /// Get the NamedDecl through which this reference occurred.
1347 ///
1348 /// This Decl may be different from the ValueDecl actually referred to in the
1349 /// presence of using declarations, etc. It always returns non-NULL, and may
1350 /// simple return the ValueDecl when appropriate.
1351
1352 NamedDecl *getFoundDecl() {
1353 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1354 }
1355
1356 /// Get the NamedDecl through which this reference occurred.
1357 /// See non-const variant.
1358 const NamedDecl *getFoundDecl() const {
1359 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1360 }
1361
1362 bool hasTemplateKWAndArgsInfo() const {
1363 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1364 }
1365
1366 /// Retrieve the location of the template keyword preceding
1367 /// this name, if any.
1368 SourceLocation getTemplateKeywordLoc() const {
1369 if (!hasTemplateKWAndArgsInfo())
1370 return SourceLocation();
1371 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1372 }
1373
1374 /// Retrieve the location of the left angle bracket starting the
1375 /// explicit template argument list following the name, if any.
1376 SourceLocation getLAngleLoc() const {
1377 if (!hasTemplateKWAndArgsInfo())
1378 return SourceLocation();
1379 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1380 }
1381
1382 /// Retrieve the location of the right angle bracket ending the
1383 /// explicit template argument list following the name, if any.
1384 SourceLocation getRAngleLoc() const {
1385 if (!hasTemplateKWAndArgsInfo())
1386 return SourceLocation();
1387 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1388 }
1389
1390 /// Determines whether the name in this declaration reference
1391 /// was preceded by the template keyword.
1392 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1393
1394 /// Determines whether this declaration reference was followed by an
1395 /// explicit template argument list.
1396 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1397
1398 /// Copies the template arguments (if present) into the given
1399 /// structure.
1400 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1401 if (hasExplicitTemplateArgs())
1402 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1403 getTrailingObjects<TemplateArgumentLoc>(), List);
1404 }
1405
1406 /// Retrieve the template arguments provided as part of this
1407 /// template-id.
1408 const TemplateArgumentLoc *getTemplateArgs() const {
1409 if (!hasExplicitTemplateArgs())
1410 return nullptr;
1411 return getTrailingObjects<TemplateArgumentLoc>();
1412 }
1413
1414 /// Retrieve the number of template arguments provided as part of this
1415 /// template-id.
1416 unsigned getNumTemplateArgs() const {
1417 if (!hasExplicitTemplateArgs())
1418 return 0;
1419 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1420 }
1421
1422 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1423 return {getTemplateArgs(), getNumTemplateArgs()};
1424 }
1425
1426 /// Returns true if this expression refers to a function that
1427 /// was resolved from an overloaded set having size greater than 1.
1428 bool hadMultipleCandidates() const {
1429 return DeclRefExprBits.HadMultipleCandidates;
1430 }
1431 /// Sets the flag telling whether this expression refers to
1432 /// a function that was resolved from an overloaded set having size
1433 /// greater than 1.
1434 void setHadMultipleCandidates(bool V = true) {
1435 DeclRefExprBits.HadMultipleCandidates = V;
1436 }
1437
1438 /// Is this expression a non-odr-use reference, and if so, why?
1439 NonOdrUseReason isNonOdrUse() const {
1440 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1441 }
1442
1443 /// Does this DeclRefExpr refer to an enclosing local or a captured
1444 /// variable?
1445 bool refersToEnclosingVariableOrCapture() const {
1446 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1447 }
1448
1449 bool isImmediateEscalating() const {
1450 return DeclRefExprBits.IsImmediateEscalating;
1451 }
1452
1453 void setIsImmediateEscalating(bool Set) {
1454 DeclRefExprBits.IsImmediateEscalating = Set;
1455 }
1456
1457 bool isCapturedByCopyInLambdaWithExplicitObjectParameter() const {
1458 return DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter;
1459 }
1460
1461 void setCapturedByCopyInLambdaWithExplicitObjectParameter(
1462 bool Set, const ASTContext &Context) {
1463 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = Set;
1464 setDependence(computeDependence(E: this, Ctx: Context));
1465 }
1466
1467 static bool classof(const Stmt *T) {
1468 return T->getStmtClass() == DeclRefExprClass;
1469 }
1470
1471 // Iterators
1472 child_range children() {
1473 return child_range(child_iterator(), child_iterator());
1474 }
1475
1476 const_child_range children() const {
1477 return const_child_range(const_child_iterator(), const_child_iterator());
1478 }
1479};
1480
1481class IntegerLiteral : public Expr, public APIntStorage {
1482 SourceLocation Loc;
1483
1484 /// Construct an empty integer literal.
1485 explicit IntegerLiteral(EmptyShell Empty)
1486 : Expr(IntegerLiteralClass, Empty) { }
1487
1488public:
1489 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1490 // or UnsignedLongLongTy
1491 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1492 SourceLocation l);
1493
1494 /// Returns a new integer literal with value 'V' and type 'type'.
1495 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1496 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1497 /// \param V - the value that the returned integer literal contains.
1498 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1499 QualType type, SourceLocation l);
1500 /// Returns a new empty integer literal.
1501 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1502
1503 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1504 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1505
1506 /// Retrieve the location of the literal.
1507 SourceLocation getLocation() const { return Loc; }
1508
1509 void setLocation(SourceLocation Location) { Loc = Location; }
1510
1511 static bool classof(const Stmt *T) {
1512 return T->getStmtClass() == IntegerLiteralClass;
1513 }
1514
1515 // Iterators
1516 child_range children() {
1517 return child_range(child_iterator(), child_iterator());
1518 }
1519 const_child_range children() const {
1520 return const_child_range(const_child_iterator(), const_child_iterator());
1521 }
1522};
1523
1524class FixedPointLiteral : public Expr, public APIntStorage {
1525 SourceLocation Loc;
1526 unsigned Scale;
1527
1528 /// \brief Construct an empty fixed-point literal.
1529 explicit FixedPointLiteral(EmptyShell Empty)
1530 : Expr(FixedPointLiteralClass, Empty) {}
1531
1532 public:
1533 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1534 SourceLocation l, unsigned Scale);
1535
1536 // Store the int as is without any bit shifting.
1537 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1538 const llvm::APInt &V,
1539 QualType type, SourceLocation l,
1540 unsigned Scale);
1541
1542 /// Returns an empty fixed-point literal.
1543 static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
1544
1545 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1546 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1547
1548 /// \brief Retrieve the location of the literal.
1549 SourceLocation getLocation() const { return Loc; }
1550
1551 void setLocation(SourceLocation Location) { Loc = Location; }
1552
1553 unsigned getScale() const { return Scale; }
1554 void setScale(unsigned S) { Scale = S; }
1555
1556 static bool classof(const Stmt *T) {
1557 return T->getStmtClass() == FixedPointLiteralClass;
1558 }
1559
1560 std::string getValueAsString(unsigned Radix) const;
1561
1562 // Iterators
1563 child_range children() {
1564 return child_range(child_iterator(), child_iterator());
1565 }
1566 const_child_range children() const {
1567 return const_child_range(const_child_iterator(), const_child_iterator());
1568 }
1569};
1570
1571enum class CharacterLiteralKind { Ascii, Wide, UTF8, UTF16, UTF32 };
1572
1573class CharacterLiteral : public Expr {
1574 unsigned Value;
1575 SourceLocation Loc;
1576public:
1577 // type should be IntTy
1578 CharacterLiteral(unsigned value, CharacterLiteralKind kind, QualType type,
1579 SourceLocation l)
1580 : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary),
1581 Value(value), Loc(l) {
1582 CharacterLiteralBits.Kind = llvm::to_underlying(E: kind);
1583 setDependence(ExprDependence::None);
1584 }
1585
1586 /// Construct an empty character literal.
1587 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1588
1589 SourceLocation getLocation() const { return Loc; }
1590 CharacterLiteralKind getKind() const {
1591 return static_cast<CharacterLiteralKind>(CharacterLiteralBits.Kind);
1592 }
1593
1594 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1595 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1596
1597 unsigned getValue() const { return Value; }
1598
1599 void setLocation(SourceLocation Location) { Loc = Location; }
1600 void setKind(CharacterLiteralKind kind) {
1601 CharacterLiteralBits.Kind = llvm::to_underlying(E: kind);
1602 }
1603 void setValue(unsigned Val) { Value = Val; }
1604
1605 static bool classof(const Stmt *T) {
1606 return T->getStmtClass() == CharacterLiteralClass;
1607 }
1608
1609 static void print(unsigned val, CharacterLiteralKind Kind, raw_ostream &OS);
1610
1611 // Iterators
1612 child_range children() {
1613 return child_range(child_iterator(), child_iterator());
1614 }
1615 const_child_range children() const {
1616 return const_child_range(const_child_iterator(), const_child_iterator());
1617 }
1618};
1619
1620class FloatingLiteral : public Expr, private APFloatStorage {
1621 SourceLocation Loc;
1622
1623 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1624 QualType Type, SourceLocation L);
1625
1626 /// Construct an empty floating-point literal.
1627 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1628
1629public:
1630 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1631 bool isexact, QualType Type, SourceLocation L);
1632 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1633
1634 llvm::APFloat getValue() const {
1635 return APFloatStorage::getValue(getSemantics());
1636 }
1637 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1638 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1639 APFloatStorage::setValue(C, Val);
1640 }
1641
1642 /// Get a raw enumeration value representing the floating-point semantics of
1643 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1644 llvm::APFloatBase::Semantics getRawSemantics() const {
1645 return static_cast<llvm::APFloatBase::Semantics>(
1646 FloatingLiteralBits.Semantics);
1647 }
1648
1649 /// Set the raw enumeration value representing the floating-point semantics of
1650 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1651 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1652 FloatingLiteralBits.Semantics = Sem;
1653 }
1654
1655 /// Return the APFloat semantics this literal uses.
1656 const llvm::fltSemantics &getSemantics() const {
1657 return llvm::APFloatBase::EnumToSemantics(
1658 S: static_cast<llvm::APFloatBase::Semantics>(
1659 FloatingLiteralBits.Semantics));
1660 }
1661
1662 /// Set the APFloat semantics this literal uses.
1663 void setSemantics(const llvm::fltSemantics &Sem) {
1664 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1665 }
1666
1667 bool isExact() const { return FloatingLiteralBits.IsExact; }
1668 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1669
1670 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1671 /// double. Note that this may cause loss of precision, but is useful for
1672 /// debugging dumps, etc.
1673 double getValueAsApproximateDouble() const;
1674
1675 SourceLocation getLocation() const { return Loc; }
1676 void setLocation(SourceLocation L) { Loc = L; }
1677
1678 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1679 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1680
1681 static bool classof(const Stmt *T) {
1682 return T->getStmtClass() == FloatingLiteralClass;
1683 }
1684
1685 // Iterators
1686 child_range children() {
1687 return child_range(child_iterator(), child_iterator());
1688 }
1689 const_child_range children() const {
1690 return const_child_range(const_child_iterator(), const_child_iterator());
1691 }
1692};
1693
1694/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1695/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1696/// IntegerLiteral classes. Instances of this class always have a Complex type
1697/// whose element type matches the subexpression.
1698///
1699class ImaginaryLiteral : public Expr {
1700 Stmt *Val;
1701public:
1702 ImaginaryLiteral(Expr *val, QualType Ty)
1703 : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) {
1704 setDependence(ExprDependence::None);
1705 }
1706
1707 /// Build an empty imaginary literal.
1708 explicit ImaginaryLiteral(EmptyShell Empty)
1709 : Expr(ImaginaryLiteralClass, Empty) { }
1710
1711 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1712 Expr *getSubExpr() { return cast<Expr>(Val); }
1713 void setSubExpr(Expr *E) { Val = E; }
1714
1715 SourceLocation getBeginLoc() const LLVM_READONLY {
1716 return Val->getBeginLoc();
1717 }
1718 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1719
1720 static bool classof(const Stmt *T) {
1721 return T->getStmtClass() == ImaginaryLiteralClass;
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
1731enum class StringLiteralKind {
1732 Ordinary,
1733 Wide,
1734 UTF8,
1735 UTF16,
1736 UTF32,
1737 Unevaluated
1738};
1739
1740/// StringLiteral - This represents a string literal expression, e.g. "foo"
1741/// or L"bar" (wide strings). The actual string data can be obtained with
1742/// getBytes() and is NOT null-terminated. The length of the string data is
1743/// determined by calling getByteLength().
1744///
1745/// The C type for a string is always a ConstantArrayType. In C++, the char
1746/// type is const qualified, in C it is not.
1747///
1748/// Note that strings in C can be formed by concatenation of multiple string
1749/// literal pptokens in translation phase #6. This keeps track of the locations
1750/// of each of these pieces.
1751///
1752/// Strings in C can also be truncated and extended by assigning into arrays,
1753/// e.g. with constructs like:
1754/// char X[2] = "foobar";
1755/// In this case, getByteLength() will return 6, but the string literal will
1756/// have type "char[2]".
1757class StringLiteral final
1758 : public Expr,
1759 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1760 char> {
1761 friend class ASTStmtReader;
1762 friend TrailingObjects;
1763
1764 /// StringLiteral is followed by several trailing objects. They are in order:
1765 ///
1766 /// * A single unsigned storing the length in characters of this string. The
1767 /// length in bytes is this length times the width of a single character.
1768 /// Always present and stored as a trailing objects because storing it in
1769 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1770 /// due to alignment requirements. If you add some data to StringLiteral,
1771 /// consider moving it inside StringLiteral.
1772 ///
1773 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1774 /// token this string is made of.
1775 ///
1776 /// * An array of getByteLength() char used to store the string data.
1777
1778 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
1779 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1780 return getNumConcatenated();
1781 }
1782
1783 unsigned numTrailingObjects(OverloadToken<char>) const {
1784 return getByteLength();
1785 }
1786
1787 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
1788 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1789
1790 const uint16_t *getStrDataAsUInt16() const {
1791 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1792 }
1793
1794 const uint32_t *getStrDataAsUInt32() const {
1795 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1796 }
1797
1798 /// Build a string literal.
1799 StringLiteral(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind,
1800 bool Pascal, QualType Ty, const SourceLocation *Loc,
1801 unsigned NumConcatenated);
1802
1803 /// Build an empty string literal.
1804 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1805 unsigned CharByteWidth);
1806
1807 /// Map a target and string kind to the appropriate character width.
1808 static unsigned mapCharByteWidth(TargetInfo const &Target,
1809 StringLiteralKind SK);
1810
1811 /// Set one of the string literal token.
1812 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1813 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1814 getTrailingObjects<SourceLocation>()[TokNum] = L;
1815 }
1816
1817public:
1818 /// This is the "fully general" constructor that allows representation of
1819 /// strings formed from multiple concatenated tokens.
1820 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1821 StringLiteralKind Kind, bool Pascal, QualType Ty,
1822 const SourceLocation *Loc,
1823 unsigned NumConcatenated);
1824
1825 /// Simple constructor for string literals made from one token.
1826 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1827 StringLiteralKind Kind, bool Pascal, QualType Ty,
1828 SourceLocation Loc) {
1829 return Create(Ctx, Str, Kind, Pascal, Ty, Loc: &Loc, NumConcatenated: 1);
1830 }
1831
1832 /// Construct an empty string literal.
1833 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1834 unsigned NumConcatenated, unsigned Length,
1835 unsigned CharByteWidth);
1836
1837 StringRef getString() const {
1838 assert((isUnevaluated() || getCharByteWidth() == 1) &&
1839 "This function is used in places that assume strings use char");
1840 return StringRef(getStrDataAsChar(), getByteLength());
1841 }
1842
1843 /// Allow access to clients that need the byte representation, such as
1844 /// ASTWriterStmt::VisitStringLiteral().
1845 StringRef getBytes() const {
1846 // FIXME: StringRef may not be the right type to use as a result for this.
1847 return StringRef(getStrDataAsChar(), getByteLength());
1848 }
1849
1850 void outputString(raw_ostream &OS) const;
1851
1852 uint32_t getCodeUnit(size_t i) const {
1853 assert(i < getLength() && "out of bounds access");
1854 switch (getCharByteWidth()) {
1855 case 1:
1856 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1857 case 2:
1858 return getStrDataAsUInt16()[i];
1859 case 4:
1860 return getStrDataAsUInt32()[i];
1861 }
1862 llvm_unreachable("Unsupported character width!");
1863 }
1864
1865 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
1866 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
1867 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1868
1869 StringLiteralKind getKind() const {
1870 return static_cast<StringLiteralKind>(StringLiteralBits.Kind);
1871 }
1872
1873 bool isOrdinary() const { return getKind() == StringLiteralKind::Ordinary; }
1874 bool isWide() const { return getKind() == StringLiteralKind::Wide; }
1875 bool isUTF8() const { return getKind() == StringLiteralKind::UTF8; }
1876 bool isUTF16() const { return getKind() == StringLiteralKind::UTF16; }
1877 bool isUTF32() const { return getKind() == StringLiteralKind::UTF32; }
1878 bool isUnevaluated() const { return getKind() == StringLiteralKind::Unevaluated; }
1879 bool isPascal() const { return StringLiteralBits.IsPascal; }
1880
1881 bool containsNonAscii() const {
1882 for (auto c : getString())
1883 if (!isASCII(c))
1884 return true;
1885 return false;
1886 }
1887
1888 bool containsNonAsciiOrNull() const {
1889 for (auto c : getString())
1890 if (!isASCII(c) || !c)
1891 return true;
1892 return false;
1893 }
1894
1895 /// getNumConcatenated - Get the number of string literal tokens that were
1896 /// concatenated in translation phase #6 to form this string literal.
1897 unsigned getNumConcatenated() const {
1898 return StringLiteralBits.NumConcatenated;
1899 }
1900
1901 /// Get one of the string literal token.
1902 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1903 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1904 return getTrailingObjects<SourceLocation>()[TokNum];
1905 }
1906
1907 /// getLocationOfByte - Return a source location that points to the specified
1908 /// byte of this string literal.
1909 ///
1910 /// Strings are amazingly complex. They can be formed from multiple tokens
1911 /// and can have escape sequences in them in addition to the usual trigraph
1912 /// and escaped newline business. This routine handles this complexity.
1913 ///
1914 SourceLocation
1915 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1916 const LangOptions &Features, const TargetInfo &Target,
1917 unsigned *StartToken = nullptr,
1918 unsigned *StartTokenByteOffset = nullptr) const;
1919
1920 typedef const SourceLocation *tokloc_iterator;
1921
1922 tokloc_iterator tokloc_begin() const {
1923 return getTrailingObjects<SourceLocation>();
1924 }
1925
1926 tokloc_iterator tokloc_end() const {
1927 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1928 }
1929
1930 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
1931 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
1932
1933 static bool classof(const Stmt *T) {
1934 return T->getStmtClass() == StringLiteralClass;
1935 }
1936
1937 // Iterators
1938 child_range children() {
1939 return child_range(child_iterator(), child_iterator());
1940 }
1941 const_child_range children() const {
1942 return const_child_range(const_child_iterator(), const_child_iterator());
1943 }
1944};
1945
1946enum class PredefinedIdentKind {
1947 Func,
1948 Function,
1949 LFunction, // Same as Function, but as wide string.
1950 FuncDName,
1951 FuncSig,
1952 LFuncSig, // Same as FuncSig, but as wide string
1953 PrettyFunction,
1954 /// The same as PrettyFunction, except that the
1955 /// 'virtual' keyword is omitted for virtual member functions.
1956 PrettyFunctionNoVirtual
1957};
1958
1959/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1960class PredefinedExpr final
1961 : public Expr,
1962 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1963 friend class ASTStmtReader;
1964 friend TrailingObjects;
1965
1966 // PredefinedExpr is optionally followed by a single trailing
1967 // "Stmt *" for the predefined identifier. It is present if and only if
1968 // hasFunctionName() is true and is always a "StringLiteral *".
1969
1970 PredefinedExpr(SourceLocation L, QualType FNTy, PredefinedIdentKind IK,
1971 bool IsTransparent, StringLiteral *SL);
1972
1973 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1974
1975 /// True if this PredefinedExpr has storage for a function name.
1976 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
1977
1978 void setFunctionName(StringLiteral *SL) {
1979 assert(hasFunctionName() &&
1980 "This PredefinedExpr has no storage for a function name!");
1981 *getTrailingObjects<Stmt *>() = SL;
1982 }
1983
1984public:
1985 /// Create a PredefinedExpr.
1986 ///
1987 /// If IsTransparent, the PredefinedExpr is transparently handled as a
1988 /// StringLiteral.
1989 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
1990 QualType FNTy, PredefinedIdentKind IK,
1991 bool IsTransparent, StringLiteral *SL);
1992
1993 /// Create an empty PredefinedExpr.
1994 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
1995 bool HasFunctionName);
1996
1997 PredefinedIdentKind getIdentKind() const {
1998 return static_cast<PredefinedIdentKind>(PredefinedExprBits.Kind);
1999 }
2000
2001 bool isTransparent() const { return PredefinedExprBits.IsTransparent; }
2002
2003 SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
2004 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
2005
2006 StringLiteral *getFunctionName() {
2007 return hasFunctionName()
2008 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2009 : nullptr;
2010 }
2011
2012 const StringLiteral *getFunctionName() const {
2013 return hasFunctionName()
2014 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2015 : nullptr;
2016 }
2017
2018 static StringRef getIdentKindName(PredefinedIdentKind IK);
2019 StringRef getIdentKindName() const {
2020 return getIdentKindName(IK: getIdentKind());
2021 }
2022
2023 static std::string ComputeName(PredefinedIdentKind IK,
2024 const Decl *CurrentDecl);
2025
2026 SourceLocation getBeginLoc() const { return getLocation(); }
2027 SourceLocation getEndLoc() const { return getLocation(); }
2028
2029 static bool classof(const Stmt *T) {
2030 return T->getStmtClass() == PredefinedExprClass;
2031 }
2032
2033 // Iterators
2034 child_range children() {
2035 return child_range(getTrailingObjects<Stmt *>(),
2036 getTrailingObjects<Stmt *>() + hasFunctionName());
2037 }
2038
2039 const_child_range children() const {
2040 return const_child_range(getTrailingObjects<Stmt *>(),
2041 getTrailingObjects<Stmt *>() + hasFunctionName());
2042 }
2043};
2044
2045// This represents a use of the __builtin_sycl_unique_stable_name, which takes a
2046// type-id, and at CodeGen time emits a unique string representation of the
2047// type in a way that permits us to properly encode information about the SYCL
2048// kernels.
2049class SYCLUniqueStableNameExpr final : public Expr {
2050 friend class ASTStmtReader;
2051 SourceLocation OpLoc, LParen, RParen;
2052 TypeSourceInfo *TypeInfo;
2053
2054 SYCLUniqueStableNameExpr(EmptyShell Empty, QualType ResultTy);
2055 SYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen,
2056 SourceLocation RParen, QualType ResultTy,
2057 TypeSourceInfo *TSI);
2058
2059 void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; }
2060
2061 void setLocation(SourceLocation L) { OpLoc = L; }
2062 void setLParenLocation(SourceLocation L) { LParen = L; }
2063 void setRParenLocation(SourceLocation L) { RParen = L; }
2064
2065public:
2066 TypeSourceInfo *getTypeSourceInfo() { return TypeInfo; }
2067
2068 const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; }
2069
2070 static SYCLUniqueStableNameExpr *
2071 Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen,
2072 SourceLocation RParen, TypeSourceInfo *TSI);
2073
2074 static SYCLUniqueStableNameExpr *CreateEmpty(const ASTContext &Ctx);
2075
2076 SourceLocation getBeginLoc() const { return getLocation(); }
2077 SourceLocation getEndLoc() const { return RParen; }
2078 SourceLocation getLocation() const { return OpLoc; }
2079 SourceLocation getLParenLocation() const { return LParen; }
2080 SourceLocation getRParenLocation() const { return RParen; }
2081
2082 static bool classof(const Stmt *T) {
2083 return T->getStmtClass() == SYCLUniqueStableNameExprClass;
2084 }
2085
2086 // Iterators
2087 child_range children() {
2088 return child_range(child_iterator(), child_iterator());
2089 }
2090
2091 const_child_range children() const {
2092 return const_child_range(const_child_iterator(), const_child_iterator());
2093 }
2094
2095 // Convenience function to generate the name of the currently stored type.
2096 std::string ComputeName(ASTContext &Context) const;
2097
2098 // Get the generated name of the type. Note that this only works after all
2099 // kernels have been instantiated.
2100 static std::string ComputeName(ASTContext &Context, QualType Ty);
2101};
2102
2103/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
2104/// AST node is only formed if full location information is requested.
2105class ParenExpr : public Expr {
2106 SourceLocation L, R;
2107 Stmt *Val;
2108public:
2109 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
2110 : Expr(ParenExprClass, val->getType(), val->getValueKind(),
2111 val->getObjectKind()),
2112 L(l), R(r), Val(val) {
2113 setDependence(computeDependence(E: this));
2114 }
2115
2116 /// Construct an empty parenthesized expression.
2117 explicit ParenExpr(EmptyShell Empty)
2118 : Expr(ParenExprClass, Empty) { }
2119
2120 const Expr *getSubExpr() const { return cast<Expr>(Val); }
2121 Expr *getSubExpr() { return cast<Expr>(Val); }
2122 void setSubExpr(Expr *E) { Val = E; }
2123
2124 SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
2125 SourceLocation getEndLoc() const LLVM_READONLY { return R; }
2126
2127 /// Get the location of the left parentheses '('.
2128 SourceLocation getLParen() const { return L; }
2129 void setLParen(SourceLocation Loc) { L = Loc; }
2130
2131 /// Get the location of the right parentheses ')'.
2132 SourceLocation getRParen() const { return R; }
2133 void setRParen(SourceLocation Loc) { R = Loc; }
2134
2135 static bool classof(const Stmt *T) {
2136 return T->getStmtClass() == ParenExprClass;
2137 }
2138
2139 // Iterators
2140 child_range children() { return child_range(&Val, &Val+1); }
2141 const_child_range children() const {
2142 return const_child_range(&Val, &Val + 1);
2143 }
2144};
2145
2146/// UnaryOperator - This represents the unary-expression's (except sizeof and
2147/// alignof), the postinc/postdec operators from postfix-expression, and various
2148/// extensions.
2149///
2150/// Notes on various nodes:
2151///
2152/// Real/Imag - These return the real/imag part of a complex operand. If
2153/// applied to a non-complex value, the former returns its operand and the
2154/// later returns zero in the type of the operand.
2155///
2156class UnaryOperator final
2157 : public Expr,
2158 private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
2159 Stmt *Val;
2160
2161 size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
2162 return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
2163 }
2164
2165 FPOptionsOverride &getTrailingFPFeatures() {
2166 assert(UnaryOperatorBits.HasFPFeatures);
2167 return *getTrailingObjects<FPOptionsOverride>();
2168 }
2169
2170 const FPOptionsOverride &getTrailingFPFeatures() const {
2171 assert(UnaryOperatorBits.HasFPFeatures);
2172 return *getTrailingObjects<FPOptionsOverride>();
2173 }
2174
2175public:
2176 typedef UnaryOperatorKind Opcode;
2177
2178protected:
2179 UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
2180 ExprValueKind VK, ExprObjectKind OK, SourceLocation l,
2181 bool CanOverflow, FPOptionsOverride FPFeatures);
2182
2183 /// Build an empty unary operator.
2184 explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
2185 : Expr(UnaryOperatorClass, Empty) {
2186 UnaryOperatorBits.Opc = UO_AddrOf;
2187 UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
2188 }
2189
2190public:
2191 static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
2192
2193 static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
2194 QualType type, ExprValueKind VK,
2195 ExprObjectKind OK, SourceLocation l,
2196 bool CanOverflow, FPOptionsOverride FPFeatures);
2197
2198 Opcode getOpcode() const {
2199 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2200 }
2201 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2202
2203 Expr *getSubExpr() const { return cast<Expr>(Val); }
2204 void setSubExpr(Expr *E) { Val = E; }
2205
2206 /// getOperatorLoc - Return the location of the operator.
2207 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
2208 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2209
2210 /// Returns true if the unary operator can cause an overflow. For instance,
2211 /// signed int i = INT_MAX; i++;
2212 /// signed char c = CHAR_MAX; c++;
2213 /// Due to integer promotions, c++ is promoted to an int before the postfix
2214 /// increment, and the result is an int that cannot overflow. However, i++
2215 /// can overflow.
2216 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
2217 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2218
2219 /// Get the FP contractability status of this operator. Only meaningful for
2220 /// operations on floating point types.
2221 bool isFPContractableWithinStatement(const LangOptions &LO) const {
2222 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
2223 }
2224
2225 /// Get the FENV_ACCESS status of this operator. Only meaningful for
2226 /// operations on floating point types.
2227 bool isFEnvAccessOn(const LangOptions &LO) const {
2228 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
2229 }
2230
2231 /// isPostfix - Return true if this is a postfix operation, like x++.
2232 static bool isPostfix(Opcode Op) {
2233 return Op == UO_PostInc || Op == UO_PostDec;
2234 }
2235
2236 /// isPrefix - Return true if this is a prefix operation, like --x.
2237 static bool isPrefix(Opcode Op) {
2238 return Op == UO_PreInc || Op == UO_PreDec;
2239 }
2240
2241 bool isPrefix() const { return isPrefix(Op: getOpcode()); }
2242 bool isPostfix() const { return isPostfix(Op: getOpcode()); }
2243
2244 static bool isIncrementOp(Opcode Op) {
2245 return Op == UO_PreInc || Op == UO_PostInc;
2246 }
2247 bool isIncrementOp() const {
2248 return isIncrementOp(Op: getOpcode());
2249 }
2250
2251 static bool isDecrementOp(Opcode Op) {
2252 return Op == UO_PreDec || Op == UO_PostDec;
2253 }
2254 bool isDecrementOp() const {
2255 return isDecrementOp(Op: getOpcode());
2256 }
2257
2258 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
2259 bool isIncrementDecrementOp() const {
2260 return isIncrementDecrementOp(Op: getOpcode());
2261 }
2262
2263 static bool isArithmeticOp(Opcode Op) {
2264 return Op >= UO_Plus && Op <= UO_LNot;
2265 }
2266 bool isArithmeticOp() const { return isArithmeticOp(Op: getOpcode()); }
2267
2268 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2269 /// corresponds to, e.g. "sizeof" or "[pre]++"
2270 static StringRef getOpcodeStr(Opcode Op);
2271
2272 /// Retrieve the unary opcode that corresponds to the given
2273 /// overloaded operator.
2274 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2275
2276 /// Retrieve the overloaded operator kind that corresponds to
2277 /// the given unary opcode.
2278 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2279
2280 SourceLocation getBeginLoc() const LLVM_READONLY {
2281 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2282 }
2283 SourceLocation getEndLoc() const LLVM_READONLY {
2284 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2285 }
2286 SourceLocation getExprLoc() const { return getOperatorLoc(); }
2287
2288 static bool classof(const Stmt *T) {
2289 return T->getStmtClass() == UnaryOperatorClass;
2290 }
2291
2292 // Iterators
2293 child_range children() { return child_range(&Val, &Val+1); }
2294 const_child_range children() const {
2295 return const_child_range(&Val, &Val + 1);
2296 }
2297
2298 /// Is FPFeatures in Trailing Storage?
2299 bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
2300
2301 /// Get FPFeatures from trailing storage.
2302 FPOptionsOverride getStoredFPFeatures() const {
2303 return getTrailingFPFeatures();
2304 }
2305
2306protected:
2307 /// Set FPFeatures in trailing storage, used by Serialization & ASTImporter.
2308 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
2309
2310public:
2311 /// Get the FP features status of this operator. Only meaningful for
2312 /// operations on floating point types.
2313 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
2314 if (UnaryOperatorBits.HasFPFeatures)
2315 return getStoredFPFeatures().applyOverrides(LO);
2316 return FPOptions::defaultWithoutTrailingStorage(LO);
2317 }
2318 FPOptionsOverride getFPOptionsOverride() const {
2319 if (UnaryOperatorBits.HasFPFeatures)
2320 return getStoredFPFeatures();
2321 return FPOptionsOverride();
2322 }
2323
2324 friend TrailingObjects;
2325 friend class ASTNodeImporter;
2326 friend class ASTReader;
2327 friend class ASTStmtReader;
2328 friend class ASTStmtWriter;
2329};
2330
2331/// Helper class for OffsetOfExpr.
2332
2333// __builtin_offsetof(type, identifier(.identifier|[expr])*)
2334class OffsetOfNode {
2335public:
2336 /// The kind of offsetof node we have.
2337 enum Kind {
2338 /// An index into an array.
2339 Array = 0x00,
2340 /// A field.
2341 Field = 0x01,
2342 /// A field in a dependent type, known only by its name.
2343 Identifier = 0x02,
2344 /// An implicit indirection through a C++ base class, when the
2345 /// field found is in a base class.
2346 Base = 0x03
2347 };
2348
2349private:
2350 enum { MaskBits = 2, Mask = 0x03 };
2351
2352 /// The source range that covers this part of the designator.
2353 SourceRange Range;
2354
2355 /// The data describing the designator, which comes in three
2356 /// different forms, depending on the lower two bits.
2357 /// - An unsigned index into the array of Expr*'s stored after this node
2358 /// in memory, for [constant-expression] designators.
2359 /// - A FieldDecl*, for references to a known field.
2360 /// - An IdentifierInfo*, for references to a field with a given name
2361 /// when the class type is dependent.
2362 /// - A CXXBaseSpecifier*, for references that look at a field in a
2363 /// base class.
2364 uintptr_t Data;
2365
2366public:
2367 /// Create an offsetof node that refers to an array element.
2368 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2369 SourceLocation RBracketLoc)
2370 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2371
2372 /// Create an offsetof node that refers to a field.
2373 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2374 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2375 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2376
2377 /// Create an offsetof node that refers to an identifier.
2378 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2379 SourceLocation NameLoc)
2380 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2381 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2382
2383 /// Create an offsetof node that refers into a C++ base class.
2384 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2385 : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2386
2387 /// Determine what kind of offsetof node this is.
2388 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2389
2390 /// For an array element node, returns the index into the array
2391 /// of expressions.
2392 unsigned getArrayExprIndex() const {
2393 assert(getKind() == Array);
2394 return Data >> 2;
2395 }
2396
2397 /// For a field offsetof node, returns the field.
2398 FieldDecl *getField() const {
2399 assert(getKind() == Field);
2400 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2401 }
2402
2403 /// For a field or identifier offsetof node, returns the name of
2404 /// the field.
2405 IdentifierInfo *getFieldName() const;
2406
2407 /// For a base class node, returns the base specifier.
2408 CXXBaseSpecifier *getBase() const {
2409 assert(getKind() == Base);
2410 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2411 }
2412
2413 /// Retrieve the source range that covers this offsetof node.
2414 ///
2415 /// For an array element node, the source range contains the locations of
2416 /// the square brackets. For a field or identifier node, the source range
2417 /// contains the location of the period (if there is one) and the
2418 /// identifier.
2419 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
2420 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
2421 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2422};
2423
2424/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2425/// offsetof(record-type, member-designator). For example, given:
2426/// @code
2427/// struct S {
2428/// float f;
2429/// double d;
2430/// };
2431/// struct T {
2432/// int i;
2433/// struct S s[10];
2434/// };
2435/// @endcode
2436/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2437
2438class OffsetOfExpr final
2439 : public Expr,
2440 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2441 SourceLocation OperatorLoc, RParenLoc;
2442 // Base type;
2443 TypeSourceInfo *TSInfo;
2444 // Number of sub-components (i.e. instances of OffsetOfNode).
2445 unsigned NumComps;
2446 // Number of sub-expressions (i.e. array subscript expressions).
2447 unsigned NumExprs;
2448
2449 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2450 return NumComps;
2451 }
2452
2453 OffsetOfExpr(const ASTContext &C, QualType type,
2454 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2455 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2456 SourceLocation RParenLoc);
2457
2458 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2459 : Expr(OffsetOfExprClass, EmptyShell()),
2460 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2461
2462public:
2463
2464 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2465 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2466 ArrayRef<OffsetOfNode> comps,
2467 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2468
2469 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2470 unsigned NumComps, unsigned NumExprs);
2471
2472 /// getOperatorLoc - Return the location of the operator.
2473 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2474 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2475
2476 /// Return the location of the right parentheses.
2477 SourceLocation getRParenLoc() const { return RParenLoc; }
2478 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2479
2480 TypeSourceInfo *getTypeSourceInfo() const {
2481 return TSInfo;
2482 }
2483 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2484 TSInfo = tsi;
2485 }
2486
2487 const OffsetOfNode &getComponent(unsigned Idx) const {
2488 assert(Idx < NumComps && "Subscript out of range");
2489 return getTrailingObjects<OffsetOfNode>()[Idx];
2490 }
2491
2492 void setComponent(unsigned Idx, OffsetOfNode ON) {
2493 assert(Idx < NumComps && "Subscript out of range");
2494 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2495 }
2496
2497 unsigned getNumComponents() const {
2498 return NumComps;
2499 }
2500
2501 Expr* getIndexExpr(unsigned Idx) {
2502 assert(Idx < NumExprs && "Subscript out of range");
2503 return getTrailingObjects<Expr *>()[Idx];
2504 }
2505
2506 const Expr *getIndexExpr(unsigned Idx) const {
2507 assert(Idx < NumExprs && "Subscript out of range");
2508 return getTrailingObjects<Expr *>()[Idx];
2509 }
2510
2511 void setIndexExpr(unsigned Idx, Expr* E) {
2512 assert(Idx < NumComps && "Subscript out of range");
2513 getTrailingObjects<Expr *>()[Idx] = E;
2514 }
2515
2516 unsigned getNumExpressions() const {
2517 return NumExprs;
2518 }
2519
2520 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
2521 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2522
2523 static bool classof(const Stmt *T) {
2524 return T->getStmtClass() == OffsetOfExprClass;
2525 }
2526
2527 // Iterators
2528 child_range children() {
2529 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2530 return child_range(begin, begin + NumExprs);
2531 }
2532 const_child_range children() const {
2533 Stmt *const *begin =
2534 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2535 return const_child_range(begin, begin + NumExprs);
2536 }
2537 friend TrailingObjects;
2538};
2539
2540/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2541/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2542/// vec_step (OpenCL 1.1 6.11.12).
2543class UnaryExprOrTypeTraitExpr : public Expr {
2544 union {
2545 TypeSourceInfo *Ty;
2546 Stmt *Ex;
2547 } Argument;
2548 SourceLocation OpLoc, RParenLoc;
2549
2550public:
2551 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2552 QualType resultType, SourceLocation op,
2553 SourceLocation rp)
2554 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue,
2555 OK_Ordinary),
2556 OpLoc(op), RParenLoc(rp) {
2557 assert(ExprKind <= UETT_Last && "invalid enum value!");
2558 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2559 assert(static_cast<unsigned>(ExprKind) ==
2560 UnaryExprOrTypeTraitExprBits.Kind &&
2561 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2562 UnaryExprOrTypeTraitExprBits.IsType = true;
2563 Argument.Ty = TInfo;
2564 setDependence(computeDependence(E: this));
2565 }
2566
2567 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2568 QualType resultType, SourceLocation op,
2569 SourceLocation rp);
2570
2571 /// Construct an empty sizeof/alignof expression.
2572 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2573 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2574
2575 UnaryExprOrTypeTrait getKind() const {
2576 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2577 }
2578 void setKind(UnaryExprOrTypeTrait K) {
2579 assert(K <= UETT_Last && "invalid enum value!");
2580 UnaryExprOrTypeTraitExprBits.Kind = K;
2581 assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
2582 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2583 }
2584
2585 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2586 QualType getArgumentType() const {
2587 return getArgumentTypeInfo()->getType();
2588 }
2589 TypeSourceInfo *getArgumentTypeInfo() const {
2590 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2591 return Argument.Ty;
2592 }
2593 Expr *getArgumentExpr() {
2594 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2595 return static_cast<Expr*>(Argument.Ex);
2596 }
2597 const Expr *getArgumentExpr() const {
2598 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2599 }
2600
2601 void setArgument(Expr *E) {
2602 Argument.Ex = E;
2603 UnaryExprOrTypeTraitExprBits.IsType = false;
2604 }
2605 void setArgument(TypeSourceInfo *TInfo) {
2606 Argument.Ty = TInfo;
2607 UnaryExprOrTypeTraitExprBits.IsType = true;
2608 }
2609
2610 /// Gets the argument type, or the type of the argument expression, whichever
2611 /// is appropriate.
2612 QualType getTypeOfArgument() const {
2613 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2614 }
2615
2616 SourceLocation getOperatorLoc() const { return OpLoc; }
2617 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2618
2619 SourceLocation getRParenLoc() const { return RParenLoc; }
2620 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2621
2622 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
2623 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2624
2625 static bool classof(const Stmt *T) {
2626 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2627 }
2628
2629 // Iterators
2630 child_range children();
2631 const_child_range children() const;
2632};
2633
2634//===----------------------------------------------------------------------===//
2635// Postfix Operators.
2636//===----------------------------------------------------------------------===//
2637
2638/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2639class ArraySubscriptExpr : public Expr {
2640 enum { LHS, RHS, END_EXPR };
2641 Stmt *SubExprs[END_EXPR];
2642
2643 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2644
2645public:
2646 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK,
2647 ExprObjectKind OK, SourceLocation rbracketloc)
2648 : Expr(ArraySubscriptExprClass, t, VK, OK) {
2649 SubExprs[LHS] = lhs;
2650 SubExprs[RHS] = rhs;
2651 ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
2652 setDependence(computeDependence(E: this));
2653 }
2654
2655 /// Create an empty array subscript expression.
2656 explicit ArraySubscriptExpr(EmptyShell Shell)
2657 : Expr(ArraySubscriptExprClass, Shell) { }
2658
2659 /// An array access can be written A[4] or 4[A] (both are equivalent).
2660 /// - getBase() and getIdx() always present the normalized view: A[4].
2661 /// In this case getBase() returns "A" and getIdx() returns "4".
2662 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2663 /// 4[A] getLHS() returns "4".
2664 /// Note: Because vector element access is also written A[4] we must
2665 /// predicate the format conversion in getBase and getIdx only on the
2666 /// the type of the RHS, as it is possible for the LHS to be a vector of
2667 /// integer type
2668 Expr *getLHS() { return cast<Expr>(Val: SubExprs[LHS]); }
2669 const Expr *getLHS() const { return cast<Expr>(Val: SubExprs[LHS]); }
2670 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2671
2672 Expr *getRHS() { return cast<Expr>(Val: SubExprs[RHS]); }
2673 const Expr *getRHS() const { return cast<Expr>(Val: SubExprs[RHS]); }
2674 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2675
2676 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
2677 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2678
2679 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
2680 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2681
2682 SourceLocation getBeginLoc() const LLVM_READONLY {
2683 return getLHS()->getBeginLoc();
2684 }
2685 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2686
2687 SourceLocation getRBracketLoc() const {
2688 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2689 }
2690 void setRBracketLoc(SourceLocation L) {
2691 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2692 }
2693
2694 SourceLocation getExprLoc() const LLVM_READONLY {
2695 return getBase()->getExprLoc();
2696 }
2697
2698 static bool classof(const Stmt *T) {
2699 return T->getStmtClass() == ArraySubscriptExprClass;
2700 }
2701
2702 // Iterators
2703 child_range children() {
2704 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2705 }
2706 const_child_range children() const {
2707 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2708 }
2709};
2710
2711/// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
2712/// extension.
2713/// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
2714/// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
2715/// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
2716/// exist during the initial construction of the AST.
2717class MatrixSubscriptExpr : public Expr {
2718 enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
2719 Stmt *SubExprs[END_EXPR];
2720
2721public:
2722 MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
2723 SourceLocation RBracketLoc)
2724 : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
2725 OK_MatrixComponent) {
2726 SubExprs[BASE] = Base;
2727 SubExprs[ROW_IDX] = RowIdx;
2728 SubExprs[COLUMN_IDX] = ColumnIdx;
2729 ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
2730 setDependence(computeDependence(E: this));
2731 }
2732
2733 /// Create an empty matrix subscript expression.
2734 explicit MatrixSubscriptExpr(EmptyShell Shell)
2735 : Expr(MatrixSubscriptExprClass, Shell) {}
2736
2737 bool isIncomplete() const {
2738 bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
2739 assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
2740 "expressions without column index must be marked as incomplete");
2741 return IsIncomplete;
2742 }
2743 Expr *getBase() { return cast<Expr>(Val: SubExprs[BASE]); }
2744 const Expr *getBase() const { return cast<Expr>(Val: SubExprs[BASE]); }
2745 void setBase(Expr *E) { SubExprs[BASE] = E; }
2746
2747 Expr *getRowIdx() { return cast<Expr>(Val: SubExprs[ROW_IDX]); }
2748 const Expr *getRowIdx() const { return cast<Expr>(Val: SubExprs[ROW_IDX]); }
2749 void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
2750
2751 Expr *getColumnIdx() { return cast_or_null<Expr>(Val: SubExprs[COLUMN_IDX]); }
2752 const Expr *getColumnIdx() const {
2753 assert(!isIncomplete() &&
2754 "cannot get the column index of an incomplete expression");
2755 return cast<Expr>(Val: SubExprs[COLUMN_IDX]);
2756 }
2757 void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
2758
2759 SourceLocation getBeginLoc() const LLVM_READONLY {
2760 return getBase()->getBeginLoc();
2761 }
2762
2763 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2764
2765 SourceLocation getExprLoc() const LLVM_READONLY {
2766 return getBase()->getExprLoc();
2767 }
2768
2769 SourceLocation getRBracketLoc() const {
2770 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2771 }
2772 void setRBracketLoc(SourceLocation L) {
2773 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2774 }
2775
2776 static bool classof(const Stmt *T) {
2777 return T->getStmtClass() == MatrixSubscriptExprClass;
2778 }
2779
2780 // Iterators
2781 child_range children() {
2782 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2783 }
2784 const_child_range children() const {
2785 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2786 }
2787};
2788
2789/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2790/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2791/// while its subclasses may represent alternative syntax that (semantically)
2792/// results in a function call. For example, CXXOperatorCallExpr is
2793/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2794/// "str1 + str2" to resolve to a function call.
2795class CallExpr : public Expr {
2796 enum { FN = 0, PREARGS_START = 1 };
2797
2798 /// The number of arguments in the call expression.
2799 unsigned NumArgs;
2800
2801 /// The location of the right parentheses. This has a different meaning for
2802 /// the derived classes of CallExpr.
2803 SourceLocation RParenLoc;
2804
2805 // CallExpr store some data in trailing objects. However since CallExpr
2806 // is used a base of other expression classes we cannot use
2807 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2808 // and casts.
2809 //
2810 // The trailing objects are in order:
2811 //
2812 // * A single "Stmt *" for the callee expression.
2813 //
2814 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2815 //
2816 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2817 //
2818 // * An optional of type FPOptionsOverride.
2819 //
2820 // Note that we store the offset in bytes from the this pointer to the start
2821 // of the trailing objects. It would be perfectly possible to compute it
2822 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2823 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2824 // compute this once and then load the offset from the bit-fields of Stmt,
2825 // instead of re-computing the offset each time the trailing objects are
2826 // accessed.
2827
2828 /// Return a pointer to the start of the trailing array of "Stmt *".
2829 Stmt **getTrailingStmts() {
2830 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2831 CallExprBits.OffsetToTrailingObjects);
2832 }
2833 Stmt *const *getTrailingStmts() const {
2834 return const_cast<CallExpr *>(this)->getTrailingStmts();
2835 }
2836
2837 /// Map a statement class to the appropriate offset in bytes from the
2838 /// this pointer to the trailing objects.
2839 static unsigned offsetToTrailingObjects(StmtClass SC);
2840
2841 unsigned getSizeOfTrailingStmts() const {
2842 return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
2843 }
2844
2845 size_t getOffsetOfTrailingFPFeatures() const {
2846 assert(hasStoredFPFeatures());
2847 return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
2848 }
2849
2850public:
2851 enum class ADLCallKind : bool { NotADL, UsesADL };
2852 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2853 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2854
2855protected:
2856 /// Build a call expression, assuming that appropriate storage has been
2857 /// allocated for the trailing objects.
2858 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2859 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2860 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
2861 unsigned MinNumArgs, ADLCallKind UsesADL);
2862
2863 /// Build an empty call expression, for deserialization.
2864 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2865 bool hasFPFeatures, EmptyShell Empty);
2866
2867 /// Return the size in bytes needed for the trailing objects.
2868 /// Used by the derived classes to allocate the right amount of storage.
2869 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
2870 bool HasFPFeatures) {
2871 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
2872 HasFPFeatures * sizeof(FPOptionsOverride);
2873 }
2874
2875 Stmt *getPreArg(unsigned I) {
2876 assert(I < getNumPreArgs() && "Prearg access out of range!");
2877 return getTrailingStmts()[PREARGS_START + I];
2878 }
2879 const Stmt *getPreArg(unsigned I) const {
2880 assert(I < getNumPreArgs() && "Prearg access out of range!");
2881 return getTrailingStmts()[PREARGS_START + I];
2882 }
2883 void setPreArg(unsigned I, Stmt *PreArg) {
2884 assert(I < getNumPreArgs() && "Prearg access out of range!");
2885 getTrailingStmts()[PREARGS_START + I] = PreArg;
2886 }
2887
2888 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2889
2890 /// Return a pointer to the trailing FPOptions
2891 FPOptionsOverride *getTrailingFPFeatures() {
2892 assert(hasStoredFPFeatures());
2893 return reinterpret_cast<FPOptionsOverride *>(
2894 reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
2895 getSizeOfTrailingStmts());
2896 }
2897 const FPOptionsOverride *getTrailingFPFeatures() const {
2898 assert(hasStoredFPFeatures());
2899 return reinterpret_cast<const FPOptionsOverride *>(
2900 reinterpret_cast<const char *>(this) +
2901 CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
2902 }
2903
2904public:
2905 /// Create a call expression.
2906 /// \param Fn The callee expression,
2907 /// \param Args The argument array,
2908 /// \param Ty The type of the call expression (which is *not* the return
2909 /// type in general),
2910 /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
2911 /// \param RParenLoc The location of the right parenthesis in the call
2912 /// expression.
2913 /// \param FPFeatures Floating-point features associated with the call,
2914 /// \param MinNumArgs Specifies the minimum number of arguments. The actual
2915 /// number of arguments will be the greater of Args.size()
2916 /// and MinNumArgs. This is used in a few places to allocate
2917 /// enough storage for the default arguments.
2918 /// \param UsesADL Specifies whether the callee was found through
2919 /// argument-dependent lookup.
2920 ///
2921 /// Note that you can use CreateTemporary if you need a temporary call
2922 /// expression on the stack.
2923 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2924 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2925 SourceLocation RParenLoc,
2926 FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
2927 ADLCallKind UsesADL = NotADL);
2928
2929 /// Create a temporary call expression with no arguments in the memory
2930 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2931 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2932 ///
2933 /// \code{.cpp}
2934 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
2935 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
2936 /// \endcode
2937 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2938 ExprValueKind VK, SourceLocation RParenLoc,
2939 ADLCallKind UsesADL = NotADL);
2940
2941 /// Create an empty call expression, for deserialization.
2942 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2943 bool HasFPFeatures, EmptyShell Empty);
2944
2945 Expr *getCallee() { return cast<Expr>(Val: getTrailingStmts()[FN]); }
2946 const Expr *getCallee() const { return cast<Expr>(Val: getTrailingStmts()[FN]); }
2947 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2948
2949 ADLCallKind getADLCallKind() const {
2950 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2951 }
2952 void setADLCallKind(ADLCallKind V = UsesADL) {
2953 CallExprBits.UsesADL = static_cast<bool>(V);
2954 }
2955 bool usesADL() const { return getADLCallKind() == UsesADL; }
2956
2957 bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
2958
2959 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
2960 const Decl *getCalleeDecl() const {
2961 return getCallee()->getReferencedDeclOfCallee();
2962 }
2963
2964 /// If the callee is a FunctionDecl, return it. Otherwise return null.
2965 FunctionDecl *getDirectCallee() {
2966 return dyn_cast_or_null<FunctionDecl>(Val: getCalleeDecl());
2967 }
2968 const FunctionDecl *getDirectCallee() const {
2969 return dyn_cast_or_null<FunctionDecl>(Val: getCalleeDecl());
2970 }
2971
2972 /// getNumArgs - Return the number of actual arguments to this call.
2973 unsigned getNumArgs() const { return NumArgs; }
2974
2975 /// Retrieve the call arguments.
2976 Expr **getArgs() {
2977 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
2978 getNumPreArgs());
2979 }
2980 const Expr *const *getArgs() const {
2981 return reinterpret_cast<const Expr *const *>(
2982 getTrailingStmts() + PREARGS_START + getNumPreArgs());
2983 }
2984
2985 /// getArg - Return the specified argument.
2986 Expr *getArg(unsigned Arg) {
2987 assert(Arg < getNumArgs() && "Arg access out of range!");
2988 return getArgs()[Arg];
2989 }
2990 const Expr *getArg(unsigned Arg) const {
2991 assert(Arg < getNumArgs() && "Arg access out of range!");
2992 return getArgs()[Arg];
2993 }
2994
2995 /// setArg - Set the specified argument.
2996 /// ! the dependence bits might be stale after calling this setter, it is
2997 /// *caller*'s responsibility to recompute them by calling
2998 /// computeDependence().
2999 void setArg(unsigned Arg, Expr *ArgExpr) {
3000 assert(Arg < getNumArgs() && "Arg access out of range!");
3001 getArgs()[Arg] = ArgExpr;
3002 }
3003
3004 /// Compute and set dependence bits.
3005 void computeDependence() {
3006 setDependence(clang::computeDependence(
3007 E: this, PreArgs: llvm::ArrayRef(
3008 reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START),
3009 getNumPreArgs())));
3010 }
3011
3012 /// Reduce the number of arguments in this call expression. This is used for
3013 /// example during error recovery to drop extra arguments. There is no way
3014 /// to perform the opposite because: 1.) We don't track how much storage
3015 /// we have for the argument array 2.) This would potentially require growing
3016 /// the argument array, something we cannot support since the arguments are
3017 /// stored in a trailing array.
3018 void shrinkNumArgs(unsigned NewNumArgs) {
3019 assert((NewNumArgs <= getNumArgs()) &&
3020 "shrinkNumArgs cannot increase the number of arguments!");
3021 NumArgs = NewNumArgs;
3022 }
3023
3024 /// Bluntly set a new number of arguments without doing any checks whatsoever.
3025 /// Only used during construction of a CallExpr in a few places in Sema.
3026 /// FIXME: Find a way to remove it.
3027 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
3028
3029 typedef ExprIterator arg_iterator;
3030 typedef ConstExprIterator const_arg_iterator;
3031 typedef llvm::iterator_range<arg_iterator> arg_range;
3032 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
3033
3034 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
3035 const_arg_range arguments() const {
3036 return const_arg_range(arg_begin(), arg_end());
3037 }
3038
3039 arg_iterator arg_begin() {
3040 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3041 }
3042 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
3043
3044 const_arg_iterator arg_begin() const {
3045 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3046 }
3047 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
3048
3049 /// This method provides fast access to all the subexpressions of
3050 /// a CallExpr without going through the slower virtual child_iterator
3051 /// interface. This provides efficient reverse iteration of the
3052 /// subexpressions. This is currently used for CFG construction.
3053 ArrayRef<Stmt *> getRawSubExprs() {
3054 return llvm::ArrayRef(getTrailingStmts(),
3055 PREARGS_START + getNumPreArgs() + getNumArgs());
3056 }
3057
3058 /// Get FPOptionsOverride from trailing storage.
3059 FPOptionsOverride getStoredFPFeatures() const {
3060 assert(hasStoredFPFeatures());
3061 return *getTrailingFPFeatures();
3062 }
3063 /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
3064 void setStoredFPFeatures(FPOptionsOverride F) {
3065 assert(hasStoredFPFeatures());
3066 *getTrailingFPFeatures() = F;
3067 }
3068
3069 /// Get the FP features status of this operator. Only meaningful for
3070 /// operations on floating point types.
3071 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3072 if (hasStoredFPFeatures())
3073 return getStoredFPFeatures().applyOverrides(LO);
3074 return FPOptions::defaultWithoutTrailingStorage(LO);
3075 }
3076
3077 FPOptionsOverride getFPFeatures() const {
3078 if (hasStoredFPFeatures())
3079 return getStoredFPFeatures();
3080 return FPOptionsOverride();
3081 }
3082
3083 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
3084 /// of the callee. If not, return 0.
3085 unsigned getBuiltinCallee() const;
3086
3087 /// Returns \c true if this is a call to a builtin which does not
3088 /// evaluate side-effects within its arguments.
3089 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
3090
3091 /// getCallReturnType - Get the return type of the call expr. This is not
3092 /// always the type of the expr itself, if the return type is a reference
3093 /// type.
3094 QualType getCallReturnType(const ASTContext &Ctx) const;
3095
3096 /// Returns the WarnUnusedResultAttr that is either declared on the called
3097 /// function, or its return type declaration.
3098 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
3099
3100 /// Returns true if this call expression should warn on unused results.
3101 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
3102 return getUnusedResultAttr(Ctx) != nullptr;
3103 }
3104
3105 SourceLocation getRParenLoc() const { return RParenLoc; }
3106 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3107
3108 SourceLocation getBeginLoc() const LLVM_READONLY;
3109 SourceLocation getEndLoc() const LLVM_READONLY;
3110
3111 /// Return true if this is a call to __assume() or __builtin_assume() with
3112 /// a non-value-dependent constant parameter evaluating as false.
3113 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
3114
3115 /// Used by Sema to implement MSVC-compatible delayed name lookup.
3116 /// (Usually Exprs themselves should set dependence).
3117 void markDependentForPostponedNameLookup() {
3118 setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
3119 }
3120
3121 bool isCallToStdMove() const;
3122
3123 static bool classof(const Stmt *T) {
3124 return T->getStmtClass() >= firstCallExprConstant &&
3125 T->getStmtClass() <= lastCallExprConstant;
3126 }
3127
3128 // Iterators
3129 child_range children() {
3130 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
3131 getNumPreArgs() + getNumArgs());
3132 }
3133
3134 const_child_range children() const {
3135 return const_child_range(getTrailingStmts(),
3136 getTrailingStmts() + PREARGS_START +
3137 getNumPreArgs() + getNumArgs());
3138 }
3139};
3140
3141/// Extra data stored in some MemberExpr objects.
3142struct MemberExprNameQualifier {
3143 /// The nested-name-specifier that qualifies the name, including
3144 /// source-location information.
3145 NestedNameSpecifierLoc QualifierLoc;
3146
3147 /// The DeclAccessPair through which the MemberDecl was found due to
3148 /// name qualifiers.
3149 DeclAccessPair FoundDecl;
3150};
3151
3152/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
3153///
3154class MemberExpr final
3155 : public Expr,
3156 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
3157 ASTTemplateKWAndArgsInfo,
3158 TemplateArgumentLoc> {
3159 friend class ASTReader;
3160 friend class ASTStmtReader;
3161 friend class ASTStmtWriter;
3162 friend TrailingObjects;
3163
3164 /// Base - the expression for the base pointer or structure references. In
3165 /// X.F, this is "X".
3166 Stmt *Base;
3167
3168 /// MemberDecl - This is the decl being referenced by the field/member name.
3169 /// In X.F, this is the decl referenced by F.
3170 ValueDecl *MemberDecl;
3171
3172 /// MemberDNLoc - Provides source/type location info for the
3173 /// declaration name embedded in MemberDecl.
3174 DeclarationNameLoc MemberDNLoc;
3175
3176 /// MemberLoc - This is the location of the member name.
3177 SourceLocation MemberLoc;
3178
3179 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
3180 return hasQualifierOrFoundDecl();
3181 }
3182
3183 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3184 return hasTemplateKWAndArgsInfo();
3185 }
3186
3187 bool hasQualifierOrFoundDecl() const {
3188 return MemberExprBits.HasQualifierOrFoundDecl;
3189 }
3190
3191 bool hasTemplateKWAndArgsInfo() const {
3192 return MemberExprBits.HasTemplateKWAndArgsInfo;
3193 }
3194
3195 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
3196 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
3197 QualType T, ExprValueKind VK, ExprObjectKind OK,
3198 NonOdrUseReason NOUR);
3199 MemberExpr(EmptyShell Empty)
3200 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
3201
3202public:
3203 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
3204 SourceLocation OperatorLoc,
3205 NestedNameSpecifierLoc QualifierLoc,
3206 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
3207 DeclAccessPair FoundDecl,
3208 DeclarationNameInfo MemberNameInfo,
3209 const TemplateArgumentListInfo *TemplateArgs,
3210 QualType T, ExprValueKind VK, ExprObjectKind OK,
3211 NonOdrUseReason NOUR);
3212
3213 /// Create an implicit MemberExpr, with no location, qualifier, template
3214 /// arguments, and so on. Suitable only for non-static member access.
3215 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
3216 bool IsArrow, ValueDecl *MemberDecl,
3217 QualType T, ExprValueKind VK,
3218 ExprObjectKind OK) {
3219 return Create(C, Base, IsArrow, OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(),
3220 TemplateKWLoc: SourceLocation(), MemberDecl,
3221 FoundDecl: DeclAccessPair::make(D: MemberDecl, AS: MemberDecl->getAccess()),
3222 MemberNameInfo: DeclarationNameInfo(), TemplateArgs: nullptr, T, VK, OK, NOUR: NOUR_None);
3223 }
3224
3225 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
3226 bool HasFoundDecl,
3227 bool HasTemplateKWAndArgsInfo,
3228 unsigned NumTemplateArgs);
3229
3230 void setBase(Expr *E) { Base = E; }
3231 Expr *getBase() const { return cast<Expr>(Val: Base); }
3232
3233 /// Retrieve the member declaration to which this expression refers.
3234 ///
3235 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
3236 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
3237 ValueDecl *getMemberDecl() const { return MemberDecl; }
3238 void setMemberDecl(ValueDecl *D);
3239
3240 /// Retrieves the declaration found by lookup.
3241 DeclAccessPair getFoundDecl() const {
3242 if (!hasQualifierOrFoundDecl())
3243 return DeclAccessPair::make(D: getMemberDecl(),
3244 AS: getMemberDecl()->getAccess());
3245 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
3246 }
3247
3248 /// Determines whether this member expression actually had
3249 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
3250 /// x->Base::foo.
3251 bool hasQualifier() const { return getQualifier() != nullptr; }
3252
3253 /// If the member name was qualified, retrieves the
3254 /// nested-name-specifier that precedes the member name, with source-location
3255 /// information.
3256 NestedNameSpecifierLoc getQualifierLoc() const {
3257 if (!hasQualifierOrFoundDecl())
3258 return NestedNameSpecifierLoc();
3259 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
3260 }
3261
3262 /// If the member name was qualified, retrieves the
3263 /// nested-name-specifier that precedes the member name. Otherwise, returns
3264 /// NULL.
3265 NestedNameSpecifier *getQualifier() const {
3266 return getQualifierLoc().getNestedNameSpecifier();
3267 }
3268
3269 /// Retrieve the location of the template keyword preceding
3270 /// the member name, if any.
3271 SourceLocation getTemplateKeywordLoc() const {
3272 if (!hasTemplateKWAndArgsInfo())
3273 return SourceLocation();
3274 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3275 }
3276
3277 /// Retrieve the location of the left angle bracket starting the
3278 /// explicit template argument list following the member name, if any.
3279 SourceLocation getLAngleLoc() const {
3280 if (!hasTemplateKWAndArgsInfo())
3281 return SourceLocation();
3282 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3283 }
3284
3285 /// Retrieve the location of the right angle bracket ending the
3286 /// explicit template argument list following the member name, if any.
3287 SourceLocation getRAngleLoc() const {
3288 if (!hasTemplateKWAndArgsInfo())
3289 return SourceLocation();
3290 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3291 }
3292
3293 /// Determines whether the member name was preceded by the template keyword.
3294 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3295
3296 /// Determines whether the member name was followed by an
3297 /// explicit template argument list.
3298 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3299
3300 /// Copies the template arguments (if present) into the given
3301 /// structure.
3302 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3303 if (hasExplicitTemplateArgs())
3304 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3305 getTrailingObjects<TemplateArgumentLoc>(), List);
3306 }
3307
3308 /// Retrieve the template arguments provided as part of this
3309 /// template-id.
3310 const TemplateArgumentLoc *getTemplateArgs() const {
3311 if (!hasExplicitTemplateArgs())
3312 return nullptr;
3313
3314 return getTrailingObjects<TemplateArgumentLoc>();
3315 }
3316
3317 /// Retrieve the number of template arguments provided as part of this
3318 /// template-id.
3319 unsigned getNumTemplateArgs() const {
3320 if (!hasExplicitTemplateArgs())
3321 return 0;
3322
3323 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3324 }
3325
3326 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3327 return {getTemplateArgs(), getNumTemplateArgs()};
3328 }
3329
3330 /// Retrieve the member declaration name info.
3331 DeclarationNameInfo getMemberNameInfo() const {
3332 return DeclarationNameInfo(MemberDecl->getDeclName(),
3333 MemberLoc, MemberDNLoc);
3334 }
3335
3336 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
3337
3338 bool isArrow() const { return MemberExprBits.IsArrow; }
3339 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
3340
3341 /// getMemberLoc - Return the location of the "member", in X->F, it is the
3342 /// location of 'F'.
3343 SourceLocation getMemberLoc() const { return MemberLoc; }
3344 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3345
3346 SourceLocation getBeginLoc() const LLVM_READONLY;
3347 SourceLocation getEndLoc() const LLVM_READONLY;
3348
3349 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
3350
3351 /// Determine whether the base of this explicit is implicit.
3352 bool isImplicitAccess() const {
3353 return getBase() && getBase()->isImplicitCXXThis();
3354 }
3355
3356 /// Returns true if this member expression refers to a method that
3357 /// was resolved from an overloaded set having size greater than 1.
3358 bool hadMultipleCandidates() const {
3359 return MemberExprBits.HadMultipleCandidates;
3360 }
3361 /// Sets the flag telling whether this expression refers to
3362 /// a method that was resolved from an overloaded set having size
3363 /// greater than 1.
3364 void setHadMultipleCandidates(bool V = true) {
3365 MemberExprBits.HadMultipleCandidates = V;
3366 }
3367
3368 /// Returns true if virtual dispatch is performed.
3369 /// If the member access is fully qualified, (i.e. X::f()), virtual
3370 /// dispatching is not performed. In -fapple-kext mode qualified
3371 /// calls to virtual method will still go through the vtable.
3372 bool performsVirtualDispatch(const LangOptions &LO) const {
3373 return LO.AppleKext || !hasQualifier();
3374 }
3375
3376 /// Is this expression a non-odr-use reference, and if so, why?
3377 /// This is only meaningful if the named member is a static member.
3378 NonOdrUseReason isNonOdrUse() const {
3379 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3380 }
3381
3382 static bool classof(const Stmt *T) {
3383 return T->getStmtClass() == MemberExprClass;
3384 }
3385
3386 // Iterators
3387 child_range children() { return child_range(&Base, &Base+1); }
3388 const_child_range children() const {
3389 return const_child_range(&Base, &Base + 1);
3390 }
3391};
3392
3393/// CompoundLiteralExpr - [C99 6.5.2.5]
3394///
3395class CompoundLiteralExpr : public Expr {
3396 /// LParenLoc - If non-null, this is the location of the left paren in a
3397 /// compound literal like "(int){4}". This can be null if this is a
3398 /// synthesized compound expression.
3399 SourceLocation LParenLoc;
3400
3401 /// The type as written. This can be an incomplete array type, in
3402 /// which case the actual expression type will be different.
3403 /// The int part of the pair stores whether this expr is file scope.
3404 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3405 Stmt *Init;
3406public:
3407 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3408 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3409 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
3410 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
3411 setDependence(computeDependence(E: this));
3412 }
3413
3414 /// Construct an empty compound literal.
3415 explicit CompoundLiteralExpr(EmptyShell Empty)
3416 : Expr(CompoundLiteralExprClass, Empty) { }
3417
3418 const Expr *getInitializer() const { return cast<Expr>(Val: Init); }
3419 Expr *getInitializer() { return cast<Expr>(Val: Init); }
3420 void setInitializer(Expr *E) { Init = E; }
3421
3422 bool isFileScope() const { return TInfoAndScope.getInt(); }
3423 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3424
3425 SourceLocation getLParenLoc() const { return LParenLoc; }
3426 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3427
3428 TypeSourceInfo *getTypeSourceInfo() const {
3429 return TInfoAndScope.getPointer();
3430 }
3431 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3432 TInfoAndScope.setPointer(tinfo);
3433 }
3434
3435 SourceLocation getBeginLoc() const LLVM_READONLY {
3436 // FIXME: Init should never be null.
3437 if (!Init)
3438 return SourceLocation();
3439 if (LParenLoc.isInvalid())
3440 return Init->getBeginLoc();
3441 return LParenLoc;
3442 }
3443 SourceLocation getEndLoc() const LLVM_READONLY {
3444 // FIXME: Init should never be null.
3445 if (!Init)
3446 return SourceLocation();
3447 return Init->getEndLoc();
3448 }
3449
3450 static bool classof(const Stmt *T) {
3451 return T->getStmtClass() == CompoundLiteralExprClass;
3452 }
3453
3454 // Iterators
3455 child_range children() { return child_range(&Init, &Init+1); }
3456 const_child_range children() const {
3457 return const_child_range(&Init, &Init + 1);
3458 }
3459};
3460
3461/// CastExpr - Base class for type casts, including both implicit
3462/// casts (ImplicitCastExpr) and explicit casts that have some
3463/// representation in the source code (ExplicitCastExpr's derived
3464/// classes).
3465class CastExpr : public Expr {
3466 Stmt *Op;
3467
3468 bool CastConsistency() const;
3469
3470 const CXXBaseSpecifier * const *path_buffer() const {
3471 return const_cast<CastExpr*>(this)->path_buffer();
3472 }
3473 CXXBaseSpecifier **path_buffer();
3474
3475 friend class ASTStmtReader;
3476
3477protected:
3478 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3479 Expr *op, unsigned BasePathSize, bool HasFPFeatures)
3480 : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
3481 CastExprBits.Kind = kind;
3482 CastExprBits.PartOfExplicitCast = false;
3483 CastExprBits.BasePathSize = BasePathSize;
3484 assert((CastExprBits.BasePathSize == BasePathSize) &&
3485 "BasePathSize overflow!");
3486 assert(CastConsistency());
3487 CastExprBits.HasFPFeatures = HasFPFeatures;
3488 }
3489
3490 /// Construct an empty cast.
3491 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
3492 bool HasFPFeatures)
3493 : Expr(SC, Empty) {
3494 CastExprBits.PartOfExplicitCast = false;
3495 CastExprBits.BasePathSize = BasePathSize;
3496 CastExprBits.HasFPFeatures = HasFPFeatures;
3497 assert((CastExprBits.BasePathSize == BasePathSize) &&
3498 "BasePathSize overflow!");
3499 }
3500
3501 /// Return a pointer to the trailing FPOptions.
3502 /// \pre hasStoredFPFeatures() == true
3503 FPOptionsOverride *getTrailingFPFeatures();
3504 const FPOptionsOverride *getTrailingFPFeatures() const {
3505 return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
3506 }
3507
3508public:
3509 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
3510 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3511
3512 static const char *getCastKindName(CastKind CK);
3513 const char *getCastKindName() const { return getCastKindName(CK: getCastKind()); }
3514
3515 Expr *getSubExpr() { return cast<Expr>(Val: Op); }
3516 const Expr *getSubExpr() const { return cast<Expr>(Val: Op); }
3517 void setSubExpr(Expr *E) { Op = E; }
3518
3519 /// Retrieve the cast subexpression as it was written in the source
3520 /// code, looking through any implicit casts or other intermediate nodes
3521 /// introduced by semantic analysis.
3522 Expr *getSubExprAsWritten();
3523 const Expr *getSubExprAsWritten() const {
3524 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3525 }
3526
3527 /// If this cast applies a user-defined conversion, retrieve the conversion
3528 /// function that it invokes.
3529 NamedDecl *getConversionFunction() const;
3530
3531 typedef CXXBaseSpecifier **path_iterator;
3532 typedef const CXXBaseSpecifier *const *path_const_iterator;
3533 bool path_empty() const { return path_size() == 0; }
3534 unsigned path_size() const { return CastExprBits.BasePathSize; }
3535 path_iterator path_begin() { return path_buffer(); }
3536 path_iterator path_end() { return path_buffer() + path_size(); }
3537 path_const_iterator path_begin() const { return path_buffer(); }
3538 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3539
3540 llvm::iterator_range<path_iterator> path() {
3541 return llvm::make_range(x: path_begin(), y: path_end());
3542 }
3543 llvm::iterator_range<path_const_iterator> path() const {
3544 return llvm::make_range(x: path_begin(), y: path_end());
3545 }
3546
3547 const FieldDecl *getTargetUnionField() const {
3548 assert(getCastKind() == CK_ToUnion);
3549 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
3550 }
3551
3552 bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
3553
3554 /// Get FPOptionsOverride from trailing storage.
3555 FPOptionsOverride getStoredFPFeatures() const {
3556 assert(hasStoredFPFeatures());
3557 return *getTrailingFPFeatures();
3558 }
3559
3560 /// Get the FP features status of this operation. Only meaningful for
3561 /// operations on floating point types.
3562 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3563 if (hasStoredFPFeatures())
3564 return getStoredFPFeatures().applyOverrides(LO);
3565 return FPOptions::defaultWithoutTrailingStorage(LO);
3566 }
3567
3568 FPOptionsOverride getFPFeatures() const {
3569 if (hasStoredFPFeatures())
3570 return getStoredFPFeatures();
3571 return FPOptionsOverride();
3572 }
3573
3574 /// Return
3575 // True : if this conversion changes the volatile-ness of a gl-value.
3576 // Qualification conversions on gl-values currently use CK_NoOp, but
3577 // it's important to recognize volatile-changing conversions in
3578 // clients code generation that normally eagerly peephole loads. Note
3579 // that the query is answering for this specific node; Sema may
3580 // produce multiple cast nodes for any particular conversion sequence.
3581 // False : Otherwise.
3582 bool changesVolatileQualification() const {
3583 return (isGLValue() && (getType().isVolatileQualified() !=
3584 getSubExpr()->getType().isVolatileQualified()));
3585 }
3586
3587 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3588 QualType opType);
3589 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3590 QualType opType);
3591
3592 static bool classof(const Stmt *T) {
3593 return T->getStmtClass() >= firstCastExprConstant &&
3594 T->getStmtClass() <= lastCastExprConstant;
3595 }
3596
3597 // Iterators
3598 child_range children() { return child_range(&Op, &Op+1); }
3599 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3600};
3601
3602/// ImplicitCastExpr - Allows us to explicitly represent implicit type
3603/// conversions, which have no direct representation in the original
3604/// source code. For example: converting T[]->T*, void f()->void
3605/// (*f)(), float->double, short->int, etc.
3606///
3607/// In C, implicit casts always produce rvalues. However, in C++, an
3608/// implicit cast whose result is being bound to a reference will be
3609/// an lvalue or xvalue. For example:
3610///
3611/// @code
3612/// class Base { };
3613/// class Derived : public Base { };
3614/// Derived &&ref();
3615/// void f(Derived d) {
3616/// Base& b = d; // initializer is an ImplicitCastExpr
3617/// // to an lvalue of type Base
3618/// Base&& r = ref(); // initializer is an ImplicitCastExpr
3619/// // to an xvalue of type Base
3620/// }
3621/// @endcode
3622class ImplicitCastExpr final
3623 : public CastExpr,
3624 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
3625 FPOptionsOverride> {
3626
3627 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3628 unsigned BasePathLength, FPOptionsOverride FPO,
3629 ExprValueKind VK)
3630 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
3631 FPO.requiresTrailingStorage()) {
3632 setDependence(computeDependence(E: this));
3633 if (hasStoredFPFeatures())
3634 *getTrailingFPFeatures() = FPO;
3635 }
3636
3637 /// Construct an empty implicit cast.
3638 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
3639 bool HasFPFeatures)
3640 : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
3641
3642 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3643 return path_size();
3644 }
3645
3646public:
3647 enum OnStack_t { OnStack };
3648 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3649 ExprValueKind VK, FPOptionsOverride FPO)
3650 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
3651 FPO.requiresTrailingStorage()) {
3652 if (hasStoredFPFeatures())
3653 *getTrailingFPFeatures() = FPO;
3654 }
3655
3656 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
3657 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3658 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3659 }
3660
3661 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3662 CastKind Kind, Expr *Operand,
3663 const CXXCastPath *BasePath,
3664 ExprValueKind Cat, FPOptionsOverride FPO);
3665
3666 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3667 unsigned PathSize, bool HasFPFeatures);
3668
3669 SourceLocation getBeginLoc() const LLVM_READONLY {
3670 return getSubExpr()->getBeginLoc();
3671 }
3672 SourceLocation getEndLoc() const LLVM_READONLY {
3673 return getSubExpr()->getEndLoc();
3674 }
3675
3676 static bool classof(const Stmt *T) {
3677 return T->getStmtClass() == ImplicitCastExprClass;
3678 }
3679
3680 friend TrailingObjects;
3681 friend class CastExpr;
3682};
3683
3684/// ExplicitCastExpr - An explicit cast written in the source
3685/// code.
3686///
3687/// This class is effectively an abstract class, because it provides
3688/// the basic representation of an explicitly-written cast without
3689/// specifying which kind of cast (C cast, functional cast, static
3690/// cast, etc.) was written; specific derived classes represent the
3691/// particular style of cast and its location information.
3692///
3693/// Unlike implicit casts, explicit cast nodes have two different
3694/// types: the type that was written into the source code, and the
3695/// actual type of the expression as determined by semantic
3696/// analysis. These types may differ slightly. For example, in C++ one
3697/// can cast to a reference type, which indicates that the resulting
3698/// expression will be an lvalue or xvalue. The reference type, however,
3699/// will not be used as the type of the expression.
3700class ExplicitCastExpr : public CastExpr {
3701 /// TInfo - Source type info for the (written) type
3702 /// this expression is casting to.
3703 TypeSourceInfo *TInfo;
3704
3705protected:
3706 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3707 CastKind kind, Expr *op, unsigned PathSize,
3708 bool HasFPFeatures, TypeSourceInfo *writtenTy)
3709 : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
3710 TInfo(writtenTy) {
3711 setDependence(computeDependence(E: this));
3712 }
3713
3714 /// Construct an empty explicit cast.
3715 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
3716 bool HasFPFeatures)
3717 : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
3718
3719public:
3720 /// getTypeInfoAsWritten - Returns the type source info for the type
3721 /// that this expression is casting to.
3722 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3723 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3724
3725 /// getTypeAsWritten - Returns the type that this expression is
3726 /// casting to, as written in the source code.
3727 QualType getTypeAsWritten() const { return TInfo->getType(); }
3728
3729 static bool classof(const Stmt *T) {
3730 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3731 T->getStmtClass() <= lastExplicitCastExprConstant;
3732 }
3733};
3734
3735/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3736/// cast in C++ (C++ [expr.cast]), which uses the syntax
3737/// (Type)expr. For example: @c (int)f.
3738class CStyleCastExpr final
3739 : public ExplicitCastExpr,
3740 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
3741 FPOptionsOverride> {
3742 SourceLocation LPLoc; // the location of the left paren
3743 SourceLocation RPLoc; // the location of the right paren
3744
3745 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3746 unsigned PathSize, FPOptionsOverride FPO,
3747 TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
3748 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3749 FPO.requiresTrailingStorage(), writtenTy),
3750 LPLoc(l), RPLoc(r) {
3751 if (hasStoredFPFeatures())
3752 *getTrailingFPFeatures() = FPO;
3753 }
3754
3755 /// Construct an empty C-style explicit cast.
3756 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
3757 bool HasFPFeatures)
3758 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
3759
3760 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3761 return path_size();
3762 }
3763
3764public:
3765 static CStyleCastExpr *
3766 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
3767 Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
3768 TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
3769
3770 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3771 unsigned PathSize, bool HasFPFeatures);
3772
3773 SourceLocation getLParenLoc() const { return LPLoc; }
3774 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3775
3776 SourceLocation getRParenLoc() const { return RPLoc; }
3777 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3778
3779 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
3780 SourceLocation getEndLoc() const LLVM_READONLY {
3781 return getSubExpr()->getEndLoc();
3782 }
3783
3784 static bool classof(const Stmt *T) {
3785 return T->getStmtClass() == CStyleCastExprClass;
3786 }
3787
3788 friend TrailingObjects;
3789 friend class CastExpr;
3790};
3791
3792/// A builtin binary operation expression such as "x + y" or "x <= y".
3793///
3794/// This expression node kind describes a builtin binary operation,
3795/// such as "x + y" for integer values "x" and "y". The operands will
3796/// already have been converted to appropriate types (e.g., by
3797/// performing promotions or conversions).
3798///
3799/// In C++, where operators may be overloaded, a different kind of
3800/// expression node (CXXOperatorCallExpr) is used to express the
3801/// invocation of an overloaded operator with operator syntax. Within
3802/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3803/// used to store an expression "x + y" depends on the subexpressions
3804/// for x and y. If neither x or y is type-dependent, and the "+"
3805/// operator resolves to a built-in operation, BinaryOperator will be
3806/// used to express the computation (x and y may still be
3807/// value-dependent). If either x or y is type-dependent, or if the
3808/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3809/// be used to express the computation.
3810class BinaryOperator : public Expr {
3811 enum { LHS, RHS, END_EXPR };
3812 Stmt *SubExprs[END_EXPR];
3813
3814public:
3815 typedef BinaryOperatorKind Opcode;
3816
3817protected:
3818 size_t offsetOfTrailingStorage() const;
3819
3820 /// Return a pointer to the trailing FPOptions
3821 FPOptionsOverride *getTrailingFPFeatures() {
3822 assert(BinaryOperatorBits.HasFPFeatures);
3823 return reinterpret_cast<FPOptionsOverride *>(
3824 reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
3825 }
3826 const FPOptionsOverride *getTrailingFPFeatures() const {
3827 assert(BinaryOperatorBits.HasFPFeatures);
3828 return reinterpret_cast<const FPOptionsOverride *>(
3829 reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
3830 }
3831
3832 /// Build a binary operator, assuming that appropriate storage has been
3833 /// allocated for the trailing objects when needed.
3834 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3835 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
3836 SourceLocation opLoc, FPOptionsOverride FPFeatures);
3837
3838 /// Construct an empty binary operator.
3839 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3840 BinaryOperatorBits.Opc = BO_Comma;
3841 }
3842
3843public:
3844 static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
3845
3846 static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
3847 Opcode opc, QualType ResTy, ExprValueKind VK,
3848 ExprObjectKind OK, SourceLocation opLoc,
3849 FPOptionsOverride FPFeatures);
3850 SourceLocation getExprLoc() const { return getOperatorLoc(); }
3851 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
3852 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
3853
3854 Opcode getOpcode() const {
3855 return static_cast<Opcode>(BinaryOperatorBits.Opc);
3856 }
3857 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3858
3859 Expr *getLHS() const { return cast<Expr>(Val: SubExprs[LHS]); }
3860 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3861 Expr *getRHS() const { return cast<Expr>(Val: SubExprs[RHS]); }
3862 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3863
3864 SourceLocation getBeginLoc() const LLVM_READONLY {
3865 return getLHS()->getBeginLoc();
3866 }
3867 SourceLocation getEndLoc() const LLVM_READONLY {
3868 return getRHS()->getEndLoc();
3869 }
3870
3871 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3872 /// corresponds to, e.g. "<<=".
3873 static StringRef getOpcodeStr(Opcode Op);
3874
3875 StringRef getOpcodeStr() const { return getOpcodeStr(Op: getOpcode()); }
3876
3877 /// Retrieve the binary opcode that corresponds to the given
3878 /// overloaded operator.
3879 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3880
3881 /// Retrieve the overloaded operator kind that corresponds to
3882 /// the given binary opcode.
3883 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3884
3885 /// predicates to categorize the respective opcodes.
3886 static bool isPtrMemOp(Opcode Opc) {
3887 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3888 }
3889 bool isPtrMemOp() const { return isPtrMemOp(Opc: getOpcode()); }
3890
3891 static bool isMultiplicativeOp(Opcode Opc) {
3892 return Opc >= BO_Mul && Opc <= BO_Rem;
3893 }
3894 bool isMultiplicativeOp() const { return isMultiplicativeOp(Opc: getOpcode()); }
3895 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3896 bool isAdditiveOp() const { return isAdditiveOp(Opc: getOpcode()); }
3897 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3898 bool isShiftOp() const { return isShiftOp(Opc: getOpcode()); }
3899
3900 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3901 bool isBitwiseOp() const { return isBitwiseOp(Opc: getOpcode()); }
3902
3903 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3904 bool isRelationalOp() const { return isRelationalOp(Opc: getOpcode()); }
3905
3906 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3907 bool isEqualityOp() const { return isEqualityOp(Opc: getOpcode()); }
3908
3909 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3910 bool isComparisonOp() const { return isComparisonOp(Opc: getOpcode()); }
3911
3912 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
3913 bool isCommaOp() const { return isCommaOp(Opc: getOpcode()); }
3914
3915 static Opcode negateComparisonOp(Opcode Opc) {
3916 switch (Opc) {
3917 default:
3918 llvm_unreachable("Not a comparison operator.");
3919 case BO_LT: return BO_GE;
3920 case BO_GT: return BO_LE;
3921 case BO_LE: return BO_GT;
3922 case BO_GE: return BO_LT;
3923 case BO_EQ: return BO_NE;
3924 case BO_NE: return BO_EQ;
3925 }
3926 }
3927
3928 static Opcode reverseComparisonOp(Opcode Opc) {
3929 switch (Opc) {
3930 default:
3931 llvm_unreachable("Not a comparison operator.");
3932 case BO_LT: return BO_GT;
3933 case BO_GT: return BO_LT;
3934 case BO_LE: return BO_GE;
3935 case BO_GE: return BO_LE;
3936 case BO_EQ:
3937 case BO_NE:
3938 return Opc;
3939 }
3940 }
3941
3942 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3943 bool isLogicalOp() const { return isLogicalOp(Opc: getOpcode()); }
3944
3945 static bool isAssignmentOp(Opcode Opc) {
3946 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3947 }
3948 bool isAssignmentOp() const { return isAssignmentOp(Opc: getOpcode()); }
3949
3950 static bool isCompoundAssignmentOp(Opcode Opc) {
3951 return Opc > BO_Assign && Opc <= BO_OrAssign;
3952 }
3953 bool isCompoundAssignmentOp() const {
3954 return isCompoundAssignmentOp(Opc: getOpcode());
3955 }
3956 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3957 assert(isCompoundAssignmentOp(Opc));
3958 if (Opc >= BO_AndAssign)
3959 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3960 else
3961 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3962 }
3963
3964 static bool isShiftAssignOp(Opcode Opc) {
3965 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3966 }
3967 bool isShiftAssignOp() const {
3968 return isShiftAssignOp(Opc: getOpcode());
3969 }
3970
3971 /// Return true if a binary operator using the specified opcode and operands
3972 /// would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3973 /// integer to a pointer.
3974 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3975 const Expr *LHS,
3976 const Expr *RHS);
3977
3978 static bool classof(const Stmt *S) {
3979 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3980 S->getStmtClass() <= lastBinaryOperatorConstant;
3981 }
3982
3983 // Iterators
3984 child_range children() {
3985 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3986 }
3987 const_child_range children() const {
3988 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3989 }
3990
3991 /// Set and fetch the bit that shows whether FPFeatures needs to be
3992 /// allocated in Trailing Storage
3993 void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
3994 bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
3995
3996 /// Get FPFeatures from trailing storage
3997 FPOptionsOverride getStoredFPFeatures() const {
3998 assert(hasStoredFPFeatures());
3999 return *getTrailingFPFeatures();
4000 }
4001 /// Set FPFeatures in trailing storage, used only by Serialization
4002 void setStoredFPFeatures(FPOptionsOverride F) {
4003 assert(BinaryOperatorBits.HasFPFeatures);
4004 *getTrailingFPFeatures() = F;
4005 }
4006
4007 /// Get the FP features status of this operator. Only meaningful for
4008 /// operations on floating point types.
4009 FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
4010 if (BinaryOperatorBits.HasFPFeatures)
4011 return getStoredFPFeatures().applyOverrides(LO);
4012 return FPOptions::defaultWithoutTrailingStorage(LO);
4013 }
4014
4015 // This is used in ASTImporter
4016 FPOptionsOverride getFPFeatures() const {
4017 if (BinaryOperatorBits.HasFPFeatures)
4018 return getStoredFPFeatures();
4019 return FPOptionsOverride();
4020 }
4021
4022 /// Get the FP contractability status of this operator. Only meaningful for
4023 /// operations on floating point types.
4024 bool isFPContractableWithinStatement(const LangOptions &LO) const {
4025 return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
4026 }
4027
4028 /// Get the FENV_ACCESS status of this operator. Only meaningful for
4029 /// operations on floating point types.
4030 bool isFEnvAccessOn(const LangOptions &LO) const {
4031 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
4032 }
4033
4034protected:
4035 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
4036 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
4037 SourceLocation opLoc, FPOptionsOverride FPFeatures,
4038 bool dead2);
4039
4040 /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
4041 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4042 BinaryOperatorBits.Opc = BO_MulAssign;
4043 }
4044
4045 /// Return the size in bytes needed for the trailing objects.
4046 /// Used to allocate the right amount of storage.
4047 static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
4048 return HasFPFeatures * sizeof(FPOptionsOverride);
4049 }
4050};
4051
4052/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
4053/// track of the type the operation is performed in. Due to the semantics of
4054/// these operators, the operands are promoted, the arithmetic performed, an
4055/// implicit conversion back to the result type done, then the assignment takes
4056/// place. This captures the intermediate type which the computation is done
4057/// in.
4058class CompoundAssignOperator : public BinaryOperator {
4059 QualType ComputationLHSType;
4060 QualType ComputationResultType;
4061
4062 /// Construct an empty CompoundAssignOperator.
4063 explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
4064 bool hasFPFeatures)
4065 : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
4066
4067protected:
4068 CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc,
4069 QualType ResType, ExprValueKind VK, ExprObjectKind OK,
4070 SourceLocation OpLoc, FPOptionsOverride FPFeatures,
4071 QualType CompLHSType, QualType CompResultType)
4072 : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
4073 true),
4074 ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
4075 assert(isCompoundAssignmentOp() &&
4076 "Only should be used for compound assignments");
4077 }
4078
4079public:
4080 static CompoundAssignOperator *CreateEmpty(const ASTContext &C,
4081 bool hasFPFeatures);
4082
4083 static CompoundAssignOperator *
4084 Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
4085 ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc,
4086 FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
4087 QualType CompResultType = QualType());
4088
4089 // The two computation types are the type the LHS is converted
4090 // to for the computation and the type of the result; the two are
4091 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
4092 QualType getComputationLHSType() const { return ComputationLHSType; }
4093 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
4094
4095 QualType getComputationResultType() const { return ComputationResultType; }
4096 void setComputationResultType(QualType T) { ComputationResultType = T; }
4097
4098 static bool classof(const Stmt *S) {
4099 return S->getStmtClass() == CompoundAssignOperatorClass;
4100 }
4101};
4102
4103inline size_t BinaryOperator::offsetOfTrailingStorage() const {
4104 assert(BinaryOperatorBits.HasFPFeatures);
4105 return isa<CompoundAssignOperator>(Val: this) ? sizeof(CompoundAssignOperator)
4106 : sizeof(BinaryOperator);
4107}
4108
4109/// AbstractConditionalOperator - An abstract base class for
4110/// ConditionalOperator and BinaryConditionalOperator.
4111class AbstractConditionalOperator : public Expr {
4112 SourceLocation QuestionLoc, ColonLoc;
4113 friend class ASTStmtReader;
4114
4115protected:
4116 AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK,
4117 ExprObjectKind OK, SourceLocation qloc,
4118 SourceLocation cloc)
4119 : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
4120
4121 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
4122 : Expr(SC, Empty) { }
4123
4124public:
4125 /// getCond - Return the expression representing the condition for
4126 /// the ?: operator.
4127 Expr *getCond() const;
4128
4129 /// getTrueExpr - Return the subexpression representing the value of
4130 /// the expression if the condition evaluates to true.
4131 Expr *getTrueExpr() const;
4132
4133 /// getFalseExpr - Return the subexpression representing the value of
4134 /// the expression if the condition evaluates to false. This is
4135 /// the same as getRHS.
4136 Expr *getFalseExpr() const;
4137
4138 SourceLocation getQuestionLoc() const { return QuestionLoc; }
4139 SourceLocation getColonLoc() const { return ColonLoc; }
4140
4141 static bool classof(const Stmt *T) {
4142 return T->getStmtClass() == ConditionalOperatorClass ||
4143 T->getStmtClass() == BinaryConditionalOperatorClass;
4144 }
4145};
4146
4147/// ConditionalOperator - The ?: ternary operator. The GNU "missing
4148/// middle" extension is a BinaryConditionalOperator.
4149class ConditionalOperator : public AbstractConditionalOperator {
4150 enum { COND, LHS, RHS, END_EXPR };
4151 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4152
4153 friend class ASTStmtReader;
4154public:
4155 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
4156 SourceLocation CLoc, Expr *rhs, QualType t,
4157 ExprValueKind VK, ExprObjectKind OK)
4158 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
4159 CLoc) {
4160 SubExprs[COND] = cond;
4161 SubExprs[LHS] = lhs;
4162 SubExprs[RHS] = rhs;
4163 setDependence(computeDependence(E: this));
4164 }
4165
4166 /// Build an empty conditional operator.
4167 explicit ConditionalOperator(EmptyShell Empty)
4168 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
4169
4170 /// getCond - Return the expression representing the condition for
4171 /// the ?: operator.
4172 Expr *getCond() const { return cast<Expr>(Val: SubExprs[COND]); }
4173
4174 /// getTrueExpr - Return the subexpression representing the value of
4175 /// the expression if the condition evaluates to true.
4176 Expr *getTrueExpr() const { return cast<Expr>(Val: SubExprs[LHS]); }
4177
4178 /// getFalseExpr - Return the subexpression representing the value of
4179 /// the expression if the condition evaluates to false. This is
4180 /// the same as getRHS.
4181 Expr *getFalseExpr() const { return cast<Expr>(Val: SubExprs[RHS]); }
4182
4183 Expr *getLHS() const { return cast<Expr>(Val: SubExprs[LHS]); }
4184 Expr *getRHS() const { return cast<Expr>(Val: SubExprs[RHS]); }
4185
4186 SourceLocation getBeginLoc() const LLVM_READONLY {
4187 return getCond()->getBeginLoc();
4188 }
4189 SourceLocation getEndLoc() const LLVM_READONLY {
4190 return getRHS()->getEndLoc();
4191 }
4192
4193 static bool classof(const Stmt *T) {
4194 return T->getStmtClass() == ConditionalOperatorClass;
4195 }
4196
4197 // Iterators
4198 child_range children() {
4199 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4200 }
4201 const_child_range children() const {
4202 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4203 }
4204};
4205
4206/// BinaryConditionalOperator - The GNU extension to the conditional
4207/// operator which allows the middle operand to be omitted.
4208///
4209/// This is a different expression kind on the assumption that almost
4210/// every client ends up needing to know that these are different.
4211class BinaryConditionalOperator : public AbstractConditionalOperator {
4212 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
4213
4214 /// - the common condition/left-hand-side expression, which will be
4215 /// evaluated as the opaque value
4216 /// - the condition, expressed in terms of the opaque value
4217 /// - the left-hand-side, expressed in terms of the opaque value
4218 /// - the right-hand-side
4219 Stmt *SubExprs[NUM_SUBEXPRS];
4220 OpaqueValueExpr *OpaqueValue;
4221
4222 friend class ASTStmtReader;
4223public:
4224 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
4225 Expr *cond, Expr *lhs, Expr *rhs,
4226 SourceLocation qloc, SourceLocation cloc,
4227 QualType t, ExprValueKind VK, ExprObjectKind OK)
4228 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
4229 qloc, cloc),
4230 OpaqueValue(opaqueValue) {
4231 SubExprs[COMMON] = common;
4232 SubExprs[COND] = cond;
4233 SubExprs[LHS] = lhs;
4234 SubExprs[RHS] = rhs;
4235 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
4236 setDependence(computeDependence(E: this));
4237 }
4238
4239 /// Build an empty conditional operator.
4240 explicit BinaryConditionalOperator(EmptyShell Empty)
4241 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
4242
4243 /// getCommon - Return the common expression, written to the
4244 /// left of the condition. The opaque value will be bound to the
4245 /// result of this expression.
4246 Expr *getCommon() const { return cast<Expr>(Val: SubExprs[COMMON]); }
4247
4248 /// getOpaqueValue - Return the opaque value placeholder.
4249 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4250
4251 /// getCond - Return the condition expression; this is defined
4252 /// in terms of the opaque value.
4253 Expr *getCond() const { return cast<Expr>(Val: SubExprs[COND]); }
4254
4255 /// getTrueExpr - Return the subexpression which will be
4256 /// evaluated if the condition evaluates to true; this is defined
4257 /// in terms of the opaque value.
4258 Expr *getTrueExpr() const {
4259 return cast<Expr>(Val: SubExprs[LHS]);
4260 }
4261
4262 /// getFalseExpr - Return the subexpression which will be
4263 /// evaluated if the condnition evaluates to false; this is
4264 /// defined in terms of the opaque value.
4265 Expr *getFalseExpr() const {
4266 return cast<Expr>(Val: SubExprs[RHS]);
4267 }
4268
4269 SourceLocation getBeginLoc() const LLVM_READONLY {
4270 return getCommon()->getBeginLoc();
4271 }
4272 SourceLocation getEndLoc() const LLVM_READONLY {
4273 return getFalseExpr()->getEndLoc();
4274 }
4275
4276 static bool classof(const Stmt *T) {
4277 return T->getStmtClass() == BinaryConditionalOperatorClass;
4278 }
4279
4280 // Iterators
4281 child_range children() {
4282 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4283 }
4284 const_child_range children() const {
4285 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4286 }
4287};
4288
4289inline Expr *AbstractConditionalOperator::getCond() const {
4290 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(Val: this))
4291 return co->getCond();
4292 return cast<BinaryConditionalOperator>(Val: this)->getCond();
4293}
4294
4295inline Expr *AbstractConditionalOperator::getTrueExpr() const {
4296 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(Val: this))
4297 return co->getTrueExpr();
4298 return cast<BinaryConditionalOperator>(Val: this)->getTrueExpr();
4299}
4300
4301inline Expr *AbstractConditionalOperator::getFalseExpr() const {
4302 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(Val: this))
4303 return co->getFalseExpr();
4304 return cast<BinaryConditionalOperator>(Val: this)->getFalseExpr();
4305}
4306
4307/// AddrLabelExpr - The GNU address of label extension, representing &&label.
4308class AddrLabelExpr : public Expr {
4309 SourceLocation AmpAmpLoc, LabelLoc;
4310 LabelDecl *Label;
4311public:
4312 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
4313 QualType t)
4314 : Expr(AddrLabelExprClass, t, VK_PRValue, OK_Ordinary), AmpAmpLoc(AALoc),
4315 LabelLoc(LLoc), Label(L) {
4316 setDependence(ExprDependence::None);
4317 }
4318
4319 /// Build an empty address of a label expression.
4320 explicit AddrLabelExpr(EmptyShell Empty)
4321 : Expr(AddrLabelExprClass, Empty) { }
4322
4323 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
4324 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
4325 SourceLocation getLabelLoc() const { return LabelLoc; }
4326 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
4327
4328 SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
4329 SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
4330
4331 LabelDecl *getLabel() const { return Label; }
4332 void setLabel(LabelDecl *L) { Label = L; }
4333
4334 static bool classof(const Stmt *T) {
4335 return T->getStmtClass() == AddrLabelExprClass;
4336 }
4337
4338 // Iterators
4339 child_range children() {
4340 return child_range(child_iterator(), child_iterator());
4341 }
4342 const_child_range children() const {
4343 return const_child_range(const_child_iterator(), const_child_iterator());
4344 }
4345};
4346
4347/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
4348/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
4349/// takes the value of the last subexpression.
4350///
4351/// A StmtExpr is always an r-value; values "returned" out of a
4352/// StmtExpr will be copied.
4353class StmtExpr : public Expr {
4354 Stmt *SubStmt;
4355 SourceLocation LParenLoc, RParenLoc;
4356public:
4357 StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc,
4358 SourceLocation RParenLoc, unsigned TemplateDepth)
4359 : Expr(StmtExprClass, T, VK_PRValue, OK_Ordinary), SubStmt(SubStmt),
4360 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4361 setDependence(computeDependence(E: this, TemplateDepth));
4362 // FIXME: A templated statement expression should have an associated
4363 // DeclContext so that nested declarations always have a dependent context.
4364 StmtExprBits.TemplateDepth = TemplateDepth;
4365 }
4366
4367 /// Build an empty statement expression.
4368 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
4369
4370 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(Val: SubStmt); }
4371 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(Val: SubStmt); }
4372 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
4373
4374 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
4375 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4376
4377 SourceLocation getLParenLoc() const { return LParenLoc; }
4378 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
4379 SourceLocation getRParenLoc() const { return RParenLoc; }
4380 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4381
4382 unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; }
4383
4384 static bool classof(const Stmt *T) {
4385 return T->getStmtClass() == StmtExprClass;
4386 }
4387
4388 // Iterators
4389 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
4390 const_child_range children() const {
4391 return const_child_range(&SubStmt, &SubStmt + 1);
4392 }
4393};
4394
4395/// ShuffleVectorExpr - clang-specific builtin-in function
4396/// __builtin_shufflevector.
4397/// This AST node represents a operator that does a constant
4398/// shuffle, similar to LLVM's shufflevector instruction. It takes
4399/// two vectors and a variable number of constant indices,
4400/// and returns the appropriately shuffled vector.
4401class ShuffleVectorExpr : public Expr {
4402 SourceLocation BuiltinLoc, RParenLoc;
4403
4404 // SubExprs - the list of values passed to the __builtin_shufflevector
4405 // function. The first two are vectors, and the rest are constant
4406 // indices. The number of values in this list is always
4407 // 2+the number of indices in the vector type.
4408 Stmt **SubExprs;
4409 unsigned NumExprs;
4410
4411public:
4412 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
4413 SourceLocation BLoc, SourceLocation RP);
4414
4415 /// Build an empty vector-shuffle expression.
4416 explicit ShuffleVectorExpr(EmptyShell Empty)
4417 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
4418
4419 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4420 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4421
4422 SourceLocation getRParenLoc() const { return RParenLoc; }
4423 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4424
4425 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4426 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4427
4428 static bool classof(const Stmt *T) {
4429 return T->getStmtClass() == ShuffleVectorExprClass;
4430 }
4431
4432 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
4433 /// constant expression, the actual arguments passed in, and the function
4434 /// pointers.
4435 unsigned getNumSubExprs() const { return NumExprs; }
4436
4437 /// Retrieve the array of expressions.
4438 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4439
4440 /// getExpr - Return the Expr at the specified index.
4441 Expr *getExpr(unsigned Index) {
4442 assert((Index < NumExprs) && "Arg access out of range!");
4443 return cast<Expr>(Val: SubExprs[Index]);
4444 }
4445 const Expr *getExpr(unsigned Index) const {
4446 assert((Index < NumExprs) && "Arg access out of range!");
4447 return cast<Expr>(Val: SubExprs[Index]);
4448 }
4449
4450 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
4451
4452 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
4453 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
4454 return getExpr(Index: N+2)->EvaluateKnownConstInt(Ctx);
4455 }
4456
4457 // Iterators
4458 child_range children() {
4459 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
4460 }
4461 const_child_range children() const {
4462 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
4463 }
4464};
4465
4466/// ConvertVectorExpr - Clang builtin function __builtin_convertvector
4467/// This AST node provides support for converting a vector type to another
4468/// vector type of the same arity.
4469class ConvertVectorExpr : public Expr {
4470private:
4471 Stmt *SrcExpr;
4472 TypeSourceInfo *TInfo;
4473 SourceLocation BuiltinLoc, RParenLoc;
4474
4475 friend class ASTReader;
4476 friend class ASTStmtReader;
4477 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
4478
4479public:
4480 ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
4481 ExprValueKind VK, ExprObjectKind OK,
4482 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4483 : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
4484 TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
4485 setDependence(computeDependence(E: this));
4486 }
4487
4488 /// getSrcExpr - Return the Expr to be converted.
4489 Expr *getSrcExpr() const { return cast<Expr>(Val: SrcExpr); }
4490
4491 /// getTypeSourceInfo - Return the destination type.
4492 TypeSourceInfo *getTypeSourceInfo() const {
4493 return TInfo;
4494 }
4495 void setTypeSourceInfo(TypeSourceInfo *ti) {
4496 TInfo = ti;
4497 }
4498
4499 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
4500 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4501
4502 /// getRParenLoc - Return the location of final right parenthesis.
4503 SourceLocation getRParenLoc() const { return RParenLoc; }
4504
4505 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4506 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4507
4508 static bool classof(const Stmt *T) {
4509 return T->getStmtClass() == ConvertVectorExprClass;
4510 }
4511
4512 // Iterators
4513 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4514 const_child_range children() const {
4515 return const_child_range(&SrcExpr, &SrcExpr + 1);
4516 }
4517};
4518
4519/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
4520/// This AST node is similar to the conditional operator (?:) in C, with
4521/// the following exceptions:
4522/// - the test expression must be a integer constant expression.
4523/// - the expression returned acts like the chosen subexpression in every
4524/// visible way: the type is the same as that of the chosen subexpression,
4525/// and all predicates (whether it's an l-value, whether it's an integer
4526/// constant expression, etc.) return the same result as for the chosen
4527/// sub-expression.
4528class ChooseExpr : public Expr {
4529 enum { COND, LHS, RHS, END_EXPR };
4530 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4531 SourceLocation BuiltinLoc, RParenLoc;
4532 bool CondIsTrue;
4533public:
4534 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
4535 ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
4536 bool condIsTrue)
4537 : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP),
4538 CondIsTrue(condIsTrue) {
4539 SubExprs[COND] = cond;
4540 SubExprs[LHS] = lhs;
4541 SubExprs[RHS] = rhs;
4542
4543 setDependence(computeDependence(E: this));
4544 }
4545
4546 /// Build an empty __builtin_choose_expr.
4547 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
4548
4549 /// isConditionTrue - Return whether the condition is true (i.e. not
4550 /// equal to zero).
4551 bool isConditionTrue() const {
4552 assert(!isConditionDependent() &&
4553 "Dependent condition isn't true or false");
4554 return CondIsTrue;
4555 }
4556 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
4557
4558 bool isConditionDependent() const {
4559 return getCond()->isTypeDependent() || getCond()->isValueDependent();
4560 }
4561
4562 /// getChosenSubExpr - Return the subexpression chosen according to the
4563 /// condition.
4564 Expr *getChosenSubExpr() const {
4565 return isConditionTrue() ? getLHS() : getRHS();
4566 }
4567
4568 Expr *getCond() const { return cast<Expr>(Val: SubExprs[COND]); }
4569 void setCond(Expr *E) { SubExprs[COND] = E; }
4570 Expr *getLHS() const { return cast<Expr>(Val: SubExprs[LHS]); }
4571 void setLHS(Expr *E) { SubExprs[LHS] = E; }
4572 Expr *getRHS() const { return cast<Expr>(Val: SubExprs[RHS]); }
4573 void setRHS(Expr *E) { SubExprs[RHS] = E; }
4574
4575 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4576 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4577
4578 SourceLocation getRParenLoc() const { return RParenLoc; }
4579 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4580
4581 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4582 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4583
4584 static bool classof(const Stmt *T) {
4585 return T->getStmtClass() == ChooseExprClass;
4586 }
4587
4588 // Iterators
4589 child_range children() {
4590 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4591 }
4592 const_child_range children() const {
4593 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4594 }
4595};
4596
4597/// GNUNullExpr - Implements the GNU __null extension, which is a name
4598/// for a null pointer constant that has integral type (e.g., int or
4599/// long) and is the same size and alignment as a pointer. The __null
4600/// extension is typically only used by system headers, which define
4601/// NULL as __null in C++ rather than using 0 (which is an integer
4602/// that may not match the size of a pointer).
4603class GNUNullExpr : public Expr {
4604 /// TokenLoc - The location of the __null keyword.
4605 SourceLocation TokenLoc;
4606
4607public:
4608 GNUNullExpr(QualType Ty, SourceLocation Loc)
4609 : Expr(GNUNullExprClass, Ty, VK_PRValue, OK_Ordinary), TokenLoc(Loc) {
4610 setDependence(ExprDependence::None);
4611 }
4612
4613 /// Build an empty GNU __null expression.
4614 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
4615
4616 /// getTokenLocation - The location of the __null token.
4617 SourceLocation getTokenLocation() const { return TokenLoc; }
4618 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
4619
4620 SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
4621 SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
4622
4623 static bool classof(const Stmt *T) {
4624 return T->getStmtClass() == GNUNullExprClass;
4625 }
4626
4627 // Iterators
4628 child_range children() {
4629 return child_range(child_iterator(), child_iterator());
4630 }
4631 const_child_range children() const {
4632 return const_child_range(const_child_iterator(), const_child_iterator());
4633 }
4634};
4635
4636/// Represents a call to the builtin function \c __builtin_va_arg.
4637class VAArgExpr : public Expr {
4638 Stmt *Val;
4639 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
4640 SourceLocation BuiltinLoc, RParenLoc;
4641public:
4642 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
4643 SourceLocation RPLoc, QualType t, bool IsMS)
4644 : Expr(VAArgExprClass, t, VK_PRValue, OK_Ordinary), Val(e),
4645 TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {
4646 setDependence(computeDependence(E: this));
4647 }
4648
4649 /// Create an empty __builtin_va_arg expression.
4650 explicit VAArgExpr(EmptyShell Empty)
4651 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
4652
4653 const Expr *getSubExpr() const { return cast<Expr>(Val); }
4654 Expr *getSubExpr() { return cast<Expr>(Val); }
4655 void setSubExpr(Expr *E) { Val = E; }
4656
4657 /// Returns whether this is really a Win64 ABI va_arg expression.
4658 bool isMicrosoftABI() const { return TInfo.getInt(); }
4659 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
4660
4661 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
4662 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
4663
4664 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4665 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4666
4667 SourceLocation getRParenLoc() const { return RParenLoc; }
4668 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4669
4670 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4671 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4672
4673 static bool classof(const Stmt *T) {
4674 return T->getStmtClass() == VAArgExprClass;
4675 }
4676
4677 // Iterators
4678 child_range children() { return child_range(&Val, &Val+1); }
4679 const_child_range children() const {
4680 return const_child_range(&Val, &Val + 1);
4681 }
4682};
4683
4684enum class SourceLocIdentKind {
4685 Function,
4686 FuncSig,
4687 File,
4688 FileName,
4689 Line,
4690 Column,
4691 SourceLocStruct
4692};
4693
4694/// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
4695/// __builtin_FUNCTION(), __builtin_FUNCSIG(), __builtin_FILE(),
4696/// __builtin_FILE_NAME() or __builtin_source_location().
4697class SourceLocExpr final : public Expr {
4698 SourceLocation BuiltinLoc, RParenLoc;
4699 DeclContext *ParentContext;
4700
4701public:
4702 SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Type,
4703 QualType ResultTy, SourceLocation BLoc,
4704 SourceLocation RParenLoc, DeclContext *Context);
4705
4706 /// Build an empty call expression.
4707 explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4708
4709 /// Return the result of evaluating this SourceLocExpr in the specified
4710 /// (and possibly null) default argument or initialization context.
4711 APValue EvaluateInContext(const ASTContext &Ctx,
4712 const Expr *DefaultExpr) const;
4713
4714 /// Return a string representing the name of the specific builtin function.
4715 StringRef getBuiltinStr() const;
4716
4717 SourceLocIdentKind getIdentKind() const {
4718 return static_cast<SourceLocIdentKind>(SourceLocExprBits.Kind);
4719 }
4720
4721 bool isIntType() const {
4722 switch (getIdentKind()) {
4723 case SourceLocIdentKind::File:
4724 case SourceLocIdentKind::FileName:
4725 case SourceLocIdentKind::Function:
4726 case SourceLocIdentKind::FuncSig:
4727 case SourceLocIdentKind::SourceLocStruct:
4728 return false;
4729 case SourceLocIdentKind::Line:
4730 case SourceLocIdentKind::Column:
4731 return true;
4732 }
4733 llvm_unreachable("unknown source location expression kind");
4734 }
4735
4736 /// If the SourceLocExpr has been resolved return the subexpression
4737 /// representing the resolved value. Otherwise return null.
4738 const DeclContext *getParentContext() const { return ParentContext; }
4739 DeclContext *getParentContext() { return ParentContext; }
4740
4741 SourceLocation getLocation() const { return BuiltinLoc; }
4742 SourceLocation getBeginLoc() const { return BuiltinLoc; }
4743 SourceLocation getEndLoc() const { return RParenLoc; }
4744
4745 child_range children() {
4746 return child_range(child_iterator(), child_iterator());
4747 }
4748
4749 const_child_range children() const {
4750 return const_child_range(child_iterator(), child_iterator());
4751 }
4752
4753 static bool classof(const Stmt *T) {
4754 return T->getStmtClass() == SourceLocExprClass;
4755 }
4756
4757 static bool MayBeDependent(SourceLocIdentKind Kind) {
4758 switch (Kind) {
4759 case SourceLocIdentKind::Function:
4760 case SourceLocIdentKind::FuncSig:
4761 case SourceLocIdentKind::SourceLocStruct:
4762 return true;
4763 default:
4764 return false;
4765 }
4766 }
4767
4768private:
4769 friend class ASTStmtReader;
4770};
4771
4772/// Describes an C or C++ initializer list.
4773///
4774/// InitListExpr describes an initializer list, which can be used to
4775/// initialize objects of different types, including
4776/// struct/class/union types, arrays, and vectors. For example:
4777///
4778/// @code
4779/// struct foo x = { 1, { 2, 3 } };
4780/// @endcode
4781///
4782/// Prior to semantic analysis, an initializer list will represent the
4783/// initializer list as written by the user, but will have the
4784/// placeholder type "void". This initializer list is called the
4785/// syntactic form of the initializer, and may contain C99 designated
4786/// initializers (represented as DesignatedInitExprs), initializations
4787/// of subobject members without explicit braces, and so on. Clients
4788/// interested in the original syntax of the initializer list should
4789/// use the syntactic form of the initializer list.
4790///
4791/// After semantic analysis, the initializer list will represent the
4792/// semantic form of the initializer, where the initializations of all
4793/// subobjects are made explicit with nested InitListExpr nodes and
4794/// C99 designators have been eliminated by placing the designated
4795/// initializations into the subobject they initialize. Additionally,
4796/// any "holes" in the initialization, where no initializer has been
4797/// specified for a particular subobject, will be replaced with
4798/// implicitly-generated ImplicitValueInitExpr expressions that
4799/// value-initialize the subobjects. Note, however, that the
4800/// initializer lists may still have fewer initializers than there are
4801/// elements to initialize within the object.
4802///
4803/// After semantic analysis has completed, given an initializer list,
4804/// method isSemanticForm() returns true if and only if this is the
4805/// semantic form of the initializer list (note: the same AST node
4806/// may at the same time be the syntactic form).
4807/// Given the semantic form of the initializer list, one can retrieve
4808/// the syntactic form of that initializer list (when different)
4809/// using method getSyntacticForm(); the method returns null if applied
4810/// to a initializer list which is already in syntactic form.
4811/// Similarly, given the syntactic form (i.e., an initializer list such
4812/// that isSemanticForm() returns false), one can retrieve the semantic
4813/// form using method getSemanticForm().
4814/// Since many initializer lists have the same syntactic and semantic forms,
4815/// getSyntacticForm() may return NULL, indicating that the current
4816/// semantic initializer list also serves as its syntactic form.
4817class InitListExpr : public Expr {
4818 // FIXME: Eliminate this vector in favor of ASTContext allocation
4819 typedef ASTVector<Stmt *> InitExprsTy;
4820 InitExprsTy InitExprs;
4821 SourceLocation LBraceLoc, RBraceLoc;
4822
4823 /// The alternative form of the initializer list (if it exists).
4824 /// The int part of the pair stores whether this initializer list is
4825 /// in semantic form. If not null, the pointer points to:
4826 /// - the syntactic form, if this is in semantic form;
4827 /// - the semantic form, if this is in syntactic form.
4828 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
4829
4830 /// Either:
4831 /// If this initializer list initializes an array with more elements than
4832 /// there are initializers in the list, specifies an expression to be used
4833 /// for value initialization of the rest of the elements.
4834 /// Or
4835 /// If this initializer list initializes a union, specifies which
4836 /// field within the union will be initialized.
4837 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
4838
4839public:
4840 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
4841 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
4842
4843 /// Build an empty initializer list.
4844 explicit InitListExpr(EmptyShell Empty)
4845 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
4846
4847 unsigned getNumInits() const { return InitExprs.size(); }
4848
4849 /// Retrieve the set of initializers.
4850 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
4851
4852 /// Retrieve the set of initializers.
4853 Expr * const *getInits() const {
4854 return reinterpret_cast<Expr * const *>(InitExprs.data());
4855 }
4856
4857 ArrayRef<Expr *> inits() { return llvm::ArrayRef(getInits(), getNumInits()); }
4858
4859 ArrayRef<Expr *> inits() const {
4860 return llvm::ArrayRef(getInits(), getNumInits());
4861 }
4862
4863 const Expr *getInit(unsigned Init) const {
4864 assert(Init < getNumInits() && "Initializer access out of range!");
4865 return cast_or_null<Expr>(Val: InitExprs[Init]);
4866 }
4867
4868 Expr *getInit(unsigned Init) {
4869 assert(Init < getNumInits() && "Initializer access out of range!");
4870 return cast_or_null<Expr>(Val: InitExprs[Init]);
4871 }
4872
4873 void setInit(unsigned Init, Expr *expr) {
4874 assert(Init < getNumInits() && "Initializer access out of range!");
4875 InitExprs[Init] = expr;
4876
4877 if (expr)
4878 setDependence(getDependence() | expr->getDependence());
4879 }
4880
4881 /// Mark the semantic form of the InitListExpr as error when the semantic
4882 /// analysis fails.
4883 void markError() {
4884 assert(isSemanticForm());
4885 setDependence(getDependence() | ExprDependence::ErrorDependent);
4886 }
4887
4888 /// Reserve space for some number of initializers.
4889 void reserveInits(const ASTContext &C, unsigned NumInits);
4890
4891 /// Specify the number of initializers
4892 ///
4893 /// If there are more than @p NumInits initializers, the remaining
4894 /// initializers will be destroyed. If there are fewer than @p
4895 /// NumInits initializers, NULL expressions will be added for the
4896 /// unknown initializers.
4897 void resizeInits(const ASTContext &Context, unsigned NumInits);
4898
4899 /// Updates the initializer at index @p Init with the new
4900 /// expression @p expr, and returns the old expression at that
4901 /// location.
4902 ///
4903 /// When @p Init is out of range for this initializer list, the
4904 /// initializer list will be extended with NULL expressions to
4905 /// accommodate the new entry.
4906 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4907
4908 /// If this initializer list initializes an array with more elements
4909 /// than there are initializers in the list, specifies an expression to be
4910 /// used for value initialization of the rest of the elements.
4911 Expr *getArrayFiller() {
4912 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4913 }
4914 const Expr *getArrayFiller() const {
4915 return const_cast<InitListExpr *>(this)->getArrayFiller();
4916 }
4917 void setArrayFiller(Expr *filler);
4918
4919 /// Return true if this is an array initializer and its array "filler"
4920 /// has been set.
4921 bool hasArrayFiller() const { return getArrayFiller(); }
4922
4923 /// Determine whether this initializer list contains a designated initializer.
4924 bool hasDesignatedInit() const {
4925 return std::any_of(first: begin(), last: end(), pred: [](const Stmt *S) {
4926 return isa<DesignatedInitExpr>(Val: S);
4927 });
4928 }
4929
4930 /// If this initializes a union, specifies which field in the
4931 /// union to initialize.
4932 ///
4933 /// Typically, this field is the first named field within the
4934 /// union. However, a designated initializer can specify the
4935 /// initialization of a different field within the union.
4936 FieldDecl *getInitializedFieldInUnion() {
4937 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4938 }
4939 const FieldDecl *getInitializedFieldInUnion() const {
4940 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4941 }
4942 void setInitializedFieldInUnion(FieldDecl *FD) {
4943 assert((FD == nullptr
4944 || getInitializedFieldInUnion() == nullptr
4945 || getInitializedFieldInUnion() == FD)
4946 && "Only one field of a union may be initialized at a time!");
4947 ArrayFillerOrUnionFieldInit = FD;
4948 }
4949
4950 // Explicit InitListExpr's originate from source code (and have valid source
4951 // locations). Implicit InitListExpr's are created by the semantic analyzer.
4952 // FIXME: This is wrong; InitListExprs created by semantic analysis have
4953 // valid source locations too!
4954 bool isExplicit() const {
4955 return LBraceLoc.isValid() && RBraceLoc.isValid();
4956 }
4957
4958 /// Is this an initializer for an array of characters, initialized by a string
4959 /// literal or an @encode?
4960 bool isStringLiteralInit() const;
4961
4962 /// Is this a transparent initializer list (that is, an InitListExpr that is
4963 /// purely syntactic, and whose semantics are that of the sole contained
4964 /// initializer)?
4965 bool isTransparent() const;
4966
4967 /// Is this the zero initializer {0} in a language which considers it
4968 /// idiomatic?
4969 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4970
4971 SourceLocation getLBraceLoc() const { return LBraceLoc; }
4972 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
4973 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4974 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4975
4976 bool isSemanticForm() const { return AltForm.getInt(); }
4977 InitListExpr *getSemanticForm() const {
4978 return isSemanticForm() ? nullptr : AltForm.getPointer();
4979 }
4980 bool isSyntacticForm() const {
4981 return !AltForm.getInt() || !AltForm.getPointer();
4982 }
4983 InitListExpr *getSyntacticForm() const {
4984 return isSemanticForm() ? AltForm.getPointer() : nullptr;
4985 }
4986
4987 void setSyntacticForm(InitListExpr *Init) {
4988 AltForm.setPointer(Init);
4989 AltForm.setInt(true);
4990 Init->AltForm.setPointer(this);
4991 Init->AltForm.setInt(false);
4992 }
4993
4994 bool hadArrayRangeDesignator() const {
4995 return InitListExprBits.HadArrayRangeDesignator != 0;
4996 }
4997 void sawArrayRangeDesignator(bool ARD = true) {
4998 InitListExprBits.HadArrayRangeDesignator = ARD;
4999 }
5000
5001 SourceLocation getBeginLoc() const LLVM_READONLY;
5002 SourceLocation getEndLoc() const LLVM_READONLY;
5003
5004 static bool classof(const Stmt *T) {
5005 return T->getStmtClass() == InitListExprClass;
5006 }
5007
5008 // Iterators
5009 child_range children() {
5010 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
5011 return child_range(cast_away_const(RHS: CCR.begin()),
5012 cast_away_const(RHS: CCR.end()));
5013 }
5014
5015 const_child_range children() const {
5016 // FIXME: This does not include the array filler expression.
5017 if (InitExprs.empty())
5018 return const_child_range(const_child_iterator(), const_child_iterator());
5019 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
5020 }
5021
5022 typedef InitExprsTy::iterator iterator;
5023 typedef InitExprsTy::const_iterator const_iterator;
5024 typedef InitExprsTy::reverse_iterator reverse_iterator;
5025 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
5026
5027 iterator begin() { return InitExprs.begin(); }
5028 const_iterator begin() const { return InitExprs.begin(); }
5029 iterator end() { return InitExprs.end(); }
5030 const_iterator end() const { return InitExprs.end(); }
5031 reverse_iterator rbegin() { return InitExprs.rbegin(); }
5032 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
5033 reverse_iterator rend() { return InitExprs.rend(); }
5034 const_reverse_iterator rend() const { return InitExprs.rend(); }
5035
5036 friend class ASTStmtReader;
5037 friend class ASTStmtWriter;
5038};
5039
5040/// Represents a C99 designated initializer expression.
5041///
5042/// A designated initializer expression (C99 6.7.8) contains one or
5043/// more designators (which can be field designators, array
5044/// designators, or GNU array-range designators) followed by an
5045/// expression that initializes the field or element(s) that the
5046/// designators refer to. For example, given:
5047///
5048/// @code
5049/// struct point {
5050/// double x;
5051/// double y;
5052/// };
5053/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
5054/// @endcode
5055///
5056/// The InitListExpr contains three DesignatedInitExprs, the first of
5057/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
5058/// designators, one array designator for @c [2] followed by one field
5059/// designator for @c .y. The initialization expression will be 1.0.
5060class DesignatedInitExpr final
5061 : public Expr,
5062 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
5063public:
5064 /// Forward declaration of the Designator class.
5065 class Designator;
5066
5067private:
5068 /// The location of the '=' or ':' prior to the actual initializer
5069 /// expression.
5070 SourceLocation EqualOrColonLoc;
5071
5072 /// Whether this designated initializer used the GNU deprecated
5073 /// syntax rather than the C99 '=' syntax.
5074 LLVM_PREFERRED_TYPE(bool)
5075 unsigned GNUSyntax : 1;
5076
5077 /// The number of designators in this initializer expression.
5078 unsigned NumDesignators : 15;
5079
5080 /// The number of subexpressions of this initializer expression,
5081 /// which contains both the initializer and any additional
5082 /// expressions used by array and array-range designators.
5083 unsigned NumSubExprs : 16;
5084
5085 /// The designators in this designated initialization
5086 /// expression.
5087 Designator *Designators;
5088
5089 DesignatedInitExpr(const ASTContext &C, QualType Ty,
5090 llvm::ArrayRef<Designator> Designators,
5091 SourceLocation EqualOrColonLoc, bool GNUSyntax,
5092 ArrayRef<Expr *> IndexExprs, Expr *Init);
5093
5094 explicit DesignatedInitExpr(unsigned NumSubExprs)
5095 : Expr(DesignatedInitExprClass, EmptyShell()),
5096 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
5097
5098public:
5099 /// Represents a single C99 designator.
5100 ///
5101 /// @todo This class is infuriatingly similar to clang::Designator,
5102 /// but minor differences (storing indices vs. storing pointers)
5103 /// keep us from reusing it. Try harder, later, to rectify these
5104 /// differences.
5105 class Designator {
5106 /// A field designator, e.g., ".x".
5107 struct FieldDesignatorInfo {
5108 /// Refers to the field that is being initialized. The low bit
5109 /// of this field determines whether this is actually a pointer
5110 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
5111 /// initially constructed, a field designator will store an
5112 /// IdentifierInfo*. After semantic analysis has resolved that
5113 /// name, the field designator will instead store a FieldDecl*.
5114 uintptr_t NameOrField;
5115
5116 /// The location of the '.' in the designated initializer.
5117 SourceLocation DotLoc;
5118
5119 /// The location of the field name in the designated initializer.
5120 SourceLocation FieldLoc;
5121
5122 FieldDesignatorInfo(const IdentifierInfo *II, SourceLocation DotLoc,
5123 SourceLocation FieldLoc)
5124 : NameOrField(reinterpret_cast<uintptr_t>(II) | 0x1), DotLoc(DotLoc),
5125 FieldLoc(FieldLoc) {}
5126 };
5127
5128 /// An array or GNU array-range designator, e.g., "[9]" or "[10...15]".
5129 struct ArrayOrRangeDesignatorInfo {
5130 /// Location of the first index expression within the designated
5131 /// initializer expression's list of subexpressions.
5132 unsigned Index;
5133
5134 /// The location of the '[' starting the array range designator.
5135 SourceLocation LBracketLoc;
5136
5137 /// The location of the ellipsis separating the start and end
5138 /// indices. Only valid for GNU array-range designators.
5139 SourceLocation EllipsisLoc;
5140
5141 /// The location of the ']' terminating the array range designator.
5142 SourceLocation RBracketLoc;
5143
5144 ArrayOrRangeDesignatorInfo(unsigned Index, SourceLocation LBracketLoc,
5145 SourceLocation RBracketLoc)
5146 : Index(Index), LBracketLoc(LBracketLoc), RBracketLoc(RBracketLoc) {}
5147
5148 ArrayOrRangeDesignatorInfo(unsigned Index,
5149 SourceLocation LBracketLoc,
5150 SourceLocation EllipsisLoc,
5151 SourceLocation RBracketLoc)
5152 : Index(Index), LBracketLoc(LBracketLoc), EllipsisLoc(EllipsisLoc),
5153 RBracketLoc(RBracketLoc) {}
5154 };
5155
5156 /// The kind of designator this describes.
5157 enum DesignatorKind {
5158 FieldDesignator,
5159 ArrayDesignator,
5160 ArrayRangeDesignator
5161 };
5162
5163 DesignatorKind Kind;
5164
5165 union {
5166 /// A field designator, e.g., ".x".
5167 struct FieldDesignatorInfo FieldInfo;
5168
5169 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
5170 struct ArrayOrRangeDesignatorInfo ArrayOrRangeInfo;
5171 };
5172
5173 Designator(DesignatorKind Kind) : Kind(Kind) {}
5174
5175 public:
5176 Designator() {}
5177
5178 bool isFieldDesignator() const { return Kind == FieldDesignator; }
5179 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
5180 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
5181
5182 //===------------------------------------------------------------------===//
5183 // FieldDesignatorInfo
5184
5185 /// Creates a field designator.
5186 static Designator CreateFieldDesignator(const IdentifierInfo *FieldName,
5187 SourceLocation DotLoc,
5188 SourceLocation FieldLoc) {
5189 Designator D(FieldDesignator);
5190 new (&D.FieldInfo) FieldDesignatorInfo(FieldName, DotLoc, FieldLoc);
5191 return D;
5192 }
5193
5194 const IdentifierInfo *getFieldName() const;
5195
5196 FieldDecl *getFieldDecl() const {
5197 assert(isFieldDesignator() && "Only valid on a field designator");
5198 if (FieldInfo.NameOrField & 0x01)
5199 return nullptr;
5200 return reinterpret_cast<FieldDecl *>(FieldInfo.NameOrField);
5201 }
5202
5203 void setFieldDecl(FieldDecl *FD) {
5204 assert(isFieldDesignator() && "Only valid on a field designator");
5205 FieldInfo.NameOrField = reinterpret_cast<uintptr_t>(FD);
5206 }
5207
5208 SourceLocation getDotLoc() const {
5209 assert(isFieldDesignator() && "Only valid on a field designator");
5210 return FieldInfo.DotLoc;
5211 }
5212
5213 SourceLocation getFieldLoc() const {
5214 assert(isFieldDesignator() && "Only valid on a field designator");
5215 return FieldInfo.FieldLoc;
5216 }
5217
5218 //===------------------------------------------------------------------===//
5219 // ArrayOrRangeDesignator
5220
5221 /// Creates an array designator.
5222 static Designator CreateArrayDesignator(unsigned Index,
5223 SourceLocation LBracketLoc,
5224 SourceLocation RBracketLoc) {
5225 Designator D(ArrayDesignator);
5226 new (&D.ArrayOrRangeInfo) ArrayOrRangeDesignatorInfo(Index, LBracketLoc,
5227 RBracketLoc);
5228 return D;
5229 }
5230
5231 /// Creates a GNU array-range designator.
5232 static Designator CreateArrayRangeDesignator(unsigned Index,
5233 SourceLocation LBracketLoc,
5234 SourceLocation EllipsisLoc,
5235 SourceLocation RBracketLoc) {
5236 Designator D(ArrayRangeDesignator);
5237 new (&D.ArrayOrRangeInfo) ArrayOrRangeDesignatorInfo(Index, LBracketLoc,
5238 EllipsisLoc,
5239 RBracketLoc);
5240 return D;
5241 }
5242
5243 unsigned getArrayIndex() const {
5244 assert((isArrayDesignator() || isArrayRangeDesignator()) &&
5245 "Only valid on an array or array-range designator");
5246 return ArrayOrRangeInfo.Index;
5247 }
5248
5249 SourceLocation getLBracketLoc() const {
5250 assert((isArrayDesignator() || isArrayRangeDesignator()) &&
5251 "Only valid on an array or array-range designator");
5252 return ArrayOrRangeInfo.LBracketLoc;
5253 }
5254
5255 SourceLocation getEllipsisLoc() const {
5256 assert(isArrayRangeDesignator() &&
5257 "Only valid on an array-range designator");
5258 return ArrayOrRangeInfo.EllipsisLoc;
5259 }
5260
5261 SourceLocation getRBracketLoc() const {
5262 assert((isArrayDesignator() || isArrayRangeDesignator()) &&
5263 "Only valid on an array or array-range designator");
5264 return ArrayOrRangeInfo.RBracketLoc;
5265 }
5266
5267 SourceLocation getBeginLoc() const LLVM_READONLY {
5268 if (isFieldDesignator())
5269 return getDotLoc().isInvalid() ? getFieldLoc() : getDotLoc();
5270 return getLBracketLoc();
5271 }
5272
5273 SourceLocation getEndLoc() const LLVM_READONLY {
5274 return isFieldDesignator() ? getFieldLoc() : getRBracketLoc();
5275 }
5276
5277 SourceRange getSourceRange() const LLVM_READONLY {
5278 return SourceRange(getBeginLoc(), getEndLoc());
5279 }
5280 };
5281
5282 static DesignatedInitExpr *Create(const ASTContext &C,
5283 llvm::ArrayRef<Designator> Designators,
5284 ArrayRef<Expr*> IndexExprs,
5285 SourceLocation EqualOrColonLoc,
5286 bool GNUSyntax, Expr *Init);
5287
5288 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
5289 unsigned NumIndexExprs);
5290
5291 /// Returns the number of designators in this initializer.
5292 unsigned size() const { return NumDesignators; }
5293
5294 // Iterator access to the designators.
5295 llvm::MutableArrayRef<Designator> designators() {
5296 return {Designators, NumDesignators};
5297 }
5298
5299 llvm::ArrayRef<Designator> designators() const {
5300 return {Designators, NumDesignators};
5301 }
5302
5303 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
5304 const Designator *getDesignator(unsigned Idx) const {
5305 return &designators()[Idx];
5306 }
5307
5308 void setDesignators(const ASTContext &C, const Designator *Desigs,
5309 unsigned NumDesigs);
5310
5311 Expr *getArrayIndex(const Designator &D) const;
5312 Expr *getArrayRangeStart(const Designator &D) const;
5313 Expr *getArrayRangeEnd(const Designator &D) const;
5314
5315 /// Retrieve the location of the '=' that precedes the
5316 /// initializer value itself, if present.
5317 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
5318 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
5319
5320 /// Whether this designated initializer should result in direct-initialization
5321 /// of the designated subobject (eg, '{.foo{1, 2, 3}}').
5322 bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); }
5323
5324 /// Determines whether this designated initializer used the
5325 /// deprecated GNU syntax for designated initializers.
5326 bool usesGNUSyntax() const { return GNUSyntax; }
5327 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
5328
5329 /// Retrieve the initializer value.
5330 Expr *getInit() const {
5331 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
5332 }
5333
5334 void setInit(Expr *init) {
5335 *child_begin() = init;
5336 }
5337
5338 /// Retrieve the total number of subexpressions in this
5339 /// designated initializer expression, including the actual
5340 /// initialized value and any expressions that occur within array
5341 /// and array-range designators.
5342 unsigned getNumSubExprs() const { return NumSubExprs; }
5343
5344 Expr *getSubExpr(unsigned Idx) const {
5345 assert(Idx < NumSubExprs && "Subscript out of range");
5346 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
5347 }
5348
5349 void setSubExpr(unsigned Idx, Expr *E) {
5350 assert(Idx < NumSubExprs && "Subscript out of range");
5351 getTrailingObjects<Stmt *>()[Idx] = E;
5352 }
5353
5354 /// Replaces the designator at index @p Idx with the series
5355 /// of designators in [First, Last).
5356 void ExpandDesignator(const ASTContext &C, unsigned Idx,
5357 const Designator *First, const Designator *Last);
5358
5359 SourceRange getDesignatorsSourceRange() const;
5360
5361 SourceLocation getBeginLoc() const LLVM_READONLY;
5362 SourceLocation getEndLoc() const LLVM_READONLY;
5363
5364 static bool classof(const Stmt *T) {
5365 return T->getStmtClass() == DesignatedInitExprClass;
5366 }
5367
5368 // Iterators
5369 child_range children() {
5370 Stmt **begin = getTrailingObjects<Stmt *>();
5371 return child_range(begin, begin + NumSubExprs);
5372 }
5373 const_child_range children() const {
5374 Stmt * const *begin = getTrailingObjects<Stmt *>();
5375 return const_child_range(begin, begin + NumSubExprs);
5376 }
5377
5378 friend TrailingObjects;
5379};
5380
5381/// Represents a place-holder for an object not to be initialized by
5382/// anything.
5383///
5384/// This only makes sense when it appears as part of an updater of a
5385/// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
5386/// initializes a big object, and the NoInitExpr's mark the spots within the
5387/// big object not to be overwritten by the updater.
5388///
5389/// \see DesignatedInitUpdateExpr
5390class NoInitExpr : public Expr {
5391public:
5392 explicit NoInitExpr(QualType ty)
5393 : Expr(NoInitExprClass, ty, VK_PRValue, OK_Ordinary) {
5394 setDependence(computeDependence(E: this));
5395 }
5396
5397 explicit NoInitExpr(EmptyShell Empty)
5398 : Expr(NoInitExprClass, Empty) { }
5399
5400 static bool classof(const Stmt *T) {
5401 return T->getStmtClass() == NoInitExprClass;
5402 }
5403
5404 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5405 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5406
5407 // Iterators
5408 child_range children() {
5409 return child_range(child_iterator(), child_iterator());
5410 }
5411 const_child_range children() const {
5412 return const_child_range(const_child_iterator(), const_child_iterator());
5413 }
5414};
5415
5416// In cases like:
5417// struct Q { int a, b, c; };
5418// Q *getQ();
5419// void foo() {
5420// struct A { Q q; } a = { *getQ(), .q.b = 3 };
5421// }
5422//
5423// We will have an InitListExpr for a, with type A, and then a
5424// DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
5425// is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
5426//
5427class DesignatedInitUpdateExpr : public Expr {
5428 // BaseAndUpdaterExprs[0] is the base expression;
5429 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
5430 Stmt *BaseAndUpdaterExprs[2];
5431
5432public:
5433 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
5434 Expr *baseExprs, SourceLocation rBraceLoc);
5435
5436 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
5437 : Expr(DesignatedInitUpdateExprClass, Empty) { }
5438
5439 SourceLocation getBeginLoc() const LLVM_READONLY;
5440 SourceLocation getEndLoc() const LLVM_READONLY;
5441
5442 static bool classof(const Stmt *T) {
5443 return T->getStmtClass() == DesignatedInitUpdateExprClass;
5444 }
5445
5446 Expr *getBase() const { return cast<Expr>(Val: BaseAndUpdaterExprs[0]); }
5447 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
5448
5449 InitListExpr *getUpdater() const {
5450 return cast<InitListExpr>(Val: BaseAndUpdaterExprs[1]);
5451 }
5452 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
5453
5454 // Iterators
5455 // children = the base and the updater
5456 child_range children() {
5457 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
5458 }
5459 const_child_range children() const {
5460 return const_child_range(&BaseAndUpdaterExprs[0],
5461 &BaseAndUpdaterExprs[0] + 2);
5462 }
5463};
5464
5465/// Represents a loop initializing the elements of an array.
5466///
5467/// The need to initialize the elements of an array occurs in a number of
5468/// contexts:
5469///
5470/// * in the implicit copy/move constructor for a class with an array member
5471/// * when a lambda-expression captures an array by value
5472/// * when a decomposition declaration decomposes an array
5473///
5474/// There are two subexpressions: a common expression (the source array)
5475/// that is evaluated once up-front, and a per-element initializer that
5476/// runs once for each array element.
5477///
5478/// Within the per-element initializer, the common expression may be referenced
5479/// via an OpaqueValueExpr, and the current index may be obtained via an
5480/// ArrayInitIndexExpr.
5481class ArrayInitLoopExpr : public Expr {
5482 Stmt *SubExprs[2];
5483
5484 explicit ArrayInitLoopExpr(EmptyShell Empty)
5485 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
5486
5487public:
5488 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
5489 : Expr(ArrayInitLoopExprClass, T, VK_PRValue, OK_Ordinary),
5490 SubExprs{CommonInit, ElementInit} {
5491 setDependence(computeDependence(E: this));
5492 }
5493
5494 /// Get the common subexpression shared by all initializations (the source
5495 /// array).
5496 OpaqueValueExpr *getCommonExpr() const {
5497 return cast<OpaqueValueExpr>(Val: SubExprs[0]);
5498 }
5499
5500 /// Get the initializer to use for each array element.
5501 Expr *getSubExpr() const { return cast<Expr>(Val: SubExprs[1]); }
5502
5503 llvm::APInt getArraySize() const {
5504 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
5505 ->getSize();
5506 }
5507
5508 static bool classof(const Stmt *S) {
5509 return S->getStmtClass() == ArrayInitLoopExprClass;
5510 }
5511
5512 SourceLocation getBeginLoc() const LLVM_READONLY {
5513 return getCommonExpr()->getBeginLoc();
5514 }
5515 SourceLocation getEndLoc() const LLVM_READONLY {
5516 return getCommonExpr()->getEndLoc();
5517 }
5518
5519 child_range children() {
5520 return child_range(SubExprs, SubExprs + 2);
5521 }
5522 const_child_range children() const {
5523 return const_child_range(SubExprs, SubExprs + 2);
5524 }
5525
5526 friend class ASTReader;
5527 friend class ASTStmtReader;
5528 friend class ASTStmtWriter;
5529};
5530
5531/// Represents the index of the current element of an array being
5532/// initialized by an ArrayInitLoopExpr. This can only appear within the
5533/// subexpression of an ArrayInitLoopExpr.
5534class ArrayInitIndexExpr : public Expr {
5535 explicit ArrayInitIndexExpr(EmptyShell Empty)
5536 : Expr(ArrayInitIndexExprClass, Empty) {}
5537
5538public:
5539 explicit ArrayInitIndexExpr(QualType T)
5540 : Expr(ArrayInitIndexExprClass, T, VK_PRValue, OK_Ordinary) {
5541 setDependence(ExprDependence::None);
5542 }
5543
5544 static bool classof(const Stmt *S) {
5545 return S->getStmtClass() == ArrayInitIndexExprClass;
5546 }
5547
5548 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5549 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5550
5551 child_range children() {
5552 return child_range(child_iterator(), child_iterator());
5553 }
5554 const_child_range children() const {
5555 return const_child_range(const_child_iterator(), const_child_iterator());
5556 }
5557
5558 friend class ASTReader;
5559 friend class ASTStmtReader;
5560};
5561
5562/// Represents an implicitly-generated value initialization of
5563/// an object of a given type.
5564///
5565/// Implicit value initializations occur within semantic initializer
5566/// list expressions (InitListExpr) as placeholders for subobject
5567/// initializations not explicitly specified by the user.
5568///
5569/// \see InitListExpr
5570class ImplicitValueInitExpr : public Expr {
5571public:
5572 explicit ImplicitValueInitExpr(QualType ty)
5573 : Expr(ImplicitValueInitExprClass, ty, VK_PRValue, OK_Ordinary) {
5574 setDependence(computeDependence(E: this));
5575 }
5576
5577 /// Construct an empty implicit value initialization.
5578 explicit ImplicitValueInitExpr(EmptyShell Empty)
5579 : Expr(ImplicitValueInitExprClass, Empty) { }
5580
5581 static bool classof(const Stmt *T) {
5582 return T->getStmtClass() == ImplicitValueInitExprClass;
5583 }
5584
5585 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5586 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5587
5588 // Iterators
5589 child_range children() {
5590 return child_range(child_iterator(), child_iterator());
5591 }
5592 const_child_range children() const {
5593 return const_child_range(const_child_iterator(), const_child_iterator());
5594 }
5595};
5596
5597class ParenListExpr final
5598 : public Expr,
5599 private llvm::TrailingObjects<ParenListExpr, Stmt *> {
5600 friend class ASTStmtReader;
5601 friend TrailingObjects;
5602
5603 /// The location of the left and right parentheses.
5604 SourceLocation LParenLoc, RParenLoc;
5605
5606 /// Build a paren list.
5607 ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
5608 SourceLocation RParenLoc);
5609
5610 /// Build an empty paren list.
5611 ParenListExpr(EmptyShell Empty, unsigned NumExprs);
5612
5613public:
5614 /// Create a paren list.
5615 static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc,
5616 ArrayRef<Expr *> Exprs,
5617 SourceLocation RParenLoc);
5618
5619 /// Create an empty paren list.
5620 static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs);
5621
5622 /// Return the number of expressions in this paren list.
5623 unsigned getNumExprs() const { return ParenListExprBits.NumExprs; }
5624
5625 Expr *getExpr(unsigned Init) {
5626 assert(Init < getNumExprs() && "Initializer access out of range!");
5627 return getExprs()[Init];
5628 }
5629
5630 const Expr *getExpr(unsigned Init) const {
5631 return const_cast<ParenListExpr *>(this)->getExpr(Init);
5632 }
5633
5634 Expr **getExprs() {
5635 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>());
5636 }
5637
5638 ArrayRef<Expr *> exprs() { return llvm::ArrayRef(getExprs(), getNumExprs()); }
5639
5640 SourceLocation getLParenLoc() const { return LParenLoc; }
5641 SourceLocation getRParenLoc() const { return RParenLoc; }
5642 SourceLocation getBeginLoc() const { return getLParenLoc(); }
5643 SourceLocation getEndLoc() const { return getRParenLoc(); }
5644
5645 static bool classof(const Stmt *T) {
5646 return T->getStmtClass() == ParenListExprClass;
5647 }
5648
5649 // Iterators
5650 child_range children() {
5651 return child_range(getTrailingObjects<Stmt *>(),
5652 getTrailingObjects<Stmt *>() + getNumExprs());
5653 }
5654 const_child_range children() const {
5655 return const_child_range(getTrailingObjects<Stmt *>(),
5656 getTrailingObjects<Stmt *>() + getNumExprs());
5657 }
5658};
5659
5660/// Represents a C11 generic selection.
5661///
5662/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
5663/// expression, followed by one or more generic associations. Each generic
5664/// association specifies a type name and an expression, or "default" and an
5665/// expression (in which case it is known as a default generic association).
5666/// The type and value of the generic selection are identical to those of its
5667/// result expression, which is defined as the expression in the generic
5668/// association with a type name that is compatible with the type of the
5669/// controlling expression, or the expression in the default generic association
5670/// if no types are compatible. For example:
5671///
5672/// @code
5673/// _Generic(X, double: 1, float: 2, default: 3)
5674/// @endcode
5675///
5676/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
5677/// or 3 if "hello".
5678///
5679/// As an extension, generic selections are allowed in C++, where the following
5680/// additional semantics apply:
5681///
5682/// Any generic selection whose controlling expression is type-dependent or
5683/// which names a dependent type in its association list is result-dependent,
5684/// which means that the choice of result expression is dependent.
5685/// Result-dependent generic associations are both type- and value-dependent.
5686///
5687/// We also allow an extended form in both C and C++ where the controlling
5688/// predicate for the selection expression is a type rather than an expression.
5689/// This type argument form does not perform any conversions for the
5690/// controlling type, which makes it suitable for use with qualified type
5691/// associations, which is not possible with the expression form.
5692class GenericSelectionExpr final
5693 : public Expr,
5694 private llvm::TrailingObjects<GenericSelectionExpr, Stmt *,
5695 TypeSourceInfo *> {
5696 friend class ASTStmtReader;
5697 friend class ASTStmtWriter;
5698 friend TrailingObjects;
5699
5700 /// The number of association expressions and the index of the result
5701 /// expression in the case where the generic selection expression is not
5702 /// result-dependent. The result index is equal to ResultDependentIndex
5703 /// if and only if the generic selection expression is result-dependent.
5704 unsigned NumAssocs : 15;
5705 unsigned ResultIndex : 15; // NB: ResultDependentIndex is tied to this width.
5706 LLVM_PREFERRED_TYPE(bool)
5707 unsigned IsExprPredicate : 1;
5708 enum : unsigned {
5709 ResultDependentIndex = 0x7FFF
5710 };
5711
5712 unsigned getIndexOfControllingExpression() const {
5713 // If controlled by an expression, the first offset into the Stmt *
5714 // trailing array is the controlling expression, the associated expressions
5715 // follow this.
5716 assert(isExprPredicate() && "Asking for the controlling expression of a "
5717 "selection expr predicated by a type");
5718 return 0;
5719 }
5720
5721 unsigned getIndexOfControllingType() const {
5722 // If controlled by a type, the first offset into the TypeSourceInfo *
5723 // trailing array is the controlling type, the associated types follow this.
5724 assert(isTypePredicate() && "Asking for the controlling type of a "
5725 "selection expr predicated by an expression");
5726 return 0;
5727 }
5728
5729 unsigned getIndexOfStartOfAssociatedExprs() const {
5730 // If the predicate is a type, then the associated expressions are the only
5731 // Stmt * in the trailing array, otherwise we need to offset past the
5732 // predicate expression.
5733 return (int)isExprPredicate();
5734 }
5735
5736 unsigned getIndexOfStartOfAssociatedTypes() const {
5737 // If the predicate is a type, then the associated types follow it in the
5738 // trailing array. Otherwise, the associated types are the only
5739 // TypeSourceInfo * in the trailing array.
5740 return (int)isTypePredicate();
5741 }
5742
5743
5744 /// The location of the "default" and of the right parenthesis.
5745 SourceLocation DefaultLoc, RParenLoc;
5746
5747 // GenericSelectionExpr is followed by several trailing objects.
5748 // They are (in order):
5749 //
5750 // * A single Stmt * for the controlling expression or a TypeSourceInfo * for
5751 // the controlling type, depending on the result of isTypePredicate() or
5752 // isExprPredicate().
5753 // * An array of getNumAssocs() Stmt * for the association expressions.
5754 // * An array of getNumAssocs() TypeSourceInfo *, one for each of the
5755 // association expressions.
5756 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
5757 // Add one to account for the controlling expression; the remainder
5758 // are the associated expressions.
5759 return getNumAssocs() + (int)isExprPredicate();
5760 }
5761
5762 unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
5763 // Add one to account for the controlling type predicate, the remainder
5764 // are the associated types.
5765 return getNumAssocs() + (int)isTypePredicate();
5766 }
5767
5768 template <bool Const> class AssociationIteratorTy;
5769 /// Bundle together an association expression and its TypeSourceInfo.
5770 /// The Const template parameter is for the const and non-const versions
5771 /// of AssociationTy.
5772 template <bool Const> class AssociationTy {
5773 friend class GenericSelectionExpr;
5774 template <bool OtherConst> friend class AssociationIteratorTy;
5775 using ExprPtrTy = std::conditional_t<Const, const Expr *, Expr *>;
5776 using TSIPtrTy =
5777 std::conditional_t<Const, const TypeSourceInfo *, TypeSourceInfo *>;
5778 ExprPtrTy E;
5779 TSIPtrTy TSI;
5780 bool Selected;
5781 AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected)
5782 : E(E), TSI(TSI), Selected(Selected) {}
5783
5784 public:
5785 ExprPtrTy getAssociationExpr() const { return E; }
5786 TSIPtrTy getTypeSourceInfo() const { return TSI; }
5787 QualType getType() const { return TSI ? TSI->getType() : QualType(); }
5788 bool isSelected() const { return Selected; }
5789 AssociationTy *operator->() { return this; }
5790 const AssociationTy *operator->() const { return this; }
5791 }; // class AssociationTy
5792
5793 /// Iterator over const and non-const Association objects. The Association
5794 /// objects are created on the fly when the iterator is dereferenced.
5795 /// This abstract over how exactly the association expressions and the
5796 /// corresponding TypeSourceInfo * are stored.
5797 template <bool Const>
5798 class AssociationIteratorTy
5799 : public llvm::iterator_facade_base<
5800 AssociationIteratorTy<Const>, std::input_iterator_tag,
5801 AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>,
5802 AssociationTy<Const>> {
5803 friend class GenericSelectionExpr;
5804 // FIXME: This iterator could conceptually be a random access iterator, and
5805 // it would be nice if we could strengthen the iterator category someday.
5806 // However this iterator does not satisfy two requirements of forward
5807 // iterators:
5808 // a) reference = T& or reference = const T&
5809 // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only
5810 // if *It1 and *It2 are bound to the same objects.
5811 // An alternative design approach was discussed during review;
5812 // store an Association object inside the iterator, and return a reference
5813 // to it when dereferenced. This idea was discarded beacuse of nasty
5814 // lifetime issues:
5815 // AssociationIterator It = ...;
5816 // const Association &Assoc = *It++; // Oops, Assoc is dangling.
5817 using BaseTy = typename AssociationIteratorTy::iterator_facade_base;
5818 using StmtPtrPtrTy =
5819 std::conditional_t<Const, const Stmt *const *, Stmt **>;
5820 using TSIPtrPtrTy = std::conditional_t<Const, const TypeSourceInfo *const *,
5821 TypeSourceInfo **>;
5822 StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped.
5823 TSIPtrPtrTy TSI; // Kept in sync with E.
5824 unsigned Offset = 0, SelectedOffset = 0;
5825 AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset,
5826 unsigned SelectedOffset)
5827 : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {}
5828
5829 public:
5830 AssociationIteratorTy() : E(nullptr), TSI(nullptr) {}
5831 typename BaseTy::reference operator*() const {
5832 return AssociationTy<Const>(cast<Expr>(*E), *TSI,
5833 Offset == SelectedOffset);
5834 }
5835 typename BaseTy::pointer operator->() const { return **this; }
5836 using BaseTy::operator++;
5837 AssociationIteratorTy &operator++() {
5838 ++E;
5839 ++TSI;
5840 ++Offset;
5841 return *this;
5842 }
5843 bool operator==(AssociationIteratorTy Other) const { return E == Other.E; }
5844 }; // class AssociationIterator
5845
5846 /// Build a non-result-dependent generic selection expression accepting an
5847 /// expression predicate.
5848 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5849 Expr *ControllingExpr,
5850 ArrayRef<TypeSourceInfo *> AssocTypes,
5851 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5852 SourceLocation RParenLoc,
5853 bool ContainsUnexpandedParameterPack,
5854 unsigned ResultIndex);
5855
5856 /// Build a result-dependent generic selection expression accepting an
5857 /// expression predicate.
5858 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5859 Expr *ControllingExpr,
5860 ArrayRef<TypeSourceInfo *> AssocTypes,
5861 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5862 SourceLocation RParenLoc,
5863 bool ContainsUnexpandedParameterPack);
5864
5865 /// Build a non-result-dependent generic selection expression accepting a
5866 /// type predicate.
5867 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5868 TypeSourceInfo *ControllingType,
5869 ArrayRef<TypeSourceInfo *> AssocTypes,
5870 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5871 SourceLocation RParenLoc,
5872 bool ContainsUnexpandedParameterPack,
5873 unsigned ResultIndex);
5874
5875 /// Build a result-dependent generic selection expression accepting a type
5876 /// predicate.
5877 GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5878 TypeSourceInfo *ControllingType,
5879 ArrayRef<TypeSourceInfo *> AssocTypes,
5880 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5881 SourceLocation RParenLoc,
5882 bool ContainsUnexpandedParameterPack);
5883
5884 /// Build an empty generic selection expression for deserialization.
5885 explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs);
5886
5887public:
5888 /// Create a non-result-dependent generic selection expression accepting an
5889 /// expression predicate.
5890 static GenericSelectionExpr *
5891 Create(const ASTContext &Context, SourceLocation GenericLoc,
5892 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
5893 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5894 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
5895 unsigned ResultIndex);
5896
5897 /// Create a result-dependent generic selection expression accepting an
5898 /// expression predicate.
5899 static GenericSelectionExpr *
5900 Create(const ASTContext &Context, SourceLocation GenericLoc,
5901 Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
5902 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5903 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
5904
5905 /// Create a non-result-dependent generic selection expression accepting a
5906 /// type predicate.
5907 static GenericSelectionExpr *
5908 Create(const ASTContext &Context, SourceLocation GenericLoc,
5909 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
5910 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5911 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
5912 unsigned ResultIndex);
5913
5914 /// Create a result-dependent generic selection expression accepting a type
5915 /// predicate
5916 static GenericSelectionExpr *
5917 Create(const ASTContext &Context, SourceLocation GenericLoc,
5918 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
5919 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5920 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
5921
5922 /// Create an empty generic selection expression for deserialization.
5923 static GenericSelectionExpr *CreateEmpty(const ASTContext &Context,
5924 unsigned NumAssocs);
5925
5926 using Association = AssociationTy<false>;
5927 using ConstAssociation = AssociationTy<true>;
5928 using AssociationIterator = AssociationIteratorTy<false>;
5929 using ConstAssociationIterator = AssociationIteratorTy<true>;
5930 using association_range = llvm::iterator_range<AssociationIterator>;
5931 using const_association_range =
5932 llvm::iterator_range<ConstAssociationIterator>;
5933
5934 /// The number of association expressions.
5935 unsigned getNumAssocs() const { return NumAssocs; }
5936
5937 /// The zero-based index of the result expression's generic association in
5938 /// the generic selection's association list. Defined only if the
5939 /// generic selection is not result-dependent.
5940 unsigned getResultIndex() const {
5941 assert(!isResultDependent() &&
5942 "Generic selection is result-dependent but getResultIndex called!");
5943 return ResultIndex;
5944 }
5945
5946 /// Whether this generic selection is result-dependent.
5947 bool isResultDependent() const { return ResultIndex == ResultDependentIndex; }
5948
5949 /// Whether this generic selection uses an expression as its controlling
5950 /// argument.
5951 bool isExprPredicate() const { return IsExprPredicate; }
5952 /// Whether this generic selection uses a type as its controlling argument.
5953 bool isTypePredicate() const { return !IsExprPredicate; }
5954
5955 /// Return the controlling expression of this generic selection expression.
5956 /// Only valid to call if the selection expression used an expression as its
5957 /// controlling argument.
5958 Expr *getControllingExpr() {
5959 return cast<Expr>(
5960 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()]);
5961 }
5962 const Expr *getControllingExpr() const {
5963 return cast<Expr>(
5964 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()]);
5965 }
5966
5967 /// Return the controlling type of this generic selection expression. Only
5968 /// valid to call if the selection expression used a type as its controlling
5969 /// argument.
5970 TypeSourceInfo *getControllingType() {
5971 return getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()];
5972 }
5973 const TypeSourceInfo* getControllingType() const {
5974 return getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()];
5975 }
5976
5977 /// Return the result expression of this controlling expression. Defined if
5978 /// and only if the generic selection expression is not result-dependent.
5979 Expr *getResultExpr() {
5980 return cast<Expr>(
5981 getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
5982 getResultIndex()]);
5983 }
5984 const Expr *getResultExpr() const {
5985 return cast<Expr>(
5986 getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
5987 getResultIndex()]);
5988 }
5989
5990 ArrayRef<Expr *> getAssocExprs() const {
5991 return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() +
5992 getIndexOfStartOfAssociatedExprs()),
5993 NumAssocs};
5994 }
5995 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
5996 return {getTrailingObjects<TypeSourceInfo *>() +
5997 getIndexOfStartOfAssociatedTypes(),
5998 NumAssocs};
5999 }
6000
6001 /// Return the Ith association expression with its TypeSourceInfo,
6002 /// bundled together in GenericSelectionExpr::(Const)Association.
6003 Association getAssociation(unsigned I) {
6004 assert(I < getNumAssocs() &&
6005 "Out-of-range index in GenericSelectionExpr::getAssociation!");
6006 return Association(
6007 cast<Expr>(
6008 getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
6009 I]),
6010 getTrailingObjects<
6011 TypeSourceInfo *>()[getIndexOfStartOfAssociatedTypes() + I],
6012 !isResultDependent() && (getResultIndex() == I));
6013 }
6014 ConstAssociation getAssociation(unsigned I) const {
6015 assert(I < getNumAssocs() &&
6016 "Out-of-range index in GenericSelectionExpr::getAssociation!");
6017 return ConstAssociation(
6018 cast<Expr>(
6019 getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
6020 I]),
6021 getTrailingObjects<
6022 TypeSourceInfo *>()[getIndexOfStartOfAssociatedTypes() + I],
6023 !isResultDependent() && (getResultIndex() == I));
6024 }
6025
6026 association_range associations() {
6027 AssociationIterator Begin(getTrailingObjects<Stmt *>() +
6028 getIndexOfStartOfAssociatedExprs(),
6029 getTrailingObjects<TypeSourceInfo *>() +
6030 getIndexOfStartOfAssociatedTypes(),
6031 /*Offset=*/0, ResultIndex);
6032 AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
6033 /*Offset=*/NumAssocs, ResultIndex);
6034 return llvm::make_range(x: Begin, y: End);
6035 }
6036
6037 const_association_range associations() const {
6038 ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() +
6039 getIndexOfStartOfAssociatedExprs(),
6040 getTrailingObjects<TypeSourceInfo *>() +
6041 getIndexOfStartOfAssociatedTypes(),
6042 /*Offset=*/0, ResultIndex);
6043 ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
6044 /*Offset=*/NumAssocs, ResultIndex);
6045 return llvm::make_range(x: Begin, y: End);
6046 }
6047
6048 SourceLocation getGenericLoc() const {
6049 return GenericSelectionExprBits.GenericLoc;
6050 }
6051 SourceLocation getDefaultLoc() const { return DefaultLoc; }
6052 SourceLocation getRParenLoc() const { return RParenLoc; }
6053 SourceLocation getBeginLoc() const { return getGenericLoc(); }
6054 SourceLocation getEndLoc() const { return getRParenLoc(); }
6055
6056 static bool classof(const Stmt *T) {
6057 return T->getStmtClass() == GenericSelectionExprClass;
6058 }
6059
6060 child_range children() {
6061 return child_range(getTrailingObjects<Stmt *>(),
6062 getTrailingObjects<Stmt *>() +
6063 numTrailingObjects(OverloadToken<Stmt *>()));
6064 }
6065 const_child_range children() const {
6066 return const_child_range(getTrailingObjects<Stmt *>(),
6067 getTrailingObjects<Stmt *>() +
6068 numTrailingObjects(OverloadToken<Stmt *>()));
6069 }
6070};
6071
6072//===----------------------------------------------------------------------===//
6073// Clang Extensions
6074//===----------------------------------------------------------------------===//
6075
6076/// ExtVectorElementExpr - This represents access to specific elements of a
6077/// vector, and may occur on the left hand side or right hand side. For example
6078/// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
6079///
6080/// Note that the base may have either vector or pointer to vector type, just
6081/// like a struct field reference.
6082///
6083class ExtVectorElementExpr : public Expr {
6084 Stmt *Base;
6085 IdentifierInfo *Accessor;
6086 SourceLocation AccessorLoc;
6087public:
6088 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
6089 IdentifierInfo &accessor, SourceLocation loc)
6090 : Expr(ExtVectorElementExprClass, ty, VK,
6091 (VK == VK_PRValue ? OK_Ordinary : OK_VectorComponent)),
6092 Base(base), Accessor(&accessor), AccessorLoc(loc) {
6093 setDependence(computeDependence(E: this));
6094 }
6095
6096 /// Build an empty vector element expression.
6097 explicit ExtVectorElementExpr(EmptyShell Empty)
6098 : Expr(ExtVectorElementExprClass, Empty) { }
6099
6100 const Expr *getBase() const { return cast<Expr>(Val: Base); }
6101 Expr *getBase() { return cast<Expr>(Val: Base); }
6102 void setBase(Expr *E) { Base = E; }
6103
6104 IdentifierInfo &getAccessor() const { return *Accessor; }
6105 void setAccessor(IdentifierInfo *II) { Accessor = II; }
6106
6107 SourceLocation getAccessorLoc() const { return AccessorLoc; }
6108 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
6109
6110 /// getNumElements - Get the number of components being selected.
6111 unsigned getNumElements() const;
6112
6113 /// containsDuplicateElements - Return true if any element access is
6114 /// repeated.
6115 bool containsDuplicateElements() const;
6116
6117 /// getEncodedElementAccess - Encode the elements accessed into an llvm
6118 /// aggregate Constant of ConstantInt(s).
6119 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
6120
6121 SourceLocation getBeginLoc() const LLVM_READONLY {
6122 return getBase()->getBeginLoc();
6123 }
6124 SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; }
6125
6126 /// isArrow - Return true if the base expression is a pointer to vector,
6127 /// return false if the base expression is a vector.
6128 bool isArrow() const;
6129
6130 static bool classof(const Stmt *T) {
6131 return T->getStmtClass() == ExtVectorElementExprClass;
6132 }
6133
6134 // Iterators
6135 child_range children() { return child_range(&Base, &Base+1); }
6136 const_child_range children() const {
6137 return const_child_range(&Base, &Base + 1);
6138 }
6139};
6140
6141/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
6142/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
6143class BlockExpr : public Expr {
6144protected:
6145 BlockDecl *TheBlock;
6146public:
6147 BlockExpr(BlockDecl *BD, QualType ty)
6148 : Expr(BlockExprClass, ty, VK_PRValue, OK_Ordinary), TheBlock(BD) {
6149 setDependence(computeDependence(E: this));
6150 }
6151
6152 /// Build an empty block expression.
6153 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
6154
6155 const BlockDecl *getBlockDecl() const { return TheBlock; }
6156 BlockDecl *getBlockDecl() { return TheBlock; }
6157 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
6158
6159 // Convenience functions for probing the underlying BlockDecl.
6160 SourceLocation getCaretLocation() const;
6161 const Stmt *getBody() const;
6162 Stmt *getBody();
6163
6164 SourceLocation getBeginLoc() const LLVM_READONLY {
6165 return getCaretLocation();
6166 }
6167 SourceLocation getEndLoc() const LLVM_READONLY {
6168 return getBody()->getEndLoc();
6169 }
6170
6171 /// getFunctionType - Return the underlying function type for this block.
6172 const FunctionProtoType *getFunctionType() const;
6173
6174 static bool classof(const Stmt *T) {
6175 return T->getStmtClass() == BlockExprClass;
6176 }
6177
6178 // Iterators
6179 child_range children() {
6180 return child_range(child_iterator(), child_iterator());
6181 }
6182 const_child_range children() const {
6183 return const_child_range(const_child_iterator(), const_child_iterator());
6184 }
6185};
6186
6187/// Copy initialization expr of a __block variable and a boolean flag that
6188/// indicates whether the expression can throw.
6189struct BlockVarCopyInit {
6190 BlockVarCopyInit() = default;
6191 BlockVarCopyInit(Expr *CopyExpr, bool CanThrow)
6192 : ExprAndFlag(CopyExpr, CanThrow) {}
6193 void setExprAndFlag(Expr *CopyExpr, bool CanThrow) {
6194 ExprAndFlag.setPointerAndInt(PtrVal: CopyExpr, IntVal: CanThrow);
6195 }
6196 Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); }
6197 bool canThrow() const { return ExprAndFlag.getInt(); }
6198 llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag;
6199};
6200
6201/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
6202/// This AST node provides support for reinterpreting a type to another
6203/// type of the same size.
6204class AsTypeExpr : public Expr {
6205private:
6206 Stmt *SrcExpr;
6207 SourceLocation BuiltinLoc, RParenLoc;
6208
6209 friend class ASTReader;
6210 friend class ASTStmtReader;
6211 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
6212
6213public:
6214 AsTypeExpr(Expr *SrcExpr, QualType DstType, ExprValueKind VK,
6215 ExprObjectKind OK, SourceLocation BuiltinLoc,
6216 SourceLocation RParenLoc)
6217 : Expr(AsTypeExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
6218 BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
6219 setDependence(computeDependence(E: this));
6220 }
6221
6222 /// getSrcExpr - Return the Expr to be converted.
6223 Expr *getSrcExpr() const { return cast<Expr>(Val: SrcExpr); }
6224
6225 /// getBuiltinLoc - Return the location of the __builtin_astype token.
6226 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
6227
6228 /// getRParenLoc - Return the location of final right parenthesis.
6229 SourceLocation getRParenLoc() const { return RParenLoc; }
6230
6231 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
6232 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
6233
6234 static bool classof(const Stmt *T) {
6235 return T->getStmtClass() == AsTypeExprClass;
6236 }
6237
6238 // Iterators
6239 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
6240 const_child_range children() const {
6241 return const_child_range(&SrcExpr, &SrcExpr + 1);
6242 }
6243};
6244
6245/// PseudoObjectExpr - An expression which accesses a pseudo-object
6246/// l-value. A pseudo-object is an abstract object, accesses to which
6247/// are translated to calls. The pseudo-object expression has a
6248/// syntactic form, which shows how the expression was actually
6249/// written in the source code, and a semantic form, which is a series
6250/// of expressions to be executed in order which detail how the
6251/// operation is actually evaluated. Optionally, one of the semantic
6252/// forms may also provide a result value for the expression.
6253///
6254/// If any of the semantic-form expressions is an OpaqueValueExpr,
6255/// that OVE is required to have a source expression, and it is bound
6256/// to the result of that source expression. Such OVEs may appear
6257/// only in subsequent semantic-form expressions and as
6258/// sub-expressions of the syntactic form.
6259///
6260/// PseudoObjectExpr should be used only when an operation can be
6261/// usefully described in terms of fairly simple rewrite rules on
6262/// objects and functions that are meant to be used by end-developers.
6263/// For example, under the Itanium ABI, dynamic casts are implemented
6264/// as a call to a runtime function called __dynamic_cast; using this
6265/// class to describe that would be inappropriate because that call is
6266/// not really part of the user-visible semantics, and instead the
6267/// cast is properly reflected in the AST and IR-generation has been
6268/// taught to generate the call as necessary. In contrast, an
6269/// Objective-C property access is semantically defined to be
6270/// equivalent to a particular message send, and this is very much
6271/// part of the user model. The name of this class encourages this
6272/// modelling design.
6273class PseudoObjectExpr final
6274 : public Expr,
6275 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
6276 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
6277 // Always at least two, because the first sub-expression is the
6278 // syntactic form.
6279
6280 // PseudoObjectExprBits.ResultIndex - The index of the
6281 // sub-expression holding the result. 0 means the result is void,
6282 // which is unambiguous because it's the index of the syntactic
6283 // form. Note that this is therefore 1 higher than the value passed
6284 // in to Create, which is an index within the semantic forms.
6285 // Note also that ASTStmtWriter assumes this encoding.
6286
6287 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
6288 const Expr * const *getSubExprsBuffer() const {
6289 return getTrailingObjects<Expr *>();
6290 }
6291
6292 PseudoObjectExpr(QualType type, ExprValueKind VK,
6293 Expr *syntactic, ArrayRef<Expr*> semantic,
6294 unsigned resultIndex);
6295
6296 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
6297
6298 unsigned getNumSubExprs() const {
6299 return PseudoObjectExprBits.NumSubExprs;
6300 }
6301
6302public:
6303 /// NoResult - A value for the result index indicating that there is
6304 /// no semantic result.
6305 enum : unsigned { NoResult = ~0U };
6306
6307 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
6308 ArrayRef<Expr*> semantic,
6309 unsigned resultIndex);
6310
6311 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
6312 unsigned numSemanticExprs);
6313
6314 /// Return the syntactic form of this expression, i.e. the
6315 /// expression it actually looks like. Likely to be expressed in
6316 /// terms of OpaqueValueExprs bound in the semantic form.
6317 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
6318 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
6319
6320 /// Return the index of the result-bearing expression into the semantics
6321 /// expressions, or PseudoObjectExpr::NoResult if there is none.
6322 unsigned getResultExprIndex() const {
6323 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
6324 return PseudoObjectExprBits.ResultIndex - 1;
6325 }
6326
6327 /// Return the result-bearing expression, or null if there is none.
6328 Expr *getResultExpr() {
6329 if (PseudoObjectExprBits.ResultIndex == 0)
6330 return nullptr;
6331 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
6332 }
6333 const Expr *getResultExpr() const {
6334 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
6335 }
6336
6337 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
6338
6339 typedef Expr * const *semantics_iterator;
6340 typedef const Expr * const *const_semantics_iterator;
6341 semantics_iterator semantics_begin() {
6342 return getSubExprsBuffer() + 1;
6343 }
6344 const_semantics_iterator semantics_begin() const {
6345 return getSubExprsBuffer() + 1;
6346 }
6347 semantics_iterator semantics_end() {
6348 return getSubExprsBuffer() + getNumSubExprs();
6349 }
6350 const_semantics_iterator semantics_end() const {
6351 return getSubExprsBuffer() + getNumSubExprs();
6352 }
6353
6354 ArrayRef<Expr*> semantics() {
6355 return ArrayRef(semantics_begin(), semantics_end());
6356 }
6357 ArrayRef<const Expr*> semantics() const {
6358 return ArrayRef(semantics_begin(), semantics_end());
6359 }
6360
6361 Expr *getSemanticExpr(unsigned index) {
6362 assert(index + 1 < getNumSubExprs());
6363 return getSubExprsBuffer()[index + 1];
6364 }
6365 const Expr *getSemanticExpr(unsigned index) const {
6366 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
6367 }
6368
6369 SourceLocation getExprLoc() const LLVM_READONLY {
6370 return getSyntacticForm()->getExprLoc();
6371 }
6372
6373 SourceLocation getBeginLoc() const LLVM_READONLY {
6374 return getSyntacticForm()->getBeginLoc();
6375 }
6376 SourceLocation getEndLoc() const LLVM_READONLY {
6377 return getSyntacticForm()->getEndLoc();
6378 }
6379
6380 child_range children() {
6381 const_child_range CCR =
6382 const_cast<const PseudoObjectExpr *>(this)->children();
6383 return child_range(cast_away_const(RHS: CCR.begin()),
6384 cast_away_const(RHS: CCR.end()));
6385 }
6386 const_child_range children() const {
6387 Stmt *const *cs = const_cast<Stmt *const *>(
6388 reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
6389 return const_child_range(cs, cs + getNumSubExprs());
6390 }
6391
6392 static bool classof(const Stmt *T) {
6393 return T->getStmtClass() == PseudoObjectExprClass;
6394 }
6395
6396 friend TrailingObjects;
6397 friend class ASTStmtReader;
6398};
6399
6400/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
6401/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
6402/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
6403/// and corresponding __opencl_atomic_* for OpenCL 2.0.
6404/// All of these instructions take one primary pointer, at least one memory
6405/// order. The instructions for which getScopeModel returns non-null value
6406/// take one synch scope.
6407class AtomicExpr : public Expr {
6408public:
6409 enum AtomicOp {
6410#define BUILTIN(ID, TYPE, ATTRS)
6411#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
6412#include "clang/Basic/Builtins.inc"
6413 // Avoid trailing comma
6414 BI_First = 0
6415 };
6416
6417private:
6418 /// Location of sub-expressions.
6419 /// The location of Scope sub-expression is NumSubExprs - 1, which is
6420 /// not fixed, therefore is not defined in enum.
6421 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
6422 Stmt *SubExprs[END_EXPR + 1];
6423 unsigned NumSubExprs;
6424 SourceLocation BuiltinLoc, RParenLoc;
6425 AtomicOp Op;
6426
6427 friend class ASTStmtReader;
6428public:
6429 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
6430 AtomicOp op, SourceLocation RP);
6431
6432 /// Determine the number of arguments the specified atomic builtin
6433 /// should have.
6434 static unsigned getNumSubExprs(AtomicOp Op);
6435
6436 /// Build an empty AtomicExpr.
6437 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
6438
6439 Expr *getPtr() const {
6440 return cast<Expr>(SubExprs[PTR]);
6441 }
6442 Expr *getOrder() const {
6443 return cast<Expr>(SubExprs[ORDER]);
6444 }
6445 Expr *getScope() const {
6446 assert(getScopeModel() && "No scope");
6447 return cast<Expr>(SubExprs[NumSubExprs - 1]);
6448 }
6449 Expr *getVal1() const {
6450 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
6451 return cast<Expr>(SubExprs[ORDER]);
6452 assert(NumSubExprs > VAL1);
6453 return cast<Expr>(SubExprs[VAL1]);
6454 }
6455 Expr *getOrderFail() const {
6456 assert(NumSubExprs > ORDER_FAIL);
6457 return cast<Expr>(SubExprs[ORDER_FAIL]);
6458 }
6459 Expr *getVal2() const {
6460 if (Op == AO__atomic_exchange || Op == AO__scoped_atomic_exchange)
6461 return cast<Expr>(SubExprs[ORDER_FAIL]);
6462 assert(NumSubExprs > VAL2);
6463 return cast<Expr>(SubExprs[VAL2]);
6464 }
6465 Expr *getWeak() const {
6466 assert(NumSubExprs > WEAK);
6467 return cast<Expr>(SubExprs[WEAK]);
6468 }
6469 QualType getValueType() const;
6470
6471 AtomicOp getOp() const { return Op; }
6472 StringRef getOpAsString() const {
6473 switch (Op) {
6474#define BUILTIN(ID, TYPE, ATTRS)
6475#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
6476 case AO##ID: \
6477 return #ID;
6478#include "clang/Basic/Builtins.inc"
6479 }
6480 llvm_unreachable("not an atomic operator?");
6481 }
6482 unsigned getNumSubExprs() const { return NumSubExprs; }
6483
6484 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
6485 const Expr * const *getSubExprs() const {
6486 return reinterpret_cast<Expr * const *>(SubExprs);
6487 }
6488
6489 bool isVolatile() const {
6490 return getPtr()->getType()->getPointeeType().isVolatileQualified();
6491 }
6492
6493 bool isCmpXChg() const {
6494 return getOp() == AO__c11_atomic_compare_exchange_strong ||
6495 getOp() == AO__c11_atomic_compare_exchange_weak ||
6496 getOp() == AO__hip_atomic_compare_exchange_strong ||
6497 getOp() == AO__opencl_atomic_compare_exchange_strong ||
6498 getOp() == AO__opencl_atomic_compare_exchange_weak ||
6499 getOp() == AO__hip_atomic_compare_exchange_weak ||
6500 getOp() == AO__atomic_compare_exchange ||
6501 getOp() == AO__atomic_compare_exchange_n ||
6502 getOp() == AO__scoped_atomic_compare_exchange ||
6503 getOp() == AO__scoped_atomic_compare_exchange_n;
6504 }
6505
6506 bool isOpenCL() const {
6507 return getOp() >= AO__opencl_atomic_compare_exchange_strong &&
6508 getOp() <= AO__opencl_atomic_store;
6509 }
6510
6511 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
6512 SourceLocation getRParenLoc() const { return RParenLoc; }
6513
6514 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
6515 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
6516
6517 static bool classof(const Stmt *T) {
6518 return T->getStmtClass() == AtomicExprClass;
6519 }
6520
6521 // Iterators
6522 child_range children() {
6523 return child_range(SubExprs, SubExprs+NumSubExprs);
6524 }
6525 const_child_range children() const {
6526 return const_child_range(SubExprs, SubExprs + NumSubExprs);
6527 }
6528
6529 /// Get atomic scope model for the atomic op code.
6530 /// \return empty atomic scope model if the atomic op code does not have
6531 /// scope operand.
6532 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
6533 // FIXME: Allow grouping of builtins to be able to only check >= and <=
6534 if (Op >= AO__opencl_atomic_compare_exchange_strong &&
6535 Op <= AO__opencl_atomic_store && Op != AO__opencl_atomic_init)
6536 return AtomicScopeModel::create(K: AtomicScopeModelKind::OpenCL);
6537 if (Op >= AO__hip_atomic_compare_exchange_strong &&
6538 Op <= AO__hip_atomic_store)
6539 return AtomicScopeModel::create(K: AtomicScopeModelKind::HIP);
6540 if (Op >= AO__scoped_atomic_add_fetch && Op <= AO__scoped_atomic_xor_fetch)
6541 return AtomicScopeModel::create(K: AtomicScopeModelKind::Generic);
6542 return AtomicScopeModel::create(K: AtomicScopeModelKind::None);
6543 }
6544
6545 /// Get atomic scope model.
6546 /// \return empty atomic scope model if this atomic expression does not have
6547 /// scope operand.
6548 std::unique_ptr<AtomicScopeModel> getScopeModel() const {
6549 return getScopeModel(getOp());
6550 }
6551};
6552
6553/// TypoExpr - Internal placeholder for expressions where typo correction
6554/// still needs to be performed and/or an error diagnostic emitted.
6555class TypoExpr : public Expr {
6556 // The location for the typo name.
6557 SourceLocation TypoLoc;
6558
6559public:
6560 TypoExpr(QualType T, SourceLocation TypoLoc)
6561 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary), TypoLoc(TypoLoc) {
6562 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
6563 setDependence(ExprDependence::TypeValueInstantiation |
6564 ExprDependence::Error);
6565 }
6566
6567 child_range children() {
6568 return child_range(child_iterator(), child_iterator());
6569 }
6570 const_child_range children() const {
6571 return const_child_range(const_child_iterator(), const_child_iterator());
6572 }
6573
6574 SourceLocation getBeginLoc() const LLVM_READONLY { return TypoLoc; }
6575 SourceLocation getEndLoc() const LLVM_READONLY { return TypoLoc; }
6576
6577 static bool classof(const Stmt *T) {
6578 return T->getStmtClass() == TypoExprClass;
6579 }
6580
6581};
6582
6583/// Frontend produces RecoveryExprs on semantic errors that prevent creating
6584/// other well-formed expressions. E.g. when type-checking of a binary operator
6585/// fails, we cannot produce a BinaryOperator expression. Instead, we can choose
6586/// to produce a recovery expression storing left and right operands.
6587///
6588/// RecoveryExpr does not have any semantic meaning in C++, it is only useful to
6589/// preserve expressions in AST that would otherwise be dropped. It captures
6590/// subexpressions of some expression that we could not construct and source
6591/// range covered by the expression.
6592///
6593/// By default, RecoveryExpr uses dependence-bits to take advantage of existing
6594/// machinery to deal with dependent code in C++, e.g. RecoveryExpr is preserved
6595/// in `decltype(<broken-expr>)` as part of the `DependentDecltypeType`. In
6596/// addition to that, clang does not report most errors on dependent
6597/// expressions, so we get rid of bogus errors for free. However, note that
6598/// unlike other dependent expressions, RecoveryExpr can be produced in
6599/// non-template contexts.
6600///
6601/// We will preserve the type in RecoveryExpr when the type is known, e.g.
6602/// preserving the return type for a broken non-overloaded function call, a
6603/// overloaded call where all candidates have the same return type. In this
6604/// case, the expression is not type-dependent (unless the known type is itself
6605/// dependent)
6606///
6607/// One can also reliably suppress all bogus errors on expressions containing
6608/// recovery expressions by examining results of Expr::containsErrors().
6609class RecoveryExpr final : public Expr,
6610 private llvm::TrailingObjects<RecoveryExpr, Expr *> {
6611public:
6612 static RecoveryExpr *Create(ASTContext &Ctx, QualType T,
6613 SourceLocation BeginLoc, SourceLocation EndLoc,
6614 ArrayRef<Expr *> SubExprs);
6615 static RecoveryExpr *CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs);
6616
6617 ArrayRef<Expr *> subExpressions() {
6618 auto *B = getTrailingObjects<Expr *>();
6619 return llvm::ArrayRef(B, B + NumExprs);
6620 }
6621
6622 ArrayRef<const Expr *> subExpressions() const {
6623 return const_cast<RecoveryExpr *>(this)->subExpressions();
6624 }
6625
6626 child_range children() {
6627 Stmt **B = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
6628 return child_range(B, B + NumExprs);
6629 }
6630
6631 SourceLocation getBeginLoc() const { return BeginLoc; }
6632 SourceLocation getEndLoc() const { return EndLoc; }
6633
6634 static bool classof(const Stmt *T) {
6635 return T->getStmtClass() == RecoveryExprClass;
6636 }
6637
6638private:
6639 RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
6640 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs);
6641 RecoveryExpr(EmptyShell Empty, unsigned NumSubExprs)
6642 : Expr(RecoveryExprClass, Empty), NumExprs(NumSubExprs) {}
6643
6644 size_t numTrailingObjects(OverloadToken<Stmt *>) const { return NumExprs; }
6645
6646 SourceLocation BeginLoc, EndLoc;
6647 unsigned NumExprs;
6648 friend TrailingObjects;
6649 friend class ASTStmtReader;
6650 friend class ASTStmtWriter;
6651};
6652
6653} // end namespace clang
6654
6655#endif // LLVM_CLANG_AST_EXPR_H
6656

source code of clang/include/clang/AST/Expr.h