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