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