Warning: This file is not a C or C++ file. It does not have highlighting.

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

Warning: This file is not a C or C++ file. It does not have highlighting.

source code of clang/include/clang/AST/Stmt.h