1//===- Stmt.h - Classes for representing statements -------------*- 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 Stmt interface and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_STMT_H
14#define LLVM_CLANG_AST_STMT_H
15
16#include "clang/AST/DeclGroup.h"
17#include "clang/AST/DependenceFlags.h"
18#include "clang/AST/StmtIterator.h"
19#include "clang/Basic/CapturedStmt.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/LLVM.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/SourceLocation.h"
24#include "clang/Basic/Specifiers.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/BitmaskEnum.h"
28#include "llvm/ADT/PointerIntPair.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/ADT/iterator.h"
31#include "llvm/ADT/iterator_range.h"
32#include "llvm/Support/Casting.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/ErrorHandling.h"
35#include <algorithm>
36#include <cassert>
37#include <cstddef>
38#include <iterator>
39#include <optional>
40#include <string>
41
42namespace llvm {
43
44class FoldingSetNodeID;
45
46} // namespace llvm
47
48namespace clang {
49
50class ASTContext;
51class Attr;
52class CapturedDecl;
53class Decl;
54class Expr;
55class AddrLabelExpr;
56class LabelDecl;
57class ODRHash;
58class PrinterHelper;
59struct PrintingPolicy;
60class RecordDecl;
61class SourceManager;
62class StringLiteral;
63class Token;
64class VarDecl;
65
66//===----------------------------------------------------------------------===//
67// AST classes for statements.
68//===----------------------------------------------------------------------===//
69
70/// Stmt - This represents one statement.
71///
72class alignas(void *) Stmt {
73public:
74 enum StmtClass {
75 NoStmtClass = 0,
76#define STMT(CLASS, PARENT) CLASS##Class,
77#define STMT_RANGE(BASE, FIRST, LAST) \
78 first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class,
79#define LAST_STMT_RANGE(BASE, FIRST, LAST) \
80 first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class
81#define ABSTRACT_STMT(STMT)
82#include "clang/AST/StmtNodes.inc"
83 };
84
85 // Make vanilla 'new' and 'delete' illegal for Stmts.
86protected:
87 friend class ASTStmtReader;
88 friend class ASTStmtWriter;
89
90 void *operator new(size_t bytes) noexcept {
91 llvm_unreachable("Stmts cannot be allocated with regular 'new'.");
92 }
93
94 void operator delete(void *data) noexcept {
95 llvm_unreachable("Stmts cannot be released with regular 'delete'.");
96 }
97
98 //===--- Statement bitfields classes ---===//
99
100 class StmtBitfields {
101 friend class ASTStmtReader;
102 friend class ASTStmtWriter;
103 friend class Stmt;
104
105 /// The statement class.
106 unsigned sClass : 8;
107 };
108 enum { NumStmtBits = 8 };
109
110 class NullStmtBitfields {
111 friend class ASTStmtReader;
112 friend class ASTStmtWriter;
113 friend class NullStmt;
114
115 unsigned : NumStmtBits;
116
117 /// True if the null statement was preceded by an empty macro, e.g:
118 /// @code
119 /// #define CALL(x)
120 /// CALL(0);
121 /// @endcode
122 unsigned HasLeadingEmptyMacro : 1;
123
124 /// The location of the semi-colon.
125 SourceLocation SemiLoc;
126 };
127
128 class CompoundStmtBitfields {
129 friend class ASTStmtReader;
130 friend class CompoundStmt;
131
132 unsigned : NumStmtBits;
133
134 /// True if the compound statement has one or more pragmas that set some
135 /// floating-point features.
136 unsigned HasFPFeatures : 1;
137
138 unsigned NumStmts;
139 };
140
141 class LabelStmtBitfields {
142 friend class LabelStmt;
143
144 unsigned : NumStmtBits;
145
146 SourceLocation IdentLoc;
147 };
148
149 class AttributedStmtBitfields {
150 friend class ASTStmtReader;
151 friend class AttributedStmt;
152
153 unsigned : NumStmtBits;
154
155 /// Number of attributes.
156 unsigned NumAttrs : 32 - NumStmtBits;
157
158 /// The location of the attribute.
159 SourceLocation AttrLoc;
160 };
161
162 class IfStmtBitfields {
163 friend class ASTStmtReader;
164 friend class IfStmt;
165
166 unsigned : NumStmtBits;
167
168 /// Whether this is a constexpr if, or a consteval if, or neither.
169 unsigned Kind : 3;
170
171 /// True if this if statement has storage for an else statement.
172 unsigned HasElse : 1;
173
174 /// True if this if statement has storage for a variable declaration.
175 unsigned HasVar : 1;
176
177 /// True if this if statement has storage for an init statement.
178 unsigned HasInit : 1;
179
180 /// The location of the "if".
181 SourceLocation IfLoc;
182 };
183
184 class SwitchStmtBitfields {
185 friend class SwitchStmt;
186
187 unsigned : NumStmtBits;
188
189 /// True if the SwitchStmt has storage for an init statement.
190 unsigned HasInit : 1;
191
192 /// True if the SwitchStmt has storage for a condition variable.
193 unsigned HasVar : 1;
194
195 /// If the SwitchStmt is a switch on an enum value, records whether all
196 /// the enum values were covered by CaseStmts. The coverage information
197 /// value is meant to be a hint for possible clients.
198 unsigned AllEnumCasesCovered : 1;
199
200 /// The location of the "switch".
201 SourceLocation SwitchLoc;
202 };
203
204 class WhileStmtBitfields {
205 friend class ASTStmtReader;
206 friend class WhileStmt;
207
208 unsigned : NumStmtBits;
209
210 /// True if the WhileStmt has storage for a condition variable.
211 unsigned HasVar : 1;
212
213 /// The location of the "while".
214 SourceLocation WhileLoc;
215 };
216
217 class DoStmtBitfields {
218 friend class DoStmt;
219
220 unsigned : NumStmtBits;
221
222 /// The location of the "do".
223 SourceLocation DoLoc;
224 };
225
226 class ForStmtBitfields {
227 friend class ForStmt;
228
229 unsigned : NumStmtBits;
230
231 /// The location of the "for".
232 SourceLocation ForLoc;
233 };
234
235 class GotoStmtBitfields {
236 friend class GotoStmt;
237 friend class IndirectGotoStmt;
238
239 unsigned : NumStmtBits;
240
241 /// The location of the "goto".
242 SourceLocation GotoLoc;
243 };
244
245 class ContinueStmtBitfields {
246 friend class ContinueStmt;
247
248 unsigned : NumStmtBits;
249
250 /// The location of the "continue".
251 SourceLocation ContinueLoc;
252 };
253
254 class BreakStmtBitfields {
255 friend class BreakStmt;
256
257 unsigned : NumStmtBits;
258
259 /// The location of the "break".
260 SourceLocation BreakLoc;
261 };
262
263 class ReturnStmtBitfields {
264 friend class ReturnStmt;
265
266 unsigned : NumStmtBits;
267
268 /// True if this ReturnStmt has storage for an NRVO candidate.
269 unsigned HasNRVOCandidate : 1;
270
271 /// The location of the "return".
272 SourceLocation RetLoc;
273 };
274
275 class SwitchCaseBitfields {
276 friend class SwitchCase;
277 friend class CaseStmt;
278
279 unsigned : NumStmtBits;
280
281 /// Used by CaseStmt to store whether it is a case statement
282 /// of the form case LHS ... RHS (a GNU extension).
283 unsigned CaseStmtIsGNURange : 1;
284
285 /// The location of the "case" or "default" keyword.
286 SourceLocation KeywordLoc;
287 };
288
289 //===--- Expression bitfields classes ---===//
290
291 class ExprBitfields {
292 friend class ASTStmtReader; // deserialization
293 friend class AtomicExpr; // ctor
294 friend class BlockDeclRefExpr; // ctor
295 friend class CallExpr; // ctor
296 friend class CXXConstructExpr; // ctor
297 friend class CXXDependentScopeMemberExpr; // ctor
298 friend class CXXNewExpr; // ctor
299 friend class CXXUnresolvedConstructExpr; // ctor
300 friend class DeclRefExpr; // computeDependence
301 friend class DependentScopeDeclRefExpr; // ctor
302 friend class DesignatedInitExpr; // ctor
303 friend class Expr;
304 friend class InitListExpr; // ctor
305 friend class ObjCArrayLiteral; // ctor
306 friend class ObjCDictionaryLiteral; // ctor
307 friend class ObjCMessageExpr; // ctor
308 friend class OffsetOfExpr; // ctor
309 friend class OpaqueValueExpr; // ctor
310 friend class OverloadExpr; // ctor
311 friend class ParenListExpr; // ctor
312 friend class PseudoObjectExpr; // ctor
313 friend class ShuffleVectorExpr; // ctor
314
315 unsigned : NumStmtBits;
316
317 unsigned ValueKind : 2;
318 unsigned ObjectKind : 3;
319 unsigned /*ExprDependence*/ Dependent : llvm::BitWidth<ExprDependence>;
320 };
321 enum { NumExprBits = NumStmtBits + 5 + llvm::BitWidth<ExprDependence> };
322
323 class ConstantExprBitfields {
324 friend class ASTStmtReader;
325 friend class ASTStmtWriter;
326 friend class ConstantExpr;
327
328 unsigned : NumExprBits;
329
330 /// The kind of result that is tail-allocated.
331 unsigned ResultKind : 2;
332
333 /// The kind of Result as defined by APValue::Kind.
334 unsigned APValueKind : 4;
335
336 /// When ResultKind == RSK_Int64, true if the tail-allocated integer is
337 /// unsigned.
338 unsigned IsUnsigned : 1;
339
340 /// When ResultKind == RSK_Int64. the BitWidth of the tail-allocated
341 /// integer. 7 bits because it is the minimal number of bits to represent a
342 /// value from 0 to 64 (the size of the tail-allocated integer).
343 unsigned BitWidth : 7;
344
345 /// When ResultKind == RSK_APValue, true if the ASTContext will cleanup the
346 /// tail-allocated APValue.
347 unsigned HasCleanup : 1;
348
349 /// True if this ConstantExpr was created for immediate invocation.
350 unsigned IsImmediateInvocation : 1;
351 };
352
353 class PredefinedExprBitfields {
354 friend class ASTStmtReader;
355 friend class PredefinedExpr;
356
357 unsigned : NumExprBits;
358
359 /// The kind of this PredefinedExpr. One of the enumeration values
360 /// in PredefinedExpr::IdentKind.
361 unsigned Kind : 4;
362
363 /// True if this PredefinedExpr has a trailing "StringLiteral *"
364 /// for the predefined identifier.
365 unsigned HasFunctionName : 1;
366
367 /// True if this PredefinedExpr should be treated as a StringLiteral (for
368 /// MSVC compatibility).
369 unsigned IsTransparent : 1;
370
371 /// The location of this PredefinedExpr.
372 SourceLocation Loc;
373 };
374
375 class DeclRefExprBitfields {
376 friend class ASTStmtReader; // deserialization
377 friend class DeclRefExpr;
378
379 unsigned : NumExprBits;
380
381 unsigned HasQualifier : 1;
382 unsigned HasTemplateKWAndArgsInfo : 1;
383 unsigned HasFoundDecl : 1;
384 unsigned HadMultipleCandidates : 1;
385 unsigned RefersToEnclosingVariableOrCapture : 1;
386 unsigned NonOdrUseReason : 2;
387 unsigned IsImmediateEscalating : 1;
388
389 /// The location of the declaration name itself.
390 SourceLocation Loc;
391 };
392
393
394 class FloatingLiteralBitfields {
395 friend class FloatingLiteral;
396
397 unsigned : NumExprBits;
398
399 static_assert(
400 llvm::APFloat::S_MaxSemantics < 16,
401 "Too many Semantics enum values to fit in bitfield of size 4");
402 unsigned Semantics : 4; // Provides semantics for APFloat construction
403 unsigned IsExact : 1;
404 };
405
406 class StringLiteralBitfields {
407 friend class ASTStmtReader;
408 friend class StringLiteral;
409
410 unsigned : NumExprBits;
411
412 /// The kind of this string literal.
413 /// One of the enumeration values of StringLiteral::StringKind.
414 unsigned Kind : 3;
415
416 /// The width of a single character in bytes. Only values of 1, 2,
417 /// and 4 bytes are supported. StringLiteral::mapCharByteWidth maps
418 /// the target + string kind to the appropriate CharByteWidth.
419 unsigned CharByteWidth : 3;
420
421 unsigned IsPascal : 1;
422
423 /// The number of concatenated token this string is made of.
424 /// This is the number of trailing SourceLocation.
425 unsigned NumConcatenated;
426 };
427
428 class CharacterLiteralBitfields {
429 friend class CharacterLiteral;
430
431 unsigned : NumExprBits;
432
433 unsigned Kind : 3;
434 };
435
436 class UnaryOperatorBitfields {
437 friend class UnaryOperator;
438
439 unsigned : NumExprBits;
440
441 unsigned Opc : 5;
442 unsigned CanOverflow : 1;
443 //
444 /// This is only meaningful for operations on floating point
445 /// types when additional values need to be in trailing storage.
446 /// It is 0 otherwise.
447 unsigned HasFPFeatures : 1;
448
449 SourceLocation Loc;
450 };
451
452 class UnaryExprOrTypeTraitExprBitfields {
453 friend class UnaryExprOrTypeTraitExpr;
454
455 unsigned : NumExprBits;
456
457 unsigned Kind : 3;
458 unsigned IsType : 1; // true if operand is a type, false if an expression.
459 };
460
461 class ArrayOrMatrixSubscriptExprBitfields {
462 friend class ArraySubscriptExpr;
463 friend class MatrixSubscriptExpr;
464
465 unsigned : NumExprBits;
466
467 SourceLocation RBracketLoc;
468 };
469
470 class CallExprBitfields {
471 friend class CallExpr;
472
473 unsigned : NumExprBits;
474
475 unsigned NumPreArgs : 1;
476
477 /// True if the callee of the call expression was found using ADL.
478 unsigned UsesADL : 1;
479
480 /// True if the call expression has some floating-point features.
481 unsigned HasFPFeatures : 1;
482
483 /// Padding used to align OffsetToTrailingObjects to a byte multiple.
484 unsigned : 24 - 3 - NumExprBits;
485
486 /// The offset in bytes from the this pointer to the start of the
487 /// trailing objects belonging to CallExpr. Intentionally byte sized
488 /// for faster access.
489 unsigned OffsetToTrailingObjects : 8;
490 };
491 enum { NumCallExprBits = 32 };
492
493 class MemberExprBitfields {
494 friend class ASTStmtReader;
495 friend class MemberExpr;
496
497 unsigned : NumExprBits;
498
499 /// IsArrow - True if this is "X->F", false if this is "X.F".
500 unsigned IsArrow : 1;
501
502 /// True if this member expression used a nested-name-specifier to
503 /// refer to the member, e.g., "x->Base::f", or found its member via
504 /// a using declaration. When true, a MemberExprNameQualifier
505 /// structure is allocated immediately after the MemberExpr.
506 unsigned HasQualifierOrFoundDecl : 1;
507
508 /// True if this member expression specified a template keyword
509 /// and/or a template argument list explicitly, e.g., x->f<int>,
510 /// x->template f, x->template f<int>.
511 /// When true, an ASTTemplateKWAndArgsInfo structure and its
512 /// TemplateArguments (if any) are present.
513 unsigned HasTemplateKWAndArgsInfo : 1;
514
515 /// True if this member expression refers to a method that
516 /// was resolved from an overloaded set having size greater than 1.
517 unsigned HadMultipleCandidates : 1;
518
519 /// Value of type NonOdrUseReason indicating why this MemberExpr does
520 /// not constitute an odr-use of the named declaration. Meaningful only
521 /// when naming a static member.
522 unsigned NonOdrUseReason : 2;
523
524 /// This is the location of the -> or . in the expression.
525 SourceLocation OperatorLoc;
526 };
527
528 class CastExprBitfields {
529 friend class CastExpr;
530 friend class ImplicitCastExpr;
531
532 unsigned : NumExprBits;
533
534 unsigned Kind : 7;
535 unsigned PartOfExplicitCast : 1; // Only set for ImplicitCastExpr.
536
537 /// True if the call expression has some floating-point features.
538 unsigned HasFPFeatures : 1;
539
540 /// The number of CXXBaseSpecifiers in the cast. 14 bits would be enough
541 /// here. ([implimits] Direct and indirect base classes [16384]).
542 unsigned BasePathSize;
543 };
544
545 class BinaryOperatorBitfields {
546 friend class BinaryOperator;
547
548 unsigned : NumExprBits;
549
550 unsigned Opc : 6;
551
552 /// This is only meaningful for operations on floating point
553 /// types when additional values need to be in trailing storage.
554 /// It is 0 otherwise.
555 unsigned HasFPFeatures : 1;
556
557 SourceLocation OpLoc;
558 };
559
560 class InitListExprBitfields {
561 friend class InitListExpr;
562
563 unsigned : NumExprBits;
564
565 /// Whether this initializer list originally had a GNU array-range
566 /// designator in it. This is a temporary marker used by CodeGen.
567 unsigned HadArrayRangeDesignator : 1;
568 };
569
570 class ParenListExprBitfields {
571 friend class ASTStmtReader;
572 friend class ParenListExpr;
573
574 unsigned : NumExprBits;
575
576 /// The number of expressions in the paren list.
577 unsigned NumExprs;
578 };
579
580 class GenericSelectionExprBitfields {
581 friend class ASTStmtReader;
582 friend class GenericSelectionExpr;
583
584 unsigned : NumExprBits;
585
586 /// The location of the "_Generic".
587 SourceLocation GenericLoc;
588 };
589
590 class PseudoObjectExprBitfields {
591 friend class ASTStmtReader; // deserialization
592 friend class PseudoObjectExpr;
593
594 unsigned : NumExprBits;
595
596 unsigned NumSubExprs : 16;
597 unsigned ResultIndex : 16;
598 };
599
600 class SourceLocExprBitfields {
601 friend class ASTStmtReader;
602 friend class SourceLocExpr;
603
604 unsigned : NumExprBits;
605
606 /// The kind of source location builtin represented by the SourceLocExpr.
607 /// Ex. __builtin_LINE, __builtin_FUNCTION, etc.
608 unsigned Kind : 3;
609 };
610
611 class StmtExprBitfields {
612 friend class ASTStmtReader;
613 friend class StmtExpr;
614
615 unsigned : NumExprBits;
616
617 /// The number of levels of template parameters enclosing this statement
618 /// expression. Used to determine if a statement expression remains
619 /// dependent after instantiation.
620 unsigned TemplateDepth;
621 };
622
623 //===--- C++ Expression bitfields classes ---===//
624
625 class CXXOperatorCallExprBitfields {
626 friend class ASTStmtReader;
627 friend class CXXOperatorCallExpr;
628
629 unsigned : NumCallExprBits;
630
631 /// The kind of this overloaded operator. One of the enumerator
632 /// value of OverloadedOperatorKind.
633 unsigned OperatorKind : 6;
634 };
635
636 class CXXRewrittenBinaryOperatorBitfields {
637 friend class ASTStmtReader;
638 friend class CXXRewrittenBinaryOperator;
639
640 unsigned : NumCallExprBits;
641
642 unsigned IsReversed : 1;
643 };
644
645 class CXXBoolLiteralExprBitfields {
646 friend class CXXBoolLiteralExpr;
647
648 unsigned : NumExprBits;
649
650 /// The value of the boolean literal.
651 unsigned Value : 1;
652
653 /// The location of the boolean literal.
654 SourceLocation Loc;
655 };
656
657 class CXXNullPtrLiteralExprBitfields {
658 friend class CXXNullPtrLiteralExpr;
659
660 unsigned : NumExprBits;
661
662 /// The location of the null pointer literal.
663 SourceLocation Loc;
664 };
665
666 class CXXThisExprBitfields {
667 friend class CXXThisExpr;
668
669 unsigned : NumExprBits;
670
671 /// Whether this is an implicit "this".
672 unsigned IsImplicit : 1;
673
674 /// The location of the "this".
675 SourceLocation Loc;
676 };
677
678 class CXXThrowExprBitfields {
679 friend class ASTStmtReader;
680 friend class CXXThrowExpr;
681
682 unsigned : NumExprBits;
683
684 /// Whether the thrown variable (if any) is in scope.
685 unsigned IsThrownVariableInScope : 1;
686
687 /// The location of the "throw".
688 SourceLocation ThrowLoc;
689 };
690
691 class CXXDefaultArgExprBitfields {
692 friend class ASTStmtReader;
693 friend class CXXDefaultArgExpr;
694
695 unsigned : NumExprBits;
696
697 /// Whether this CXXDefaultArgExpr rewrote its argument and stores a copy.
698 unsigned HasRewrittenInit : 1;
699
700 /// The location where the default argument expression was used.
701 SourceLocation Loc;
702 };
703
704 class CXXDefaultInitExprBitfields {
705 friend class ASTStmtReader;
706 friend class CXXDefaultInitExpr;
707
708 unsigned : NumExprBits;
709
710 /// Whether this CXXDefaultInitExprBitfields rewrote its argument and stores
711 /// a copy.
712 unsigned HasRewrittenInit : 1;
713
714 /// The location where the default initializer expression was used.
715 SourceLocation Loc;
716 };
717
718 class CXXScalarValueInitExprBitfields {
719 friend class ASTStmtReader;
720 friend class CXXScalarValueInitExpr;
721
722 unsigned : NumExprBits;
723
724 SourceLocation RParenLoc;
725 };
726
727 class CXXNewExprBitfields {
728 friend class ASTStmtReader;
729 friend class ASTStmtWriter;
730 friend class CXXNewExpr;
731
732 unsigned : NumExprBits;
733
734 /// Was the usage ::new, i.e. is the global new to be used?
735 unsigned IsGlobalNew : 1;
736
737 /// Do we allocate an array? If so, the first trailing "Stmt *" is the
738 /// size expression.
739 unsigned IsArray : 1;
740
741 /// Should the alignment be passed to the allocation function?
742 unsigned ShouldPassAlignment : 1;
743
744 /// If this is an array allocation, does the usual deallocation
745 /// function for the allocated type want to know the allocated size?
746 unsigned UsualArrayDeleteWantsSize : 1;
747
748 /// What kind of initializer do we have? Could be none, parens, or braces.
749 /// In storage, we distinguish between "none, and no initializer expr", and
750 /// "none, but an implicit initializer expr".
751 unsigned StoredInitializationStyle : 2;
752
753 /// True if the allocated type was expressed as a parenthesized type-id.
754 unsigned IsParenTypeId : 1;
755
756 /// The number of placement new arguments.
757 unsigned NumPlacementArgs;
758 };
759
760 class CXXDeleteExprBitfields {
761 friend class ASTStmtReader;
762 friend class CXXDeleteExpr;
763
764 unsigned : NumExprBits;
765
766 /// Is this a forced global delete, i.e. "::delete"?
767 unsigned GlobalDelete : 1;
768
769 /// Is this the array form of delete, i.e. "delete[]"?
770 unsigned ArrayForm : 1;
771
772 /// ArrayFormAsWritten can be different from ArrayForm if 'delete' is
773 /// applied to pointer-to-array type (ArrayFormAsWritten will be false
774 /// while ArrayForm will be true).
775 unsigned ArrayFormAsWritten : 1;
776
777 /// Does the usual deallocation function for the element type require
778 /// a size_t argument?
779 unsigned UsualArrayDeleteWantsSize : 1;
780
781 /// Location of the expression.
782 SourceLocation Loc;
783 };
784
785 class TypeTraitExprBitfields {
786 friend class ASTStmtReader;
787 friend class ASTStmtWriter;
788 friend class TypeTraitExpr;
789
790 unsigned : NumExprBits;
791
792 /// The kind of type trait, which is a value of a TypeTrait enumerator.
793 unsigned Kind : 8;
794
795 /// If this expression is not value-dependent, this indicates whether
796 /// the trait evaluated true or false.
797 unsigned Value : 1;
798
799 /// The number of arguments to this type trait. According to [implimits]
800 /// 8 bits would be enough, but we require (and test for) at least 16 bits
801 /// to mirror FunctionType.
802 unsigned NumArgs;
803 };
804
805 class DependentScopeDeclRefExprBitfields {
806 friend class ASTStmtReader;
807 friend class ASTStmtWriter;
808 friend class DependentScopeDeclRefExpr;
809
810 unsigned : NumExprBits;
811
812 /// Whether the name includes info for explicit template
813 /// keyword and arguments.
814 unsigned HasTemplateKWAndArgsInfo : 1;
815 };
816
817 class CXXConstructExprBitfields {
818 friend class ASTStmtReader;
819 friend class CXXConstructExpr;
820
821 unsigned : NumExprBits;
822
823 unsigned Elidable : 1;
824 unsigned HadMultipleCandidates : 1;
825 unsigned ListInitialization : 1;
826 unsigned StdInitListInitialization : 1;
827 unsigned ZeroInitialization : 1;
828 unsigned ConstructionKind : 3;
829 unsigned IsImmediateEscalating : 1;
830
831 SourceLocation Loc;
832 };
833
834 class ExprWithCleanupsBitfields {
835 friend class ASTStmtReader; // deserialization
836 friend class ExprWithCleanups;
837
838 unsigned : NumExprBits;
839
840 // When false, it must not have side effects.
841 unsigned CleanupsHaveSideEffects : 1;
842
843 unsigned NumObjects : 32 - 1 - NumExprBits;
844 };
845
846 class CXXUnresolvedConstructExprBitfields {
847 friend class ASTStmtReader;
848 friend class CXXUnresolvedConstructExpr;
849
850 unsigned : NumExprBits;
851
852 /// The number of arguments used to construct the type.
853 unsigned NumArgs;
854 };
855
856 class CXXDependentScopeMemberExprBitfields {
857 friend class ASTStmtReader;
858 friend class CXXDependentScopeMemberExpr;
859
860 unsigned : NumExprBits;
861
862 /// Whether this member expression used the '->' operator or
863 /// the '.' operator.
864 unsigned IsArrow : 1;
865
866 /// Whether this member expression has info for explicit template
867 /// keyword and arguments.
868 unsigned HasTemplateKWAndArgsInfo : 1;
869
870 /// See getFirstQualifierFoundInScope() and the comment listing
871 /// the trailing objects.
872 unsigned HasFirstQualifierFoundInScope : 1;
873
874 /// The location of the '->' or '.' operator.
875 SourceLocation OperatorLoc;
876 };
877
878 class OverloadExprBitfields {
879 friend class ASTStmtReader;
880 friend class OverloadExpr;
881
882 unsigned : NumExprBits;
883
884 /// Whether the name includes info for explicit template
885 /// keyword and arguments.
886 unsigned HasTemplateKWAndArgsInfo : 1;
887
888 /// Padding used by the derived classes to store various bits. If you
889 /// need to add some data here, shrink this padding and add your data
890 /// above. NumOverloadExprBits also needs to be updated.
891 unsigned : 32 - NumExprBits - 1;
892
893 /// The number of results.
894 unsigned NumResults;
895 };
896 enum { NumOverloadExprBits = NumExprBits + 1 };
897
898 class UnresolvedLookupExprBitfields {
899 friend class ASTStmtReader;
900 friend class UnresolvedLookupExpr;
901
902 unsigned : NumOverloadExprBits;
903
904 /// True if these lookup results should be extended by
905 /// argument-dependent lookup if this is the operand of a function call.
906 unsigned RequiresADL : 1;
907
908 /// True if these lookup results are overloaded. This is pretty trivially
909 /// rederivable if we urgently need to kill this field.
910 unsigned Overloaded : 1;
911 };
912 static_assert(sizeof(UnresolvedLookupExprBitfields) <= 4,
913 "UnresolvedLookupExprBitfields must be <= than 4 bytes to"
914 "avoid trashing OverloadExprBitfields::NumResults!");
915
916 class UnresolvedMemberExprBitfields {
917 friend class ASTStmtReader;
918 friend class UnresolvedMemberExpr;
919
920 unsigned : NumOverloadExprBits;
921
922 /// Whether this member expression used the '->' operator or
923 /// the '.' operator.
924 unsigned IsArrow : 1;
925
926 /// Whether the lookup results contain an unresolved using declaration.
927 unsigned HasUnresolvedUsing : 1;
928 };
929 static_assert(sizeof(UnresolvedMemberExprBitfields) <= 4,
930 "UnresolvedMemberExprBitfields must be <= than 4 bytes to"
931 "avoid trashing OverloadExprBitfields::NumResults!");
932
933 class CXXNoexceptExprBitfields {
934 friend class ASTStmtReader;
935 friend class CXXNoexceptExpr;
936
937 unsigned : NumExprBits;
938
939 unsigned Value : 1;
940 };
941
942 class SubstNonTypeTemplateParmExprBitfields {
943 friend class ASTStmtReader;
944 friend class SubstNonTypeTemplateParmExpr;
945
946 unsigned : NumExprBits;
947
948 /// The location of the non-type template parameter reference.
949 SourceLocation NameLoc;
950 };
951
952 class LambdaExprBitfields {
953 friend class ASTStmtReader;
954 friend class ASTStmtWriter;
955 friend class LambdaExpr;
956
957 unsigned : NumExprBits;
958
959 /// The default capture kind, which is a value of type
960 /// LambdaCaptureDefault.
961 unsigned CaptureDefault : 2;
962
963 /// Whether this lambda had an explicit parameter list vs. an
964 /// implicit (and empty) parameter list.
965 unsigned ExplicitParams : 1;
966
967 /// Whether this lambda had the result type explicitly specified.
968 unsigned ExplicitResultType : 1;
969
970 /// The number of captures.
971 unsigned NumCaptures : 16;
972 };
973
974 class RequiresExprBitfields {
975 friend class ASTStmtReader;
976 friend class ASTStmtWriter;
977 friend class RequiresExpr;
978
979 unsigned : NumExprBits;
980
981 unsigned IsSatisfied : 1;
982 SourceLocation RequiresKWLoc;
983 };
984
985 //===--- C++ Coroutines bitfields classes ---===//
986
987 class CoawaitExprBitfields {
988 friend class CoawaitExpr;
989
990 unsigned : NumExprBits;
991
992 unsigned IsImplicit : 1;
993 };
994
995 //===--- Obj-C Expression bitfields classes ---===//
996
997 class ObjCIndirectCopyRestoreExprBitfields {
998 friend class ObjCIndirectCopyRestoreExpr;
999
1000 unsigned : NumExprBits;
1001
1002 unsigned ShouldCopy : 1;
1003 };
1004
1005 //===--- Clang Extensions bitfields classes ---===//
1006
1007 class OpaqueValueExprBitfields {
1008 friend class ASTStmtReader;
1009 friend class OpaqueValueExpr;
1010
1011 unsigned : NumExprBits;
1012
1013 /// The OVE is a unique semantic reference to its source expression if this
1014 /// bit is set to true.
1015 unsigned IsUnique : 1;
1016
1017 SourceLocation Loc;
1018 };
1019
1020 union {
1021 // Same order as in StmtNodes.td.
1022 // Statements
1023 StmtBitfields StmtBits;
1024 NullStmtBitfields NullStmtBits;
1025 CompoundStmtBitfields CompoundStmtBits;
1026 LabelStmtBitfields LabelStmtBits;
1027 AttributedStmtBitfields AttributedStmtBits;
1028 IfStmtBitfields IfStmtBits;
1029 SwitchStmtBitfields SwitchStmtBits;
1030 WhileStmtBitfields WhileStmtBits;
1031 DoStmtBitfields DoStmtBits;
1032 ForStmtBitfields ForStmtBits;
1033 GotoStmtBitfields GotoStmtBits;
1034 ContinueStmtBitfields ContinueStmtBits;
1035 BreakStmtBitfields BreakStmtBits;
1036 ReturnStmtBitfields ReturnStmtBits;
1037 SwitchCaseBitfields SwitchCaseBits;
1038
1039 // Expressions
1040 ExprBitfields ExprBits;
1041 ConstantExprBitfields ConstantExprBits;
1042 PredefinedExprBitfields PredefinedExprBits;
1043 DeclRefExprBitfields DeclRefExprBits;
1044 FloatingLiteralBitfields FloatingLiteralBits;
1045 StringLiteralBitfields StringLiteralBits;
1046 CharacterLiteralBitfields CharacterLiteralBits;
1047 UnaryOperatorBitfields UnaryOperatorBits;
1048 UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits;
1049 ArrayOrMatrixSubscriptExprBitfields ArrayOrMatrixSubscriptExprBits;
1050 CallExprBitfields CallExprBits;
1051 MemberExprBitfields MemberExprBits;
1052 CastExprBitfields CastExprBits;
1053 BinaryOperatorBitfields BinaryOperatorBits;
1054 InitListExprBitfields InitListExprBits;
1055 ParenListExprBitfields ParenListExprBits;
1056 GenericSelectionExprBitfields GenericSelectionExprBits;
1057 PseudoObjectExprBitfields PseudoObjectExprBits;
1058 SourceLocExprBitfields SourceLocExprBits;
1059
1060 // GNU Extensions.
1061 StmtExprBitfields StmtExprBits;
1062
1063 // C++ Expressions
1064 CXXOperatorCallExprBitfields CXXOperatorCallExprBits;
1065 CXXRewrittenBinaryOperatorBitfields CXXRewrittenBinaryOperatorBits;
1066 CXXBoolLiteralExprBitfields CXXBoolLiteralExprBits;
1067 CXXNullPtrLiteralExprBitfields CXXNullPtrLiteralExprBits;
1068 CXXThisExprBitfields CXXThisExprBits;
1069 CXXThrowExprBitfields CXXThrowExprBits;
1070 CXXDefaultArgExprBitfields CXXDefaultArgExprBits;
1071 CXXDefaultInitExprBitfields CXXDefaultInitExprBits;
1072 CXXScalarValueInitExprBitfields CXXScalarValueInitExprBits;
1073 CXXNewExprBitfields CXXNewExprBits;
1074 CXXDeleteExprBitfields CXXDeleteExprBits;
1075 TypeTraitExprBitfields TypeTraitExprBits;
1076 DependentScopeDeclRefExprBitfields DependentScopeDeclRefExprBits;
1077 CXXConstructExprBitfields CXXConstructExprBits;
1078 ExprWithCleanupsBitfields ExprWithCleanupsBits;
1079 CXXUnresolvedConstructExprBitfields CXXUnresolvedConstructExprBits;
1080 CXXDependentScopeMemberExprBitfields CXXDependentScopeMemberExprBits;
1081 OverloadExprBitfields OverloadExprBits;
1082 UnresolvedLookupExprBitfields UnresolvedLookupExprBits;
1083 UnresolvedMemberExprBitfields UnresolvedMemberExprBits;
1084 CXXNoexceptExprBitfields CXXNoexceptExprBits;
1085 SubstNonTypeTemplateParmExprBitfields SubstNonTypeTemplateParmExprBits;
1086 LambdaExprBitfields LambdaExprBits;
1087 RequiresExprBitfields RequiresExprBits;
1088
1089 // C++ Coroutines expressions
1090 CoawaitExprBitfields CoawaitBits;
1091
1092 // Obj-C Expressions
1093 ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits;
1094
1095 // Clang Extensions
1096 OpaqueValueExprBitfields OpaqueValueExprBits;
1097 };
1098
1099public:
1100 // Only allow allocation of Stmts using the allocator in ASTContext
1101 // or by doing a placement new.
1102 void* operator new(size_t bytes, const ASTContext& C,
1103 unsigned alignment = 8);
1104
1105 void* operator new(size_t bytes, const ASTContext* C,
1106 unsigned alignment = 8) {
1107 return operator new(bytes, *C, alignment);
1108 }
1109
1110 void *operator new(size_t bytes, void *mem) noexcept { return mem; }
1111
1112 void operator delete(void *, const ASTContext &, unsigned) noexcept {}
1113 void operator delete(void *, const ASTContext *, unsigned) noexcept {}
1114 void operator delete(void *, size_t) noexcept {}
1115 void operator delete(void *, void *) noexcept {}
1116
1117public:
1118 /// A placeholder type used to construct an empty shell of a
1119 /// type, that will be filled in later (e.g., by some
1120 /// de-serialization).
1121 struct EmptyShell {};
1122
1123 /// The likelihood of a branch being taken.
1124 enum Likelihood {
1125 LH_Unlikely = -1, ///< Branch has the [[unlikely]] attribute.
1126 LH_None, ///< No attribute set or branches of the IfStmt have
1127 ///< the same attribute.
1128 LH_Likely ///< Branch has the [[likely]] attribute.
1129 };
1130
1131protected:
1132 /// Iterator for iterating over Stmt * arrays that contain only T *.
1133 ///
1134 /// This is needed because AST nodes use Stmt* arrays to store
1135 /// references to children (to be compatible with StmtIterator).
1136 template<typename T, typename TPtr = T *, typename StmtPtr = Stmt *>
1137 struct CastIterator
1138 : llvm::iterator_adaptor_base<CastIterator<T, TPtr, StmtPtr>, StmtPtr *,
1139 std::random_access_iterator_tag, TPtr> {
1140 using Base = typename CastIterator::iterator_adaptor_base;
1141
1142 CastIterator() : Base(nullptr) {}
1143 CastIterator(StmtPtr *I) : Base(I) {}
1144
1145 typename Base::value_type operator*() const {
1146 return cast_or_null<T>(*this->I);
1147 }
1148 };
1149
1150 /// Const iterator for iterating over Stmt * arrays that contain only T *.
1151 template <typename T>
1152 using ConstCastIterator = CastIterator<T, const T *const, const Stmt *const>;
1153
1154 using ExprIterator = CastIterator<Expr>;
1155 using ConstExprIterator = ConstCastIterator<Expr>;
1156
1157private:
1158 /// Whether statistic collection is enabled.
1159 static bool StatisticsEnabled;
1160
1161protected:
1162 /// Construct an empty statement.
1163 explicit Stmt(StmtClass SC, EmptyShell) : Stmt(SC) {}
1164
1165public:
1166 Stmt() = delete;
1167 Stmt(const Stmt &) = delete;
1168 Stmt(Stmt &&) = delete;
1169 Stmt &operator=(const Stmt &) = delete;
1170 Stmt &operator=(Stmt &&) = delete;
1171
1172 Stmt(StmtClass SC) {
1173 static_assert(sizeof(*this) <= 8,
1174 "changing bitfields changed sizeof(Stmt)");
1175 static_assert(sizeof(*this) % alignof(void *) == 0,
1176 "Insufficient alignment!");
1177 StmtBits.sClass = SC;
1178 if (StatisticsEnabled) Stmt::addStmtClass(SC);
1179 }
1180
1181 StmtClass getStmtClass() const {
1182 return static_cast<StmtClass>(StmtBits.sClass);
1183 }
1184
1185 const char *getStmtClassName() const;
1186
1187 /// SourceLocation tokens are not useful in isolation - they are low level
1188 /// value objects created/interpreted by SourceManager. We assume AST
1189 /// clients will have a pointer to the respective SourceManager.
1190 SourceRange getSourceRange() const LLVM_READONLY;
1191 SourceLocation getBeginLoc() const LLVM_READONLY;
1192 SourceLocation getEndLoc() const LLVM_READONLY;
1193
1194 // global temp stats (until we have a per-module visitor)
1195 static void addStmtClass(const StmtClass s);
1196 static void EnableStatistics();
1197 static void PrintStats();
1198
1199 /// \returns the likelihood of a set of attributes.
1200 static Likelihood getLikelihood(ArrayRef<const Attr *> Attrs);
1201
1202 /// \returns the likelihood of a statement.
1203 static Likelihood getLikelihood(const Stmt *S);
1204
1205 /// \returns the likelihood attribute of a statement.
1206 static const Attr *getLikelihoodAttr(const Stmt *S);
1207
1208 /// \returns the likelihood of the 'then' branch of an 'if' statement. The
1209 /// 'else' branch is required to determine whether both branches specify the
1210 /// same likelihood, which affects the result.
1211 static Likelihood getLikelihood(const Stmt *Then, const Stmt *Else);
1212
1213 /// \returns whether the likelihood of the branches of an if statement are
1214 /// conflicting. When the first element is \c true there's a conflict and
1215 /// the Attr's are the conflicting attributes of the Then and Else Stmt.
1216 static std::tuple<bool, const Attr *, const Attr *>
1217 determineLikelihoodConflict(const Stmt *Then, const Stmt *Else);
1218
1219 /// Dumps the specified AST fragment and all subtrees to
1220 /// \c llvm::errs().
1221 void dump() const;
1222 void dump(raw_ostream &OS, const ASTContext &Context) const;
1223
1224 /// \return Unique reproducible object identifier
1225 int64_t getID(const ASTContext &Context) const;
1226
1227 /// dumpColor - same as dump(), but forces color highlighting.
1228 void dumpColor() const;
1229
1230 /// dumpPretty/printPretty - These two methods do a "pretty print" of the AST
1231 /// back to its original source language syntax.
1232 void dumpPretty(const ASTContext &Context) const;
1233 void printPretty(raw_ostream &OS, PrinterHelper *Helper,
1234 const PrintingPolicy &Policy, unsigned Indentation = 0,
1235 StringRef NewlineSymbol = "\n",
1236 const ASTContext *Context = nullptr) const;
1237 void printPrettyControlled(raw_ostream &OS, PrinterHelper *Helper,
1238 const PrintingPolicy &Policy,
1239 unsigned Indentation = 0,
1240 StringRef NewlineSymbol = "\n",
1241 const ASTContext *Context = nullptr) const;
1242
1243 /// Pretty-prints in JSON format.
1244 void printJson(raw_ostream &Out, PrinterHelper *Helper,
1245 const PrintingPolicy &Policy, bool AddQuotes) const;
1246
1247 /// viewAST - Visualize an AST rooted at this Stmt* using GraphViz. Only
1248 /// works on systems with GraphViz (Mac OS X) or dot+gv installed.
1249 void viewAST() const;
1250
1251 /// Skip no-op (attributed, compound) container stmts and skip captured
1252 /// stmt at the top, if \a IgnoreCaptured is true.
1253 Stmt *IgnoreContainers(bool IgnoreCaptured = false);
1254 const Stmt *IgnoreContainers(bool IgnoreCaptured = false) const {
1255 return const_cast<Stmt *>(this)->IgnoreContainers(IgnoreCaptured);
1256 }
1257
1258 const Stmt *stripLabelLikeStatements() const;
1259 Stmt *stripLabelLikeStatements() {
1260 return const_cast<Stmt*>(
1261 const_cast<const Stmt*>(this)->stripLabelLikeStatements());
1262 }
1263
1264 /// Child Iterators: All subclasses must implement 'children'
1265 /// to permit easy iteration over the substatements/subexpressions of an
1266 /// AST node. This permits easy iteration over all nodes in the AST.
1267 using child_iterator = StmtIterator;
1268 using const_child_iterator = ConstStmtIterator;
1269
1270 using child_range = llvm::iterator_range<child_iterator>;
1271 using const_child_range = llvm::iterator_range<const_child_iterator>;
1272
1273 child_range children();
1274
1275 const_child_range children() const {
1276 auto Children = const_cast<Stmt *>(this)->children();
1277 return const_child_range(Children.begin(), Children.end());
1278 }
1279
1280 child_iterator child_begin() { return children().begin(); }
1281 child_iterator child_end() { return children().end(); }
1282
1283 const_child_iterator child_begin() const { return children().begin(); }
1284 const_child_iterator child_end() const { return children().end(); }
1285
1286 /// Produce a unique representation of the given statement.
1287 ///
1288 /// \param ID once the profiling operation is complete, will contain
1289 /// the unique representation of the given statement.
1290 ///
1291 /// \param Context the AST context in which the statement resides
1292 ///
1293 /// \param Canonical whether the profile should be based on the canonical
1294 /// representation of this statement (e.g., where non-type template
1295 /// parameters are identified by index/level rather than their
1296 /// declaration pointers) or the exact representation of the statement as
1297 /// written in the source.
1298 /// \param ProfileLambdaExpr whether or not to profile lambda expressions.
1299 /// When false, the lambda expressions are never considered to be equal to
1300 /// other lambda expressions. When true, the lambda expressions with the same
1301 /// implementation will be considered to be the same. ProfileLambdaExpr should
1302 /// only be true when we try to merge two declarations within modules.
1303 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
1304 bool Canonical, bool ProfileLambdaExpr = false) const;
1305
1306 /// Calculate a unique representation for a statement that is
1307 /// stable across compiler invocations.
1308 ///
1309 /// \param ID profile information will be stored in ID.
1310 ///
1311 /// \param Hash an ODRHash object which will be called where pointers would
1312 /// have been used in the Profile function.
1313 void ProcessODRHash(llvm::FoldingSetNodeID &ID, ODRHash& Hash) const;
1314};
1315
1316/// DeclStmt - Adaptor class for mixing declarations with statements and
1317/// expressions. For example, CompoundStmt mixes statements, expressions
1318/// and declarations (variables, types). Another example is ForStmt, where
1319/// the first statement can be an expression or a declaration.
1320class DeclStmt : public Stmt {
1321 DeclGroupRef DG;
1322 SourceLocation StartLoc, EndLoc;
1323
1324public:
1325 DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc)
1326 : Stmt(DeclStmtClass), DG(dg), StartLoc(startLoc), EndLoc(endLoc) {}
1327
1328 /// Build an empty declaration statement.
1329 explicit DeclStmt(EmptyShell Empty) : Stmt(DeclStmtClass, Empty) {}
1330
1331 /// isSingleDecl - This method returns true if this DeclStmt refers
1332 /// to a single Decl.
1333 bool isSingleDecl() const { return DG.isSingleDecl(); }
1334
1335 const Decl *getSingleDecl() const { return DG.getSingleDecl(); }
1336 Decl *getSingleDecl() { return DG.getSingleDecl(); }
1337
1338 const DeclGroupRef getDeclGroup() const { return DG; }
1339 DeclGroupRef getDeclGroup() { return DG; }
1340 void setDeclGroup(DeclGroupRef DGR) { DG = DGR; }
1341
1342 void setStartLoc(SourceLocation L) { StartLoc = L; }
1343 SourceLocation getEndLoc() const { return EndLoc; }
1344 void setEndLoc(SourceLocation L) { EndLoc = L; }
1345
1346 SourceLocation getBeginLoc() const LLVM_READONLY { return StartLoc; }
1347
1348 static bool classof(const Stmt *T) {
1349 return T->getStmtClass() == DeclStmtClass;
1350 }
1351
1352 // Iterators over subexpressions.
1353 child_range children() {
1354 return child_range(child_iterator(DG.begin(), DG.end()),
1355 child_iterator(DG.end(), DG.end()));
1356 }
1357
1358 const_child_range children() const {
1359 auto Children = const_cast<DeclStmt *>(this)->children();
1360 return const_child_range(Children);
1361 }
1362
1363 using decl_iterator = DeclGroupRef::iterator;
1364 using const_decl_iterator = DeclGroupRef::const_iterator;
1365 using decl_range = llvm::iterator_range<decl_iterator>;
1366 using decl_const_range = llvm::iterator_range<const_decl_iterator>;
1367
1368 decl_range decls() { return decl_range(decl_begin(), decl_end()); }
1369
1370 decl_const_range decls() const {
1371 return decl_const_range(decl_begin(), decl_end());
1372 }
1373
1374 decl_iterator decl_begin() { return DG.begin(); }
1375 decl_iterator decl_end() { return DG.end(); }
1376 const_decl_iterator decl_begin() const { return DG.begin(); }
1377 const_decl_iterator decl_end() const { return DG.end(); }
1378
1379 using reverse_decl_iterator = std::reverse_iterator<decl_iterator>;
1380
1381 reverse_decl_iterator decl_rbegin() {
1382 return reverse_decl_iterator(decl_end());
1383 }
1384
1385 reverse_decl_iterator decl_rend() {
1386 return reverse_decl_iterator(decl_begin());
1387 }
1388};
1389
1390/// NullStmt - This is the null statement ";": C99 6.8.3p3.
1391///
1392class NullStmt : public Stmt {
1393public:
1394 NullStmt(SourceLocation L, bool hasLeadingEmptyMacro = false)
1395 : Stmt(NullStmtClass) {
1396 NullStmtBits.HasLeadingEmptyMacro = hasLeadingEmptyMacro;
1397 setSemiLoc(L);
1398 }
1399
1400 /// Build an empty null statement.
1401 explicit NullStmt(EmptyShell Empty) : Stmt(NullStmtClass, Empty) {}
1402
1403 SourceLocation getSemiLoc() const { return NullStmtBits.SemiLoc; }
1404 void setSemiLoc(SourceLocation L) { NullStmtBits.SemiLoc = L; }
1405
1406 bool hasLeadingEmptyMacro() const {
1407 return NullStmtBits.HasLeadingEmptyMacro;
1408 }
1409
1410 SourceLocation getBeginLoc() const { return getSemiLoc(); }
1411 SourceLocation getEndLoc() const { return getSemiLoc(); }
1412
1413 static bool classof(const Stmt *T) {
1414 return T->getStmtClass() == NullStmtClass;
1415 }
1416
1417 child_range children() {
1418 return child_range(child_iterator(), child_iterator());
1419 }
1420
1421 const_child_range children() const {
1422 return const_child_range(const_child_iterator(), const_child_iterator());
1423 }
1424};
1425
1426/// CompoundStmt - This represents a group of statements like { stmt stmt }.
1427class CompoundStmt final
1428 : public Stmt,
1429 private llvm::TrailingObjects<CompoundStmt, Stmt *, FPOptionsOverride> {
1430 friend class ASTStmtReader;
1431 friend TrailingObjects;
1432
1433 /// The location of the opening "{".
1434 SourceLocation LBraceLoc;
1435
1436 /// The location of the closing "}".
1437 SourceLocation RBraceLoc;
1438
1439 CompoundStmt(ArrayRef<Stmt *> Stmts, FPOptionsOverride FPFeatures,
1440 SourceLocation LB, SourceLocation RB);
1441 explicit CompoundStmt(EmptyShell Empty) : Stmt(CompoundStmtClass, Empty) {}
1442
1443 void setStmts(ArrayRef<Stmt *> Stmts);
1444
1445 /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
1446 void setStoredFPFeatures(FPOptionsOverride F) {
1447 assert(hasStoredFPFeatures());
1448 *getTrailingObjects<FPOptionsOverride>() = F;
1449 }
1450
1451 size_t numTrailingObjects(OverloadToken<Stmt *>) const {
1452 return CompoundStmtBits.NumStmts;
1453 }
1454
1455public:
1456 static CompoundStmt *Create(const ASTContext &C, ArrayRef<Stmt *> Stmts,
1457 FPOptionsOverride FPFeatures, SourceLocation LB,
1458 SourceLocation RB);
1459
1460 // Build an empty compound statement with a location.
1461 explicit CompoundStmt(SourceLocation Loc)
1462 : Stmt(CompoundStmtClass), LBraceLoc(Loc), RBraceLoc(Loc) {
1463 CompoundStmtBits.NumStmts = 0;
1464 CompoundStmtBits.HasFPFeatures = 0;
1465 }
1466
1467 // Build an empty compound statement.
1468 static CompoundStmt *CreateEmpty(const ASTContext &C, unsigned NumStmts,
1469 bool HasFPFeatures);
1470
1471 bool body_empty() const { return CompoundStmtBits.NumStmts == 0; }
1472 unsigned size() const { return CompoundStmtBits.NumStmts; }
1473
1474 bool hasStoredFPFeatures() const { return CompoundStmtBits.HasFPFeatures; }
1475
1476 /// Get FPOptionsOverride from trailing storage.
1477 FPOptionsOverride getStoredFPFeatures() const {
1478 assert(hasStoredFPFeatures());
1479 return *getTrailingObjects<FPOptionsOverride>();
1480 }
1481
1482 using body_iterator = Stmt **;
1483 using body_range = llvm::iterator_range<body_iterator>;
1484
1485 body_range body() { return body_range(body_begin(), body_end()); }
1486 body_iterator body_begin() { return getTrailingObjects<Stmt *>(); }
1487 body_iterator body_end() { return body_begin() + size(); }
1488 Stmt *body_front() { return !body_empty() ? body_begin()[0] : nullptr; }
1489
1490 Stmt *body_back() {
1491 return !body_empty() ? body_begin()[size() - 1] : nullptr;
1492 }
1493
1494 using const_body_iterator = Stmt *const *;
1495 using body_const_range = llvm::iterator_range<const_body_iterator>;
1496
1497 body_const_range body() const {
1498 return body_const_range(body_begin(), body_end());
1499 }
1500
1501 const_body_iterator body_begin() const {
1502 return getTrailingObjects<Stmt *>();
1503 }
1504
1505 const_body_iterator body_end() const { return body_begin() + size(); }
1506
1507 const Stmt *body_front() const {
1508 return !body_empty() ? body_begin()[0] : nullptr;
1509 }
1510
1511 const Stmt *body_back() const {
1512 return !body_empty() ? body_begin()[size() - 1] : nullptr;
1513 }
1514
1515 using reverse_body_iterator = std::reverse_iterator<body_iterator>;
1516
1517 reverse_body_iterator body_rbegin() {
1518 return reverse_body_iterator(body_end());
1519 }
1520
1521 reverse_body_iterator body_rend() {
1522 return reverse_body_iterator(body_begin());
1523 }
1524
1525 using const_reverse_body_iterator =
1526 std::reverse_iterator<const_body_iterator>;
1527
1528 const_reverse_body_iterator body_rbegin() const {
1529 return const_reverse_body_iterator(body_end());
1530 }
1531
1532 const_reverse_body_iterator body_rend() const {
1533 return const_reverse_body_iterator(body_begin());
1534 }
1535
1536 // Get the Stmt that StmtExpr would consider to be the result of this
1537 // compound statement. This is used by StmtExpr to properly emulate the GCC
1538 // compound expression extension, which ignores trailing NullStmts when
1539 // getting the result of the expression.
1540 // i.e. ({ 5;;; })
1541 // ^^ ignored
1542 // If we don't find something that isn't a NullStmt, just return the last
1543 // Stmt.
1544 Stmt *getStmtExprResult() {
1545 for (auto *B : llvm::reverse(body())) {
1546 if (!isa<NullStmt>(B))
1547 return B;
1548 }
1549 return body_back();
1550 }
1551
1552 const Stmt *getStmtExprResult() const {
1553 return const_cast<CompoundStmt *>(this)->getStmtExprResult();
1554 }
1555
1556 SourceLocation getBeginLoc() const { return LBraceLoc; }
1557 SourceLocation getEndLoc() const { return RBraceLoc; }
1558
1559 SourceLocation getLBracLoc() const { return LBraceLoc; }
1560 SourceLocation getRBracLoc() const { return RBraceLoc; }
1561
1562 static bool classof(const Stmt *T) {
1563 return T->getStmtClass() == CompoundStmtClass;
1564 }
1565
1566 // Iterators
1567 child_range children() { return child_range(body_begin(), body_end()); }
1568
1569 const_child_range children() const {
1570 return const_child_range(body_begin(), body_end());
1571 }
1572};
1573
1574// SwitchCase is the base class for CaseStmt and DefaultStmt,
1575class SwitchCase : public Stmt {
1576protected:
1577 /// The location of the ":".
1578 SourceLocation ColonLoc;
1579
1580 // The location of the "case" or "default" keyword. Stored in SwitchCaseBits.
1581 // SourceLocation KeywordLoc;
1582
1583 /// A pointer to the following CaseStmt or DefaultStmt class,
1584 /// used by SwitchStmt.
1585 SwitchCase *NextSwitchCase = nullptr;
1586
1587 SwitchCase(StmtClass SC, SourceLocation KWLoc, SourceLocation ColonLoc)
1588 : Stmt(SC), ColonLoc(ColonLoc) {
1589 setKeywordLoc(KWLoc);
1590 }
1591
1592 SwitchCase(StmtClass SC, EmptyShell) : Stmt(SC) {}
1593
1594public:
1595 const SwitchCase *getNextSwitchCase() const { return NextSwitchCase; }
1596 SwitchCase *getNextSwitchCase() { return NextSwitchCase; }
1597 void setNextSwitchCase(SwitchCase *SC) { NextSwitchCase = SC; }
1598
1599 SourceLocation getKeywordLoc() const { return SwitchCaseBits.KeywordLoc; }
1600 void setKeywordLoc(SourceLocation L) { SwitchCaseBits.KeywordLoc = L; }
1601 SourceLocation getColonLoc() const { return ColonLoc; }
1602 void setColonLoc(SourceLocation L) { ColonLoc = L; }
1603
1604 inline Stmt *getSubStmt();
1605 const Stmt *getSubStmt() const {
1606 return const_cast<SwitchCase *>(this)->getSubStmt();
1607 }
1608
1609 SourceLocation getBeginLoc() const { return getKeywordLoc(); }
1610 inline SourceLocation getEndLoc() const LLVM_READONLY;
1611
1612 static bool classof(const Stmt *T) {
1613 return T->getStmtClass() == CaseStmtClass ||
1614 T->getStmtClass() == DefaultStmtClass;
1615 }
1616};
1617
1618/// CaseStmt - Represent a case statement. It can optionally be a GNU case
1619/// statement of the form LHS ... RHS representing a range of cases.
1620class CaseStmt final
1621 : public SwitchCase,
1622 private llvm::TrailingObjects<CaseStmt, Stmt *, SourceLocation> {
1623 friend TrailingObjects;
1624
1625 // CaseStmt is followed by several trailing objects, some of which optional.
1626 // Note that it would be more convenient to put the optional trailing objects
1627 // at the end but this would impact children().
1628 // The trailing objects are in order:
1629 //
1630 // * A "Stmt *" for the LHS of the case statement. Always present.
1631 //
1632 // * A "Stmt *" for the RHS of the case statement. This is a GNU extension
1633 // which allow ranges in cases statement of the form LHS ... RHS.
1634 // Present if and only if caseStmtIsGNURange() is true.
1635 //
1636 // * A "Stmt *" for the substatement of the case statement. Always present.
1637 //
1638 // * A SourceLocation for the location of the ... if this is a case statement
1639 // with a range. Present if and only if caseStmtIsGNURange() is true.
1640 enum { LhsOffset = 0, SubStmtOffsetFromRhs = 1 };
1641 enum { NumMandatoryStmtPtr = 2 };
1642
1643 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
1644 return NumMandatoryStmtPtr + caseStmtIsGNURange();
1645 }
1646
1647 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1648 return caseStmtIsGNURange();
1649 }
1650
1651 unsigned lhsOffset() const { return LhsOffset; }
1652 unsigned rhsOffset() const { return LhsOffset + caseStmtIsGNURange(); }
1653 unsigned subStmtOffset() const { return rhsOffset() + SubStmtOffsetFromRhs; }
1654
1655 /// Build a case statement assuming that the storage for the
1656 /// trailing objects has been properly allocated.
1657 CaseStmt(Expr *lhs, Expr *rhs, SourceLocation caseLoc,
1658 SourceLocation ellipsisLoc, SourceLocation colonLoc)
1659 : SwitchCase(CaseStmtClass, caseLoc, colonLoc) {
1660 // Handle GNU case statements of the form LHS ... RHS.
1661 bool IsGNURange = rhs != nullptr;
1662 SwitchCaseBits.CaseStmtIsGNURange = IsGNURange;
1663 setLHS(lhs);
1664 setSubStmt(nullptr);
1665 if (IsGNURange) {
1666 setRHS(rhs);
1667 setEllipsisLoc(ellipsisLoc);
1668 }
1669 }
1670
1671 /// Build an empty switch case statement.
1672 explicit CaseStmt(EmptyShell Empty, bool CaseStmtIsGNURange)
1673 : SwitchCase(CaseStmtClass, Empty) {
1674 SwitchCaseBits.CaseStmtIsGNURange = CaseStmtIsGNURange;
1675 }
1676
1677public:
1678 /// Build a case statement.
1679 static CaseStmt *Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
1680 SourceLocation caseLoc, SourceLocation ellipsisLoc,
1681 SourceLocation colonLoc);
1682
1683 /// Build an empty case statement.
1684 static CaseStmt *CreateEmpty(const ASTContext &Ctx, bool CaseStmtIsGNURange);
1685
1686 /// True if this case statement is of the form case LHS ... RHS, which
1687 /// is a GNU extension. In this case the RHS can be obtained with getRHS()
1688 /// and the location of the ellipsis can be obtained with getEllipsisLoc().
1689 bool caseStmtIsGNURange() const { return SwitchCaseBits.CaseStmtIsGNURange; }
1690
1691 SourceLocation getCaseLoc() const { return getKeywordLoc(); }
1692 void setCaseLoc(SourceLocation L) { setKeywordLoc(L); }
1693
1694 /// Get the location of the ... in a case statement of the form LHS ... RHS.
1695 SourceLocation getEllipsisLoc() const {
1696 return caseStmtIsGNURange() ? *getTrailingObjects<SourceLocation>()
1697 : SourceLocation();
1698 }
1699
1700 /// Set the location of the ... in a case statement of the form LHS ... RHS.
1701 /// Assert that this case statement is of this form.
1702 void setEllipsisLoc(SourceLocation L) {
1703 assert(
1704 caseStmtIsGNURange() &&
1705 "setEllipsisLoc but this is not a case stmt of the form LHS ... RHS!");
1706 *getTrailingObjects<SourceLocation>() = L;
1707 }
1708
1709 Expr *getLHS() {
1710 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[lhsOffset()]);
1711 }
1712
1713 const Expr *getLHS() const {
1714 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[lhsOffset()]);
1715 }
1716
1717 void setLHS(Expr *Val) {
1718 getTrailingObjects<Stmt *>()[lhsOffset()] = reinterpret_cast<Stmt *>(Val);
1719 }
1720
1721 Expr *getRHS() {
1722 return caseStmtIsGNURange() ? reinterpret_cast<Expr *>(
1723 getTrailingObjects<Stmt *>()[rhsOffset()])
1724 : nullptr;
1725 }
1726
1727 const Expr *getRHS() const {
1728 return caseStmtIsGNURange() ? reinterpret_cast<Expr *>(
1729 getTrailingObjects<Stmt *>()[rhsOffset()])
1730 : nullptr;
1731 }
1732
1733 void setRHS(Expr *Val) {
1734 assert(caseStmtIsGNURange() &&
1735 "setRHS but this is not a case stmt of the form LHS ... RHS!");
1736 getTrailingObjects<Stmt *>()[rhsOffset()] = reinterpret_cast<Stmt *>(Val);
1737 }
1738
1739 Stmt *getSubStmt() { return getTrailingObjects<Stmt *>()[subStmtOffset()]; }
1740 const Stmt *getSubStmt() const {
1741 return getTrailingObjects<Stmt *>()[subStmtOffset()];
1742 }
1743
1744 void setSubStmt(Stmt *S) {
1745 getTrailingObjects<Stmt *>()[subStmtOffset()] = S;
1746 }
1747
1748 SourceLocation getBeginLoc() const { return getKeywordLoc(); }
1749 SourceLocation getEndLoc() const LLVM_READONLY {
1750 // Handle deeply nested case statements with iteration instead of recursion.
1751 const CaseStmt *CS = this;
1752 while (const auto *CS2 = dyn_cast<CaseStmt>(CS->getSubStmt()))
1753 CS = CS2;
1754
1755 return CS->getSubStmt()->getEndLoc();
1756 }
1757
1758 static bool classof(const Stmt *T) {
1759 return T->getStmtClass() == CaseStmtClass;
1760 }
1761
1762 // Iterators
1763 child_range children() {
1764 return child_range(getTrailingObjects<Stmt *>(),
1765 getTrailingObjects<Stmt *>() +
1766 numTrailingObjects(OverloadToken<Stmt *>()));
1767 }
1768
1769 const_child_range children() const {
1770 return const_child_range(getTrailingObjects<Stmt *>(),
1771 getTrailingObjects<Stmt *>() +
1772 numTrailingObjects(OverloadToken<Stmt *>()));
1773 }
1774};
1775
1776class DefaultStmt : public SwitchCase {
1777 Stmt *SubStmt;
1778
1779public:
1780 DefaultStmt(SourceLocation DL, SourceLocation CL, Stmt *substmt)
1781 : SwitchCase(DefaultStmtClass, DL, CL), SubStmt(substmt) {}
1782
1783 /// Build an empty default statement.
1784 explicit DefaultStmt(EmptyShell Empty)
1785 : SwitchCase(DefaultStmtClass, Empty) {}
1786
1787 Stmt *getSubStmt() { return SubStmt; }
1788 const Stmt *getSubStmt() const { return SubStmt; }
1789 void setSubStmt(Stmt *S) { SubStmt = S; }
1790
1791 SourceLocation getDefaultLoc() const { return getKeywordLoc(); }
1792 void setDefaultLoc(SourceLocation L) { setKeywordLoc(L); }
1793
1794 SourceLocation getBeginLoc() const { return getKeywordLoc(); }
1795 SourceLocation getEndLoc() const LLVM_READONLY {
1796 return SubStmt->getEndLoc();
1797 }
1798
1799 static bool classof(const Stmt *T) {
1800 return T->getStmtClass() == DefaultStmtClass;
1801 }
1802
1803 // Iterators
1804 child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
1805
1806 const_child_range children() const {
1807 return const_child_range(&SubStmt, &SubStmt + 1);
1808 }
1809};
1810
1811SourceLocation SwitchCase::getEndLoc() const {
1812 if (const auto *CS = dyn_cast<CaseStmt>(this))
1813 return CS->getEndLoc();
1814 else if (const auto *DS = dyn_cast<DefaultStmt>(this))
1815 return DS->getEndLoc();
1816 llvm_unreachable("SwitchCase is neither a CaseStmt nor a DefaultStmt!");
1817}
1818
1819Stmt *SwitchCase::getSubStmt() {
1820 if (auto *CS = dyn_cast<CaseStmt>(this))
1821 return CS->getSubStmt();
1822 else if (auto *DS = dyn_cast<DefaultStmt>(this))
1823 return DS->getSubStmt();
1824 llvm_unreachable("SwitchCase is neither a CaseStmt nor a DefaultStmt!");
1825}
1826
1827/// Represents a statement that could possibly have a value and type. This
1828/// covers expression-statements, as well as labels and attributed statements.
1829///
1830/// Value statements have a special meaning when they are the last non-null
1831/// statement in a GNU statement expression, where they determine the value
1832/// of the statement expression.
1833class ValueStmt : public Stmt {
1834protected:
1835 using Stmt::Stmt;
1836
1837public:
1838 const Expr *getExprStmt() const;
1839 Expr *getExprStmt() {
1840 const ValueStmt *ConstThis = this;
1841 return const_cast<Expr*>(ConstThis->getExprStmt());
1842 }
1843
1844 static bool classof(const Stmt *T) {
1845 return T->getStmtClass() >= firstValueStmtConstant &&
1846 T->getStmtClass() <= lastValueStmtConstant;
1847 }
1848};
1849
1850/// LabelStmt - Represents a label, which has a substatement. For example:
1851/// foo: return;
1852class LabelStmt : public ValueStmt {
1853 LabelDecl *TheDecl;
1854 Stmt *SubStmt;
1855 bool SideEntry = false;
1856
1857public:
1858 /// Build a label statement.
1859 LabelStmt(SourceLocation IL, LabelDecl *D, Stmt *substmt)
1860 : ValueStmt(LabelStmtClass), TheDecl(D), SubStmt(substmt) {
1861 setIdentLoc(IL);
1862 }
1863
1864 /// Build an empty label statement.
1865 explicit LabelStmt(EmptyShell Empty) : ValueStmt(LabelStmtClass, Empty) {}
1866
1867 SourceLocation getIdentLoc() const { return LabelStmtBits.IdentLoc; }
1868 void setIdentLoc(SourceLocation L) { LabelStmtBits.IdentLoc = L; }
1869
1870 LabelDecl *getDecl() const { return TheDecl; }
1871 void setDecl(LabelDecl *D) { TheDecl = D; }
1872
1873 const char *getName() const;
1874 Stmt *getSubStmt() { return SubStmt; }
1875
1876 const Stmt *getSubStmt() const { return SubStmt; }
1877 void setSubStmt(Stmt *SS) { SubStmt = SS; }
1878
1879 SourceLocation getBeginLoc() const { return getIdentLoc(); }
1880 SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc();}
1881
1882 child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
1883
1884 const_child_range children() const {
1885 return const_child_range(&SubStmt, &SubStmt + 1);
1886 }
1887
1888 static bool classof(const Stmt *T) {
1889 return T->getStmtClass() == LabelStmtClass;
1890 }
1891 bool isSideEntry() const { return SideEntry; }
1892 void setSideEntry(bool SE) { SideEntry = SE; }
1893};
1894
1895/// Represents an attribute applied to a statement.
1896///
1897/// Represents an attribute applied to a statement. For example:
1898/// [[omp::for(...)]] for (...) { ... }
1899class AttributedStmt final
1900 : public ValueStmt,
1901 private llvm::TrailingObjects<AttributedStmt, const Attr *> {
1902 friend class ASTStmtReader;
1903 friend TrailingObjects;
1904
1905 Stmt *SubStmt;
1906
1907 AttributedStmt(SourceLocation Loc, ArrayRef<const Attr *> Attrs,
1908 Stmt *SubStmt)
1909 : ValueStmt(AttributedStmtClass), SubStmt(SubStmt) {
1910 AttributedStmtBits.NumAttrs = Attrs.size();
1911 AttributedStmtBits.AttrLoc = Loc;
1912 std::copy(Attrs.begin(), Attrs.end(), getAttrArrayPtr());
1913 }
1914
1915 explicit AttributedStmt(EmptyShell Empty, unsigned NumAttrs)
1916 : ValueStmt(AttributedStmtClass, Empty) {
1917 AttributedStmtBits.NumAttrs = NumAttrs;
1918 AttributedStmtBits.AttrLoc = SourceLocation{};
1919 std::fill_n(getAttrArrayPtr(), NumAttrs, nullptr);
1920 }
1921
1922 const Attr *const *getAttrArrayPtr() const {
1923 return getTrailingObjects<const Attr *>();
1924 }
1925 const Attr **getAttrArrayPtr() { return getTrailingObjects<const Attr *>(); }
1926
1927public:
1928 static AttributedStmt *Create(const ASTContext &C, SourceLocation Loc,
1929 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
1930
1931 // Build an empty attributed statement.
1932 static AttributedStmt *CreateEmpty(const ASTContext &C, unsigned NumAttrs);
1933
1934 SourceLocation getAttrLoc() const { return AttributedStmtBits.AttrLoc; }
1935 ArrayRef<const Attr *> getAttrs() const {
1936 return llvm::ArrayRef(getAttrArrayPtr(), AttributedStmtBits.NumAttrs);
1937 }
1938
1939 Stmt *getSubStmt() { return SubStmt; }
1940 const Stmt *getSubStmt() const { return SubStmt; }
1941
1942 SourceLocation getBeginLoc() const { return getAttrLoc(); }
1943 SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc();}
1944
1945 child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
1946
1947 const_child_range children() const {
1948 return const_child_range(&SubStmt, &SubStmt + 1);
1949 }
1950
1951 static bool classof(const Stmt *T) {
1952 return T->getStmtClass() == AttributedStmtClass;
1953 }
1954};
1955
1956/// IfStmt - This represents an if/then/else.
1957class IfStmt final
1958 : public Stmt,
1959 private llvm::TrailingObjects<IfStmt, Stmt *, SourceLocation> {
1960 friend TrailingObjects;
1961
1962 // IfStmt is followed by several trailing objects, some of which optional.
1963 // Note that it would be more convenient to put the optional trailing
1964 // objects at then end but this would change the order of the children.
1965 // The trailing objects are in order:
1966 //
1967 // * A "Stmt *" for the init statement.
1968 // Present if and only if hasInitStorage().
1969 //
1970 // * A "Stmt *" for the condition variable.
1971 // Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
1972 //
1973 // * A "Stmt *" for the condition.
1974 // Always present. This is in fact a "Expr *".
1975 //
1976 // * A "Stmt *" for the then statement.
1977 // Always present.
1978 //
1979 // * A "Stmt *" for the else statement.
1980 // Present if and only if hasElseStorage().
1981 //
1982 // * A "SourceLocation" for the location of the "else".
1983 // Present if and only if hasElseStorage().
1984 enum { InitOffset = 0, ThenOffsetFromCond = 1, ElseOffsetFromCond = 2 };
1985 enum { NumMandatoryStmtPtr = 2 };
1986 SourceLocation LParenLoc;
1987 SourceLocation RParenLoc;
1988
1989 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
1990 return NumMandatoryStmtPtr + hasElseStorage() + hasVarStorage() +
1991 hasInitStorage();
1992 }
1993
1994 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1995 return hasElseStorage();
1996 }
1997
1998 unsigned initOffset() const { return InitOffset; }
1999 unsigned varOffset() const { return InitOffset + hasInitStorage(); }
2000 unsigned condOffset() const {
2001 return InitOffset + hasInitStorage() + hasVarStorage();
2002 }
2003 unsigned thenOffset() const { return condOffset() + ThenOffsetFromCond; }
2004 unsigned elseOffset() const { return condOffset() + ElseOffsetFromCond; }
2005
2006 /// Build an if/then/else statement.
2007 IfStmt(const ASTContext &Ctx, SourceLocation IL, IfStatementKind Kind,
2008 Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LParenLoc,
2009 SourceLocation RParenLoc, Stmt *Then, SourceLocation EL, Stmt *Else);
2010
2011 /// Build an empty if/then/else statement.
2012 explicit IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit);
2013
2014public:
2015 /// Create an IfStmt.
2016 static IfStmt *Create(const ASTContext &Ctx, SourceLocation IL,
2017 IfStatementKind Kind, Stmt *Init, VarDecl *Var,
2018 Expr *Cond, SourceLocation LPL, SourceLocation RPL,
2019 Stmt *Then, SourceLocation EL = SourceLocation(),
2020 Stmt *Else = nullptr);
2021
2022 /// Create an empty IfStmt optionally with storage for an else statement,
2023 /// condition variable and init expression.
2024 static IfStmt *CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar,
2025 bool HasInit);
2026
2027 /// True if this IfStmt has the storage for an init statement.
2028 bool hasInitStorage() const { return IfStmtBits.HasInit; }
2029
2030 /// True if this IfStmt has storage for a variable declaration.
2031 bool hasVarStorage() const { return IfStmtBits.HasVar; }
2032
2033 /// True if this IfStmt has storage for an else statement.
2034 bool hasElseStorage() const { return IfStmtBits.HasElse; }
2035
2036 Expr *getCond() {
2037 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2038 }
2039
2040 const Expr *getCond() const {
2041 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2042 }
2043
2044 void setCond(Expr *Cond) {
2045 getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
2046 }
2047
2048 Stmt *getThen() { return getTrailingObjects<Stmt *>()[thenOffset()]; }
2049 const Stmt *getThen() const {
2050 return getTrailingObjects<Stmt *>()[thenOffset()];
2051 }
2052
2053 void setThen(Stmt *Then) {
2054 getTrailingObjects<Stmt *>()[thenOffset()] = Then;
2055 }
2056
2057 Stmt *getElse() {
2058 return hasElseStorage() ? getTrailingObjects<Stmt *>()[elseOffset()]
2059 : nullptr;
2060 }
2061
2062 const Stmt *getElse() const {
2063 return hasElseStorage() ? getTrailingObjects<Stmt *>()[elseOffset()]
2064 : nullptr;
2065 }
2066
2067 void setElse(Stmt *Else) {
2068 assert(hasElseStorage() &&
2069 "This if statement has no storage for an else statement!");
2070 getTrailingObjects<Stmt *>()[elseOffset()] = Else;
2071 }
2072
2073 /// Retrieve the variable declared in this "if" statement, if any.
2074 ///
2075 /// In the following example, "x" is the condition variable.
2076 /// \code
2077 /// if (int x = foo()) {
2078 /// printf("x is %d", x);
2079 /// }
2080 /// \endcode
2081 VarDecl *getConditionVariable();
2082 const VarDecl *getConditionVariable() const {
2083 return const_cast<IfStmt *>(this)->getConditionVariable();
2084 }
2085
2086 /// Set the condition variable for this if statement.
2087 /// The if statement must have storage for the condition variable.
2088 void setConditionVariable(const ASTContext &Ctx, VarDecl *V);
2089
2090 /// If this IfStmt has a condition variable, return the faux DeclStmt
2091 /// associated with the creation of that condition variable.
2092 DeclStmt *getConditionVariableDeclStmt() {
2093 return hasVarStorage() ? static_cast<DeclStmt *>(
2094 getTrailingObjects<Stmt *>()[varOffset()])
2095 : nullptr;
2096 }
2097
2098 const DeclStmt *getConditionVariableDeclStmt() const {
2099 return hasVarStorage() ? static_cast<DeclStmt *>(
2100 getTrailingObjects<Stmt *>()[varOffset()])
2101 : nullptr;
2102 }
2103
2104 void setConditionVariableDeclStmt(DeclStmt *CondVar) {
2105 assert(hasVarStorage());
2106 getTrailingObjects<Stmt *>()[varOffset()] = CondVar;
2107 }
2108
2109 Stmt *getInit() {
2110 return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
2111 : nullptr;
2112 }
2113
2114 const Stmt *getInit() const {
2115 return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
2116 : nullptr;
2117 }
2118
2119 void setInit(Stmt *Init) {
2120 assert(hasInitStorage() &&
2121 "This if statement has no storage for an init statement!");
2122 getTrailingObjects<Stmt *>()[initOffset()] = Init;
2123 }
2124
2125 SourceLocation getIfLoc() const { return IfStmtBits.IfLoc; }
2126 void setIfLoc(SourceLocation IfLoc) { IfStmtBits.IfLoc = IfLoc; }
2127
2128 SourceLocation getElseLoc() const {
2129 return hasElseStorage() ? *getTrailingObjects<SourceLocation>()
2130 : SourceLocation();
2131 }
2132
2133 void setElseLoc(SourceLocation ElseLoc) {
2134 assert(hasElseStorage() &&
2135 "This if statement has no storage for an else statement!");
2136 *getTrailingObjects<SourceLocation>() = ElseLoc;
2137 }
2138
2139 bool isConsteval() const {
2140 return getStatementKind() == IfStatementKind::ConstevalNonNegated ||
2141 getStatementKind() == IfStatementKind::ConstevalNegated;
2142 }
2143
2144 bool isNonNegatedConsteval() const {
2145 return getStatementKind() == IfStatementKind::ConstevalNonNegated;
2146 }
2147
2148 bool isNegatedConsteval() const {
2149 return getStatementKind() == IfStatementKind::ConstevalNegated;
2150 }
2151
2152 bool isConstexpr() const {
2153 return getStatementKind() == IfStatementKind::Constexpr;
2154 }
2155
2156 void setStatementKind(IfStatementKind Kind) {
2157 IfStmtBits.Kind = static_cast<unsigned>(Kind);
2158 }
2159
2160 IfStatementKind getStatementKind() const {
2161 return static_cast<IfStatementKind>(IfStmtBits.Kind);
2162 }
2163
2164 /// If this is an 'if constexpr', determine which substatement will be taken.
2165 /// Otherwise, or if the condition is value-dependent, returns std::nullopt.
2166 std::optional<const Stmt *> getNondiscardedCase(const ASTContext &Ctx) const;
2167 std::optional<Stmt *> getNondiscardedCase(const ASTContext &Ctx);
2168
2169 bool isObjCAvailabilityCheck() const;
2170
2171 SourceLocation getBeginLoc() const { return getIfLoc(); }
2172 SourceLocation getEndLoc() const LLVM_READONLY {
2173 if (getElse())
2174 return getElse()->getEndLoc();
2175 return getThen()->getEndLoc();
2176 }
2177 SourceLocation getLParenLoc() const { return LParenLoc; }
2178 void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
2179 SourceLocation getRParenLoc() const { return RParenLoc; }
2180 void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
2181
2182 // Iterators over subexpressions. The iterators will include iterating
2183 // over the initialization expression referenced by the condition variable.
2184 child_range children() {
2185 // We always store a condition, but there is none for consteval if
2186 // statements, so skip it.
2187 return child_range(getTrailingObjects<Stmt *>() +
2188 (isConsteval() ? thenOffset() : 0),
2189 getTrailingObjects<Stmt *>() +
2190 numTrailingObjects(OverloadToken<Stmt *>()));
2191 }
2192
2193 const_child_range children() const {
2194 // We always store a condition, but there is none for consteval if
2195 // statements, so skip it.
2196 return const_child_range(getTrailingObjects<Stmt *>() +
2197 (isConsteval() ? thenOffset() : 0),
2198 getTrailingObjects<Stmt *>() +
2199 numTrailingObjects(OverloadToken<Stmt *>()));
2200 }
2201
2202 static bool classof(const Stmt *T) {
2203 return T->getStmtClass() == IfStmtClass;
2204 }
2205};
2206
2207/// SwitchStmt - This represents a 'switch' stmt.
2208class SwitchStmt final : public Stmt,
2209 private llvm::TrailingObjects<SwitchStmt, Stmt *> {
2210 friend TrailingObjects;
2211
2212 /// Points to a linked list of case and default statements.
2213 SwitchCase *FirstCase = nullptr;
2214
2215 // SwitchStmt is followed by several trailing objects,
2216 // some of which optional. Note that it would be more convenient to
2217 // put the optional trailing objects at the end but this would change
2218 // the order in children().
2219 // The trailing objects are in order:
2220 //
2221 // * A "Stmt *" for the init statement.
2222 // Present if and only if hasInitStorage().
2223 //
2224 // * A "Stmt *" for the condition variable.
2225 // Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
2226 //
2227 // * A "Stmt *" for the condition.
2228 // Always present. This is in fact an "Expr *".
2229 //
2230 // * A "Stmt *" for the body.
2231 // Always present.
2232 enum { InitOffset = 0, BodyOffsetFromCond = 1 };
2233 enum { NumMandatoryStmtPtr = 2 };
2234 SourceLocation LParenLoc;
2235 SourceLocation RParenLoc;
2236
2237 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
2238 return NumMandatoryStmtPtr + hasInitStorage() + hasVarStorage();
2239 }
2240
2241 unsigned initOffset() const { return InitOffset; }
2242 unsigned varOffset() const { return InitOffset + hasInitStorage(); }
2243 unsigned condOffset() const {
2244 return InitOffset + hasInitStorage() + hasVarStorage();
2245 }
2246 unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
2247
2248 /// Build a switch statement.
2249 SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond,
2250 SourceLocation LParenLoc, SourceLocation RParenLoc);
2251
2252 /// Build a empty switch statement.
2253 explicit SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar);
2254
2255public:
2256 /// Create a switch statement.
2257 static SwitchStmt *Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
2258 Expr *Cond, SourceLocation LParenLoc,
2259 SourceLocation RParenLoc);
2260
2261 /// Create an empty switch statement optionally with storage for
2262 /// an init expression and a condition variable.
2263 static SwitchStmt *CreateEmpty(const ASTContext &Ctx, bool HasInit,
2264 bool HasVar);
2265
2266 /// True if this SwitchStmt has storage for an init statement.
2267 bool hasInitStorage() const { return SwitchStmtBits.HasInit; }
2268
2269 /// True if this SwitchStmt has storage for a condition variable.
2270 bool hasVarStorage() const { return SwitchStmtBits.HasVar; }
2271
2272 Expr *getCond() {
2273 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2274 }
2275
2276 const Expr *getCond() const {
2277 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2278 }
2279
2280 void setCond(Expr *Cond) {
2281 getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
2282 }
2283
2284 Stmt *getBody() { return getTrailingObjects<Stmt *>()[bodyOffset()]; }
2285 const Stmt *getBody() const {
2286 return getTrailingObjects<Stmt *>()[bodyOffset()];
2287 }
2288
2289 void setBody(Stmt *Body) {
2290 getTrailingObjects<Stmt *>()[bodyOffset()] = Body;
2291 }
2292
2293 Stmt *getInit() {
2294 return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
2295 : nullptr;
2296 }
2297
2298 const Stmt *getInit() const {
2299 return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
2300 : nullptr;
2301 }
2302
2303 void setInit(Stmt *Init) {
2304 assert(hasInitStorage() &&
2305 "This switch statement has no storage for an init statement!");
2306 getTrailingObjects<Stmt *>()[initOffset()] = Init;
2307 }
2308
2309 /// Retrieve the variable declared in this "switch" statement, if any.
2310 ///
2311 /// In the following example, "x" is the condition variable.
2312 /// \code
2313 /// switch (int x = foo()) {
2314 /// case 0: break;
2315 /// // ...
2316 /// }
2317 /// \endcode
2318 VarDecl *getConditionVariable();
2319 const VarDecl *getConditionVariable() const {
2320 return const_cast<SwitchStmt *>(this)->getConditionVariable();
2321 }
2322
2323 /// Set the condition variable in this switch statement.
2324 /// The switch statement must have storage for it.
2325 void setConditionVariable(const ASTContext &Ctx, VarDecl *VD);
2326
2327 /// If this SwitchStmt has a condition variable, return the faux DeclStmt
2328 /// associated with the creation of that condition variable.
2329 DeclStmt *getConditionVariableDeclStmt() {
2330 return hasVarStorage() ? static_cast<DeclStmt *>(
2331 getTrailingObjects<Stmt *>()[varOffset()])
2332 : nullptr;
2333 }
2334
2335 const DeclStmt *getConditionVariableDeclStmt() const {
2336 return hasVarStorage() ? static_cast<DeclStmt *>(
2337 getTrailingObjects<Stmt *>()[varOffset()])
2338 : nullptr;
2339 }
2340
2341 void setConditionVariableDeclStmt(DeclStmt *CondVar) {
2342 assert(hasVarStorage());
2343 getTrailingObjects<Stmt *>()[varOffset()] = CondVar;
2344 }
2345
2346 SwitchCase *getSwitchCaseList() { return FirstCase; }
2347 const SwitchCase *getSwitchCaseList() const { return FirstCase; }
2348 void setSwitchCaseList(SwitchCase *SC) { FirstCase = SC; }
2349
2350 SourceLocation getSwitchLoc() const { return SwitchStmtBits.SwitchLoc; }
2351 void setSwitchLoc(SourceLocation L) { SwitchStmtBits.SwitchLoc = L; }
2352 SourceLocation getLParenLoc() const { return LParenLoc; }
2353 void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
2354 SourceLocation getRParenLoc() const { return RParenLoc; }
2355 void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
2356
2357 void setBody(Stmt *S, SourceLocation SL) {
2358 setBody(S);
2359 setSwitchLoc(SL);
2360 }
2361
2362 void addSwitchCase(SwitchCase *SC) {
2363 assert(!SC->getNextSwitchCase() &&
2364 "case/default already added to a switch");
2365 SC->setNextSwitchCase(FirstCase);
2366 FirstCase = SC;
2367 }
2368
2369 /// Set a flag in the SwitchStmt indicating that if the 'switch (X)' is a
2370 /// switch over an enum value then all cases have been explicitly covered.
2371 void setAllEnumCasesCovered() { SwitchStmtBits.AllEnumCasesCovered = true; }
2372
2373 /// Returns true if the SwitchStmt is a switch of an enum value and all cases
2374 /// have been explicitly covered.
2375 bool isAllEnumCasesCovered() const {
2376 return SwitchStmtBits.AllEnumCasesCovered;
2377 }
2378
2379 SourceLocation getBeginLoc() const { return getSwitchLoc(); }
2380 SourceLocation getEndLoc() const LLVM_READONLY {
2381 return getBody() ? getBody()->getEndLoc()
2382 : reinterpret_cast<const Stmt *>(getCond())->getEndLoc();
2383 }
2384
2385 // Iterators
2386 child_range children() {
2387 return child_range(getTrailingObjects<Stmt *>(),
2388 getTrailingObjects<Stmt *>() +
2389 numTrailingObjects(OverloadToken<Stmt *>()));
2390 }
2391
2392 const_child_range children() const {
2393 return const_child_range(getTrailingObjects<Stmt *>(),
2394 getTrailingObjects<Stmt *>() +
2395 numTrailingObjects(OverloadToken<Stmt *>()));
2396 }
2397
2398 static bool classof(const Stmt *T) {
2399 return T->getStmtClass() == SwitchStmtClass;
2400 }
2401};
2402
2403/// WhileStmt - This represents a 'while' stmt.
2404class WhileStmt final : public Stmt,
2405 private llvm::TrailingObjects<WhileStmt, Stmt *> {
2406 friend TrailingObjects;
2407
2408 // WhileStmt is followed by several trailing objects,
2409 // some of which optional. Note that it would be more
2410 // convenient to put the optional trailing object at the end
2411 // but this would affect children().
2412 // The trailing objects are in order:
2413 //
2414 // * A "Stmt *" for the condition variable.
2415 // Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
2416 //
2417 // * A "Stmt *" for the condition.
2418 // Always present. This is in fact an "Expr *".
2419 //
2420 // * A "Stmt *" for the body.
2421 // Always present.
2422 //
2423 enum { VarOffset = 0, BodyOffsetFromCond = 1 };
2424 enum { NumMandatoryStmtPtr = 2 };
2425
2426 SourceLocation LParenLoc, RParenLoc;
2427
2428 unsigned varOffset() const { return VarOffset; }
2429 unsigned condOffset() const { return VarOffset + hasVarStorage(); }
2430 unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
2431
2432 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
2433 return NumMandatoryStmtPtr + hasVarStorage();
2434 }
2435
2436 /// Build a while statement.
2437 WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, Stmt *Body,
2438 SourceLocation WL, SourceLocation LParenLoc,
2439 SourceLocation RParenLoc);
2440
2441 /// Build an empty while statement.
2442 explicit WhileStmt(EmptyShell Empty, bool HasVar);
2443
2444public:
2445 /// Create a while statement.
2446 static WhileStmt *Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
2447 Stmt *Body, SourceLocation WL,
2448 SourceLocation LParenLoc, SourceLocation RParenLoc);
2449
2450 /// Create an empty while statement optionally with storage for
2451 /// a condition variable.
2452 static WhileStmt *CreateEmpty(const ASTContext &Ctx, bool HasVar);
2453
2454 /// True if this WhileStmt has storage for a condition variable.
2455 bool hasVarStorage() const { return WhileStmtBits.HasVar; }
2456
2457 Expr *getCond() {
2458 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2459 }
2460
2461 const Expr *getCond() const {
2462 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2463 }
2464
2465 void setCond(Expr *Cond) {
2466 getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
2467 }
2468
2469 Stmt *getBody() { return getTrailingObjects<Stmt *>()[bodyOffset()]; }
2470 const Stmt *getBody() const {
2471 return getTrailingObjects<Stmt *>()[bodyOffset()];
2472 }
2473
2474 void setBody(Stmt *Body) {
2475 getTrailingObjects<Stmt *>()[bodyOffset()] = Body;
2476 }
2477
2478 /// Retrieve the variable declared in this "while" statement, if any.
2479 ///
2480 /// In the following example, "x" is the condition variable.
2481 /// \code
2482 /// while (int x = random()) {
2483 /// // ...
2484 /// }
2485 /// \endcode
2486 VarDecl *getConditionVariable();
2487 const VarDecl *getConditionVariable() const {
2488 return const_cast<WhileStmt *>(this)->getConditionVariable();
2489 }
2490
2491 /// Set the condition variable of this while statement.
2492 /// The while statement must have storage for it.
2493 void setConditionVariable(const ASTContext &Ctx, VarDecl *V);
2494
2495 /// If this WhileStmt has a condition variable, return the faux DeclStmt
2496 /// associated with the creation of that condition variable.
2497 DeclStmt *getConditionVariableDeclStmt() {
2498 return hasVarStorage() ? static_cast<DeclStmt *>(
2499 getTrailingObjects<Stmt *>()[varOffset()])
2500 : nullptr;
2501 }
2502
2503 const DeclStmt *getConditionVariableDeclStmt() const {
2504 return hasVarStorage() ? static_cast<DeclStmt *>(
2505 getTrailingObjects<Stmt *>()[varOffset()])
2506 : nullptr;
2507 }
2508
2509 void setConditionVariableDeclStmt(DeclStmt *CondVar) {
2510 assert(hasVarStorage());
2511 getTrailingObjects<Stmt *>()[varOffset()] = CondVar;
2512 }
2513
2514 SourceLocation getWhileLoc() const { return WhileStmtBits.WhileLoc; }
2515 void setWhileLoc(SourceLocation L) { WhileStmtBits.WhileLoc = L; }
2516
2517 SourceLocation getLParenLoc() const { return LParenLoc; }
2518 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2519 SourceLocation getRParenLoc() const { return RParenLoc; }
2520 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2521
2522 SourceLocation getBeginLoc() const { return getWhileLoc(); }
2523 SourceLocation getEndLoc() const LLVM_READONLY {
2524 return getBody()->getEndLoc();
2525 }
2526
2527 static bool classof(const Stmt *T) {
2528 return T->getStmtClass() == WhileStmtClass;
2529 }
2530
2531 // Iterators
2532 child_range children() {
2533 return child_range(getTrailingObjects<Stmt *>(),
2534 getTrailingObjects<Stmt *>() +
2535 numTrailingObjects(OverloadToken<Stmt *>()));
2536 }
2537
2538 const_child_range children() const {
2539 return const_child_range(getTrailingObjects<Stmt *>(),
2540 getTrailingObjects<Stmt *>() +
2541 numTrailingObjects(OverloadToken<Stmt *>()));
2542 }
2543};
2544
2545/// DoStmt - This represents a 'do/while' stmt.
2546class DoStmt : public Stmt {
2547 enum { BODY, COND, END_EXPR };
2548 Stmt *SubExprs[END_EXPR];
2549 SourceLocation WhileLoc;
2550 SourceLocation RParenLoc; // Location of final ')' in do stmt condition.
2551
2552public:
2553 DoStmt(Stmt *Body, Expr *Cond, SourceLocation DL, SourceLocation WL,
2554 SourceLocation RP)
2555 : Stmt(DoStmtClass), WhileLoc(WL), RParenLoc(RP) {
2556 setCond(Cond);
2557 setBody(Body);
2558 setDoLoc(DL);
2559 }
2560
2561 /// Build an empty do-while statement.
2562 explicit DoStmt(EmptyShell Empty) : Stmt(DoStmtClass, Empty) {}
2563
2564 Expr *getCond() { return reinterpret_cast<Expr *>(SubExprs[COND]); }
2565 const Expr *getCond() const {
2566 return reinterpret_cast<Expr *>(SubExprs[COND]);
2567 }
2568
2569 void setCond(Expr *Cond) { SubExprs[COND] = reinterpret_cast<Stmt *>(Cond); }
2570
2571 Stmt *getBody() { return SubExprs[BODY]; }
2572 const Stmt *getBody() const { return SubExprs[BODY]; }
2573 void setBody(Stmt *Body) { SubExprs[BODY] = Body; }
2574
2575 SourceLocation getDoLoc() const { return DoStmtBits.DoLoc; }
2576 void setDoLoc(SourceLocation L) { DoStmtBits.DoLoc = L; }
2577 SourceLocation getWhileLoc() const { return WhileLoc; }
2578 void setWhileLoc(SourceLocation L) { WhileLoc = L; }
2579 SourceLocation getRParenLoc() const { return RParenLoc; }
2580 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2581
2582 SourceLocation getBeginLoc() const { return getDoLoc(); }
2583 SourceLocation getEndLoc() const { return getRParenLoc(); }
2584
2585 static bool classof(const Stmt *T) {
2586 return T->getStmtClass() == DoStmtClass;
2587 }
2588
2589 // Iterators
2590 child_range children() {
2591 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2592 }
2593
2594 const_child_range children() const {
2595 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2596 }
2597};
2598
2599/// ForStmt - This represents a 'for (init;cond;inc)' stmt. Note that any of
2600/// the init/cond/inc parts of the ForStmt will be null if they were not
2601/// specified in the source.
2602class ForStmt : public Stmt {
2603 friend class ASTStmtReader;
2604
2605 enum { INIT, CONDVAR, COND, INC, BODY, END_EXPR };
2606 Stmt* SubExprs[END_EXPR]; // SubExprs[INIT] is an expression or declstmt.
2607 SourceLocation LParenLoc, RParenLoc;
2608
2609public:
2610 ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
2611 Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
2612 SourceLocation RP);
2613
2614 /// Build an empty for statement.
2615 explicit ForStmt(EmptyShell Empty) : Stmt(ForStmtClass, Empty) {}
2616
2617 Stmt *getInit() { return SubExprs[INIT]; }
2618
2619 /// Retrieve the variable declared in this "for" statement, if any.
2620 ///
2621 /// In the following example, "y" is the condition variable.
2622 /// \code
2623 /// for (int x = random(); int y = mangle(x); ++x) {
2624 /// // ...
2625 /// }
2626 /// \endcode
2627 VarDecl *getConditionVariable() const;
2628 void setConditionVariable(const ASTContext &C, VarDecl *V);
2629
2630 /// If this ForStmt has a condition variable, return the faux DeclStmt
2631 /// associated with the creation of that condition variable.
2632 DeclStmt *getConditionVariableDeclStmt() {
2633 return reinterpret_cast<DeclStmt*>(SubExprs[CONDVAR]);
2634 }
2635
2636 const DeclStmt *getConditionVariableDeclStmt() const {
2637 return reinterpret_cast<DeclStmt*>(SubExprs[CONDVAR]);
2638 }
2639
2640 void setConditionVariableDeclStmt(DeclStmt *CondVar) {
2641 SubExprs[CONDVAR] = CondVar;
2642 }
2643
2644 Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); }
2645 Expr *getInc() { return reinterpret_cast<Expr*>(SubExprs[INC]); }
2646 Stmt *getBody() { return SubExprs[BODY]; }
2647
2648 const Stmt *getInit() const { return SubExprs[INIT]; }
2649 const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);}
2650 const Expr *getInc() const { return reinterpret_cast<Expr*>(SubExprs[INC]); }
2651 const Stmt *getBody() const { return SubExprs[BODY]; }
2652
2653 void setInit(Stmt *S) { SubExprs[INIT] = S; }
2654 void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); }
2655 void setInc(Expr *E) { SubExprs[INC] = reinterpret_cast<Stmt*>(E); }
2656 void setBody(Stmt *S) { SubExprs[BODY] = S; }
2657
2658 SourceLocation getForLoc() const { return ForStmtBits.ForLoc; }
2659 void setForLoc(SourceLocation L) { ForStmtBits.ForLoc = L; }
2660 SourceLocation getLParenLoc() const { return LParenLoc; }
2661 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2662 SourceLocation getRParenLoc() const { return RParenLoc; }
2663 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2664
2665 SourceLocation getBeginLoc() const { return getForLoc(); }
2666 SourceLocation getEndLoc() const { return getBody()->getEndLoc(); }
2667
2668 static bool classof(const Stmt *T) {
2669 return T->getStmtClass() == ForStmtClass;
2670 }
2671
2672 // Iterators
2673 child_range children() {
2674 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2675 }
2676
2677 const_child_range children() const {
2678 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2679 }
2680};
2681
2682/// GotoStmt - This represents a direct goto.
2683class GotoStmt : public Stmt {
2684 LabelDecl *Label;
2685 SourceLocation LabelLoc;
2686
2687public:
2688 GotoStmt(LabelDecl *label, SourceLocation GL, SourceLocation LL)
2689 : Stmt(GotoStmtClass), Label(label), LabelLoc(LL) {
2690 setGotoLoc(GL);
2691 }
2692
2693 /// Build an empty goto statement.
2694 explicit GotoStmt(EmptyShell Empty) : Stmt(GotoStmtClass, Empty) {}
2695
2696 LabelDecl *getLabel() const { return Label; }
2697 void setLabel(LabelDecl *D) { Label = D; }
2698
2699 SourceLocation getGotoLoc() const { return GotoStmtBits.GotoLoc; }
2700 void setGotoLoc(SourceLocation L) { GotoStmtBits.GotoLoc = L; }
2701 SourceLocation getLabelLoc() const { return LabelLoc; }
2702 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2703
2704 SourceLocation getBeginLoc() const { return getGotoLoc(); }
2705 SourceLocation getEndLoc() const { return getLabelLoc(); }
2706
2707 static bool classof(const Stmt *T) {
2708 return T->getStmtClass() == GotoStmtClass;
2709 }
2710
2711 // Iterators
2712 child_range children() {
2713 return child_range(child_iterator(), child_iterator());
2714 }
2715
2716 const_child_range children() const {
2717 return const_child_range(const_child_iterator(), const_child_iterator());
2718 }
2719};
2720
2721/// IndirectGotoStmt - This represents an indirect goto.
2722class IndirectGotoStmt : public Stmt {
2723 SourceLocation StarLoc;
2724 Stmt *Target;
2725
2726public:
2727 IndirectGotoStmt(SourceLocation gotoLoc, SourceLocation starLoc, Expr *target)
2728 : Stmt(IndirectGotoStmtClass), StarLoc(starLoc) {
2729 setTarget(target);
2730 setGotoLoc(gotoLoc);
2731 }
2732
2733 /// Build an empty indirect goto statement.
2734 explicit IndirectGotoStmt(EmptyShell Empty)
2735 : Stmt(IndirectGotoStmtClass, Empty) {}
2736
2737 void setGotoLoc(SourceLocation L) { GotoStmtBits.GotoLoc = L; }
2738 SourceLocation getGotoLoc() const { return GotoStmtBits.GotoLoc; }
2739 void setStarLoc(SourceLocation L) { StarLoc = L; }
2740 SourceLocation getStarLoc() const { return StarLoc; }
2741
2742 Expr *getTarget() { return reinterpret_cast<Expr *>(Target); }
2743 const Expr *getTarget() const {
2744 return reinterpret_cast<const Expr *>(Target);
2745 }
2746 void setTarget(Expr *E) { Target = reinterpret_cast<Stmt *>(E); }
2747
2748 /// getConstantTarget - Returns the fixed target of this indirect
2749 /// goto, if one exists.
2750 LabelDecl *getConstantTarget();
2751 const LabelDecl *getConstantTarget() const {
2752 return const_cast<IndirectGotoStmt *>(this)->getConstantTarget();
2753 }
2754
2755 SourceLocation getBeginLoc() const { return getGotoLoc(); }
2756 SourceLocation getEndLoc() const LLVM_READONLY { return Target->getEndLoc(); }
2757
2758 static bool classof(const Stmt *T) {
2759 return T->getStmtClass() == IndirectGotoStmtClass;
2760 }
2761
2762 // Iterators
2763 child_range children() { return child_range(&Target, &Target + 1); }
2764
2765 const_child_range children() const {
2766 return const_child_range(&Target, &Target + 1);
2767 }
2768};
2769
2770/// ContinueStmt - This represents a continue.
2771class ContinueStmt : public Stmt {
2772public:
2773 ContinueStmt(SourceLocation CL) : Stmt(ContinueStmtClass) {
2774 setContinueLoc(CL);
2775 }
2776
2777 /// Build an empty continue statement.
2778 explicit ContinueStmt(EmptyShell Empty) : Stmt(ContinueStmtClass, Empty) {}
2779
2780 SourceLocation getContinueLoc() const { return ContinueStmtBits.ContinueLoc; }
2781 void setContinueLoc(SourceLocation L) { ContinueStmtBits.ContinueLoc = L; }
2782
2783 SourceLocation getBeginLoc() const { return getContinueLoc(); }
2784 SourceLocation getEndLoc() const { return getContinueLoc(); }
2785
2786 static bool classof(const Stmt *T) {
2787 return T->getStmtClass() == ContinueStmtClass;
2788 }
2789
2790 // Iterators
2791 child_range children() {
2792 return child_range(child_iterator(), child_iterator());
2793 }
2794
2795 const_child_range children() const {
2796 return const_child_range(const_child_iterator(), const_child_iterator());
2797 }
2798};
2799
2800/// BreakStmt - This represents a break.
2801class BreakStmt : public Stmt {
2802public:
2803 BreakStmt(SourceLocation BL) : Stmt(BreakStmtClass) {
2804 setBreakLoc(BL);
2805 }
2806
2807 /// Build an empty break statement.
2808 explicit BreakStmt(EmptyShell Empty) : Stmt(BreakStmtClass, Empty) {}
2809
2810 SourceLocation getBreakLoc() const { return BreakStmtBits.BreakLoc; }
2811 void setBreakLoc(SourceLocation L) { BreakStmtBits.BreakLoc = L; }
2812
2813 SourceLocation getBeginLoc() const { return getBreakLoc(); }
2814 SourceLocation getEndLoc() const { return getBreakLoc(); }
2815
2816 static bool classof(const Stmt *T) {
2817 return T->getStmtClass() == BreakStmtClass;
2818 }
2819
2820 // Iterators
2821 child_range children() {
2822 return child_range(child_iterator(), child_iterator());
2823 }
2824
2825 const_child_range children() const {
2826 return const_child_range(const_child_iterator(), const_child_iterator());
2827 }
2828};
2829
2830/// ReturnStmt - This represents a return, optionally of an expression:
2831/// return;
2832/// return 4;
2833///
2834/// Note that GCC allows return with no argument in a function declared to
2835/// return a value, and it allows returning a value in functions declared to
2836/// return void. We explicitly model this in the AST, which means you can't
2837/// depend on the return type of the function and the presence of an argument.
2838class ReturnStmt final
2839 : public Stmt,
2840 private llvm::TrailingObjects<ReturnStmt, const VarDecl *> {
2841 friend TrailingObjects;
2842
2843 /// The return expression.
2844 Stmt *RetExpr;
2845
2846 // ReturnStmt is followed optionally by a trailing "const VarDecl *"
2847 // for the NRVO candidate. Present if and only if hasNRVOCandidate().
2848
2849 /// True if this ReturnStmt has storage for an NRVO candidate.
2850 bool hasNRVOCandidate() const { return ReturnStmtBits.HasNRVOCandidate; }
2851
2852 unsigned numTrailingObjects(OverloadToken<const VarDecl *>) const {
2853 return hasNRVOCandidate();
2854 }
2855
2856 /// Build a return statement.
2857 ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate);
2858
2859 /// Build an empty return statement.
2860 explicit ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate);
2861
2862public:
2863 /// Create a return statement.
2864 static ReturnStmt *Create(const ASTContext &Ctx, SourceLocation RL, Expr *E,
2865 const VarDecl *NRVOCandidate);
2866
2867 /// Create an empty return statement, optionally with
2868 /// storage for an NRVO candidate.
2869 static ReturnStmt *CreateEmpty(const ASTContext &Ctx, bool HasNRVOCandidate);
2870
2871 Expr *getRetValue() { return reinterpret_cast<Expr *>(RetExpr); }
2872 const Expr *getRetValue() const { return reinterpret_cast<Expr *>(RetExpr); }
2873 void setRetValue(Expr *E) { RetExpr = reinterpret_cast<Stmt *>(E); }
2874
2875 /// Retrieve the variable that might be used for the named return
2876 /// value optimization.
2877 ///
2878 /// The optimization itself can only be performed if the variable is
2879 /// also marked as an NRVO object.
2880 const VarDecl *getNRVOCandidate() const {
2881 return hasNRVOCandidate() ? *getTrailingObjects<const VarDecl *>()
2882 : nullptr;
2883 }
2884
2885 /// Set the variable that might be used for the named return value
2886 /// optimization. The return statement must have storage for it,
2887 /// which is the case if and only if hasNRVOCandidate() is true.
2888 void setNRVOCandidate(const VarDecl *Var) {
2889 assert(hasNRVOCandidate() &&
2890 "This return statement has no storage for an NRVO candidate!");
2891 *getTrailingObjects<const VarDecl *>() = Var;
2892 }
2893
2894 SourceLocation getReturnLoc() const { return ReturnStmtBits.RetLoc; }
2895 void setReturnLoc(SourceLocation L) { ReturnStmtBits.RetLoc = L; }
2896
2897 SourceLocation getBeginLoc() const { return getReturnLoc(); }
2898 SourceLocation getEndLoc() const LLVM_READONLY {
2899 return RetExpr ? RetExpr->getEndLoc() : getReturnLoc();
2900 }
2901
2902 static bool classof(const Stmt *T) {
2903 return T->getStmtClass() == ReturnStmtClass;
2904 }
2905
2906 // Iterators
2907 child_range children() {
2908 if (RetExpr)
2909 return child_range(&RetExpr, &RetExpr + 1);
2910 return child_range(child_iterator(), child_iterator());
2911 }
2912
2913 const_child_range children() const {
2914 if (RetExpr)
2915 return const_child_range(&RetExpr, &RetExpr + 1);
2916 return const_child_range(const_child_iterator(), const_child_iterator());
2917 }
2918};
2919
2920/// AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
2921class AsmStmt : public Stmt {
2922protected:
2923 friend class ASTStmtReader;
2924
2925 SourceLocation AsmLoc;
2926
2927 /// True if the assembly statement does not have any input or output
2928 /// operands.
2929 bool IsSimple;
2930
2931 /// If true, treat this inline assembly as having side effects.
2932 /// This assembly statement should not be optimized, deleted or moved.
2933 bool IsVolatile;
2934
2935 unsigned NumOutputs;
2936 unsigned NumInputs;
2937 unsigned NumClobbers;
2938
2939 Stmt **Exprs = nullptr;
2940
2941 AsmStmt(StmtClass SC, SourceLocation asmloc, bool issimple, bool isvolatile,
2942 unsigned numoutputs, unsigned numinputs, unsigned numclobbers)
2943 : Stmt (SC), AsmLoc(asmloc), IsSimple(issimple), IsVolatile(isvolatile),
2944 NumOutputs(numoutputs), NumInputs(numinputs),
2945 NumClobbers(numclobbers) {}
2946
2947public:
2948 /// Build an empty inline-assembly statement.
2949 explicit AsmStmt(StmtClass SC, EmptyShell Empty) : Stmt(SC, Empty) {}
2950
2951 SourceLocation getAsmLoc() const { return AsmLoc; }
2952 void setAsmLoc(SourceLocation L) { AsmLoc = L; }
2953
2954 bool isSimple() const { return IsSimple; }
2955 void setSimple(bool V) { IsSimple = V; }
2956
2957 bool isVolatile() const { return IsVolatile; }
2958 void setVolatile(bool V) { IsVolatile = V; }
2959
2960 SourceLocation getBeginLoc() const LLVM_READONLY { return {}; }
2961 SourceLocation getEndLoc() const LLVM_READONLY { return {}; }
2962
2963 //===--- Asm String Analysis ---===//
2964
2965 /// Assemble final IR asm string.
2966 std::string generateAsmString(const ASTContext &C) const;
2967
2968 //===--- Output operands ---===//
2969
2970 unsigned getNumOutputs() const { return NumOutputs; }
2971
2972 /// getOutputConstraint - Return the constraint string for the specified
2973 /// output operand. All output constraints are known to be non-empty (either
2974 /// '=' or '+').
2975 StringRef getOutputConstraint(unsigned i) const;
2976
2977 /// isOutputPlusConstraint - Return true if the specified output constraint
2978 /// is a "+" constraint (which is both an input and an output) or false if it
2979 /// is an "=" constraint (just an output).
2980 bool isOutputPlusConstraint(unsigned i) const {
2981 return getOutputConstraint(i)[0] == '+';
2982 }
2983
2984 const Expr *getOutputExpr(unsigned i) const;
2985
2986 /// getNumPlusOperands - Return the number of output operands that have a "+"
2987 /// constraint.
2988 unsigned getNumPlusOperands() const;
2989
2990 //===--- Input operands ---===//
2991
2992 unsigned getNumInputs() const { return NumInputs; }
2993
2994 /// getInputConstraint - Return the specified input constraint. Unlike output
2995 /// constraints, these can be empty.
2996 StringRef getInputConstraint(unsigned i) const;
2997
2998 const Expr *getInputExpr(unsigned i) const;
2999
3000 //===--- Other ---===//
3001
3002 unsigned getNumClobbers() const { return NumClobbers; }
3003 StringRef getClobber(unsigned i) const;
3004
3005 static bool classof(const Stmt *T) {
3006 return T->getStmtClass() == GCCAsmStmtClass ||
3007 T->getStmtClass() == MSAsmStmtClass;
3008 }
3009
3010 // Input expr iterators.
3011
3012 using inputs_iterator = ExprIterator;
3013 using const_inputs_iterator = ConstExprIterator;
3014 using inputs_range = llvm::iterator_range<inputs_iterator>;
3015 using inputs_const_range = llvm::iterator_range<const_inputs_iterator>;
3016
3017 inputs_iterator begin_inputs() {
3018 return &Exprs[0] + NumOutputs;
3019 }
3020
3021 inputs_iterator end_inputs() {
3022 return &Exprs[0] + NumOutputs + NumInputs;
3023 }
3024
3025 inputs_range inputs() { return inputs_range(begin_inputs(), end_inputs()); }
3026
3027 const_inputs_iterator begin_inputs() const {
3028 return &Exprs[0] + NumOutputs;
3029 }
3030
3031 const_inputs_iterator end_inputs() const {
3032 return &Exprs[0] + NumOutputs + NumInputs;
3033 }
3034
3035 inputs_const_range inputs() const {
3036 return inputs_const_range(begin_inputs(), end_inputs());
3037 }
3038
3039 // Output expr iterators.
3040
3041 using outputs_iterator = ExprIterator;
3042 using const_outputs_iterator = ConstExprIterator;
3043 using outputs_range = llvm::iterator_range<outputs_iterator>;
3044 using outputs_const_range = llvm::iterator_range<const_outputs_iterator>;
3045
3046 outputs_iterator begin_outputs() {
3047 return &Exprs[0];
3048 }
3049
3050 outputs_iterator end_outputs() {
3051 return &Exprs[0] + NumOutputs;
3052 }
3053
3054 outputs_range outputs() {
3055 return outputs_range(begin_outputs(), end_outputs());
3056 }
3057
3058 const_outputs_iterator begin_outputs() const {
3059 return &Exprs[0];
3060 }
3061
3062 const_outputs_iterator end_outputs() const {
3063 return &Exprs[0] + NumOutputs;
3064 }
3065
3066 outputs_const_range outputs() const {
3067 return outputs_const_range(begin_outputs(), end_outputs());
3068 }
3069
3070 child_range children() {
3071 return child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs);
3072 }
3073
3074 const_child_range children() const {
3075 return const_child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs);
3076 }
3077};
3078
3079/// This represents a GCC inline-assembly statement extension.
3080class GCCAsmStmt : public AsmStmt {
3081 friend class ASTStmtReader;
3082
3083 SourceLocation RParenLoc;
3084 StringLiteral *AsmStr;
3085
3086 // FIXME: If we wanted to, we could allocate all of these in one big array.
3087 StringLiteral **Constraints = nullptr;
3088 StringLiteral **Clobbers = nullptr;
3089 IdentifierInfo **Names = nullptr;
3090 unsigned NumLabels = 0;
3091
3092public:
3093 GCCAsmStmt(const ASTContext &C, SourceLocation asmloc, bool issimple,
3094 bool isvolatile, unsigned numoutputs, unsigned numinputs,
3095 IdentifierInfo **names, StringLiteral **constraints, Expr **exprs,
3096 StringLiteral *asmstr, unsigned numclobbers,
3097 StringLiteral **clobbers, unsigned numlabels,
3098 SourceLocation rparenloc);
3099
3100 /// Build an empty inline-assembly statement.
3101 explicit GCCAsmStmt(EmptyShell Empty) : AsmStmt(GCCAsmStmtClass, Empty) {}
3102
3103 SourceLocation getRParenLoc() const { return RParenLoc; }
3104 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3105
3106 //===--- Asm String Analysis ---===//
3107
3108 const StringLiteral *getAsmString() const { return AsmStr; }
3109 StringLiteral *getAsmString() { return AsmStr; }
3110 void setAsmString(StringLiteral *E) { AsmStr = E; }
3111
3112 /// AsmStringPiece - this is part of a decomposed asm string specification
3113 /// (for use with the AnalyzeAsmString function below). An asm string is
3114 /// considered to be a concatenation of these parts.
3115 class AsmStringPiece {
3116 public:
3117 enum Kind {
3118 String, // String in .ll asm string form, "$" -> "$$" and "%%" -> "%".
3119 Operand // Operand reference, with optional modifier %c4.
3120 };
3121
3122 private:
3123 Kind MyKind;
3124 std::string Str;
3125 unsigned OperandNo;
3126
3127 // Source range for operand references.
3128 CharSourceRange Range;
3129
3130 public:
3131 AsmStringPiece(const std::string &S) : MyKind(String), Str(S) {}
3132 AsmStringPiece(unsigned OpNo, const std::string &S, SourceLocation Begin,
3133 SourceLocation End)
3134 : MyKind(Operand), Str(S), OperandNo(OpNo),
3135 Range(CharSourceRange::getCharRange(Begin, End)) {}
3136
3137 bool isString() const { return MyKind == String; }
3138 bool isOperand() const { return MyKind == Operand; }
3139
3140 const std::string &getString() const { return Str; }
3141
3142 unsigned getOperandNo() const {
3143 assert(isOperand());
3144 return OperandNo;
3145 }
3146
3147 CharSourceRange getRange() const {
3148 assert(isOperand() && "Range is currently used only for Operands.");
3149 return Range;
3150 }
3151
3152 /// getModifier - Get the modifier for this operand, if present. This
3153 /// returns '\0' if there was no modifier.
3154 char getModifier() const;
3155 };
3156
3157 /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
3158 /// it into pieces. If the asm string is erroneous, emit errors and return
3159 /// true, otherwise return false. This handles canonicalization and
3160 /// translation of strings from GCC syntax to LLVM IR syntax, and handles
3161 //// flattening of named references like %[foo] to Operand AsmStringPiece's.
3162 unsigned AnalyzeAsmString(SmallVectorImpl<AsmStringPiece> &Pieces,
3163 const ASTContext &C, unsigned &DiagOffs) const;
3164
3165 /// Assemble final IR asm string.
3166 std::string generateAsmString(const ASTContext &C) const;
3167
3168 //===--- Output operands ---===//
3169
3170 IdentifierInfo *getOutputIdentifier(unsigned i) const { return Names[i]; }
3171
3172 StringRef getOutputName(unsigned i) const {
3173 if (IdentifierInfo *II = getOutputIdentifier(i))
3174 return II->getName();
3175
3176 return {};
3177 }
3178
3179 StringRef getOutputConstraint(unsigned i) const;
3180
3181 const StringLiteral *getOutputConstraintLiteral(unsigned i) const {
3182 return Constraints[i];
3183 }
3184 StringLiteral *getOutputConstraintLiteral(unsigned i) {
3185 return Constraints[i];
3186 }
3187
3188 Expr *getOutputExpr(unsigned i);
3189
3190 const Expr *getOutputExpr(unsigned i) const {
3191 return const_cast<GCCAsmStmt*>(this)->getOutputExpr(i);
3192 }
3193
3194 //===--- Input operands ---===//
3195
3196 IdentifierInfo *getInputIdentifier(unsigned i) const {
3197 return Names[i + NumOutputs];
3198 }
3199
3200 StringRef getInputName(unsigned i) const {
3201 if (IdentifierInfo *II = getInputIdentifier(i))
3202 return II->getName();
3203
3204 return {};
3205 }
3206
3207 StringRef getInputConstraint(unsigned i) const;
3208
3209 const StringLiteral *getInputConstraintLiteral(unsigned i) const {
3210 return Constraints[i + NumOutputs];
3211 }
3212 StringLiteral *getInputConstraintLiteral(unsigned i) {
3213 return Constraints[i + NumOutputs];
3214 }
3215
3216 Expr *getInputExpr(unsigned i);
3217 void setInputExpr(unsigned i, Expr *E);
3218
3219 const Expr *getInputExpr(unsigned i) const {
3220 return const_cast<GCCAsmStmt*>(this)->getInputExpr(i);
3221 }
3222
3223 //===--- Labels ---===//
3224
3225 bool isAsmGoto() const {
3226 return NumLabels > 0;
3227 }
3228
3229 unsigned getNumLabels() const {
3230 return NumLabels;
3231 }
3232
3233 IdentifierInfo *getLabelIdentifier(unsigned i) const {
3234 return Names[i + NumOutputs + NumInputs];
3235 }
3236
3237 AddrLabelExpr *getLabelExpr(unsigned i) const;
3238 StringRef getLabelName(unsigned i) const;
3239 using labels_iterator = CastIterator<AddrLabelExpr>;
3240 using const_labels_iterator = ConstCastIterator<AddrLabelExpr>;
3241 using labels_range = llvm::iterator_range<labels_iterator>;
3242 using labels_const_range = llvm::iterator_range<const_labels_iterator>;
3243
3244 labels_iterator begin_labels() {
3245 return &Exprs[0] + NumOutputs + NumInputs;
3246 }
3247
3248 labels_iterator end_labels() {
3249 return &Exprs[0] + NumOutputs + NumInputs + NumLabels;
3250 }
3251
3252 labels_range labels() {
3253 return labels_range(begin_labels(), end_labels());
3254 }
3255
3256 const_labels_iterator begin_labels() const {
3257 return &Exprs[0] + NumOutputs + NumInputs;
3258 }
3259
3260 const_labels_iterator end_labels() const {
3261 return &Exprs[0] + NumOutputs + NumInputs + NumLabels;
3262 }
3263
3264 labels_const_range labels() const {
3265 return labels_const_range(begin_labels(), end_labels());
3266 }
3267
3268private:
3269 void setOutputsAndInputsAndClobbers(const ASTContext &C,
3270 IdentifierInfo **Names,
3271 StringLiteral **Constraints,
3272 Stmt **Exprs,
3273 unsigned NumOutputs,
3274 unsigned NumInputs,
3275 unsigned NumLabels,
3276 StringLiteral **Clobbers,
3277 unsigned NumClobbers);
3278
3279public:
3280 //===--- Other ---===//
3281
3282 /// getNamedOperand - Given a symbolic operand reference like %[foo],
3283 /// translate this into a numeric value needed to reference the same operand.
3284 /// This returns -1 if the operand name is invalid.
3285 int getNamedOperand(StringRef SymbolicName) const;
3286
3287 StringRef getClobber(unsigned i) const;
3288
3289 StringLiteral *getClobberStringLiteral(unsigned i) { return Clobbers[i]; }
3290 const StringLiteral *getClobberStringLiteral(unsigned i) const {
3291 return Clobbers[i];
3292 }
3293
3294 SourceLocation getBeginLoc() const LLVM_READONLY { return AsmLoc; }
3295 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3296
3297 static bool classof(const Stmt *T) {
3298 return T->getStmtClass() == GCCAsmStmtClass;
3299 }
3300};
3301
3302/// This represents a Microsoft inline-assembly statement extension.
3303class MSAsmStmt : public AsmStmt {
3304 friend class ASTStmtReader;
3305
3306 SourceLocation LBraceLoc, EndLoc;
3307 StringRef AsmStr;
3308
3309 unsigned NumAsmToks = 0;
3310
3311 Token *AsmToks = nullptr;
3312 StringRef *Constraints = nullptr;
3313 StringRef *Clobbers = nullptr;
3314
3315public:
3316 MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
3317 SourceLocation lbraceloc, bool issimple, bool isvolatile,
3318 ArrayRef<Token> asmtoks, unsigned numoutputs, unsigned numinputs,
3319 ArrayRef<StringRef> constraints,
3320 ArrayRef<Expr*> exprs, StringRef asmstr,
3321 ArrayRef<StringRef> clobbers, SourceLocation endloc);
3322
3323 /// Build an empty MS-style inline-assembly statement.
3324 explicit MSAsmStmt(EmptyShell Empty) : AsmStmt(MSAsmStmtClass, Empty) {}
3325
3326 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3327 void setLBraceLoc(SourceLocation L) { LBraceLoc = L; }
3328 SourceLocation getEndLoc() const { return EndLoc; }
3329 void setEndLoc(SourceLocation L) { EndLoc = L; }
3330
3331 bool hasBraces() const { return LBraceLoc.isValid(); }
3332
3333 unsigned getNumAsmToks() { return NumAsmToks; }
3334 Token *getAsmToks() { return AsmToks; }
3335
3336 //===--- Asm String Analysis ---===//
3337 StringRef getAsmString() const { return AsmStr; }
3338
3339 /// Assemble final IR asm string.
3340 std::string generateAsmString(const ASTContext &C) const;
3341
3342 //===--- Output operands ---===//
3343
3344 StringRef getOutputConstraint(unsigned i) const {
3345 assert(i < NumOutputs);
3346 return Constraints[i];
3347 }
3348
3349 Expr *getOutputExpr(unsigned i);
3350
3351 const Expr *getOutputExpr(unsigned i) const {
3352 return const_cast<MSAsmStmt*>(this)->getOutputExpr(i);
3353 }
3354
3355 //===--- Input operands ---===//
3356
3357 StringRef getInputConstraint(unsigned i) const {
3358 assert(i < NumInputs);
3359 return Constraints[i + NumOutputs];
3360 }
3361
3362 Expr *getInputExpr(unsigned i);
3363 void setInputExpr(unsigned i, Expr *E);
3364
3365 const Expr *getInputExpr(unsigned i) const {
3366 return const_cast<MSAsmStmt*>(this)->getInputExpr(i);
3367 }
3368
3369 //===--- Other ---===//
3370
3371 ArrayRef<StringRef> getAllConstraints() const {
3372 return llvm::ArrayRef(Constraints, NumInputs + NumOutputs);
3373 }
3374
3375 ArrayRef<StringRef> getClobbers() const {
3376 return llvm::ArrayRef(Clobbers, NumClobbers);
3377 }
3378
3379 ArrayRef<Expr*> getAllExprs() const {
3380 return llvm::ArrayRef(reinterpret_cast<Expr **>(Exprs),
3381 NumInputs + NumOutputs);
3382 }
3383
3384 StringRef getClobber(unsigned i) const { return getClobbers()[i]; }
3385
3386private:
3387 void initialize(const ASTContext &C, StringRef AsmString,
3388 ArrayRef<Token> AsmToks, ArrayRef<StringRef> Constraints,
3389 ArrayRef<Expr*> Exprs, ArrayRef<StringRef> Clobbers);
3390
3391public:
3392 SourceLocation getBeginLoc() const LLVM_READONLY { return AsmLoc; }
3393
3394 static bool classof(const Stmt *T) {
3395 return T->getStmtClass() == MSAsmStmtClass;
3396 }
3397
3398 child_range children() {
3399 return child_range(&Exprs[0], &Exprs[NumInputs + NumOutputs]);
3400 }
3401
3402 const_child_range children() const {
3403 return const_child_range(&Exprs[0], &Exprs[NumInputs + NumOutputs]);
3404 }
3405};
3406
3407class SEHExceptStmt : public Stmt {
3408 friend class ASTReader;
3409 friend class ASTStmtReader;
3410
3411 SourceLocation Loc;
3412 Stmt *Children[2];
3413
3414 enum { FILTER_EXPR, BLOCK };
3415
3416 SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block);
3417 explicit SEHExceptStmt(EmptyShell E) : Stmt(SEHExceptStmtClass, E) {}
3418
3419public:
3420 static SEHExceptStmt* Create(const ASTContext &C,
3421 SourceLocation ExceptLoc,
3422 Expr *FilterExpr,
3423 Stmt *Block);
3424
3425 SourceLocation getBeginLoc() const LLVM_READONLY { return getExceptLoc(); }
3426
3427 SourceLocation getExceptLoc() const { return Loc; }
3428 SourceLocation getEndLoc() const { return getBlock()->getEndLoc(); }
3429
3430 Expr *getFilterExpr() const {
3431 return reinterpret_cast<Expr*>(Children[FILTER_EXPR]);
3432 }
3433
3434 CompoundStmt *getBlock() const {
3435 return cast<CompoundStmt>(Children[BLOCK]);
3436 }
3437
3438 child_range children() {
3439 return child_range(Children, Children+2);
3440 }
3441
3442 const_child_range children() const {
3443 return const_child_range(Children, Children + 2);
3444 }
3445
3446 static bool classof(const Stmt *T) {
3447 return T->getStmtClass() == SEHExceptStmtClass;
3448 }
3449};
3450
3451class SEHFinallyStmt : public Stmt {
3452 friend class ASTReader;
3453 friend class ASTStmtReader;
3454
3455 SourceLocation Loc;
3456 Stmt *Block;
3457
3458 SEHFinallyStmt(SourceLocation Loc, Stmt *Block);
3459 explicit SEHFinallyStmt(EmptyShell E) : Stmt(SEHFinallyStmtClass, E) {}
3460
3461public:
3462 static SEHFinallyStmt* Create(const ASTContext &C,
3463 SourceLocation FinallyLoc,
3464 Stmt *Block);
3465
3466 SourceLocation getBeginLoc() const LLVM_READONLY { return getFinallyLoc(); }
3467
3468 SourceLocation getFinallyLoc() const { return Loc; }
3469 SourceLocation getEndLoc() const { return Block->getEndLoc(); }
3470
3471 CompoundStmt *getBlock() const { return cast<CompoundStmt>(Block); }
3472
3473 child_range children() {
3474 return child_range(&Block,&Block+1);
3475 }
3476
3477 const_child_range children() const {
3478 return const_child_range(&Block, &Block + 1);
3479 }
3480
3481 static bool classof(const Stmt *T) {
3482 return T->getStmtClass() == SEHFinallyStmtClass;
3483 }
3484};
3485
3486class SEHTryStmt : public Stmt {
3487 friend class ASTReader;
3488 friend class ASTStmtReader;
3489
3490 bool IsCXXTry;
3491 SourceLocation TryLoc;
3492 Stmt *Children[2];
3493
3494 enum { TRY = 0, HANDLER = 1 };
3495
3496 SEHTryStmt(bool isCXXTry, // true if 'try' otherwise '__try'
3497 SourceLocation TryLoc,
3498 Stmt *TryBlock,
3499 Stmt *Handler);
3500
3501 explicit SEHTryStmt(EmptyShell E) : Stmt(SEHTryStmtClass, E) {}
3502
3503public:
3504 static SEHTryStmt* Create(const ASTContext &C, bool isCXXTry,
3505 SourceLocation TryLoc, Stmt *TryBlock,
3506 Stmt *Handler);
3507
3508 SourceLocation getBeginLoc() const LLVM_READONLY { return getTryLoc(); }
3509
3510 SourceLocation getTryLoc() const { return TryLoc; }
3511 SourceLocation getEndLoc() const { return Children[HANDLER]->getEndLoc(); }
3512
3513 bool getIsCXXTry() const { return IsCXXTry; }
3514
3515 CompoundStmt* getTryBlock() const {
3516 return cast<CompoundStmt>(Children[TRY]);
3517 }
3518
3519 Stmt *getHandler() const { return Children[HANDLER]; }
3520
3521 /// Returns 0 if not defined
3522 SEHExceptStmt *getExceptHandler() const;
3523 SEHFinallyStmt *getFinallyHandler() const;
3524
3525 child_range children() {
3526 return child_range(Children, Children+2);
3527 }
3528
3529 const_child_range children() const {
3530 return const_child_range(Children, Children + 2);
3531 }
3532
3533 static bool classof(const Stmt *T) {
3534 return T->getStmtClass() == SEHTryStmtClass;
3535 }
3536};
3537
3538/// Represents a __leave statement.
3539class SEHLeaveStmt : public Stmt {
3540 SourceLocation LeaveLoc;
3541
3542public:
3543 explicit SEHLeaveStmt(SourceLocation LL)
3544 : Stmt(SEHLeaveStmtClass), LeaveLoc(LL) {}
3545
3546 /// Build an empty __leave statement.
3547 explicit SEHLeaveStmt(EmptyShell Empty) : Stmt(SEHLeaveStmtClass, Empty) {}
3548
3549 SourceLocation getLeaveLoc() const { return LeaveLoc; }
3550 void setLeaveLoc(SourceLocation L) { LeaveLoc = L; }
3551
3552 SourceLocation getBeginLoc() const LLVM_READONLY { return LeaveLoc; }
3553 SourceLocation getEndLoc() const LLVM_READONLY { return LeaveLoc; }
3554
3555 static bool classof(const Stmt *T) {
3556 return T->getStmtClass() == SEHLeaveStmtClass;
3557 }
3558
3559 // Iterators
3560 child_range children() {
3561 return child_range(child_iterator(), child_iterator());
3562 }
3563
3564 const_child_range children() const {
3565 return const_child_range(const_child_iterator(), const_child_iterator());
3566 }
3567};
3568
3569/// This captures a statement into a function. For example, the following
3570/// pragma annotated compound statement can be represented as a CapturedStmt,
3571/// and this compound statement is the body of an anonymous outlined function.
3572/// @code
3573/// #pragma omp parallel
3574/// {
3575/// compute();
3576/// }
3577/// @endcode
3578class CapturedStmt : public Stmt {
3579public:
3580 /// The different capture forms: by 'this', by reference, capture for
3581 /// variable-length array type etc.
3582 enum VariableCaptureKind {
3583 VCK_This,
3584 VCK_ByRef,
3585 VCK_ByCopy,
3586 VCK_VLAType,
3587 };
3588
3589 /// Describes the capture of either a variable, or 'this', or
3590 /// variable-length array type.
3591 class Capture {
3592 llvm::PointerIntPair<VarDecl *, 2, VariableCaptureKind> VarAndKind;
3593 SourceLocation Loc;
3594
3595 Capture() = default;
3596
3597 public:
3598 friend class ASTStmtReader;
3599 friend class CapturedStmt;
3600
3601 /// Create a new capture.
3602 ///
3603 /// \param Loc The source location associated with this capture.
3604 ///
3605 /// \param Kind The kind of capture (this, ByRef, ...).
3606 ///
3607 /// \param Var The variable being captured, or null if capturing this.
3608 Capture(SourceLocation Loc, VariableCaptureKind Kind,
3609 VarDecl *Var = nullptr);
3610
3611 /// Determine the kind of capture.
3612 VariableCaptureKind getCaptureKind() const;
3613
3614 /// Retrieve the source location at which the variable or 'this' was
3615 /// first used.
3616 SourceLocation getLocation() const { return Loc; }
3617
3618 /// Determine whether this capture handles the C++ 'this' pointer.
3619 bool capturesThis() const { return getCaptureKind() == VCK_This; }
3620
3621 /// Determine whether this capture handles a variable (by reference).
3622 bool capturesVariable() const { return getCaptureKind() == VCK_ByRef; }
3623
3624 /// Determine whether this capture handles a variable by copy.
3625 bool capturesVariableByCopy() const {
3626 return getCaptureKind() == VCK_ByCopy;
3627 }
3628
3629 /// Determine whether this capture handles a variable-length array
3630 /// type.
3631 bool capturesVariableArrayType() const {
3632 return getCaptureKind() == VCK_VLAType;
3633 }
3634
3635 /// Retrieve the declaration of the variable being captured.
3636 ///
3637 /// This operation is only valid if this capture captures a variable.
3638 VarDecl *getCapturedVar() const;
3639 };
3640
3641private:
3642 /// The number of variable captured, including 'this'.
3643 unsigned NumCaptures;
3644
3645 /// The pointer part is the implicit the outlined function and the
3646 /// int part is the captured region kind, 'CR_Default' etc.
3647 llvm::PointerIntPair<CapturedDecl *, 2, CapturedRegionKind> CapDeclAndKind;
3648
3649 /// The record for captured variables, a RecordDecl or CXXRecordDecl.
3650 RecordDecl *TheRecordDecl = nullptr;
3651
3652 /// Construct a captured statement.
3653 CapturedStmt(Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures,
3654 ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD);
3655
3656 /// Construct an empty captured statement.
3657 CapturedStmt(EmptyShell Empty, unsigned NumCaptures);
3658
3659 Stmt **getStoredStmts() { return reinterpret_cast<Stmt **>(this + 1); }
3660
3661 Stmt *const *getStoredStmts() const {
3662 return reinterpret_cast<Stmt *const *>(this + 1);
3663 }
3664
3665 Capture *getStoredCaptures() const;
3666
3667 void setCapturedStmt(Stmt *S) { getStoredStmts()[NumCaptures] = S; }
3668
3669public:
3670 friend class ASTStmtReader;
3671
3672 static CapturedStmt *Create(const ASTContext &Context, Stmt *S,
3673 CapturedRegionKind Kind,
3674 ArrayRef<Capture> Captures,
3675 ArrayRef<Expr *> CaptureInits,
3676 CapturedDecl *CD, RecordDecl *RD);
3677
3678 static CapturedStmt *CreateDeserialized(const ASTContext &Context,
3679 unsigned NumCaptures);
3680
3681 /// Retrieve the statement being captured.
3682 Stmt *getCapturedStmt() { return getStoredStmts()[NumCaptures]; }
3683 const Stmt *getCapturedStmt() const { return getStoredStmts()[NumCaptures]; }
3684
3685 /// Retrieve the outlined function declaration.
3686 CapturedDecl *getCapturedDecl();
3687 const CapturedDecl *getCapturedDecl() const;
3688
3689 /// Set the outlined function declaration.
3690 void setCapturedDecl(CapturedDecl *D);
3691
3692 /// Retrieve the captured region kind.
3693 CapturedRegionKind getCapturedRegionKind() const;
3694
3695 /// Set the captured region kind.
3696 void setCapturedRegionKind(CapturedRegionKind Kind);
3697
3698 /// Retrieve the record declaration for captured variables.
3699 const RecordDecl *getCapturedRecordDecl() const { return TheRecordDecl; }
3700
3701 /// Set the record declaration for captured variables.
3702 void setCapturedRecordDecl(RecordDecl *D) {
3703 assert(D && "null RecordDecl");
3704 TheRecordDecl = D;
3705 }
3706
3707 /// True if this variable has been captured.
3708 bool capturesVariable(const VarDecl *Var) const;
3709
3710 /// An iterator that walks over the captures.
3711 using capture_iterator = Capture *;
3712 using const_capture_iterator = const Capture *;
3713 using capture_range = llvm::iterator_range<capture_iterator>;
3714 using capture_const_range = llvm::iterator_range<const_capture_iterator>;
3715
3716 capture_range captures() {
3717 return capture_range(capture_begin(), capture_end());
3718 }
3719 capture_const_range captures() const {
3720 return capture_const_range(capture_begin(), capture_end());
3721 }
3722
3723 /// Retrieve an iterator pointing to the first capture.
3724 capture_iterator capture_begin() { return getStoredCaptures(); }
3725 const_capture_iterator capture_begin() const { return getStoredCaptures(); }
3726
3727 /// Retrieve an iterator pointing past the end of the sequence of
3728 /// captures.
3729 capture_iterator capture_end() const {
3730 return getStoredCaptures() + NumCaptures;
3731 }
3732
3733 /// Retrieve the number of captures, including 'this'.
3734 unsigned capture_size() const { return NumCaptures; }
3735
3736 /// Iterator that walks over the capture initialization arguments.
3737 using capture_init_iterator = Expr **;
3738 using capture_init_range = llvm::iterator_range<capture_init_iterator>;
3739
3740 /// Const iterator that walks over the capture initialization
3741 /// arguments.
3742 using const_capture_init_iterator = Expr *const *;
3743 using const_capture_init_range =
3744 llvm::iterator_range<const_capture_init_iterator>;
3745
3746 capture_init_range capture_inits() {
3747 return capture_init_range(capture_init_begin(), capture_init_end());
3748 }
3749
3750 const_capture_init_range capture_inits() const {
3751 return const_capture_init_range(capture_init_begin(), capture_init_end());
3752 }
3753
3754 /// Retrieve the first initialization argument.
3755 capture_init_iterator capture_init_begin() {
3756 return reinterpret_cast<Expr **>(getStoredStmts());
3757 }
3758
3759 const_capture_init_iterator capture_init_begin() const {
3760 return reinterpret_cast<Expr *const *>(getStoredStmts());
3761 }
3762
3763 /// Retrieve the iterator pointing one past the last initialization
3764 /// argument.
3765 capture_init_iterator capture_init_end() {
3766 return capture_init_begin() + NumCaptures;
3767 }
3768
3769 const_capture_init_iterator capture_init_end() const {
3770 return capture_init_begin() + NumCaptures;
3771 }
3772
3773 SourceLocation getBeginLoc() const LLVM_READONLY {
3774 return getCapturedStmt()->getBeginLoc();
3775 }
3776
3777 SourceLocation getEndLoc() const LLVM_READONLY {
3778 return getCapturedStmt()->getEndLoc();
3779 }
3780
3781 SourceRange getSourceRange() const LLVM_READONLY {
3782 return getCapturedStmt()->getSourceRange();
3783 }
3784
3785 static bool classof(const Stmt *T) {
3786 return T->getStmtClass() == CapturedStmtClass;
3787 }
3788
3789 child_range children();
3790
3791 const_child_range children() const;
3792};
3793
3794} // namespace clang
3795
3796#endif // LLVM_CLANG_AST_STMT_H
3797