clang 19.0.0git
Expr.h
Go to the documentation of this file.
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
17#include "clang/AST/APValue.h"
18#include "clang/AST/ASTVector.h"
20#include "clang/AST/Decl.h"
24#include "clang/AST/Stmt.h"
26#include "clang/AST/Type.h"
31#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APSInt.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/ADT/iterator.h"
36#include "llvm/ADT/iterator_range.h"
37#include "llvm/Support/AtomicOrdering.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/TrailingObjects.h"
40#include <optional>
41
42namespace clang {
43 class APValue;
44 class ASTContext;
45 class BlockDecl;
46 class CXXBaseSpecifier;
47 class CXXMemberCallExpr;
48 class CXXOperatorCallExpr;
49 class CastExpr;
50 class Decl;
51 class IdentifierInfo;
52 class MaterializeTemporaryExpr;
53 class NamedDecl;
54 class ObjCPropertyRefExpr;
55 class OpaqueValueExpr;
56 class ParmVarDecl;
57 class StringLiteral;
58 class TargetInfo;
59 class ValueDecl;
60
61/// A simple array of base specifiers.
63
64/// An adjustment to be made to the temporary created when emitting a
65/// reference binding, which accesses a particular subobject of that temporary.
67 enum {
72
73 struct DTB {
76 };
77
78 struct P {
81 };
82
83 union {
86 struct P Ptr;
87 };
88
90 const CXXRecordDecl *DerivedClass)
92 DerivedToBase.BasePath = BasePath;
93 DerivedToBase.DerivedClass = DerivedClass;
94 }
95
97 this->Field = Field;
98 }
99
102 this->Ptr.MPT = MPT;
103 this->Ptr.RHS = RHS;
104 }
105};
106
107/// This represents one expression. Note that Expr's are subclasses of Stmt.
108/// This allows an expression to be transparently used any place a Stmt is
109/// required.
110class Expr : public ValueStmt {
111 QualType TR;
112
113public:
114 Expr() = delete;
115 Expr(const Expr&) = delete;
116 Expr(Expr &&) = delete;
117 Expr &operator=(const Expr&) = delete;
118 Expr &operator=(Expr&&) = delete;
119
120protected:
122 : ValueStmt(SC) {
123 ExprBits.Dependent = 0;
124 ExprBits.ValueKind = VK;
125 ExprBits.ObjectKind = OK;
126 assert(ExprBits.ObjectKind == OK && "truncated kind");
127 setType(T);
128 }
129
130 /// Construct an empty expression.
131 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
132
133 /// Each concrete expr subclass is expected to compute its dependence and call
134 /// this in the constructor.
136 ExprBits.Dependent = static_cast<unsigned>(Deps);
137 }
138 friend class ASTImporter; // Sets dependence directly.
139 friend class ASTStmtReader; // Sets dependence directly.
140
141public:
142 QualType getType() const { return TR; }
144 // In C++, the type of an expression is always adjusted so that it
145 // will not have reference type (C++ [expr]p6). Use
146 // QualType::getNonReferenceType() to retrieve the non-reference
147 // type. Additionally, inspect Expr::isLvalue to determine whether
148 // an expression that is adjusted in this manner should be
149 // considered an lvalue.
150 assert((t.isNull() || !t->isReferenceType()) &&
151 "Expressions can't have reference type");
152
153 TR = t;
154 }
155
156 /// If this expression is an enumeration constant, return the
157 /// enumeration type under which said constant was declared.
158 /// Otherwise return the expression's type.
159 /// Note this effectively circumvents the weak typing of C's enum constants
160 QualType getEnumCoercedType(const ASTContext &Ctx) const;
161
163 return static_cast<ExprDependence>(ExprBits.Dependent);
164 }
165
166 /// Determines whether the value of this expression depends on
167 /// - a template parameter (C++ [temp.dep.constexpr])
168 /// - or an error, whose resolution is unknown
169 ///
170 /// For example, the array bound of "Chars" in the following example is
171 /// value-dependent.
172 /// @code
173 /// template<int Size, char (&Chars)[Size]> struct meta_string;
174 /// @endcode
175 bool isValueDependent() const {
176 return static_cast<bool>(getDependence() & ExprDependence::Value);
177 }
178
179 /// Determines whether the type of this expression depends on
180 /// - a template parameter (C++ [temp.dep.expr], which means that its type
181 /// could change from one template instantiation to the next)
182 /// - or an error
183 ///
184 /// For example, the expressions "x" and "x + y" are type-dependent in
185 /// the following code, but "y" is not type-dependent:
186 /// @code
187 /// template<typename T>
188 /// void add(T x, int y) {
189 /// x + y;
190 /// }
191 /// @endcode
192 bool isTypeDependent() const {
193 return static_cast<bool>(getDependence() & ExprDependence::Type);
194 }
195
196 /// Whether this expression is instantiation-dependent, meaning that
197 /// it depends in some way on
198 /// - a template parameter (even if neither its type nor (constant) value
199 /// can change due to the template instantiation)
200 /// - or an error
201 ///
202 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
203 /// instantiation-dependent (since it involves a template parameter \c T), but
204 /// is neither type- nor value-dependent, since the type of the inner
205 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
206 /// \c sizeof is known.
207 ///
208 /// \code
209 /// template<typename T>
210 /// void f(T x, T y) {
211 /// sizeof(sizeof(T() + T());
212 /// }
213 /// \endcode
214 ///
215 /// \code
216 /// void func(int) {
217 /// func(); // the expression is instantiation-dependent, because it depends
218 /// // on an error.
219 /// }
220 /// \endcode
222 return static_cast<bool>(getDependence() & ExprDependence::Instantiation);
223 }
224
225 /// Whether this expression contains an unexpanded parameter
226 /// pack (for C++11 variadic templates).
227 ///
228 /// Given the following function template:
229 ///
230 /// \code
231 /// template<typename F, typename ...Types>
232 /// void forward(const F &f, Types &&...args) {
233 /// f(static_cast<Types&&>(args)...);
234 /// }
235 /// \endcode
236 ///
237 /// The expressions \c args and \c static_cast<Types&&>(args) both
238 /// contain parameter packs.
240 return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
241 }
242
243 /// Whether this expression contains subexpressions which had errors, e.g. a
244 /// TypoExpr.
245 bool containsErrors() const {
246 return static_cast<bool>(getDependence() & ExprDependence::Error);
247 }
248
249 /// getExprLoc - Return the preferred location for the arrow when diagnosing
250 /// a problem with a generic expression.
251 SourceLocation getExprLoc() const LLVM_READONLY;
252
253 /// Determine whether an lvalue-to-rvalue conversion should implicitly be
254 /// applied to this expression if it appears as a discarded-value expression
255 /// in C++11 onwards. This applies to certain forms of volatile glvalues.
257
258 /// isUnusedResultAWarning - Return true if this immediate expression should
259 /// be warned about if the result is unused. If so, fill in expr, location,
260 /// and ranges with expr to warn on and source locations/ranges appropriate
261 /// for a warning.
262 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
263 SourceRange &R1, SourceRange &R2,
264 ASTContext &Ctx) const;
265
266 /// isLValue - True if this expression is an "l-value" according to
267 /// the rules of the current language. C and C++ give somewhat
268 /// different rules for this concept, but in general, the result of
269 /// an l-value expression identifies a specific object whereas the
270 /// result of an r-value expression is a value detached from any
271 /// specific storage.
272 ///
273 /// C++11 divides the concept of "r-value" into pure r-values
274 /// ("pr-values") and so-called expiring values ("x-values"), which
275 /// identify specific objects that can be safely cannibalized for
276 /// their resources.
277 bool isLValue() const { return getValueKind() == VK_LValue; }
278 bool isPRValue() const { return getValueKind() == VK_PRValue; }
279 bool isXValue() const { return getValueKind() == VK_XValue; }
280 bool isGLValue() const { return getValueKind() != VK_PRValue; }
281
293 };
294 /// Reasons why an expression might not be an l-value.
296
303 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
315 };
316 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
317 /// does not have an incomplete type, does not have a const-qualified type,
318 /// and if it is a structure or union, does not have any member (including,
319 /// recursively, any member or element of all contained aggregates or unions)
320 /// with a const-qualified type.
321 ///
322 /// \param Loc [in,out] - A source location which *may* be filled
323 /// in with the location of the expression making this a
324 /// non-modifiable lvalue, if specified.
326 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
327
328 /// The return type of classify(). Represents the C++11 expression
329 /// taxonomy.
331 public:
332 /// The various classification results. Most of these mean prvalue.
333 enum Kinds {
336 CL_Function, // Functions cannot be lvalues in C.
337 CL_Void, // Void cannot be an lvalue in C.
338 CL_AddressableVoid, // Void expression whose address can be taken in C.
339 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
340 CL_MemberFunction, // An expression referring to a member function
342 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
343 CL_ArrayTemporary, // A temporary of array type.
344 CL_ObjCMessageRValue, // ObjC message is an rvalue
345 CL_PRValue // A prvalue for any other reason, of any other type
346 };
347 /// The results of modification testing.
349 CM_Untested, // testModifiable was false.
351 CM_RValue, // Not modifiable because it's an rvalue
352 CM_Function, // Not modifiable because it's a function; C++ only
353 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
354 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
360 };
361
362 private:
363 friend class Expr;
364
365 unsigned short Kind;
366 unsigned short Modifiable;
367
368 explicit Classification(Kinds k, ModifiableType m)
369 : Kind(k), Modifiable(m)
370 {}
371
372 public:
374
375 Kinds getKind() const { return static_cast<Kinds>(Kind); }
377 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
378 return static_cast<ModifiableType>(Modifiable);
379 }
380 bool isLValue() const { return Kind == CL_LValue; }
381 bool isXValue() const { return Kind == CL_XValue; }
382 bool isGLValue() const { return Kind <= CL_XValue; }
383 bool isPRValue() const { return Kind >= CL_Function; }
384 bool isRValue() const { return Kind >= CL_XValue; }
385 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
386
387 /// Create a simple, modifiably lvalue
390 }
391
392 };
393 /// Classify - Classify this expression according to the C++11
394 /// expression taxonomy.
395 ///
396 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
397 /// old lvalue vs rvalue. This function determines the type of expression this
398 /// is. There are three expression types:
399 /// - lvalues are classical lvalues as in C++03.
400 /// - prvalues are equivalent to rvalues in C++03.
401 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
402 /// function returning an rvalue reference.
403 /// lvalues and xvalues are collectively referred to as glvalues, while
404 /// prvalues and xvalues together form rvalues.
406 return ClassifyImpl(Ctx, nullptr);
407 }
408
409 /// ClassifyModifiable - Classify this expression according to the
410 /// C++11 expression taxonomy, and see if it is valid on the left side
411 /// of an assignment.
412 ///
413 /// This function extends classify in that it also tests whether the
414 /// expression is modifiable (C99 6.3.2.1p1).
415 /// \param Loc A source location that might be filled with a relevant location
416 /// if the expression is not modifiable.
418 return ClassifyImpl(Ctx, &Loc);
419 }
420
421 /// Returns the set of floating point options that apply to this expression.
422 /// Only meaningful for operations on floating point values.
424
425 /// getValueKindForType - Given a formal return or parameter type,
426 /// give its value kind.
428 if (const ReferenceType *RT = T->getAs<ReferenceType>())
429 return (isa<LValueReferenceType>(RT)
430 ? VK_LValue
431 : (RT->getPointeeType()->isFunctionType()
432 ? VK_LValue : VK_XValue));
433 return VK_PRValue;
434 }
435
436 /// getValueKind - The value kind that this expression produces.
438 return static_cast<ExprValueKind>(ExprBits.ValueKind);
439 }
440
441 /// getObjectKind - The object kind that this expression produces.
442 /// Object kinds are meaningful only for expressions that yield an
443 /// l-value or x-value.
445 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
446 }
447
450 return (OK == OK_Ordinary || OK == OK_BitField);
451 }
452
453 /// setValueKind - Set the value kind produced by this expression.
454 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
455
456 /// setObjectKind - Set the object kind produced by this expression.
457 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
458
459private:
460 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
461
462public:
463
464 /// Returns true if this expression is a gl-value that
465 /// potentially refers to a bit-field.
466 ///
467 /// In C++, whether a gl-value refers to a bitfield is essentially
468 /// an aspect of the value-kind type system.
469 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
470
471 /// If this expression refers to a bit-field, retrieve the
472 /// declaration of that bit-field.
473 ///
474 /// Note that this returns a non-null pointer in subtly different
475 /// places than refersToBitField returns true. In particular, this can
476 /// return a non-null pointer even for r-values loaded from
477 /// bit-fields, but it will return null for a conditional bit-field.
479
480 /// If this expression refers to an enum constant, retrieve its declaration
482
484 return const_cast<Expr *>(this)->getEnumConstantDecl();
485 }
486
488 return const_cast<Expr*>(this)->getSourceBitField();
489 }
490
493 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
494 }
495
496 /// If this expression is an l-value for an Objective C
497 /// property, find the underlying property reference expression.
499
500 /// Check if this expression is the ObjC 'self' implicit parameter.
501 bool isObjCSelfExpr() const;
502
503 /// Returns whether this expression refers to a vector element.
504 bool refersToVectorElement() const;
505
506 /// Returns whether this expression refers to a matrix element.
509 }
510
511 /// Returns whether this expression refers to a global register
512 /// variable.
513 bool refersToGlobalRegisterVar() const;
514
515 /// Returns whether this expression has a placeholder type.
516 bool hasPlaceholderType() const {
517 return getType()->isPlaceholderType();
518 }
519
520 /// Returns whether this expression has a specific placeholder type.
523 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
524 return BT->getKind() == K;
525 return false;
526 }
527
528 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
529 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
530 /// but also int expressions which are produced by things like comparisons in
531 /// C.
532 ///
533 /// \param Semantic If true, only return true for expressions that are known
534 /// to be semantically boolean, which might not be true even for expressions
535 /// that are known to evaluate to 0/1. For instance, reading an unsigned
536 /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
537 /// semantically correspond to a bool.
538 bool isKnownToHaveBooleanValue(bool Semantic = true) const;
539
540 /// Check whether this array fits the idiom of a flexible array member,
541 /// depending on the value of -fstrict-flex-array.
542 /// When IgnoreTemplateOrMacroSubstitution is set, it doesn't consider sizes
543 /// resulting from the substitution of a macro or a template as special sizes.
545 ASTContext &Context,
546 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
547 bool IgnoreTemplateOrMacroSubstitution = false) const;
548
549 /// isIntegerConstantExpr - Return the value if this expression is a valid
550 /// integer constant expression. If not a valid i-c-e, return std::nullopt
551 /// and fill in Loc (if specified) with the location of the invalid
552 /// expression.
553 ///
554 /// Note: This does not perform the implicit conversions required by C++11
555 /// [expr.const]p5.
556 std::optional<llvm::APSInt>
558 SourceLocation *Loc = nullptr) const;
559 bool isIntegerConstantExpr(const ASTContext &Ctx,
560 SourceLocation *Loc = nullptr) const;
561
562 /// isCXX98IntegralConstantExpr - Return true if this expression is an
563 /// integral constant expression in C++98. Can only be used in C++.
564 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
565
566 /// isCXX11ConstantExpr - Return true if this expression is a constant
567 /// expression in C++11. Can only be used in C++.
568 ///
569 /// Note: This does not perform the implicit conversions required by C++11
570 /// [expr.const]p5.
571 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
572 SourceLocation *Loc = nullptr) const;
573
574 /// isPotentialConstantExpr - Return true if this function's definition
575 /// might be usable in a constant expression in C++11, if it were marked
576 /// constexpr. Return false if the function can never produce a constant
577 /// expression, along with diagnostics describing why not.
578 static bool isPotentialConstantExpr(const FunctionDecl *FD,
580 PartialDiagnosticAt> &Diags);
581
582 /// isPotentialConstantExprUnevaluated - Return true if this expression might
583 /// be usable in a constant expression in C++11 in an unevaluated context, if
584 /// it were in function FD marked constexpr. Return false if the function can
585 /// never produce a constant expression, along with diagnostics describing
586 /// why not.
588 const FunctionDecl *FD,
590 PartialDiagnosticAt> &Diags);
591
592 /// isConstantInitializer - Returns true if this expression can be emitted to
593 /// IR as a constant, and thus can be used as a constant initializer in C.
594 /// If this expression is not constant and Culprit is non-null,
595 /// it is used to store the address of first non constant expr.
596 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
597 const Expr **Culprit = nullptr) const;
598
599 /// If this expression is an unambiguous reference to a single declaration,
600 /// in the style of __builtin_function_start, return that declaration. Note
601 /// that this may return a non-static member function or field in C++ if this
602 /// expression is a member pointer constant.
603 const ValueDecl *getAsBuiltinConstantDeclRef(const ASTContext &Context) const;
604
605 /// EvalStatus is a struct with detailed info about an evaluation in progress.
606 struct EvalStatus {
607 /// Whether the evaluated expression has side effects.
608 /// For example, (f() && 0) can be folded, but it still has side effects.
609 bool HasSideEffects = false;
610
611 /// Whether the evaluation hit undefined behavior.
612 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
613 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
615
616 /// Diag - If this is non-null, it will be filled in with a stack of notes
617 /// indicating why evaluation failed (or why it failed to produce a constant
618 /// expression).
619 /// If the expression is unfoldable, the notes will indicate why it's not
620 /// foldable. If the expression is foldable, but not a constant expression,
621 /// the notes will describes why it isn't a constant expression. If the
622 /// expression *is* a constant expression, no notes will be produced.
623 ///
624 /// FIXME: this causes significant performance concerns and should be
625 /// refactored at some point. Not all evaluations of the constant
626 /// expression interpreter will display the given diagnostics, this means
627 /// those kinds of uses are paying the expense of generating a diagnostic
628 /// (which may include expensive operations like converting APValue objects
629 /// to a string representation).
631
632 EvalStatus() = default;
633
634 // hasSideEffects - Return true if the evaluated expression has
635 // side effects.
636 bool hasSideEffects() const {
637 return HasSideEffects;
638 }
639 };
640
641 /// EvalResult is a struct with detailed info about an evaluated expression.
643 /// Val - This is the value the expression can be folded to.
645
646 // isGlobalLValue - Return true if the evaluated lvalue expression
647 // is global.
648 bool isGlobalLValue() const;
649 };
650
651 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
652 /// an rvalue using any crazy technique (that has nothing to do with language
653 /// standards) that we want to, even if the expression has side-effects. If
654 /// this function returns true, it returns the folded constant in Result. If
655 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
656 /// applied.
658 bool InConstantContext = false) const;
659
660 /// EvaluateAsBooleanCondition - Return true if this is a constant
661 /// which we can fold and convert to a boolean condition using
662 /// any crazy technique that we want to, even if the expression has
663 /// side-effects.
664 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
665 bool InConstantContext = false) const;
666
668 SE_NoSideEffects, ///< Strictly evaluate the expression.
669 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
670 ///< arbitrary unmodeled side effects.
671 SE_AllowSideEffects ///< Allow any unmodeled side effect.
672 };
673
674 /// EvaluateAsInt - Return true if this is a constant which we can fold and
675 /// convert to an integer, using any crazy technique that we want to.
676 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
677 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
678 bool InConstantContext = false) const;
679
680 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
681 /// convert to a floating point value, using any crazy technique that we
682 /// want to.
683 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
684 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
685 bool InConstantContext = false) const;
686
687 /// EvaluateAsFixedPoint - Return true if this is a constant which we can fold
688 /// and convert to a fixed point value.
689 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
690 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
691 bool InConstantContext = false) const;
692
693 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
694 /// constant folded without side-effects, but discard the result.
695 bool isEvaluatable(const ASTContext &Ctx,
696 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
697
698 /// HasSideEffects - This routine returns true for all those expressions
699 /// which have any effect other than producing a value. Example is a function
700 /// call, volatile variable read, or throwing an exception. If
701 /// IncludePossibleEffects is false, this call treats certain expressions with
702 /// potential side effects (such as function call-like expressions,
703 /// instantiation-dependent expressions, or invocations from a macro) as not
704 /// having side effects.
705 bool HasSideEffects(const ASTContext &Ctx,
706 bool IncludePossibleEffects = true) const;
707
708 /// Determine whether this expression involves a call to any function
709 /// that is not trivial.
710 bool hasNonTrivialCall(const ASTContext &Ctx) const;
711
712 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
713 /// integer. This must be called on an expression that constant folds to an
714 /// integer.
715 llvm::APSInt EvaluateKnownConstInt(
716 const ASTContext &Ctx,
718
720 const ASTContext &Ctx,
722
723 void EvaluateForOverflow(const ASTContext &Ctx) const;
724
725 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
726 /// lvalue with link time known address, with no side-effects.
727 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
728 bool InConstantContext = false) const;
729
730 /// EvaluateAsInitializer - Evaluate an expression as if it were the
731 /// initializer of the given declaration. Returns true if the initializer
732 /// can be folded to a constant, and produces any relevant notes. In C++11,
733 /// notes will be produced if the expression is not a constant expression.
735 const VarDecl *VD,
737 bool IsConstantInitializer) const;
738
739 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
740 /// of a call to the given function with the given arguments, inside an
741 /// unevaluated context. Returns true if the expression could be folded to a
742 /// constant.
744 const FunctionDecl *Callee,
746 const Expr *This = nullptr) const;
747
748 enum class ConstantExprKind {
749 /// An integer constant expression (an array bound, enumerator, case value,
750 /// bit-field width, or similar) or similar.
751 Normal,
752 /// A non-class template argument. Such a value is only used for mangling,
753 /// not for code generation, so can refer to dllimported functions.
755 /// A class template argument. Such a value is used for code generation.
757 /// An immediate invocation. The destruction of the end result of this
758 /// evaluation is not part of the evaluation, but all other temporaries
759 /// are destroyed.
761 };
762
763 /// Evaluate an expression that is required to be a constant expression. Does
764 /// not check the syntactic constraints for C and C++98 constant expressions.
766 EvalResult &Result, const ASTContext &Ctx,
767 ConstantExprKind Kind = ConstantExprKind::Normal) const;
768
769 /// If the current Expr is a pointer, this will try to statically
770 /// determine the number of bytes available where the pointer is pointing.
771 /// Returns true if all of the above holds and we were able to figure out the
772 /// size, false otherwise.
773 ///
774 /// \param Type - How to evaluate the size of the Expr, as defined by the
775 /// "type" parameter of __builtin_object_size
776 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
777 unsigned Type) const;
778
779 /// If the current Expr is a pointer, this will try to statically
780 /// determine the strlen of the string pointed to.
781 /// Returns true if all of the above holds and we were able to figure out the
782 /// strlen, false otherwise.
783 bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const;
784
785 bool EvaluateCharRangeAsString(std::string &Result,
786 const Expr *SizeExpression,
787 const Expr *PtrExpression, ASTContext &Ctx,
788 EvalResult &Status) const;
789
790 /// Enumeration used to describe the kind of Null pointer constant
791 /// returned from \c isNullPointerConstant().
793 /// Expression is not a Null pointer constant.
795
796 /// Expression is a Null pointer constant built from a zero integer
797 /// expression that is not a simple, possibly parenthesized, zero literal.
798 /// C++ Core Issue 903 will classify these expressions as "not pointers"
799 /// once it is adopted.
800 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
802
803 /// Expression is a Null pointer constant built from a literal zero.
805
806 /// Expression is a C++11 nullptr.
808
809 /// Expression is a GNU-style __null constant.
811 };
812
813 /// Enumeration used to describe how \c isNullPointerConstant()
814 /// should cope with value-dependent expressions.
816 /// Specifies that the expression should never be value-dependent.
818
819 /// Specifies that a value-dependent expression of integral or
820 /// dependent type should be considered a null pointer constant.
822
823 /// Specifies that a value-dependent expression should be considered
824 /// to never be a null pointer constant.
826 };
827
828 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
829 /// a Null pointer constant. The return value can further distinguish the
830 /// kind of NULL pointer constant that was detected.
832 ASTContext &Ctx,
834
835 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
836 /// write barrier.
837 bool isOBJCGCCandidate(ASTContext &Ctx) const;
838
839 /// Returns true if this expression is a bound member function.
840 bool isBoundMemberFunction(ASTContext &Ctx) const;
841
842 /// Given an expression of bound-member type, find the type
843 /// of the member. Returns null if this is an *overloaded* bound
844 /// member expression.
845 static QualType findBoundMemberType(const Expr *expr);
846
847 /// Skip past any invisible AST nodes which might surround this
848 /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
849 /// but also injected CXXMemberExpr and CXXConstructExpr which represent
850 /// implicit conversions.
853 return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
854 }
855
856 /// Skip past any implicit casts which might surround this expression until
857 /// reaching a fixed point. Skips:
858 /// * ImplicitCastExpr
859 /// * FullExpr
860 Expr *IgnoreImpCasts() LLVM_READONLY;
861 const Expr *IgnoreImpCasts() const {
862 return const_cast<Expr *>(this)->IgnoreImpCasts();
863 }
864
865 /// Skip past any casts which might surround this expression until reaching
866 /// a fixed point. Skips:
867 /// * CastExpr
868 /// * FullExpr
869 /// * MaterializeTemporaryExpr
870 /// * SubstNonTypeTemplateParmExpr
871 Expr *IgnoreCasts() LLVM_READONLY;
872 const Expr *IgnoreCasts() const {
873 return const_cast<Expr *>(this)->IgnoreCasts();
874 }
875
876 /// Skip past any implicit AST nodes which might surround this expression
877 /// until reaching a fixed point. Skips:
878 /// * What IgnoreImpCasts() skips
879 /// * MaterializeTemporaryExpr
880 /// * CXXBindTemporaryExpr
881 Expr *IgnoreImplicit() LLVM_READONLY;
882 const Expr *IgnoreImplicit() const {
883 return const_cast<Expr *>(this)->IgnoreImplicit();
884 }
885
886 /// Skip past any implicit AST nodes which might surround this expression
887 /// until reaching a fixed point. Same as IgnoreImplicit, except that it
888 /// also skips over implicit calls to constructors and conversion functions.
889 ///
890 /// FIXME: Should IgnoreImplicit do this?
891 Expr *IgnoreImplicitAsWritten() LLVM_READONLY;
893 return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
894 }
895
896 /// Skip past any parentheses which might surround this expression until
897 /// reaching a fixed point. Skips:
898 /// * ParenExpr
899 /// * UnaryOperator if `UO_Extension`
900 /// * GenericSelectionExpr if `!isResultDependent()`
901 /// * ChooseExpr if `!isConditionDependent()`
902 /// * ConstantExpr
903 Expr *IgnoreParens() LLVM_READONLY;
904 const Expr *IgnoreParens() const {
905 return const_cast<Expr *>(this)->IgnoreParens();
906 }
907
908 /// Skip past any parentheses and implicit casts which might surround this
909 /// expression until reaching a fixed point.
910 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
911 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
912 /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
913 /// * What IgnoreParens() skips
914 /// * What IgnoreImpCasts() skips
915 /// * MaterializeTemporaryExpr
916 /// * SubstNonTypeTemplateParmExpr
917 Expr *IgnoreParenImpCasts() LLVM_READONLY;
918 const Expr *IgnoreParenImpCasts() const {
919 return const_cast<Expr *>(this)->IgnoreParenImpCasts();
920 }
921
922 /// Skip past any parentheses and casts which might surround this expression
923 /// until reaching a fixed point. Skips:
924 /// * What IgnoreParens() skips
925 /// * What IgnoreCasts() skips
926 Expr *IgnoreParenCasts() LLVM_READONLY;
927 const Expr *IgnoreParenCasts() const {
928 return const_cast<Expr *>(this)->IgnoreParenCasts();
929 }
930
931 /// Skip conversion operators. If this Expr is a call to a conversion
932 /// operator, return the argument.
935 return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
936 }
937
938 /// Skip past any parentheses and lvalue casts which might surround this
939 /// expression until reaching a fixed point. Skips:
940 /// * What IgnoreParens() skips
941 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
942 /// casts are skipped
943 /// FIXME: This is intended purely as a temporary workaround for code
944 /// that hasn't yet been rewritten to do the right thing about those
945 /// casts, and may disappear along with the last internal use.
946 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
948 return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
949 }
950
951 /// Skip past any parentheses and casts which do not change the value
952 /// (including ptr->int casts of the same size) until reaching a fixed point.
953 /// Skips:
954 /// * What IgnoreParens() skips
955 /// * CastExpr which do not change the value
956 /// * SubstNonTypeTemplateParmExpr
957 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
958 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
959 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
960 }
961
962 /// Skip past any parentheses and derived-to-base casts until reaching a
963 /// fixed point. Skips:
964 /// * What IgnoreParens() skips
965 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
966 /// CK_UncheckedDerivedToBase and CK_NoOp)
967 Expr *IgnoreParenBaseCasts() LLVM_READONLY;
968 const Expr *IgnoreParenBaseCasts() const {
969 return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
970 }
971
972 /// Determine whether this expression is a default function argument.
973 ///
974 /// Default arguments are implicitly generated in the abstract syntax tree
975 /// by semantic analysis for function calls, object constructions, etc. in
976 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
977 /// this routine also looks through any implicit casts to determine whether
978 /// the expression is a default argument.
979 bool isDefaultArgument() const;
980
981 /// Determine whether the result of this expression is a
982 /// temporary object of the given class type.
983 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
984
985 /// Whether this expression is an implicit reference to 'this' in C++.
986 bool isImplicitCXXThis() const;
987
989
990 /// For an expression of class type or pointer to class type,
991 /// return the most derived class decl the expression is known to refer to.
992 ///
993 /// If this expression is a cast, this method looks through it to find the
994 /// most derived decl that can be inferred from the expression.
995 /// This is valid because derived-to-base conversions have undefined
996 /// behavior if the object isn't dynamically of the derived type.
998
999 /// Get the inner expression that determines the best dynamic class.
1000 /// If this is a prvalue, we guarantee that it is of the most-derived type
1001 /// for the object itself.
1002 const Expr *getBestDynamicClassTypeExpr() const;
1003
1004 /// Walk outwards from an expression we want to bind a reference to and
1005 /// find the expression whose lifetime needs to be extended. Record
1006 /// the LHSs of comma expressions and adjustments needed along the path.
1009 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
1013 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1014 }
1015
1016 /// Checks that the two Expr's will refer to the same value as a comparison
1017 /// operand. The caller must ensure that the values referenced by the Expr's
1018 /// are not modified between E1 and E2 or the result my be invalid.
1019 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
1020
1021 static bool classof(const Stmt *T) {
1022 return T->getStmtClass() >= firstExprConstant &&
1023 T->getStmtClass() <= lastExprConstant;
1024 }
1025};
1026// PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
1027// Expr. Verify that we got it right.
1029 llvm::detail::ConstantLog2<alignof(Expr)>::value,
1030 "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
1031
1033
1034//===----------------------------------------------------------------------===//
1035// Wrapper Expressions.
1036//===----------------------------------------------------------------------===//
1037
1038/// FullExpr - Represents a "full-expression" node.
1039class FullExpr : public Expr {
1040protected:
1042
1044 : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
1045 subexpr->getObjectKind()),
1046 SubExpr(subexpr) {
1048 }
1050 : Expr(SC, Empty) {}
1051public:
1052 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1053 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1054
1055 /// As with any mutator of the AST, be very careful when modifying an
1056 /// existing AST to preserve its invariants.
1057 void setSubExpr(Expr *E) { SubExpr = E; }
1058
1059 static bool classof(const Stmt *T) {
1060 return T->getStmtClass() >= firstFullExprConstant &&
1061 T->getStmtClass() <= lastFullExprConstant;
1062 }
1063};
1064
1065/// Describes the kind of result that can be tail-allocated.
1067
1068/// ConstantExpr - An expression that occurs in a constant context and
1069/// optionally the result of evaluating the expression.
1070class ConstantExpr final
1071 : public FullExpr,
1072 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
1073 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
1074 "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
1075 "for tail-allocated storage");
1076 friend TrailingObjects;
1077 friend class ASTStmtReader;
1078 friend class ASTStmtWriter;
1079
1080 size_t numTrailingObjects(OverloadToken<APValue>) const {
1082 }
1083 size_t numTrailingObjects(OverloadToken<uint64_t>) const {
1085 }
1086
1087 uint64_t &Int64Result() {
1089 "invalid accessor");
1090 return *getTrailingObjects<uint64_t>();
1091 }
1092 const uint64_t &Int64Result() const {
1093 return const_cast<ConstantExpr *>(this)->Int64Result();
1094 }
1095 APValue &APValueResult() {
1097 "invalid accessor");
1098 return *getTrailingObjects<APValue>();
1099 }
1100 APValue &APValueResult() const {
1101 return const_cast<ConstantExpr *>(this)->APValueResult();
1102 }
1103
1104 ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
1105 bool IsImmediateInvocation);
1106 ConstantExpr(EmptyShell Empty, ConstantResultStorageKind StorageKind);
1107
1108public:
1109 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1110 const APValue &Result);
1111 static ConstantExpr *
1112 Create(const ASTContext &Context, Expr *E,
1114 bool IsImmediateInvocation = false);
1115 static ConstantExpr *CreateEmpty(const ASTContext &Context,
1116 ConstantResultStorageKind StorageKind);
1117
1118 static ConstantResultStorageKind getStorageKind(const APValue &Value);
1120 const ASTContext &Context);
1121
1122 SourceLocation getBeginLoc() const LLVM_READONLY {
1123 return SubExpr->getBeginLoc();
1124 }
1125 SourceLocation getEndLoc() const LLVM_READONLY {
1126 return SubExpr->getEndLoc();
1127 }
1128
1129 static bool classof(const Stmt *T) {
1130 return T->getStmtClass() == ConstantExprClass;
1131 }
1132
1133 void SetResult(APValue Value, const ASTContext &Context) {
1134 MoveIntoResult(Value, Context);
1135 }
1136 void MoveIntoResult(APValue &Value, const ASTContext &Context);
1137
1139 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1140 }
1142 return static_cast<ConstantResultStorageKind>(ConstantExprBits.ResultKind);
1143 }
1145 return ConstantExprBits.IsImmediateInvocation;
1146 }
1147 bool hasAPValueResult() const {
1148 return ConstantExprBits.APValueKind != APValue::None;
1149 }
1150 APValue getAPValueResult() const;
1151 llvm::APSInt getResultAsAPSInt() const;
1152 // Iterators
1155 return const_child_range(&SubExpr, &SubExpr + 1);
1156 }
1157};
1158
1159//===----------------------------------------------------------------------===//
1160// Primary Expressions.
1161//===----------------------------------------------------------------------===//
1162
1163/// OpaqueValueExpr - An expression referring to an opaque object of a
1164/// fixed type and value class. These don't correspond to concrete
1165/// syntax; instead they're used to express operations (usually copy
1166/// operations) on values whose source is generally obvious from
1167/// context.
1168class OpaqueValueExpr : public Expr {
1169 friend class ASTStmtReader;
1170 Expr *SourceExpr;
1171
1172public:
1174 ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
1175 : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
1176 setIsUnique(false);
1179 }
1180
1181 /// Given an expression which invokes a copy constructor --- i.e. a
1182 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1183 /// find the OpaqueValueExpr that's the source of the construction.
1184 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1185
1187 : Expr(OpaqueValueExprClass, Empty) {}
1188
1189 /// Retrieve the location of this expression.
1191
1192 SourceLocation getBeginLoc() const LLVM_READONLY {
1193 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1194 }
1195 SourceLocation getEndLoc() const LLVM_READONLY {
1196 return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1197 }
1198 SourceLocation getExprLoc() const LLVM_READONLY {
1199 return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1200 }
1201
1204 }
1205
1208 }
1209
1210 /// The source expression of an opaque value expression is the
1211 /// expression which originally generated the value. This is
1212 /// provided as a convenience for analyses that don't wish to
1213 /// precisely model the execution behavior of the program.
1214 ///
1215 /// The source expression is typically set when building the
1216 /// expression which binds the opaque value expression in the first
1217 /// place.
1218 Expr *getSourceExpr() const { return SourceExpr; }
1219
1220 void setIsUnique(bool V) {
1221 assert((!V || SourceExpr) &&
1222 "unique OVEs are expected to have source expressions");
1223 OpaqueValueExprBits.IsUnique = V;
1224 }
1225
1226 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1227
1228 static bool classof(const Stmt *T) {
1229 return T->getStmtClass() == OpaqueValueExprClass;
1230 }
1231};
1232
1233/// A reference to a declared variable, function, enum, etc.
1234/// [C99 6.5.1p2]
1235///
1236/// This encodes all the information about how a declaration is referenced
1237/// within an expression.
1238///
1239/// There are several optional constructs attached to DeclRefExprs only when
1240/// they apply in order to conserve memory. These are laid out past the end of
1241/// the object, and flags in the DeclRefExprBitfield track whether they exist:
1242///
1243/// DeclRefExprBits.HasQualifier:
1244/// Specifies when this declaration reference expression has a C++
1245/// nested-name-specifier.
1246/// DeclRefExprBits.HasFoundDecl:
1247/// Specifies when this declaration reference expression has a record of
1248/// a NamedDecl (different from the referenced ValueDecl) which was found
1249/// during name lookup and/or overload resolution.
1250/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1251/// Specifies when this declaration reference expression has an explicit
1252/// C++ template keyword and/or template argument list.
1253/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1254/// Specifies when this declaration reference expression (validly)
1255/// refers to an enclosed local or a captured variable.
1256class DeclRefExpr final
1257 : public Expr,
1258 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1259 NamedDecl *, ASTTemplateKWAndArgsInfo,
1260 TemplateArgumentLoc> {
1261 friend class ASTStmtReader;
1262 friend class ASTStmtWriter;
1263 friend TrailingObjects;
1264
1265 /// The declaration that we are referencing.
1266 ValueDecl *D;
1267
1268 /// Provides source/type location info for the declaration name
1269 /// embedded in D.
1270 DeclarationNameLoc DNLoc;
1271
1272 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1273 return hasQualifier();
1274 }
1275
1276 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1277 return hasFoundDecl();
1278 }
1279
1280 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1281 return hasTemplateKWAndArgsInfo();
1282 }
1283
1284 /// Test whether there is a distinct FoundDecl attached to the end of
1285 /// this DRE.
1286 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1287
1288 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1289 SourceLocation TemplateKWLoc, ValueDecl *D,
1290 bool RefersToEnlosingVariableOrCapture,
1291 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1292 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1294
1295 /// Construct an empty declaration reference expression.
1296 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1297
1298public:
1299 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1300 bool RefersToEnclosingVariableOrCapture, QualType T,
1301 ExprValueKind VK, SourceLocation L,
1302 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1303 NonOdrUseReason NOUR = NOUR_None);
1304
1305 static DeclRefExpr *
1306 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1307 SourceLocation TemplateKWLoc, ValueDecl *D,
1308 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1309 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1310 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1311 NonOdrUseReason NOUR = NOUR_None);
1312
1313 static DeclRefExpr *
1314 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1315 SourceLocation TemplateKWLoc, ValueDecl *D,
1316 bool RefersToEnclosingVariableOrCapture,
1317 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1318 NamedDecl *FoundD = nullptr,
1319 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1320 NonOdrUseReason NOUR = NOUR_None);
1321
1322 /// Construct an empty declaration reference expression.
1323 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1324 bool HasFoundDecl,
1325 bool HasTemplateKWAndArgsInfo,
1326 unsigned NumTemplateArgs);
1327
1328 ValueDecl *getDecl() { return D; }
1329 const ValueDecl *getDecl() const { return D; }
1330 void setDecl(ValueDecl *NewD);
1331
1333 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1334 }
1335
1338 SourceLocation getBeginLoc() const LLVM_READONLY;
1339 SourceLocation getEndLoc() const LLVM_READONLY;
1340
1341 /// Determine whether this declaration reference was preceded by a
1342 /// C++ nested-name-specifier, e.g., \c N::foo.
1343 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1344
1345 /// If the name was qualified, retrieves the nested-name-specifier
1346 /// that precedes the name, with source-location information.
1348 if (!hasQualifier())
1349 return NestedNameSpecifierLoc();
1350 return *getTrailingObjects<NestedNameSpecifierLoc>();
1351 }
1352
1353 /// If the name was qualified, retrieves the nested-name-specifier
1354 /// that precedes the name. Otherwise, returns NULL.
1357 }
1358
1359 /// Get the NamedDecl through which this reference occurred.
1360 ///
1361 /// This Decl may be different from the ValueDecl actually referred to in the
1362 /// presence of using declarations, etc. It always returns non-NULL, and may
1363 /// simple return the ValueDecl when appropriate.
1364
1366 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1367 }
1368
1369 /// Get the NamedDecl through which this reference occurred.
1370 /// See non-const variant.
1371 const NamedDecl *getFoundDecl() const {
1372 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1373 }
1374
1376 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1377 }
1378
1379 /// Retrieve the location of the template keyword preceding
1380 /// this name, if any.
1383 return SourceLocation();
1384 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1385 }
1386
1387 /// Retrieve the location of the left angle bracket starting the
1388 /// explicit template argument list following the name, if any.
1391 return SourceLocation();
1392 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1393 }
1394
1395 /// Retrieve the location of the right angle bracket ending the
1396 /// explicit template argument list following the name, if any.
1399 return SourceLocation();
1400 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1401 }
1402
1403 /// Determines whether the name in this declaration reference
1404 /// was preceded by the template keyword.
1406
1407 /// Determines whether this declaration reference was followed by an
1408 /// explicit template argument list.
1409 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1410
1411 /// Copies the template arguments (if present) into the given
1412 /// structure.
1415 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1416 getTrailingObjects<TemplateArgumentLoc>(), List);
1417 }
1418
1419 /// Retrieve the template arguments provided as part of this
1420 /// template-id.
1423 return nullptr;
1424 return getTrailingObjects<TemplateArgumentLoc>();
1425 }
1426
1427 /// Retrieve the number of template arguments provided as part of this
1428 /// template-id.
1429 unsigned getNumTemplateArgs() const {
1431 return 0;
1432 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1433 }
1434
1436 return {getTemplateArgs(), getNumTemplateArgs()};
1437 }
1438
1439 /// Returns true if this expression refers to a function that
1440 /// was resolved from an overloaded set having size greater than 1.
1442 return DeclRefExprBits.HadMultipleCandidates;
1443 }
1444 /// Sets the flag telling whether this expression refers to
1445 /// a function that was resolved from an overloaded set having size
1446 /// greater than 1.
1447 void setHadMultipleCandidates(bool V = true) {
1448 DeclRefExprBits.HadMultipleCandidates = V;
1449 }
1450
1451 /// Is this expression a non-odr-use reference, and if so, why?
1453 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1454 }
1455
1456 /// Does this DeclRefExpr refer to an enclosing local or a captured
1457 /// variable?
1459 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1460 }
1461
1463 return DeclRefExprBits.IsImmediateEscalating;
1464 }
1465
1467 DeclRefExprBits.IsImmediateEscalating = Set;
1468 }
1469
1471 return DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter;
1472 }
1473
1475 bool Set, const ASTContext &Context) {
1476 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = Set;
1477 setDependence(computeDependence(this, Context));
1478 }
1479
1480 static bool classof(const Stmt *T) {
1481 return T->getStmtClass() == DeclRefExprClass;
1482 }
1483
1484 // Iterators
1487 }
1488
1491 }
1492};
1493
1494class IntegerLiteral : public Expr, public APIntStorage {
1495 SourceLocation Loc;
1496
1497 /// Construct an empty integer literal.
1498 explicit IntegerLiteral(EmptyShell Empty)
1499 : Expr(IntegerLiteralClass, Empty) { }
1500
1501public:
1502 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1503 // or UnsignedLongLongTy
1504 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1505 SourceLocation l);
1506
1507 /// Returns a new integer literal with value 'V' and type 'type'.
1508 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1509 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1510 /// \param V - the value that the returned integer literal contains.
1511 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1513 /// Returns a new empty integer literal.
1514 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1515
1516 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1517 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1518
1519 /// Retrieve the location of the literal.
1520 SourceLocation getLocation() const { return Loc; }
1521
1522 void setLocation(SourceLocation Location) { Loc = Location; }
1523
1524 static bool classof(const Stmt *T) {
1525 return T->getStmtClass() == IntegerLiteralClass;
1526 }
1527
1528 // Iterators
1531 }
1534 }
1535};
1536
1537class FixedPointLiteral : public Expr, public APIntStorage {
1538 SourceLocation Loc;
1539 unsigned Scale;
1540
1541 /// \brief Construct an empty fixed-point literal.
1542 explicit FixedPointLiteral(EmptyShell Empty)
1543 : Expr(FixedPointLiteralClass, Empty) {}
1544
1545 public:
1546 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1547 SourceLocation l, unsigned Scale);
1548
1549 // Store the int as is without any bit shifting.
1551 const llvm::APInt &V,
1553 unsigned Scale);
1554
1555 /// Returns an empty fixed-point literal.
1556 static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
1557
1558 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1559 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1560
1561 /// \brief Retrieve the location of the literal.
1562 SourceLocation getLocation() const { return Loc; }
1563
1564 void setLocation(SourceLocation Location) { Loc = Location; }
1565
1566 unsigned getScale() const { return Scale; }
1567 void setScale(unsigned S) { Scale = S; }
1568
1569 static bool classof(const Stmt *T) {
1570 return T->getStmtClass() == FixedPointLiteralClass;
1571 }
1572
1573 std::string getValueAsString(unsigned Radix) const;
1574
1575 // Iterators
1578 }
1581 }
1582};
1583
1585
1586class CharacterLiteral : public Expr {
1587 unsigned Value;
1588 SourceLocation Loc;
1589public:
1590 // type should be IntTy
1593 : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary),
1594 Value(value), Loc(l) {
1595 CharacterLiteralBits.Kind = llvm::to_underlying(kind);
1596 setDependence(ExprDependence::None);
1597 }
1598
1599 /// Construct an empty character literal.
1600 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1601
1602 SourceLocation getLocation() const { return Loc; }
1604 return static_cast<CharacterLiteralKind>(CharacterLiteralBits.Kind);
1605 }
1606
1607 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1608 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1609
1610 unsigned getValue() const { return Value; }
1611
1612 void setLocation(SourceLocation Location) { Loc = Location; }
1614 CharacterLiteralBits.Kind = llvm::to_underlying(kind);
1615 }
1616 void setValue(unsigned Val) { Value = Val; }
1617
1618 static bool classof(const Stmt *T) {
1619 return T->getStmtClass() == CharacterLiteralClass;
1620 }
1621
1622 static void print(unsigned val, CharacterLiteralKind Kind, raw_ostream &OS);
1623
1624 // Iterators
1627 }
1630 }
1631};
1632
1633class FloatingLiteral : public Expr, private APFloatStorage {
1634 SourceLocation Loc;
1635
1636 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1638
1639 /// Construct an empty floating-point literal.
1640 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1641
1642public:
1643 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1644 bool isexact, QualType Type, SourceLocation L);
1645 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1646
1647 llvm::APFloat getValue() const {
1649 }
1650 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1651 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1653 }
1654
1655 /// Get a raw enumeration value representing the floating-point semantics of
1656 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1657 llvm::APFloatBase::Semantics getRawSemantics() const {
1658 return static_cast<llvm::APFloatBase::Semantics>(
1659 FloatingLiteralBits.Semantics);
1660 }
1661
1662 /// Set the raw enumeration value representing the floating-point semantics of
1663 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1664 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1665 FloatingLiteralBits.Semantics = Sem;
1666 }
1667
1668 /// Return the APFloat semantics this literal uses.
1669 const llvm::fltSemantics &getSemantics() const {
1670 return llvm::APFloatBase::EnumToSemantics(
1671 static_cast<llvm::APFloatBase::Semantics>(
1672 FloatingLiteralBits.Semantics));
1673 }
1674
1675 /// Set the APFloat semantics this literal uses.
1676 void setSemantics(const llvm::fltSemantics &Sem) {
1677 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1678 }
1679
1680 bool isExact() const { return FloatingLiteralBits.IsExact; }
1681 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1682
1683 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1684 /// double. Note that this may cause loss of precision, but is useful for
1685 /// debugging dumps, etc.
1686 double getValueAsApproximateDouble() const;
1687
1688 SourceLocation getLocation() const { return Loc; }
1690
1691 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1692 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1693
1694 static bool classof(const Stmt *T) {
1695 return T->getStmtClass() == FloatingLiteralClass;
1696 }
1697
1698 // Iterators
1701 }
1704 }
1705};
1706
1707/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1708/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1709/// IntegerLiteral classes. Instances of this class always have a Complex type
1710/// whose element type matches the subexpression.
1711///
1712class ImaginaryLiteral : public Expr {
1713 Stmt *Val;
1714public:
1716 : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) {
1717 setDependence(ExprDependence::None);
1718 }
1719
1720 /// Build an empty imaginary literal.
1722 : Expr(ImaginaryLiteralClass, Empty) { }
1723
1724 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1725 Expr *getSubExpr() { return cast<Expr>(Val); }
1726 void setSubExpr(Expr *E) { Val = E; }
1727
1728 SourceLocation getBeginLoc() const LLVM_READONLY {
1729 return Val->getBeginLoc();
1730 }
1731 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1732
1733 static bool classof(const Stmt *T) {
1734 return T->getStmtClass() == ImaginaryLiteralClass;
1735 }
1736
1737 // Iterators
1738 child_range children() { return child_range(&Val, &Val+1); }
1740 return const_child_range(&Val, &Val + 1);
1741 }
1742};
1743
1745 Ordinary,
1746 Wide,
1747 UTF8,
1748 UTF16,
1749 UTF32,
1751};
1752
1753/// StringLiteral - This represents a string literal expression, e.g. "foo"
1754/// or L"bar" (wide strings). The actual string data can be obtained with
1755/// getBytes() and is NOT null-terminated. The length of the string data is
1756/// determined by calling getByteLength().
1757///
1758/// The C type for a string is always a ConstantArrayType. In C++, the char
1759/// type is const qualified, in C it is not.
1760///
1761/// Note that strings in C can be formed by concatenation of multiple string
1762/// literal pptokens in translation phase #6. This keeps track of the locations
1763/// of each of these pieces.
1764///
1765/// Strings in C can also be truncated and extended by assigning into arrays,
1766/// e.g. with constructs like:
1767/// char X[2] = "foobar";
1768/// In this case, getByteLength() will return 6, but the string literal will
1769/// have type "char[2]".
1770class StringLiteral final
1771 : public Expr,
1772 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1773 char> {
1774 friend class ASTStmtReader;
1775 friend TrailingObjects;
1776
1777 /// StringLiteral is followed by several trailing objects. They are in order:
1778 ///
1779 /// * A single unsigned storing the length in characters of this string. The
1780 /// length in bytes is this length times the width of a single character.
1781 /// Always present and stored as a trailing objects because storing it in
1782 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1783 /// due to alignment requirements. If you add some data to StringLiteral,
1784 /// consider moving it inside StringLiteral.
1785 ///
1786 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1787 /// token this string is made of.
1788 ///
1789 /// * An array of getByteLength() char used to store the string data.
1790
1791 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
1792 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1793 return getNumConcatenated();
1794 }
1795
1796 unsigned numTrailingObjects(OverloadToken<char>) const {
1797 return getByteLength();
1798 }
1799
1800 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
1801 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1802
1803 const uint16_t *getStrDataAsUInt16() const {
1804 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1805 }
1806
1807 const uint32_t *getStrDataAsUInt32() const {
1808 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1809 }
1810
1811 /// Build a string literal.
1812 StringLiteral(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind,
1813 bool Pascal, QualType Ty, const SourceLocation *Loc,
1814 unsigned NumConcatenated);
1815
1816 /// Build an empty string literal.
1817 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1818 unsigned CharByteWidth);
1819
1820 /// Map a target and string kind to the appropriate character width.
1821 static unsigned mapCharByteWidth(TargetInfo const &Target,
1823
1824 /// Set one of the string literal token.
1825 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1826 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1827 getTrailingObjects<SourceLocation>()[TokNum] = L;
1828 }
1829
1830public:
1831 /// This is the "fully general" constructor that allows representation of
1832 /// strings formed from multiple concatenated tokens.
1833 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1834 StringLiteralKind Kind, bool Pascal, QualType Ty,
1835 const SourceLocation *Loc,
1836 unsigned NumConcatenated);
1837
1838 /// Simple constructor for string literals made from one token.
1839 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1840 StringLiteralKind Kind, bool Pascal, QualType Ty,
1842 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1843 }
1844
1845 /// Construct an empty string literal.
1846 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1847 unsigned NumConcatenated, unsigned Length,
1848 unsigned CharByteWidth);
1849
1850 StringRef getString() const {
1851 assert((isUnevaluated() || getCharByteWidth() == 1) &&
1852 "This function is used in places that assume strings use char");
1853 return StringRef(getStrDataAsChar(), getByteLength());
1854 }
1855
1856 /// Allow access to clients that need the byte representation, such as
1857 /// ASTWriterStmt::VisitStringLiteral().
1858 StringRef getBytes() const {
1859 // FIXME: StringRef may not be the right type to use as a result for this.
1860 return StringRef(getStrDataAsChar(), getByteLength());
1861 }
1862
1863 void outputString(raw_ostream &OS) const;
1864
1865 uint32_t getCodeUnit(size_t i) const {
1866 assert(i < getLength() && "out of bounds access");
1867 switch (getCharByteWidth()) {
1868 case 1:
1869 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1870 case 2:
1871 return getStrDataAsUInt16()[i];
1872 case 4:
1873 return getStrDataAsUInt32()[i];
1874 }
1875 llvm_unreachable("Unsupported character width!");
1876 }
1877
1878 // Get code unit but preserve sign info.
1879 int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const {
1880 int64_t V = getCodeUnit(I);
1881 if (isOrdinary() || isWide()) {
1882 unsigned Width = getCharByteWidth() * BitWidth;
1883 llvm::APInt AInt(Width, (uint64_t)V);
1884 V = AInt.getSExtValue();
1885 }
1886 return V;
1887 }
1888
1889 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
1890 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
1891 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1892
1894 return static_cast<StringLiteralKind>(StringLiteralBits.Kind);
1895 }
1896
1897 bool isOrdinary() const { return getKind() == StringLiteralKind::Ordinary; }
1898 bool isWide() const { return getKind() == StringLiteralKind::Wide; }
1899 bool isUTF8() const { return getKind() == StringLiteralKind::UTF8; }
1900 bool isUTF16() const { return getKind() == StringLiteralKind::UTF16; }
1901 bool isUTF32() const { return getKind() == StringLiteralKind::UTF32; }
1903 bool isPascal() const { return StringLiteralBits.IsPascal; }
1904
1905 bool containsNonAscii() const {
1906 for (auto c : getString())
1907 if (!isASCII(c))
1908 return true;
1909 return false;
1910 }
1911
1913 for (auto c : getString())
1914 if (!isASCII(c) || !c)
1915 return true;
1916 return false;
1917 }
1918
1919 /// getNumConcatenated - Get the number of string literal tokens that were
1920 /// concatenated in translation phase #6 to form this string literal.
1921 unsigned getNumConcatenated() const {
1922 return StringLiteralBits.NumConcatenated;
1923 }
1924
1925 /// Get one of the string literal token.
1926 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1927 assert(TokNum < getNumConcatenated() && "Invalid tok number");
1928 return getTrailingObjects<SourceLocation>()[TokNum];
1929 }
1930
1931 /// getLocationOfByte - Return a source location that points to the specified
1932 /// byte of this string literal.
1933 ///
1934 /// Strings are amazingly complex. They can be formed from multiple tokens
1935 /// and can have escape sequences in them in addition to the usual trigraph
1936 /// and escaped newline business. This routine handles this complexity.
1937 ///
1939 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1940 const LangOptions &Features, const TargetInfo &Target,
1941 unsigned *StartToken = nullptr,
1942 unsigned *StartTokenByteOffset = nullptr) const;
1943
1945
1947 return getTrailingObjects<SourceLocation>();
1948 }
1949
1951 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1952 }
1953
1954 SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
1955 SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
1956
1957 static bool classof(const Stmt *T) {
1958 return T->getStmtClass() == StringLiteralClass;
1959 }
1960
1961 // Iterators
1964 }
1967 }
1968};
1969
1971 Func,
1972 Function,
1973 LFunction, // Same as Function, but as wide string.
1974 FuncDName,
1975 FuncSig,
1976 LFuncSig, // Same as FuncSig, but as wide string
1978 /// The same as PrettyFunction, except that the
1979 /// 'virtual' keyword is omitted for virtual member functions.
1981};
1982
1983/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1985 : public Expr,
1986 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1987 friend class ASTStmtReader;
1988 friend TrailingObjects;
1989
1990 // PredefinedExpr is optionally followed by a single trailing
1991 // "Stmt *" for the predefined identifier. It is present if and only if
1992 // hasFunctionName() is true and is always a "StringLiteral *".
1993
1995 bool IsTransparent, StringLiteral *SL);
1996
1997 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1998
1999 /// True if this PredefinedExpr has storage for a function name.
2000 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
2001
2002 void setFunctionName(StringLiteral *SL) {
2003 assert(hasFunctionName() &&
2004 "This PredefinedExpr has no storage for a function name!");
2005 *getTrailingObjects<Stmt *>() = SL;
2006 }
2007
2008public:
2009 /// Create a PredefinedExpr.
2010 ///
2011 /// If IsTransparent, the PredefinedExpr is transparently handled as a
2012 /// StringLiteral.
2013 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
2014 QualType FNTy, PredefinedIdentKind IK,
2015 bool IsTransparent, StringLiteral *SL);
2016
2017 /// Create an empty PredefinedExpr.
2018 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
2019 bool HasFunctionName);
2020
2022 return static_cast<PredefinedIdentKind>(PredefinedExprBits.Kind);
2023 }
2024
2025 bool isTransparent() const { return PredefinedExprBits.IsTransparent; }
2026
2029
2031 return hasFunctionName()
2032 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2033 : nullptr;
2034 }
2035
2037 return hasFunctionName()
2038 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2039 : nullptr;
2040 }
2041
2042 static StringRef getIdentKindName(PredefinedIdentKind IK);
2043 StringRef getIdentKindName() const {
2045 }
2046
2047 static std::string ComputeName(PredefinedIdentKind IK,
2048 const Decl *CurrentDecl,
2049 bool ForceElaboratedPrinting = false);
2050
2053
2054 static bool classof(const Stmt *T) {
2055 return T->getStmtClass() == PredefinedExprClass;
2056 }
2057
2058 // Iterators
2060 return child_range(getTrailingObjects<Stmt *>(),
2061 getTrailingObjects<Stmt *>() + hasFunctionName());
2062 }
2063
2065 return const_child_range(getTrailingObjects<Stmt *>(),
2066 getTrailingObjects<Stmt *>() + hasFunctionName());
2067 }
2068};
2069
2070// This represents a use of the __builtin_sycl_unique_stable_name, which takes a
2071// type-id, and at CodeGen time emits a unique string representation of the
2072// type in a way that permits us to properly encode information about the SYCL
2073// kernels.
2074class SYCLUniqueStableNameExpr final : public Expr {
2075 friend class ASTStmtReader;
2076 SourceLocation OpLoc, LParen, RParen;
2078
2081 SourceLocation RParen, QualType ResultTy,
2082 TypeSourceInfo *TSI);
2083
2084 void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; }
2085
2086 void setLocation(SourceLocation L) { OpLoc = L; }
2087 void setLParenLocation(SourceLocation L) { LParen = L; }
2088 void setRParenLocation(SourceLocation L) { RParen = L; }
2089
2090public:
2092
2093 const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; }
2094
2096 Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen,
2097 SourceLocation RParen, TypeSourceInfo *TSI);
2098
2100
2102 SourceLocation getEndLoc() const { return RParen; }
2103 SourceLocation getLocation() const { return OpLoc; }
2104 SourceLocation getLParenLocation() const { return LParen; }
2105 SourceLocation getRParenLocation() const { return RParen; }
2106
2107 static bool classof(const Stmt *T) {
2108 return T->getStmtClass() == SYCLUniqueStableNameExprClass;
2109 }
2110
2111 // Iterators
2114 }
2115
2118 }
2119
2120 // Convenience function to generate the name of the currently stored type.
2121 std::string ComputeName(ASTContext &Context) const;
2122
2123 // Get the generated name of the type. Note that this only works after all
2124 // kernels have been instantiated.
2125 static std::string ComputeName(ASTContext &Context, QualType Ty);
2126};
2127
2128/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
2129/// AST node is only formed if full location information is requested.
2130class ParenExpr : public Expr {
2131 SourceLocation L, R;
2132 Stmt *Val;
2133public:
2135 : Expr(ParenExprClass, val->getType(), val->getValueKind(),
2136 val->getObjectKind()),
2137 L(l), R(r), Val(val) {
2139 }
2140
2141 /// Construct an empty parenthesized expression.
2142 explicit ParenExpr(EmptyShell Empty)
2143 : Expr(ParenExprClass, Empty) { }
2144
2145 const Expr *getSubExpr() const { return cast<Expr>(Val); }
2146 Expr *getSubExpr() { return cast<Expr>(Val); }
2147 void setSubExpr(Expr *E) { Val = E; }
2148
2149 SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
2150 SourceLocation getEndLoc() const LLVM_READONLY { return R; }
2151
2152 /// Get the location of the left parentheses '('.
2153 SourceLocation getLParen() const { return L; }
2155
2156 /// Get the location of the right parentheses ')'.
2157 SourceLocation getRParen() const { return R; }
2159
2160 static bool classof(const Stmt *T) {
2161 return T->getStmtClass() == ParenExprClass;
2162 }
2163
2164 // Iterators
2165 child_range children() { return child_range(&Val, &Val+1); }
2167 return const_child_range(&Val, &Val + 1);
2168 }
2169};
2170
2171/// UnaryOperator - This represents the unary-expression's (except sizeof and
2172/// alignof), the postinc/postdec operators from postfix-expression, and various
2173/// extensions.
2174///
2175/// Notes on various nodes:
2176///
2177/// Real/Imag - These return the real/imag part of a complex operand. If
2178/// applied to a non-complex value, the former returns its operand and the
2179/// later returns zero in the type of the operand.
2180///
2181class UnaryOperator final
2182 : public Expr,
2183 private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
2184 Stmt *Val;
2185
2186 size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
2187 return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
2188 }
2189
2190 FPOptionsOverride &getTrailingFPFeatures() {
2191 assert(UnaryOperatorBits.HasFPFeatures);
2192 return *getTrailingObjects<FPOptionsOverride>();
2193 }
2194
2195 const FPOptionsOverride &getTrailingFPFeatures() const {
2196 assert(UnaryOperatorBits.HasFPFeatures);
2197 return *getTrailingObjects<FPOptionsOverride>();
2198 }
2199
2200public:
2202
2203protected:
2204 UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
2206 bool CanOverflow, FPOptionsOverride FPFeatures);
2207
2208 /// Build an empty unary operator.
2209 explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
2210 : Expr(UnaryOperatorClass, Empty) {
2211 UnaryOperatorBits.Opc = UO_AddrOf;
2212 UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
2213 }
2214
2215public:
2216 static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
2217
2218 static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
2221 bool CanOverflow, FPOptionsOverride FPFeatures);
2222
2224 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2225 }
2226 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2227
2228 Expr *getSubExpr() const { return cast<Expr>(Val); }
2229 void setSubExpr(Expr *E) { Val = E; }
2230
2231 /// getOperatorLoc - Return the location of the operator.
2234
2235 /// Returns true if the unary operator can cause an overflow. For instance,
2236 /// signed int i = INT_MAX; i++;
2237 /// signed char c = CHAR_MAX; c++;
2238 /// Due to integer promotions, c++ is promoted to an int before the postfix
2239 /// increment, and the result is an int that cannot overflow. However, i++
2240 /// can overflow.
2241 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
2242 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2243
2244 /// Get the FP contractability status of this operator. Only meaningful for
2245 /// operations on floating point types.
2248 }
2249
2250 /// Get the FENV_ACCESS status of this operator. Only meaningful for
2251 /// operations on floating point types.
2252 bool isFEnvAccessOn(const LangOptions &LO) const {
2253 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
2254 }
2255
2256 /// isPostfix - Return true if this is a postfix operation, like x++.
2257 static bool isPostfix(Opcode Op) {
2258 return Op == UO_PostInc || Op == UO_PostDec;
2259 }
2260
2261 /// isPrefix - Return true if this is a prefix operation, like --x.
2262 static bool isPrefix(Opcode Op) {
2263 return Op == UO_PreInc || Op == UO_PreDec;
2264 }
2265
2266 bool isPrefix() const { return isPrefix(getOpcode()); }
2267 bool isPostfix() const { return isPostfix(getOpcode()); }
2268
2269 static bool isIncrementOp(Opcode Op) {
2270 return Op == UO_PreInc || Op == UO_PostInc;
2271 }
2272 bool isIncrementOp() const {
2273 return isIncrementOp(getOpcode());
2274 }
2275
2276 static bool isDecrementOp(Opcode Op) {
2277 return Op == UO_PreDec || Op == UO_PostDec;
2278 }
2279 bool isDecrementOp() const {
2280 return isDecrementOp(getOpcode());
2281 }
2282
2283 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
2286 }
2287
2288 static bool isArithmeticOp(Opcode Op) {
2289 return Op >= UO_Plus && Op <= UO_LNot;
2290 }
2291 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2292
2293 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2294 /// corresponds to, e.g. "sizeof" or "[pre]++"
2295 static StringRef getOpcodeStr(Opcode Op);
2296
2297 /// Retrieve the unary opcode that corresponds to the given
2298 /// overloaded operator.
2299 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2300
2301 /// Retrieve the overloaded operator kind that corresponds to
2302 /// the given unary opcode.
2304
2305 SourceLocation getBeginLoc() const LLVM_READONLY {
2306 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2307 }
2308 SourceLocation getEndLoc() const LLVM_READONLY {
2309 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2310 }
2312
2313 static bool classof(const Stmt *T) {
2314 return T->getStmtClass() == UnaryOperatorClass;
2315 }
2316
2317 // Iterators
2318 child_range children() { return child_range(&Val, &Val+1); }
2320 return const_child_range(&Val, &Val + 1);
2321 }
2322
2323 /// Is FPFeatures in Trailing Storage?
2324 bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
2325
2326 /// Get FPFeatures from trailing storage.
2328 return getTrailingFPFeatures();
2329 }
2330
2331protected:
2332 /// Set FPFeatures in trailing storage, used by Serialization & ASTImporter.
2333 void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
2334
2335public:
2336 /// Get the FP features status of this operator. Only meaningful for
2337 /// operations on floating point types.
2339 if (UnaryOperatorBits.HasFPFeatures)
2342 }
2344 if (UnaryOperatorBits.HasFPFeatures)
2345 return getStoredFPFeatures();
2346 return FPOptionsOverride();
2347 }
2348
2350 friend class ASTNodeImporter;
2351 friend class ASTReader;
2352 friend class ASTStmtReader;
2353 friend class ASTStmtWriter;
2354};
2355
2356/// Helper class for OffsetOfExpr.
2357
2358// __builtin_offsetof(type, identifier(.identifier|[expr])*)
2360public:
2361 /// The kind of offsetof node we have.
2362 enum Kind {
2363 /// An index into an array.
2364 Array = 0x00,
2365 /// A field.
2366 Field = 0x01,
2367 /// A field in a dependent type, known only by its name.
2369 /// An implicit indirection through a C++ base class, when the
2370 /// field found is in a base class.
2371 Base = 0x03
2373
2374private:
2375 enum { MaskBits = 2, Mask = 0x03 };
2376
2377 /// The source range that covers this part of the designator.
2378 SourceRange Range;
2379
2380 /// The data describing the designator, which comes in three
2381 /// different forms, depending on the lower two bits.
2382 /// - An unsigned index into the array of Expr*'s stored after this node
2383 /// in memory, for [constant-expression] designators.
2384 /// - A FieldDecl*, for references to a known field.
2385 /// - An IdentifierInfo*, for references to a field with a given name
2386 /// when the class type is dependent.
2387 /// - A CXXBaseSpecifier*, for references that look at a field in a
2388 /// base class.
2389 uintptr_t Data;
2390
2391public:
2392 /// Create an offsetof node that refers to an array element.
2393 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2394 SourceLocation RBracketLoc)
2395 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2396
2397 /// Create an offsetof node that refers to a field.
2399 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2400 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2401
2402 /// Create an offsetof node that refers to an identifier.
2404 SourceLocation NameLoc)
2405 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2406 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2407
2408 /// Create an offsetof node that refers into a C++ base class.
2410 : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2411
2412 /// Determine what kind of offsetof node this is.
2413 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2414
2415 /// For an array element node, returns the index into the array
2416 /// of expressions.
2417 unsigned getArrayExprIndex() const {
2418 assert(getKind() == Array);
2419 return Data >> 2;
2420 }
2421
2422 /// For a field offsetof node, returns the field.
2424 assert(getKind() == Field);
2425 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2426 }
2427
2428 /// For a field or identifier offsetof node, returns the name of
2429 /// the field.
2431
2432 /// For a base class node, returns the base specifier.
2434 assert(getKind() == Base);
2435 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2436 }
2437
2438 /// Retrieve the source range that covers this offsetof node.
2439 ///
2440 /// For an array element node, the source range contains the locations of
2441 /// the square brackets. For a field or identifier node, the source range
2442 /// contains the location of the period (if there is one) and the
2443 /// identifier.
2444 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
2445 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
2446 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2447};
2448
2449/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2450/// offsetof(record-type, member-designator). For example, given:
2451/// @code
2452/// struct S {
2453/// float f;
2454/// double d;
2455/// };
2456/// struct T {
2457/// int i;
2458/// struct S s[10];
2459/// };
2460/// @endcode
2461/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2462
2463class OffsetOfExpr final
2464 : public Expr,
2465 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2466 SourceLocation OperatorLoc, RParenLoc;
2467 // Base type;
2468 TypeSourceInfo *TSInfo;
2469 // Number of sub-components (i.e. instances of OffsetOfNode).
2470 unsigned NumComps;
2471 // Number of sub-expressions (i.e. array subscript expressions).
2472 unsigned NumExprs;
2473
2474 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2475 return NumComps;
2476 }
2477
2479 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2481 SourceLocation RParenLoc);
2482
2483 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2484 : Expr(OffsetOfExprClass, EmptyShell()),
2485 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2486
2487public:
2488
2489 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2490 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2492 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2493
2494 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2495 unsigned NumComps, unsigned NumExprs);
2496
2497 /// getOperatorLoc - Return the location of the operator.
2498 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2499 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2500
2501 /// Return the location of the right parentheses.
2502 SourceLocation getRParenLoc() const { return RParenLoc; }
2503 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2504
2506 return TSInfo;
2507 }
2509 TSInfo = tsi;
2510 }
2511
2512 const OffsetOfNode &getComponent(unsigned Idx) const {
2513 assert(Idx < NumComps && "Subscript out of range");
2514 return getTrailingObjects<OffsetOfNode>()[Idx];
2515 }
2516
2517 void setComponent(unsigned Idx, OffsetOfNode ON) {
2518 assert(Idx < NumComps && "Subscript out of range");
2519 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2520 }
2521
2522 unsigned getNumComponents() const {
2523 return NumComps;
2524 }
2525
2526 Expr* getIndexExpr(unsigned Idx) {
2527 assert(Idx < NumExprs && "Subscript out of range");
2528 return getTrailingObjects<Expr *>()[Idx];
2529 }
2530
2531 const Expr *getIndexExpr(unsigned Idx) const {
2532 assert(Idx < NumExprs && "Subscript out of range");
2533 return getTrailingObjects<Expr *>()[Idx];
2534 }
2535
2536 void setIndexExpr(unsigned Idx, Expr* E) {
2537 assert(Idx < NumComps && "Subscript out of range");
2538 getTrailingObjects<Expr *>()[Idx] = E;
2539 }
2540
2541 unsigned getNumExpressions() const {
2542 return NumExprs;
2543 }
2544
2545 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
2546 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2547
2548 static bool classof(const Stmt *T) {
2549 return T->getStmtClass() == OffsetOfExprClass;
2550 }
2551
2552 // Iterators
2554 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2555 return child_range(begin, begin + NumExprs);
2556 }
2558 Stmt *const *begin =
2559 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2560 return const_child_range(begin, begin + NumExprs);
2561 }
2563};
2564
2565/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2566/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2567/// vec_step (OpenCL 1.1 6.11.12).
2569 union {
2572 } Argument;
2573 SourceLocation OpLoc, RParenLoc;
2574
2575public:
2577 QualType resultType, SourceLocation op,
2578 SourceLocation rp)
2579 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue,
2580 OK_Ordinary),
2581 OpLoc(op), RParenLoc(rp) {
2582 assert(ExprKind <= UETT_Last && "invalid enum value!");
2583 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2584 assert(static_cast<unsigned>(ExprKind) ==
2586 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2587 UnaryExprOrTypeTraitExprBits.IsType = true;
2588 Argument.Ty = TInfo;
2590 }
2591
2593 QualType resultType, SourceLocation op,
2594 SourceLocation rp);
2595
2596 /// Construct an empty sizeof/alignof expression.
2598 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2599
2601 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2602 }
2604 assert(K <= UETT_Last && "invalid enum value!");
2606 assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
2607 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2608 }
2609
2610 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2612 return getArgumentTypeInfo()->getType();
2613 }
2615 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2616 return Argument.Ty;
2617 }
2619 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2620 return static_cast<Expr*>(Argument.Ex);
2621 }
2622 const Expr *getArgumentExpr() const {
2623 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2624 }
2625
2627 Argument.Ex = E;
2628 UnaryExprOrTypeTraitExprBits.IsType = false;
2629 }
2631 Argument.Ty = TInfo;
2632 UnaryExprOrTypeTraitExprBits.IsType = true;
2633 }
2634
2635 /// Gets the argument type, or the type of the argument expression, whichever
2636 /// is appropriate.
2639 }
2640
2641 SourceLocation getOperatorLoc() const { return OpLoc; }
2642 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2643
2644 SourceLocation getRParenLoc() const { return RParenLoc; }
2645 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2646
2647 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
2648 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2649
2650 static bool classof(const Stmt *T) {
2651 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2652 }
2653
2654 // Iterators
2657};
2658
2659//===----------------------------------------------------------------------===//
2660// Postfix Operators.
2661//===----------------------------------------------------------------------===//
2662
2663/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2664class ArraySubscriptExpr : public Expr {
2665 enum { LHS, RHS, END_EXPR };
2666 Stmt *SubExprs[END_EXPR];
2667
2668 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2669
2670public:
2672 ExprObjectKind OK, SourceLocation rbracketloc)
2673 : Expr(ArraySubscriptExprClass, t, VK, OK) {
2674 SubExprs[LHS] = lhs;
2675 SubExprs[RHS] = rhs;
2676 ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
2678 }
2679
2680 /// Create an empty array subscript expression.
2682 : Expr(ArraySubscriptExprClass, Shell) { }
2683
2684 /// An array access can be written A[4] or 4[A] (both are equivalent).
2685 /// - getBase() and getIdx() always present the normalized view: A[4].
2686 /// In this case getBase() returns "A" and getIdx() returns "4".
2687 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2688 /// 4[A] getLHS() returns "4".
2689 /// Note: Because vector element access is also written A[4] we must
2690 /// predicate the format conversion in getBase and getIdx only on the
2691 /// the type of the RHS, as it is possible for the LHS to be a vector of
2692 /// integer type
2693 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2694 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2695 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2696
2697 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2698 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2699 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2700
2701 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
2702 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2703
2704 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
2705 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2706
2707 SourceLocation getBeginLoc() const LLVM_READONLY {
2708 return getLHS()->getBeginLoc();
2709 }
2711
2713 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2714 }
2716 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2717 }
2718
2719 SourceLocation getExprLoc() const LLVM_READONLY {
2720 return getBase()->getExprLoc();
2721 }
2722
2723 static bool classof(const Stmt *T) {
2724 return T->getStmtClass() == ArraySubscriptExprClass;
2725 }
2726
2727 // Iterators
2729 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2730 }
2732 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2733 }
2734};
2735
2736/// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
2737/// extension.
2738/// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
2739/// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
2740/// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
2741/// exist during the initial construction of the AST.
2743 enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
2744 Stmt *SubExprs[END_EXPR];
2745
2746public:
2748 SourceLocation RBracketLoc)
2749 : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
2751 SubExprs[BASE] = Base;
2752 SubExprs[ROW_IDX] = RowIdx;
2753 SubExprs[COLUMN_IDX] = ColumnIdx;
2754 ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
2756 }
2757
2758 /// Create an empty matrix subscript expression.
2760 : Expr(MatrixSubscriptExprClass, Shell) {}
2761
2762 bool isIncomplete() const {
2763 bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
2764 assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
2765 "expressions without column index must be marked as incomplete");
2766 return IsIncomplete;
2767 }
2768 Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
2769 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
2770 void setBase(Expr *E) { SubExprs[BASE] = E; }
2771
2772 Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); }
2773 const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); }
2774 void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
2775
2776 Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); }
2777 const Expr *getColumnIdx() const {
2778 assert(!isIncomplete() &&
2779 "cannot get the column index of an incomplete expression");
2780 return cast<Expr>(SubExprs[COLUMN_IDX]);
2781 }
2782 void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
2783
2784 SourceLocation getBeginLoc() const LLVM_READONLY {
2785 return getBase()->getBeginLoc();
2786 }
2787
2789
2790 SourceLocation getExprLoc() const LLVM_READONLY {
2791 return getBase()->getExprLoc();
2792 }
2793
2795 return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2796 }
2798 ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2799 }
2800
2801 static bool classof(const Stmt *T) {
2802 return T->getStmtClass() == MatrixSubscriptExprClass;
2803 }
2804
2805 // Iterators
2807 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2808 }
2810 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2811 }
2812};
2813
2814/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2815/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2816/// while its subclasses may represent alternative syntax that (semantically)
2817/// results in a function call. For example, CXXOperatorCallExpr is
2818/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2819/// "str1 + str2" to resolve to a function call.
2820class CallExpr : public Expr {
2821 enum { FN = 0, PREARGS_START = 1 };
2822
2823 /// The number of arguments in the call expression.
2824 unsigned NumArgs;
2825
2826 /// The location of the right parentheses. This has a different meaning for
2827 /// the derived classes of CallExpr.
2828 SourceLocation RParenLoc;
2829
2830 // CallExpr store some data in trailing objects. However since CallExpr
2831 // is used a base of other expression classes we cannot use
2832 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2833 // and casts.
2834 //
2835 // The trailing objects are in order:
2836 //
2837 // * A single "Stmt *" for the callee expression.
2838 //
2839 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2840 //
2841 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2842 //
2843 // * An optional of type FPOptionsOverride.
2844 //
2845 // Note that we store the offset in bytes from the this pointer to the start
2846 // of the trailing objects. It would be perfectly possible to compute it
2847 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2848 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2849 // compute this once and then load the offset from the bit-fields of Stmt,
2850 // instead of re-computing the offset each time the trailing objects are
2851 // accessed.
2852
2853 /// Return a pointer to the start of the trailing array of "Stmt *".
2854 Stmt **getTrailingStmts() {
2855 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2856 CallExprBits.OffsetToTrailingObjects);
2857 }
2858 Stmt *const *getTrailingStmts() const {
2859 return const_cast<CallExpr *>(this)->getTrailingStmts();
2860 }
2861
2862 /// Map a statement class to the appropriate offset in bytes from the
2863 /// this pointer to the trailing objects.
2864 static unsigned offsetToTrailingObjects(StmtClass SC);
2865
2866 unsigned getSizeOfTrailingStmts() const {
2867 return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
2868 }
2869
2870 size_t getOffsetOfTrailingFPFeatures() const {
2871 assert(hasStoredFPFeatures());
2872 return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
2873 }
2874
2875public:
2876 enum class ADLCallKind : bool { NotADL, UsesADL };
2879
2880protected:
2881 /// Build a call expression, assuming that appropriate storage has been
2882 /// allocated for the trailing objects.
2883 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2885 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
2886 unsigned MinNumArgs, ADLCallKind UsesADL);
2887
2888 /// Build an empty call expression, for deserialization.
2889 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2890 bool hasFPFeatures, EmptyShell Empty);
2891
2892 /// Return the size in bytes needed for the trailing objects.
2893 /// Used by the derived classes to allocate the right amount of storage.
2894 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
2895 bool HasFPFeatures) {
2896 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
2897 HasFPFeatures * sizeof(FPOptionsOverride);
2898 }
2899
2900 Stmt *getPreArg(unsigned I) {
2901 assert(I < getNumPreArgs() && "Prearg access out of range!");
2902 return getTrailingStmts()[PREARGS_START + I];
2903 }
2904 const Stmt *getPreArg(unsigned I) const {
2905 assert(I < getNumPreArgs() && "Prearg access out of range!");
2906 return getTrailingStmts()[PREARGS_START + I];
2907 }
2908 void setPreArg(unsigned I, Stmt *PreArg) {
2909 assert(I < getNumPreArgs() && "Prearg access out of range!");
2910 getTrailingStmts()[PREARGS_START + I] = PreArg;
2911 }
2912
2913 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2914
2915 /// Return a pointer to the trailing FPOptions
2917 assert(hasStoredFPFeatures());
2918 return reinterpret_cast<FPOptionsOverride *>(
2919 reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
2920 getSizeOfTrailingStmts());
2921 }
2923 assert(hasStoredFPFeatures());
2924 return reinterpret_cast<const FPOptionsOverride *>(
2925 reinterpret_cast<const char *>(this) +
2926 CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
2927 }
2928
2929public:
2930 /// Create a call expression.
2931 /// \param Fn The callee expression,
2932 /// \param Args The argument array,
2933 /// \param Ty The type of the call expression (which is *not* the return
2934 /// type in general),
2935 /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
2936 /// \param RParenLoc The location of the right parenthesis in the call
2937 /// expression.
2938 /// \param FPFeatures Floating-point features associated with the call,
2939 /// \param MinNumArgs Specifies the minimum number of arguments. The actual
2940 /// number of arguments will be the greater of Args.size()
2941 /// and MinNumArgs. This is used in a few places to allocate
2942 /// enough storage for the default arguments.
2943 /// \param UsesADL Specifies whether the callee was found through
2944 /// argument-dependent lookup.
2945 ///
2946 /// Note that you can use CreateTemporary if you need a temporary call
2947 /// expression on the stack.
2948 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2950 SourceLocation RParenLoc,
2951 FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
2953
2954 /// Create a temporary call expression with no arguments in the memory
2955 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2956 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2957 ///
2958 /// \code{.cpp}
2959 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
2960 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
2961 /// \endcode
2962 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2963 ExprValueKind VK, SourceLocation RParenLoc,
2965
2966 /// Create an empty call expression, for deserialization.
2967 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2968 bool HasFPFeatures, EmptyShell Empty);
2969
2970 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
2971 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
2972 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2973
2975 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2976 }
2978 CallExprBits.UsesADL = static_cast<bool>(V);
2979 }
2980 bool usesADL() const { return getADLCallKind() == UsesADL; }
2981
2982 bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
2983
2985 const Decl *getCalleeDecl() const {
2987 }
2988
2989 /// If the callee is a FunctionDecl, return it. Otherwise return null.
2991 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2992 }
2994 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2995 }
2996
2997 /// getNumArgs - Return the number of actual arguments to this call.
2998 unsigned getNumArgs() const { return NumArgs; }
2999
3000 /// Retrieve the call arguments.
3002 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
3003 getNumPreArgs());
3004 }
3005 const Expr *const *getArgs() const {
3006 return reinterpret_cast<const Expr *const *>(
3007 getTrailingStmts() + PREARGS_START + getNumPreArgs());
3008 }
3009
3010 /// getArg - Return the specified argument.
3011 Expr *getArg(unsigned Arg) {
3012 assert(Arg < getNumArgs() && "Arg access out of range!");
3013 return getArgs()[Arg];
3014 }
3015 const Expr *getArg(unsigned Arg) const {
3016 assert(Arg < getNumArgs() && "Arg access out of range!");
3017 return getArgs()[Arg];
3018 }
3019
3020 /// setArg - Set the specified argument.
3021 /// ! the dependence bits might be stale after calling this setter, it is
3022 /// *caller*'s responsibility to recompute them by calling
3023 /// computeDependence().
3024 void setArg(unsigned Arg, Expr *ArgExpr) {
3025 assert(Arg < getNumArgs() && "Arg access out of range!");
3026 getArgs()[Arg] = ArgExpr;
3027 }
3028
3029 /// Compute and set dependence bits.
3032 this, llvm::ArrayRef(
3033 reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START),
3034 getNumPreArgs())));
3035 }
3036
3037 /// Reduce the number of arguments in this call expression. This is used for
3038 /// example during error recovery to drop extra arguments. There is no way
3039 /// to perform the opposite because: 1.) We don't track how much storage
3040 /// we have for the argument array 2.) This would potentially require growing
3041 /// the argument array, something we cannot support since the arguments are
3042 /// stored in a trailing array.
3043 void shrinkNumArgs(unsigned NewNumArgs) {
3044 assert((NewNumArgs <= getNumArgs()) &&
3045 "shrinkNumArgs cannot increase the number of arguments!");
3046 NumArgs = NewNumArgs;
3047 }
3048
3049 /// Bluntly set a new number of arguments without doing any checks whatsoever.
3050 /// Only used during construction of a CallExpr in a few places in Sema.
3051 /// FIXME: Find a way to remove it.
3052 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
3053
3056 typedef llvm::iterator_range<arg_iterator> arg_range;
3057 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
3058
3061 return const_arg_range(arg_begin(), arg_end());
3062 }
3063
3065 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3066 }
3068
3070 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3071 }
3073
3074 /// This method provides fast access to all the subexpressions of
3075 /// a CallExpr without going through the slower virtual child_iterator
3076 /// interface. This provides efficient reverse iteration of the
3077 /// subexpressions. This is currently used for CFG construction.
3079 return llvm::ArrayRef(getTrailingStmts(),
3080 PREARGS_START + getNumPreArgs() + getNumArgs());
3081 }
3082
3083 /// Get FPOptionsOverride from trailing storage.
3085 assert(hasStoredFPFeatures());
3086 return *getTrailingFPFeatures();
3087 }
3088 /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
3090 assert(hasStoredFPFeatures());
3091 *getTrailingFPFeatures() = F;
3092 }
3093
3094 /// Get the FP features status of this operator. Only meaningful for
3095 /// operations on floating point types.
3097 if (hasStoredFPFeatures())
3100 }
3101
3103 if (hasStoredFPFeatures())
3104 return getStoredFPFeatures();
3105 return FPOptionsOverride();
3106 }
3107
3108 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
3109 /// of the callee. If not, return 0.
3110 unsigned getBuiltinCallee() const;
3111
3112 /// Returns \c true if this is a call to a builtin which does not
3113 /// evaluate side-effects within its arguments.
3114 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
3115
3116 /// getCallReturnType - Get the return type of the call expr. This is not
3117 /// always the type of the expr itself, if the return type is a reference
3118 /// type.
3119 QualType getCallReturnType(const ASTContext &Ctx) const;
3120
3121 /// Returns the WarnUnusedResultAttr that is either declared on the called
3122 /// function, or its return type declaration.
3123 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
3124
3125 /// Returns true if this call expression should warn on unused results.
3126 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
3127 return getUnusedResultAttr(Ctx) != nullptr;
3128 }
3129
3130 SourceLocation getRParenLoc() const { return RParenLoc; }
3131 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3132
3133 SourceLocation getBeginLoc() const LLVM_READONLY;
3134 SourceLocation getEndLoc() const LLVM_READONLY;
3135
3136 /// Return true if this is a call to __assume() or __builtin_assume() with
3137 /// a non-value-dependent constant parameter evaluating as false.
3138 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
3139
3140 /// Used by Sema to implement MSVC-compatible delayed name lookup.
3141 /// (Usually Exprs themselves should set dependence).
3143 setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
3144 }
3145
3146 bool isCallToStdMove() const;
3147
3148 static bool classof(const Stmt *T) {
3149 return T->getStmtClass() >= firstCallExprConstant &&
3150 T->getStmtClass() <= lastCallExprConstant;
3151 }
3152
3153 // Iterators
3155 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
3157 }
3158
3160 return const_child_range(getTrailingStmts(),
3161 getTrailingStmts() + PREARGS_START +
3163 }
3164};
3165
3166/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
3167///
3168class MemberExpr final
3169 : public Expr,
3170 private llvm::TrailingObjects<MemberExpr, NestedNameSpecifierLoc,
3171 DeclAccessPair, ASTTemplateKWAndArgsInfo,
3172 TemplateArgumentLoc> {
3173 friend class ASTReader;
3174 friend class ASTStmtReader;
3175 friend class ASTStmtWriter;
3176 friend TrailingObjects;
3177
3178 /// Base - the expression for the base pointer or structure references. In
3179 /// X.F, this is "X".
3180 Stmt *Base;
3181
3182 /// MemberDecl - This is the decl being referenced by the field/member name.
3183 /// In X.F, this is the decl referenced by F.
3184 ValueDecl *MemberDecl;
3185
3186 /// MemberDNLoc - Provides source/type location info for the
3187 /// declaration name embedded in MemberDecl.
3188 DeclarationNameLoc MemberDNLoc;
3189
3190 /// MemberLoc - This is the location of the member name.
3191 SourceLocation MemberLoc;
3192
3193 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
3194 return hasQualifier();
3195 }
3196
3197 size_t numTrailingObjects(OverloadToken<DeclAccessPair>) const {
3198 return hasFoundDecl();
3199 }
3200
3201 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3202 return hasTemplateKWAndArgsInfo();
3203 }
3204
3205 bool hasFoundDecl() const { return MemberExprBits.HasFoundDecl; }
3206
3207 bool hasTemplateKWAndArgsInfo() const {
3208 return MemberExprBits.HasTemplateKWAndArgsInfo;
3209 }
3210
3211 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
3212 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
3213 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
3214 const DeclarationNameInfo &NameInfo,
3215 const TemplateArgumentListInfo *TemplateArgs, QualType T,
3217 MemberExpr(EmptyShell Empty)
3218 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
3219
3220public:
3221 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
3222 SourceLocation OperatorLoc,
3223 NestedNameSpecifierLoc QualifierLoc,
3224 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
3225 DeclAccessPair FoundDecl,
3226 DeclarationNameInfo MemberNameInfo,
3227 const TemplateArgumentListInfo *TemplateArgs,
3228 QualType T, ExprValueKind VK, ExprObjectKind OK,
3229 NonOdrUseReason NOUR);
3230
3231 /// Create an implicit MemberExpr, with no location, qualifier, template
3232 /// arguments, and so on. Suitable only for non-static member access.
3234 bool IsArrow, ValueDecl *MemberDecl,
3236 ExprObjectKind OK) {
3237 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
3238 SourceLocation(), MemberDecl,
3239 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
3240 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
3241 }
3242
3243 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
3244 bool HasFoundDecl,
3245 bool HasTemplateKWAndArgsInfo,
3246 unsigned NumTemplateArgs);
3247
3248 void setBase(Expr *E) { Base = E; }
3249 Expr *getBase() const { return cast<Expr>(Base); }
3250
3251 /// Retrieve the member declaration to which this expression refers.
3252 ///
3253 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
3254 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
3255 ValueDecl *getMemberDecl() const { return MemberDecl; }
3256 void setMemberDecl(ValueDecl *D);
3257
3258 /// Retrieves the declaration found by lookup.
3260 if (!hasFoundDecl())
3262 getMemberDecl()->getAccess());
3263 return *getTrailingObjects<DeclAccessPair>();
3264 }
3265
3266 /// Determines whether this member expression actually had
3267 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
3268 /// x->Base::foo.
3269 bool hasQualifier() const { return MemberExprBits.HasQualifier; }
3270
3271 /// If the member name was qualified, retrieves the
3272 /// nested-name-specifier that precedes the member name, with source-location
3273 /// information.
3275 if (!hasQualifier())
3276 return NestedNameSpecifierLoc();
3277 return *getTrailingObjects<NestedNameSpecifierLoc>();
3278 }
3279
3280 /// If the member name was qualified, retrieves the
3281 /// nested-name-specifier that precedes the member name. Otherwise, returns
3282 /// NULL.
3285 }
3286
3287 /// Retrieve the location of the template keyword preceding
3288 /// the member name, if any.
3290 if (!hasTemplateKWAndArgsInfo())
3291 return SourceLocation();
3292 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3293 }
3294
3295 /// Retrieve the location of the left angle bracket starting the
3296 /// explicit template argument list following the member name, if any.
3298 if (!hasTemplateKWAndArgsInfo())
3299 return SourceLocation();
3300 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3301 }
3302
3303 /// Retrieve the location of the right angle bracket ending the
3304 /// explicit template argument list following the member name, if any.
3306 if (!hasTemplateKWAndArgsInfo())
3307 return SourceLocation();
3308 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3309 }
3310
3311 /// Determines whether the member name was preceded by the template keyword.
3313
3314 /// Determines whether the member name was followed by an
3315 /// explicit template argument list.
3316 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3317
3318 /// Copies the template arguments (if present) into the given
3319 /// structure.
3322 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3323 getTrailingObjects<TemplateArgumentLoc>(), List);
3324 }
3325
3326 /// Retrieve the template arguments provided as part of this
3327 /// template-id.
3330 return nullptr;
3331
3332 return getTrailingObjects<TemplateArgumentLoc>();
3333 }
3334
3335 /// Retrieve the number of template arguments provided as part of this
3336 /// template-id.
3337 unsigned getNumTemplateArgs() const {
3339 return 0;
3340
3341 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3342 }
3343
3345 return {getTemplateArgs(), getNumTemplateArgs()};
3346 }
3347
3348 /// Retrieve the member declaration name info.
3350 return DeclarationNameInfo(MemberDecl->getDeclName(),
3351 MemberLoc, MemberDNLoc);
3352 }
3353
3354 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
3355
3356 bool isArrow() const { return MemberExprBits.IsArrow; }
3357 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
3358
3359 /// getMemberLoc - Return the location of the "member", in X->F, it is the
3360 /// location of 'F'.
3361 SourceLocation getMemberLoc() const { return MemberLoc; }
3362 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3363
3364 SourceLocation getBeginLoc() const LLVM_READONLY;
3365 SourceLocation getEndLoc() const LLVM_READONLY;
3366
3367 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
3368
3369 /// Determine whether the base of this explicit is implicit.
3370 bool isImplicitAccess() const {
3371 return getBase() && getBase()->isImplicitCXXThis();
3372 }
3373
3374 /// Returns true if this member expression refers to a method that
3375 /// was resolved from an overloaded set having size greater than 1.
3377 return MemberExprBits.HadMultipleCandidates;
3378 }
3379 /// Sets the flag telling whether this expression refers to
3380 /// a method that was resolved from an overloaded set having size
3381 /// greater than 1.
3382 void setHadMultipleCandidates(bool V = true) {
3383 MemberExprBits.HadMultipleCandidates = V;
3384 }
3385
3386 /// Returns true if virtual dispatch is performed.
3387 /// If the member access is fully qualified, (i.e. X::f()), virtual
3388 /// dispatching is not performed. In -fapple-kext mode qualified
3389 /// calls to virtual method will still go through the vtable.
3390 bool performsVirtualDispatch(const LangOptions &LO) const {
3391 return LO.AppleKext || !hasQualifier();
3392 }
3393
3394 /// Is this expression a non-odr-use reference, and if so, why?
3395 /// This is only meaningful if the named member is a static member.
3397 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3398 }
3399
3400 static bool classof(const Stmt *T) {
3401 return T->getStmtClass() == MemberExprClass;
3402 }
3403
3404 // Iterators
3407 return const_child_range(&Base, &Base + 1);
3408 }
3409};
3410
3411/// CompoundLiteralExpr - [C99 6.5.2.5]
3412///
3414 /// LParenLoc - If non-null, this is the location of the left paren in a
3415 /// compound literal like "(int){4}". This can be null if this is a
3416 /// synthesized compound expression.
3417 SourceLocation LParenLoc;
3418
3419 /// The type as written. This can be an incomplete array type, in
3420 /// which case the actual expression type will be different.
3421 /// The int part of the pair stores whether this expr is file scope.
3422 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3423 Stmt *Init;
3424public:
3426 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3427 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
3428 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
3430 }
3431
3432 /// Construct an empty compound literal.
3434 : Expr(CompoundLiteralExprClass, Empty) { }
3435
3436 const Expr *getInitializer() const { return cast<Expr>(Init); }
3437 Expr *getInitializer() { return cast<Expr>(Init); }
3438 void setInitializer(Expr *E) { Init = E; }
3439
3440 bool isFileScope() const { return TInfoAndScope.getInt(); }
3441 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3442
3443 SourceLocation getLParenLoc() const { return LParenLoc; }
3444 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3445
3447 return TInfoAndScope.getPointer();
3448 }
3450 TInfoAndScope.setPointer(tinfo);
3451 }
3452
3453 SourceLocation getBeginLoc() const LLVM_READONLY {
3454 // FIXME: Init should never be null.
3455 if (!Init)
3456 return SourceLocation();
3457 if (LParenLoc.isInvalid())
3458 return Init->getBeginLoc();
3459 return LParenLoc;
3460 }
3461 SourceLocation getEndLoc() const LLVM_READONLY {
3462 // FIXME: Init should never be null.
3463 if (!Init)
3464 return SourceLocation();
3465 return Init->getEndLoc();
3466 }
3467
3468 static bool classof(const Stmt *T) {
3469 return T->getStmtClass() == CompoundLiteralExprClass;
3470 }
3471
3472 // Iterators
3473 child_range children() { return child_range(&Init, &Init+1); }
3475 return const_child_range(&Init, &Init + 1);
3476 }
3477};
3478
3479/// CastExpr - Base class for type casts, including both implicit
3480/// casts (ImplicitCastExpr) and explicit casts that have some
3481/// representation in the source code (ExplicitCastExpr's derived
3482/// classes).
3483class CastExpr : public Expr {
3484 Stmt *Op;
3485
3486 bool CastConsistency() const;
3487
3488 const CXXBaseSpecifier * const *path_buffer() const {
3489 return const_cast<CastExpr*>(this)->path_buffer();
3490 }
3491 CXXBaseSpecifier **path_buffer();
3492
3493 friend class ASTStmtReader;
3494
3495protected:
3497 Expr *op, unsigned BasePathSize, bool HasFPFeatures)
3498 : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
3499 CastExprBits.Kind = kind;
3500 CastExprBits.PartOfExplicitCast = false;
3501 CastExprBits.BasePathSize = BasePathSize;
3502 assert((CastExprBits.BasePathSize == BasePathSize) &&
3503 "BasePathSize overflow!");
3504 assert(CastConsistency());
3505 CastExprBits.HasFPFeatures = HasFPFeatures;
3506 }
3507
3508 /// Construct an empty cast.
3509 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
3510 bool HasFPFeatures)
3511 : Expr(SC, Empty) {
3512 CastExprBits.PartOfExplicitCast = false;
3513 CastExprBits.BasePathSize = BasePathSize;
3514 CastExprBits.HasFPFeatures = HasFPFeatures;
3515 assert((CastExprBits.BasePathSize == BasePathSize) &&
3516 "BasePathSize overflow!");
3517 }
3518
3519 /// Return a pointer to the trailing FPOptions.
3520 /// \pre hasStoredFPFeatures() == true
3523 return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
3524 }
3525
3526public:
3527 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
3528 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3529
3530 static const char *getCastKindName(CastKind CK);
3531 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3532
3533 Expr *getSubExpr() { return cast<Expr>(Op); }
3534 const Expr *getSubExpr() const { return cast<Expr>(Op); }
3535 void setSubExpr(Expr *E) { Op = E; }
3536
3537 /// Retrieve the cast subexpression as it was written in the source
3538 /// code, looking through any implicit casts or other intermediate nodes
3539 /// introduced by semantic analysis.
3541 const Expr *getSubExprAsWritten() const {
3542 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3543 }
3544
3545 /// If this cast applies a user-defined conversion, retrieve the conversion
3546 /// function that it invokes.
3548
3551 bool path_empty() const { return path_size() == 0; }
3552 unsigned path_size() const { return CastExprBits.BasePathSize; }
3553 path_iterator path_begin() { return path_buffer(); }
3554 path_iterator path_end() { return path_buffer() + path_size(); }
3555 path_const_iterator path_begin() const { return path_buffer(); }
3556 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3557
3558 /// Path through the class hierarchy taken by casts between base and derived
3559 /// classes (see implementation of `CastConsistency()` for a full list of
3560 /// cast kinds that have a path).
3561 ///
3562 /// For each derived-to-base edge in the path, the path contains a
3563 /// `CXXBaseSpecifier` for the base class of that edge; the entries are
3564 /// ordered from derived class to base class.
3565 ///
3566 /// For example, given classes `Base`, `Intermediate : public Base` and
3567 /// `Derived : public Intermediate`, the path for a cast from `Derived *` to
3568 /// `Base *` contains two entries: One for `Intermediate`, and one for `Base`,
3569 /// in that order.
3570 llvm::iterator_range<path_iterator> path() {
3571 return llvm::make_range(path_begin(), path_end());
3572 }
3573 llvm::iterator_range<path_const_iterator> path() const {
3574 return llvm::make_range(path_begin(), path_end());
3575 }
3576
3578 assert(getCastKind() == CK_ToUnion);
3580 }
3581
3582 bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
3583
3584 /// Get FPOptionsOverride from trailing storage.
3586 assert(hasStoredFPFeatures());
3587 return *getTrailingFPFeatures();
3588 }
3589
3590 /// Get the FP features status of this operation. Only meaningful for
3591 /// operations on floating point types.
3593 if (hasStoredFPFeatures())
3596 }
3597
3599 if (hasStoredFPFeatures())
3600 return getStoredFPFeatures();
3601 return FPOptionsOverride();
3602 }
3603
3604 /// Return
3605 // True : if this conversion changes the volatile-ness of a gl-value.
3606 // Qualification conversions on gl-values currently use CK_NoOp, but
3607 // it's important to recognize volatile-changing conversions in
3608 // clients code generation that normally eagerly peephole loads. Note
3609 // that the query is answering for this specific node; Sema may
3610 // produce multiple cast nodes for any particular conversion sequence.
3611 // False : Otherwise.
3613 return (isGLValue() && (getType().isVolatileQualified() !=
3614 getSubExpr()->getType().isVolatileQualified()));
3615 }
3616
3617 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3618 QualType opType);
3619 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3620 QualType opType);
3621
3622 static bool classof(const Stmt *T) {
3623 return T->getStmtClass() >= firstCastExprConstant &&
3624 T->getStmtClass() <= lastCastExprConstant;
3625 }
3626
3627 // Iterators
3628 child_range children() { return child_range(&Op, &Op+1); }
3629 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3630};
3631
3632/// ImplicitCastExpr - Allows us to explicitly represent implicit type
3633/// conversions, which have no direct representation in the original
3634/// source code. For example: converting T[]->T*, void f()->void
3635/// (*f)(), float->double, short->int, etc.
3636///
3637/// In C, implicit casts always produce rvalues. However, in C++, an
3638/// implicit cast whose result is being bound to a reference will be
3639/// an lvalue or xvalue. For example:
3640///
3641/// @code
3642/// class Base { };
3643/// class Derived : public Base { };
3644/// Derived &&ref();
3645/// void f(Derived d) {
3646/// Base& b = d; // initializer is an ImplicitCastExpr
3647/// // to an lvalue of type Base
3648/// Base&& r = ref(); // initializer is an ImplicitCastExpr
3649/// // to an xvalue of type Base
3650/// }
3651/// @endcode
3653 : public CastExpr,
3654 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
3655 FPOptionsOverride> {
3656
3657 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3658 unsigned BasePathLength, FPOptionsOverride FPO,
3659 ExprValueKind VK)
3660 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
3663 if (hasStoredFPFeatures())
3664 *getTrailingFPFeatures() = FPO;
3665 }
3666
3667 /// Construct an empty implicit cast.
3668 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
3669 bool HasFPFeatures)
3670 : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
3671
3672 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3673 return path_size();
3674 }
3675
3676public:
3680 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
3681 FPO.requiresTrailingStorage()) {
3682 if (hasStoredFPFeatures())
3683 *getTrailingFPFeatures() = FPO;
3684 }
3685
3686 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
3687 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3688 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3689 }
3690
3691 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3692 CastKind Kind, Expr *Operand,
3693 const CXXCastPath *BasePath,
3695
3696 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3697 unsigned PathSize, bool HasFPFeatures);
3698
3699 SourceLocation getBeginLoc() const LLVM_READONLY {
3700 return getSubExpr()->getBeginLoc();
3701 }
3702 SourceLocation getEndLoc() const LLVM_READONLY {
3703 return getSubExpr()->getEndLoc();
3704 }
3705
3706 static bool classof(const Stmt *T) {
3707 return T->getStmtClass() == ImplicitCastExprClass;
3708 }
3709
3711 friend class CastExpr;
3712};
3713
3714/// ExplicitCastExpr - An explicit cast written in the source
3715/// code.
3716///
3717/// This class is effectively an abstract class, because it provides
3718/// the basic representation of an explicitly-written cast without
3719/// specifying which kind of cast (C cast, functional cast, static
3720/// cast, etc.) was written; specific derived classes represent the
3721/// particular style of cast and its location information.
3722///
3723/// Unlike implicit casts, explicit cast nodes have two different
3724/// types: the type that was written into the source code, and the
3725/// actual type of the expression as determined by semantic
3726/// analysis. These types may differ slightly. For example, in C++ one
3727/// can cast to a reference type, which indicates that the resulting
3728/// expression will be an lvalue or xvalue. The reference type, however,
3729/// will not be used as the type of the expression.
3731 /// TInfo - Source type info for the (written) type
3732 /// this expression is casting to.
3733 TypeSourceInfo *TInfo;
3734
3735protected:
3737 CastKind kind, Expr *op, unsigned PathSize,
3738 bool HasFPFeatures, TypeSourceInfo *writtenTy)
3739 : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
3740 TInfo(writtenTy) {
3742 }
3743
3744 /// Construct an empty explicit cast.
3745 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
3746 bool HasFPFeatures)
3747 : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
3748
3749public:
3750 /// getTypeInfoAsWritten - Returns the type source info for the type
3751 /// that this expression is casting to.
3752 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3753 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3754
3755 /// getTypeAsWritten - Returns the type that this expression is
3756 /// casting to, as written in the source code.
3757 QualType getTypeAsWritten() const { return TInfo->getType(); }
3758
3759 static bool classof(const Stmt *T) {
3760 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3761 T->getStmtClass() <= lastExplicitCastExprConstant;
3762 }
3763};
3764
3765/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3766/// cast in C++ (C++ [expr.cast]), which uses the syntax
3767/// (Type)expr. For example: @c (int)f.
3769 : public ExplicitCastExpr,
3770 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
3771 FPOptionsOverride> {
3772 SourceLocation LPLoc; // the location of the left paren
3773 SourceLocation RPLoc; // the location of the right paren
3774
3775 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3776 unsigned PathSize, FPOptionsOverride FPO,
3778 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3779 FPO.requiresTrailingStorage(), writtenTy),
3780 LPLoc(l), RPLoc(r) {
3781 if (hasStoredFPFeatures())
3782 *getTrailingFPFeatures() = FPO;
3783 }
3784
3785 /// Construct an empty C-style explicit cast.
3786 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
3787 bool HasFPFeatures)
3788 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
3789
3790 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3791 return path_size();
3792 }
3793
3794public:
3795 static CStyleCastExpr *
3796 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
3797 Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
3799
3800 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3801 unsigned PathSize, bool HasFPFeatures);
3802
3803 SourceLocation getLParenLoc() const { return LPLoc; }
3804 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3805
3806 SourceLocation getRParenLoc() const { return RPLoc; }
3807 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3808
3809 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
3810 SourceLocation getEndLoc() const LLVM_READONLY {
3811 return getSubExpr()->getEndLoc();
3812 }
3813
3814 static bool classof(const Stmt *T) {
3815 return T->getStmtClass() == CStyleCastExprClass;
3816 }
3817
3819 friend class CastExpr;
3820};
3821
3822/// A builtin binary operation expression such as "x + y" or "x <= y".
3823///
3824/// This expression node kind describes a builtin binary operation,
3825/// such as "x + y" for integer values "x" and "y". The operands will
3826/// already have been converted to appropriate types (e.g., by
3827/// performing promotions or conversions).
3828///
3829/// In C++, where operators may be overloaded, a different kind of
3830/// expression node (CXXOperatorCallExpr) is used to express the
3831/// invocation of an overloaded operator with operator syntax. Within
3832/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3833/// used to store an expression "x + y" depends on the subexpressions
3834/// for x and y. If neither x or y is type-dependent, and the "+"
3835/// operator resolves to a built-in operation, BinaryOperator will be
3836/// used to express the computation (x and y may still be
3837/// value-dependent). If either x or y is type-dependent, or if the
3838/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3839/// be used to express the computation.
3840class BinaryOperator : public Expr {
3841 enum { LHS, RHS, END_EXPR };
3842 Stmt *SubExprs[END_EXPR];
3843
3844public:
3846
3847protected:
3848 size_t offsetOfTrailingStorage() const;
3849
3850 /// Return a pointer to the trailing FPOptions
3852 assert(BinaryOperatorBits.HasFPFeatures);
3853 return reinterpret_cast<FPOptionsOverride *>(
3854 reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
3855 }
3857 assert(BinaryOperatorBits.HasFPFeatures);
3858 return reinterpret_cast<const FPOptionsOverride *>(
3859 reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
3860 }
3861
3862 /// Build a binary operator, assuming that appropriate storage has been
3863 /// allocated for the trailing objects when needed.
3864 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3866 SourceLocation opLoc, FPOptionsOverride FPFeatures);
3867
3868 /// Construct an empty binary operator.
3869 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3870 BinaryOperatorBits.Opc = BO_Comma;
3871 }
3872
3873public:
3874 static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
3875
3876 static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
3877 Opcode opc, QualType ResTy, ExprValueKind VK,
3879 FPOptionsOverride FPFeatures);
3883
3885 return static_cast<Opcode>(BinaryOperatorBits.Opc);
3886 }
3887 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3888
3889 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3890 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3891 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3892 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3893
3894 SourceLocation getBeginLoc() const LLVM_READONLY {
3895 return getLHS()->getBeginLoc();
3896 }
3897 SourceLocation getEndLoc() const LLVM_READONLY {
3898 return getRHS()->getEndLoc();
3899 }
3900
3901 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3902 /// corresponds to, e.g. "<<=".
3903 static StringRef getOpcodeStr(Opcode Op);
3904
3905 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3906
3907 /// Retrieve the binary opcode that corresponds to the given
3908 /// overloaded operator.
3910
3911 /// Retrieve the overloaded operator kind that corresponds to
3912 /// the given binary opcode.
3914
3915 /// predicates to categorize the respective opcodes.
3916 static bool isPtrMemOp(Opcode Opc) {
3917 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3918 }
3919 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3920
3921 static bool isMultiplicativeOp(Opcode Opc) {
3922 return Opc >= BO_Mul && Opc <= BO_Rem;
3923 }
3925 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3926 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3927 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3928 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3929
3930 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3931 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3932
3933 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3934 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3935
3936 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3937 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3938
3939 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3940 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3941
3942 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
3943 bool isCommaOp() const { return isCommaOp(getOpcode()); }
3944
3946 switch (Opc) {
3947 default:
3948 llvm_unreachable("Not a comparison operator.");
3949 case BO_LT: return BO_GE;
3950 case BO_GT: return BO_LE;
3951 case BO_LE: return BO_GT;
3952 case BO_GE: return BO_LT;
3953 case BO_EQ: return BO_NE;
3954 case BO_NE: return BO_EQ;
3955 }
3956 }
3957
3959 switch (Opc) {
3960 default:
3961 llvm_unreachable("Not a comparison operator.");
3962 case BO_LT: return BO_GT;
3963 case BO_GT: return BO_LT;
3964 case BO_LE: return BO_GE;
3965 case BO_GE: return BO_LE;
3966 case BO_EQ:
3967 case BO_NE:
3968 return Opc;
3969 }
3970 }
3971
3972 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3973 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3974
3975 static bool isAssignmentOp(Opcode Opc) {
3976 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3977 }
3978 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3979
3981 return Opc > BO_Assign && Opc <= BO_OrAssign;
3982 }
3985 }
3987 assert(isCompoundAssignmentOp(Opc));
3988 if (Opc >= BO_AndAssign)
3989 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3990 else
3991 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3992 }
3993
3994 static bool isShiftAssignOp(Opcode Opc) {
3995 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3996 }
3997 bool isShiftAssignOp() const {
3998 return isShiftAssignOp(getOpcode());
3999 }
4000
4001 /// Return true if a binary operator using the specified opcode and operands
4002 /// would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
4003 /// integer to a pointer.
4005 const Expr *LHS,
4006 const Expr *RHS);
4007
4008 static bool classof(const Stmt *S) {
4009 return S->getStmtClass() >= firstBinaryOperatorConstant &&
4010 S->getStmtClass() <= lastBinaryOperatorConstant;
4011 }
4012
4013 // Iterators
4015 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4016 }
4018 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4019 }
4020
4021 /// Set and fetch the bit that shows whether FPFeatures needs to be
4022 /// allocated in Trailing Storage
4023 void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
4024 bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
4025
4026 /// Get FPFeatures from trailing storage
4028 assert(hasStoredFPFeatures());
4029 return *getTrailingFPFeatures();
4030 }
4031 /// Set FPFeatures in trailing storage, used only by Serialization
4033 assert(BinaryOperatorBits.HasFPFeatures);
4034 *getTrailingFPFeatures() = F;
4035 }
4036
4037 /// Get the FP features status of this operator. Only meaningful for
4038 /// operations on floating point types.
4040 if (BinaryOperatorBits.HasFPFeatures)
4043 }
4044
4045 // This is used in ASTImporter
4047 if (BinaryOperatorBits.HasFPFeatures)
4048 return getStoredFPFeatures();
4049 return FPOptionsOverride();
4050 }
4051
4052 /// Get the FP contractability status of this operator. Only meaningful for
4053 /// operations on floating point types.
4056 }
4057
4058 /// Get the FENV_ACCESS status of this operator. Only meaningful for
4059 /// operations on floating point types.
4060 bool isFEnvAccessOn(const LangOptions &LO) const {
4061 return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
4062 }
4063
4064protected:
4065 BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
4067 SourceLocation opLoc, FPOptionsOverride FPFeatures,
4068 bool dead2);
4069
4070 /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
4071 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4072 BinaryOperatorBits.Opc = BO_MulAssign;
4073 }
4074
4075 /// Return the size in bytes needed for the trailing objects.
4076 /// Used to allocate the right amount of storage.
4077 static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
4078 return HasFPFeatures * sizeof(FPOptionsOverride);
4079 }
4080};
4081
4082/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
4083/// track of the type the operation is performed in. Due to the semantics of
4084/// these operators, the operands are promoted, the arithmetic performed, an
4085/// implicit conversion back to the result type done, then the assignment takes
4086/// place. This captures the intermediate type which the computation is done
4087/// in.
4089 QualType ComputationLHSType;
4090 QualType ComputationResultType;
4091
4092 /// Construct an empty CompoundAssignOperator.
4093 explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
4094 bool hasFPFeatures)
4095 : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
4096
4097protected:
4099 QualType ResType, ExprValueKind VK, ExprObjectKind OK,
4100 SourceLocation OpLoc, FPOptionsOverride FPFeatures,
4101 QualType CompLHSType, QualType CompResultType)
4102 : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
4103 true),
4104 ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
4105 assert(isCompoundAssignmentOp() &&
4106 "Only should be used for compound assignments");
4107 }
4108
4109public:
4111 bool hasFPFeatures);
4112
4113 static CompoundAssignOperator *
4114 Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
4116 FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
4117 QualType CompResultType = QualType());
4118
4119 // The two computation types are the type the LHS is converted
4120 // to for the computation and the type of the result; the two are
4121 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
4122 QualType getComputationLHSType() const { return ComputationLHSType; }
4123 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
4124
4125 QualType getComputationResultType() const { return ComputationResultType; }
4126 void setComputationResultType(QualType T) { ComputationResultType = T; }
4127
4128 static bool classof(const Stmt *S) {
4129 return S->getStmtClass() == CompoundAssignOperatorClass;
4130 }
4131};
4132
4134 assert(BinaryOperatorBits.HasFPFeatures);
4135 return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator)
4136 : sizeof(BinaryOperator);
4137}
4138
4139/// AbstractConditionalOperator - An abstract base class for
4140/// ConditionalOperator and BinaryConditionalOperator.
4142 SourceLocation QuestionLoc, ColonLoc;
4143 friend class ASTStmtReader;
4144
4145protected:
4148 SourceLocation cloc)
4149 : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
4150
4152 : Expr(SC, Empty) { }
4153
4154public:
4155 /// getCond - Return the expression representing the condition for
4156 /// the ?: operator.
4157 Expr *getCond() const;
4158
4159 /// getTrueExpr - Return the subexpression representing the value of
4160 /// the expression if the condition evaluates to true.
4161 Expr *getTrueExpr() const;
4162
4163 /// getFalseExpr - Return the subexpression representing the value of
4164 /// the expression if the condition evaluates to false. This is
4165 /// the same as getRHS.
4166 Expr *getFalseExpr() const;
4167
4168 SourceLocation getQuestionLoc() const { return QuestionLoc; }
4169 SourceLocation getColonLoc() const { return ColonLoc; }
4170
4171 static bool classof(const Stmt *T) {
4172 return T->getStmtClass() == ConditionalOperatorClass ||
4173 T->getStmtClass() == BinaryConditionalOperatorClass;
4174 }
4175};
4176
4177/// ConditionalOperator - The ?: ternary operator. The GNU "missing
4178/// middle" extension is a BinaryConditionalOperator.
4180 enum { COND, LHS, RHS, END_EXPR };
4181 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4182
4183 friend class ASTStmtReader;
4184public:
4186 SourceLocation CLoc, Expr *rhs, QualType t,
4188 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
4189 CLoc) {
4190 SubExprs[COND] = cond;
4191 SubExprs[LHS] = lhs;
4192 SubExprs[RHS] = rhs;
4194 }
4195
4196 /// Build an empty conditional operator.
4198 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
4199
4200 /// getCond - Return the expression representing the condition for
4201 /// the ?: operator.
4202 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4203
4204 /// getTrueExpr - Return the subexpression representing the value of
4205 /// the expression if the condition evaluates to true.
4206 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
4207
4208 /// getFalseExpr - Return the subexpression representing the value of
4209 /// the expression if the condition evaluates to false. This is
4210 /// the same as getRHS.
4211 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
4212
4213 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
4214 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4215
4216 SourceLocation getBeginLoc() const LLVM_READONLY {
4217 return getCond()->getBeginLoc();
4218 }
4219 SourceLocation getEndLoc() const LLVM_READONLY {
4220 return getRHS()->getEndLoc();
4221 }
4222
4223 static bool classof(const Stmt *T) {
4224 return T->getStmtClass() == ConditionalOperatorClass;
4225 }
4226
4227 // Iterators
4229 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4230 }
4232 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4233 }
4234};
4235
4236/// BinaryConditionalOperator - The GNU extension to the conditional
4237/// operator which allows the middle operand to be omitted.
4238///
4239/// This is a different expression kind on the assumption that almost
4240/// every client ends up needing to know that these are different.
4242 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
4243
4244 /// - the common condition/left-hand-side expression, which will be
4245 /// evaluated as the opaque value
4246 /// - the condition, expressed in terms of the opaque value
4247 /// - the left-hand-side, expressed in terms of the opaque value
4248 /// - the right-hand-side
4249 Stmt *SubExprs[NUM_SUBEXPRS];
4250 OpaqueValueExpr *OpaqueValue;
4251
4252 friend class ASTStmtReader;
4253public:
4255 Expr *cond, Expr *lhs, Expr *rhs,
4256 SourceLocation qloc, SourceLocation cloc,
4258 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
4259 qloc, cloc),
4260 OpaqueValue(opaqueValue) {
4261 SubExprs[COMMON] = common;
4262 SubExprs[COND] = cond;
4263 SubExprs[LHS] = lhs;
4264 SubExprs[RHS] = rhs;
4265 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
4267 }
4268
4269 /// Build an empty conditional operator.
4271 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
4272
4273 /// getCommon - Return the common expression, written to the
4274 /// left of the condition. The opaque value will be bound to the
4275 /// result of this expression.
4276 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
4277
4278 /// getOpaqueValue - Return the opaque value placeholder.
4279 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4280
4281 /// getCond - Return the condition expression; this is defined