Warning: This file is not a C or C++ file. It does not have highlighting.

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

Warning: This file is not a C or C++ file. It does not have highlighting.

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