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