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