1//===--- Sema.h - Semantic Analysis & AST Building --------------*- 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 Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LocInfoType.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/PrettyPrinter.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/AST/TypeOrdering.h"
37#include "clang/Basic/BitmaskEnum.h"
38#include "clang/Basic/ExpressionTraits.h"
39#include "clang/Basic/Module.h"
40#include "clang/Basic/OpenCLOptions.h"
41#include "clang/Basic/OpenMPKinds.h"
42#include "clang/Basic/PragmaKinds.h"
43#include "clang/Basic/Specifiers.h"
44#include "clang/Basic/TemplateKinds.h"
45#include "clang/Basic/TypeTraits.h"
46#include "clang/Sema/AnalysisBasedWarnings.h"
47#include "clang/Sema/CleanupInfo.h"
48#include "clang/Sema/DeclSpec.h"
49#include "clang/Sema/ExternalSemaSource.h"
50#include "clang/Sema/IdentifierResolver.h"
51#include "clang/Sema/ObjCMethodList.h"
52#include "clang/Sema/Ownership.h"
53#include "clang/Sema/Scope.h"
54#include "clang/Sema/SemaConcept.h"
55#include "clang/Sema/TypoCorrection.h"
56#include "clang/Sema/Weak.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/Optional.h"
59#include "llvm/ADT/SetVector.h"
60#include "llvm/ADT/SmallBitVector.h"
61#include "llvm/ADT/SmallPtrSet.h"
62#include "llvm/ADT/SmallSet.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/ADT/TinyPtrVector.h"
65#include "llvm/Frontend/OpenMP/OMPConstants.h"
66#include <deque>
67#include <memory>
68#include <string>
69#include <tuple>
70#include <vector>
71
72namespace llvm {
73 class APSInt;
74 template <typename ValueT> struct DenseMapInfo;
75 template <typename ValueT, typename ValueInfoT> class DenseSet;
76 class SmallBitVector;
77 struct InlineAsmIdentifierInfo;
78}
79
80namespace clang {
81 class ADLResult;
82 class ASTConsumer;
83 class ASTContext;
84 class ASTMutationListener;
85 class ASTReader;
86 class ASTWriter;
87 class ArrayType;
88 class ParsedAttr;
89 class BindingDecl;
90 class BlockDecl;
91 class CapturedDecl;
92 class CXXBasePath;
93 class CXXBasePaths;
94 class CXXBindTemporaryExpr;
95 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
96 class CXXConstructorDecl;
97 class CXXConversionDecl;
98 class CXXDeleteExpr;
99 class CXXDestructorDecl;
100 class CXXFieldCollector;
101 class CXXMemberCallExpr;
102 class CXXMethodDecl;
103 class CXXScopeSpec;
104 class CXXTemporary;
105 class CXXTryStmt;
106 class CallExpr;
107 class ClassTemplateDecl;
108 class ClassTemplatePartialSpecializationDecl;
109 class ClassTemplateSpecializationDecl;
110 class VarTemplatePartialSpecializationDecl;
111 class CodeCompleteConsumer;
112 class CodeCompletionAllocator;
113 class CodeCompletionTUInfo;
114 class CodeCompletionResult;
115 class CoroutineBodyStmt;
116 class Decl;
117 class DeclAccessPair;
118 class DeclContext;
119 class DeclRefExpr;
120 class DeclaratorDecl;
121 class DeducedTemplateArgument;
122 class DependentDiagnostic;
123 class DesignatedInitExpr;
124 class Designation;
125 class EnableIfAttr;
126 class EnumConstantDecl;
127 class Expr;
128 class ExtVectorType;
129 class FormatAttr;
130 class FriendDecl;
131 class FunctionDecl;
132 class FunctionProtoType;
133 class FunctionTemplateDecl;
134 class ImplicitConversionSequence;
135 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
136 class InitListExpr;
137 class InitializationKind;
138 class InitializationSequence;
139 class InitializedEntity;
140 class IntegerLiteral;
141 class LabelStmt;
142 class LambdaExpr;
143 class LangOptions;
144 class LocalInstantiationScope;
145 class LookupResult;
146 class MacroInfo;
147 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
148 class ModuleLoader;
149 class MultiLevelTemplateArgumentList;
150 class NamedDecl;
151 class ObjCCategoryDecl;
152 class ObjCCategoryImplDecl;
153 class ObjCCompatibleAliasDecl;
154 class ObjCContainerDecl;
155 class ObjCImplDecl;
156 class ObjCImplementationDecl;
157 class ObjCInterfaceDecl;
158 class ObjCIvarDecl;
159 template <class T> class ObjCList;
160 class ObjCMessageExpr;
161 class ObjCMethodDecl;
162 class ObjCPropertyDecl;
163 class ObjCProtocolDecl;
164 class OMPThreadPrivateDecl;
165 class OMPRequiresDecl;
166 class OMPDeclareReductionDecl;
167 class OMPDeclareSimdDecl;
168 class OMPClause;
169 struct OMPVarListLocTy;
170 struct OverloadCandidate;
171 enum class OverloadCandidateParamOrder : char;
172 enum OverloadCandidateRewriteKind : unsigned;
173 class OverloadCandidateSet;
174 class OverloadExpr;
175 class ParenListExpr;
176 class ParmVarDecl;
177 class Preprocessor;
178 class PseudoDestructorTypeStorage;
179 class PseudoObjectExpr;
180 class QualType;
181 class StandardConversionSequence;
182 class Stmt;
183 class StringLiteral;
184 class SwitchStmt;
185 class TemplateArgument;
186 class TemplateArgumentList;
187 class TemplateArgumentLoc;
188 class TemplateDecl;
189 class TemplateInstantiationCallback;
190 class TemplateParameterList;
191 class TemplatePartialOrderingContext;
192 class TemplateTemplateParmDecl;
193 class Token;
194 class TypeAliasDecl;
195 class TypedefDecl;
196 class TypedefNameDecl;
197 class TypeLoc;
198 class TypoCorrectionConsumer;
199 class UnqualifiedId;
200 class UnresolvedLookupExpr;
201 class UnresolvedMemberExpr;
202 class UnresolvedSetImpl;
203 class UnresolvedSetIterator;
204 class UsingDecl;
205 class UsingShadowDecl;
206 class ValueDecl;
207 class VarDecl;
208 class VarTemplateSpecializationDecl;
209 class VisibilityAttr;
210 class VisibleDeclConsumer;
211 class IndirectFieldDecl;
212 struct DeductionFailureInfo;
213 class TemplateSpecCandidateSet;
214
215namespace sema {
216 class AccessedEntity;
217 class BlockScopeInfo;
218 class Capture;
219 class CapturedRegionScopeInfo;
220 class CapturingScopeInfo;
221 class CompoundScopeInfo;
222 class DelayedDiagnostic;
223 class DelayedDiagnosticPool;
224 class FunctionScopeInfo;
225 class LambdaScopeInfo;
226 class PossiblyUnreachableDiag;
227 class SemaPPCallbacks;
228 class TemplateDeductionInfo;
229}
230
231namespace threadSafety {
232 class BeforeSet;
233 void threadSafetyCleanup(BeforeSet* Cache);
234}
235
236// FIXME: No way to easily map from TemplateTypeParmTypes to
237// TemplateTypeParmDecls, so we have this horrible PointerUnion.
238typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
239 SourceLocation> UnexpandedParameterPack;
240
241/// Describes whether we've seen any nullability information for the given
242/// file.
243struct FileNullability {
244 /// The first pointer declarator (of any pointer kind) in the file that does
245 /// not have a corresponding nullability annotation.
246 SourceLocation PointerLoc;
247
248 /// The end location for the first pointer declarator in the file. Used for
249 /// placing fix-its.
250 SourceLocation PointerEndLoc;
251
252 /// Which kind of pointer declarator we saw.
253 uint8_t PointerKind;
254
255 /// Whether we saw any type nullability annotations in the given file.
256 bool SawTypeNullability = false;
257};
258
259/// A mapping from file IDs to a record of whether we've seen nullability
260/// information in that file.
261class FileNullabilityMap {
262 /// A mapping from file IDs to the nullability information for each file ID.
263 llvm::DenseMap<FileID, FileNullability> Map;
264
265 /// A single-element cache based on the file ID.
266 struct {
267 FileID File;
268 FileNullability Nullability;
269 } Cache;
270
271public:
272 FileNullability &operator[](FileID file) {
273 // Check the single-element cache.
274 if (file == Cache.File)
275 return Cache.Nullability;
276
277 // It's not in the single-element cache; flush the cache if we have one.
278 if (!Cache.File.isInvalid()) {
279 Map[Cache.File] = Cache.Nullability;
280 }
281
282 // Pull this entry into the cache.
283 Cache.File = file;
284 Cache.Nullability = Map[file];
285 return Cache.Nullability;
286 }
287};
288
289/// Tracks expected type during expression parsing, for use in code completion.
290/// The type is tied to a particular token, all functions that update or consume
291/// the type take a start location of the token they are looking at as a
292/// parameter. This avoids updating the type on hot paths in the parser.
293class PreferredTypeBuilder {
294public:
295 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
296
297 void enterCondition(Sema &S, SourceLocation Tok);
298 void enterReturn(Sema &S, SourceLocation Tok);
299 void enterVariableInit(SourceLocation Tok, Decl *D);
300 /// Handles e.g. BaseType{ .D = Tok...
301 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
302 const Designation &D);
303 /// Computing a type for the function argument may require running
304 /// overloading, so we postpone its computation until it is actually needed.
305 ///
306 /// Clients should be very careful when using this funciton, as it stores a
307 /// function_ref, clients should make sure all calls to get() with the same
308 /// location happen while function_ref is alive.
309 ///
310 /// The callback should also emit signature help as a side-effect, but only
311 /// if the completion point has been reached.
312 void enterFunctionArgument(SourceLocation Tok,
313 llvm::function_ref<QualType()> ComputeType);
314
315 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
316 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
317 SourceLocation OpLoc);
318 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
319 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
320 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
321 /// Handles all type casts, including C-style cast, C++ casts, etc.
322 void enterTypeCast(SourceLocation Tok, QualType CastType);
323
324 /// Get the expected type associated with this location, if any.
325 ///
326 /// If the location is a function argument, determining the expected type
327 /// involves considering all function overloads and the arguments so far.
328 /// In this case, signature help for these function overloads will be reported
329 /// as a side-effect (only if the completion point has been reached).
330 QualType get(SourceLocation Tok) const {
331 if (!Enabled || Tok != ExpectedLoc)
332 return QualType();
333 if (!Type.isNull())
334 return Type;
335 if (ComputeType)
336 return ComputeType();
337 return QualType();
338 }
339
340private:
341 bool Enabled;
342 /// Start position of a token for which we store expected type.
343 SourceLocation ExpectedLoc;
344 /// Expected type for a token starting at ExpectedLoc.
345 QualType Type;
346 /// A function to compute expected type at ExpectedLoc. It is only considered
347 /// if Type is null.
348 llvm::function_ref<QualType()> ComputeType;
349};
350
351/// Sema - This implements semantic analysis and AST building for C.
352class Sema final {
353 Sema(const Sema &) = delete;
354 void operator=(const Sema &) = delete;
355
356 ///Source of additional semantic information.
357 ExternalSemaSource *ExternalSource;
358
359 ///Whether Sema has generated a multiplexer and has to delete it.
360 bool isMultiplexExternalSource;
361
362 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
363
364 bool isVisibleSlow(const NamedDecl *D);
365
366 /// Determine whether two declarations should be linked together, given that
367 /// the old declaration might not be visible and the new declaration might
368 /// not have external linkage.
369 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
370 const NamedDecl *New) {
371 if (isVisible(Old))
372 return true;
373 // See comment in below overload for why it's safe to compute the linkage
374 // of the new declaration here.
375 if (New->isExternallyDeclarable()) {
376 assert(Old->isExternallyDeclarable() &&
377 "should not have found a non-externally-declarable previous decl");
378 return true;
379 }
380 return false;
381 }
382 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
383
384 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
385 QualType ResultTy,
386 ArrayRef<QualType> Args);
387
388public:
389 /// The maximum alignment, same as in llvm::Value. We duplicate them here
390 /// because that allows us not to duplicate the constants in clang code,
391 /// which we must to since we can't directly use the llvm constants.
392 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
393 ///
394 /// This is the greatest alignment value supported by load, store, and alloca
395 /// instructions, and global values.
396 static const unsigned MaxAlignmentExponent = 29;
397 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
398
399 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
400 typedef OpaquePtr<TemplateName> TemplateTy;
401 typedef OpaquePtr<QualType> TypeTy;
402
403 OpenCLOptions OpenCLFeatures;
404 FPOptions CurFPFeatures;
405
406 const LangOptions &LangOpts;
407 Preprocessor &PP;
408 ASTContext &Context;
409 ASTConsumer &Consumer;
410 DiagnosticsEngine &Diags;
411 SourceManager &SourceMgr;
412
413 /// Flag indicating whether or not to collect detailed statistics.
414 bool CollectStats;
415
416 /// Code-completion consumer.
417 CodeCompleteConsumer *CodeCompleter;
418
419 /// CurContext - This is the current declaration context of parsing.
420 DeclContext *CurContext;
421
422 /// Generally null except when we temporarily switch decl contexts,
423 /// like in \see ActOnObjCTemporaryExitContainerContext.
424 DeclContext *OriginalLexicalContext;
425
426 /// VAListTagName - The declaration name corresponding to __va_list_tag.
427 /// This is used as part of a hack to omit that class from ADL results.
428 DeclarationName VAListTagName;
429
430 bool MSStructPragmaOn; // True when \#pragma ms_struct on
431
432 /// Controls member pointer representation format under the MS ABI.
433 LangOptions::PragmaMSPointersToMembersKind
434 MSPointerToMemberRepresentationMethod;
435
436 /// Stack of active SEH __finally scopes. Can be empty.
437 SmallVector<Scope*, 2> CurrentSEHFinally;
438
439 /// Source location for newly created implicit MSInheritanceAttrs
440 SourceLocation ImplicitMSInheritanceAttrLoc;
441
442 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
443 /// `TransformTypos` in order to keep track of any TypoExprs that are created
444 /// recursively during typo correction and wipe them away if the correction
445 /// fails.
446 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
447
448 /// pragma clang section kind
449 enum PragmaClangSectionKind {
450 PCSK_Invalid = 0,
451 PCSK_BSS = 1,
452 PCSK_Data = 2,
453 PCSK_Rodata = 3,
454 PCSK_Text = 4,
455 PCSK_Relro = 5
456 };
457
458 enum PragmaClangSectionAction {
459 PCSA_Set = 0,
460 PCSA_Clear = 1
461 };
462
463 struct PragmaClangSection {
464 std::string SectionName;
465 bool Valid = false;
466 SourceLocation PragmaLocation;
467 };
468
469 PragmaClangSection PragmaClangBSSSection;
470 PragmaClangSection PragmaClangDataSection;
471 PragmaClangSection PragmaClangRodataSection;
472 PragmaClangSection PragmaClangRelroSection;
473 PragmaClangSection PragmaClangTextSection;
474
475 enum PragmaMsStackAction {
476 PSK_Reset = 0x0, // #pragma ()
477 PSK_Set = 0x1, // #pragma (value)
478 PSK_Push = 0x2, // #pragma (push[, id])
479 PSK_Pop = 0x4, // #pragma (pop[, id])
480 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
481 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
482 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
483 };
484
485 // #pragma pack and align.
486 class AlignPackInfo {
487 public:
488 // `Native` represents default align mode, which may vary based on the
489 // platform.
490 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
491
492 // #pragma pack info constructor
493 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
494 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
495 assert(Num == PackNumber && "The pack number has been truncated.");
496 }
497
498 // #pragma align info constructor
499 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
500 : PackAttr(false), AlignMode(M),
501 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
502
503 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
504
505 AlignPackInfo() : AlignPackInfo(Native, false) {}
506
507 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
508 // integer encoding for it. This should only be passed to
509 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
510 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
511 std::uint32_t Encoding{};
512 if (Info.IsXLStack())
513 Encoding |= IsXLMask;
514
515 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
516
517 if (Info.IsPackAttr())
518 Encoding |= PackAttrMask;
519
520 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
521
522 return Encoding;
523 }
524
525 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
526 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
527 AlignPackInfo::Mode M =
528 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
529 int PackNumber = (Encoding & PackNumMask) >> 4;
530
531 if (Encoding & PackAttrMask)
532 return AlignPackInfo(M, PackNumber, IsXL);
533
534 return AlignPackInfo(M, IsXL);
535 }
536
537 bool IsPackAttr() const { return PackAttr; }
538
539 bool IsAlignAttr() const { return !PackAttr; }
540
541 Mode getAlignMode() const { return AlignMode; }
542
543 unsigned getPackNumber() const { return PackNumber; }
544
545 bool IsPackSet() const {
546 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
547 // attriute on a decl.
548 return PackNumber != UninitPackVal && PackNumber != 0;
549 }
550
551 bool IsXLStack() const { return XLStack; }
552
553 bool operator==(const AlignPackInfo &Info) const {
554 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
555 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
556 Info.XLStack);
557 }
558
559 bool operator!=(const AlignPackInfo &Info) const {
560 return !(*this == Info);
561 }
562
563 private:
564 /// \brief True if this is a pragma pack attribute,
565 /// not a pragma align attribute.
566 bool PackAttr;
567
568 /// \brief The alignment mode that is in effect.
569 Mode AlignMode;
570
571 /// \brief The pack number of the stack.
572 unsigned char PackNumber;
573
574 /// \brief True if it is a XL #pragma align/pack stack.
575 bool XLStack;
576
577 /// \brief Uninitialized pack value.
578 static constexpr unsigned char UninitPackVal = -1;
579
580 // Masks to encode and decode an AlignPackInfo.
581 static constexpr uint32_t IsXLMask{0x0000'0001};
582 static constexpr uint32_t AlignModeMask{0x0000'0006};
583 static constexpr uint32_t PackAttrMask{0x00000'0008};
584 static constexpr uint32_t PackNumMask{0x0000'01F0};
585 };
586
587 template<typename ValueType>
588 struct PragmaStack {
589 struct Slot {
590 llvm::StringRef StackSlotLabel;
591 ValueType Value;
592 SourceLocation PragmaLocation;
593 SourceLocation PragmaPushLocation;
594 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
595 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
596 : StackSlotLabel(StackSlotLabel), Value(Value),
597 PragmaLocation(PragmaLocation),
598 PragmaPushLocation(PragmaPushLocation) {}
599 };
600
601 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
602 llvm::StringRef StackSlotLabel, ValueType Value) {
603 if (Action == PSK_Reset) {
604 CurrentValue = DefaultValue;
605 CurrentPragmaLocation = PragmaLocation;
606 return;
607 }
608 if (Action & PSK_Push)
609 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
610 PragmaLocation);
611 else if (Action & PSK_Pop) {
612 if (!StackSlotLabel.empty()) {
613 // If we've got a label, try to find it and jump there.
614 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
615 return x.StackSlotLabel == StackSlotLabel;
616 });
617 // If we found the label so pop from there.
618 if (I != Stack.rend()) {
619 CurrentValue = I->Value;
620 CurrentPragmaLocation = I->PragmaLocation;
621 Stack.erase(std::prev(I.base()), Stack.end());
622 }
623 } else if (!Stack.empty()) {
624 // We do not have a label, just pop the last entry.
625 CurrentValue = Stack.back().Value;
626 CurrentPragmaLocation = Stack.back().PragmaLocation;
627 Stack.pop_back();
628 }
629 }
630 if (Action & PSK_Set) {
631 CurrentValue = Value;
632 CurrentPragmaLocation = PragmaLocation;
633 }
634 }
635
636 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
637 // method body to restore the stacks on exit, so it works like this:
638 //
639 // struct S {
640 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
641 // void Method {}
642 // #pragma <name>(pop, InternalPragmaSlot)
643 // };
644 //
645 // It works even with #pragma vtordisp, although MSVC doesn't support
646 // #pragma vtordisp(push [, id], n)
647 // syntax.
648 //
649 // Push / pop a named sentinel slot.
650 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
651 assert((Action == PSK_Push || Action == PSK_Pop) &&
652 "Can only push / pop #pragma stack sentinels!");
653 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
654 }
655
656 // Constructors.
657 explicit PragmaStack(const ValueType &Default)
658 : DefaultValue(Default), CurrentValue(Default) {}
659
660 bool hasValue() const { return CurrentValue != DefaultValue; }
661
662 SmallVector<Slot, 2> Stack;
663 ValueType DefaultValue; // Value used for PSK_Reset action.
664 ValueType CurrentValue;
665 SourceLocation CurrentPragmaLocation;
666 };
667 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
668 // we shouldn't do so if they're in a module).
669
670 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
671 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
672 ///
673 /// 0: Suppress all vtordisps
674 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
675 /// structors
676 /// 2: Always insert vtordisps to support RTTI on partially constructed
677 /// objects
678 PragmaStack<MSVtorDispMode> VtorDispStack;
679 PragmaStack<AlignPackInfo> AlignPackStack;
680 // The current #pragma align/pack values and locations at each #include.
681 struct AlignPackIncludeState {
682 AlignPackInfo CurrentValue;
683 SourceLocation CurrentPragmaLocation;
684 bool HasNonDefaultValue, ShouldWarnOnInclude;
685 };
686 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
687 // Segment #pragmas.
688 PragmaStack<StringLiteral *> DataSegStack;
689 PragmaStack<StringLiteral *> BSSSegStack;
690 PragmaStack<StringLiteral *> ConstSegStack;
691 PragmaStack<StringLiteral *> CodeSegStack;
692
693 // This stack tracks the current state of Sema.CurFPFeatures.
694 PragmaStack<FPOptionsOverride> FpPragmaStack;
695 FPOptionsOverride CurFPFeatureOverrides() {
696 FPOptionsOverride result;
697 if (!FpPragmaStack.hasValue()) {
698 result = FPOptionsOverride();
699 } else {
700 result = FpPragmaStack.CurrentValue;
701 }
702 return result;
703 }
704
705 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
706 // Actions should be performed only if we enter / exit a C++ method body.
707 class PragmaStackSentinelRAII {
708 public:
709 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
710 ~PragmaStackSentinelRAII();
711
712 private:
713 Sema &S;
714 StringRef SlotLabel;
715 bool ShouldAct;
716 };
717
718 /// A mapping that describes the nullability we've seen in each header file.
719 FileNullabilityMap NullabilityMap;
720
721 /// Last section used with #pragma init_seg.
722 StringLiteral *CurInitSeg;
723 SourceLocation CurInitSegLoc;
724
725 /// VisContext - Manages the stack for \#pragma GCC visibility.
726 void *VisContext; // Really a "PragmaVisStack*"
727
728 /// This an attribute introduced by \#pragma clang attribute.
729 struct PragmaAttributeEntry {
730 SourceLocation Loc;
731 ParsedAttr *Attribute;
732 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
733 bool IsUsed;
734 };
735
736 /// A push'd group of PragmaAttributeEntries.
737 struct PragmaAttributeGroup {
738 /// The location of the push attribute.
739 SourceLocation Loc;
740 /// The namespace of this push group.
741 const IdentifierInfo *Namespace;
742 SmallVector<PragmaAttributeEntry, 2> Entries;
743 };
744
745 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
746
747 /// The declaration that is currently receiving an attribute from the
748 /// #pragma attribute stack.
749 const Decl *PragmaAttributeCurrentTargetDecl;
750
751 /// This represents the last location of a "#pragma clang optimize off"
752 /// directive if such a directive has not been closed by an "on" yet. If
753 /// optimizations are currently "on", this is set to an invalid location.
754 SourceLocation OptimizeOffPragmaLocation;
755
756 /// Flag indicating if Sema is building a recovery call expression.
757 ///
758 /// This flag is used to avoid building recovery call expressions
759 /// if Sema is already doing so, which would cause infinite recursions.
760 bool IsBuildingRecoveryCallExpr;
761
762 /// Used to control the generation of ExprWithCleanups.
763 CleanupInfo Cleanup;
764
765 /// ExprCleanupObjects - This is the stack of objects requiring
766 /// cleanup that are created by the current full expression.
767 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
768
769 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
770 /// to a variable (constant) that may or may not be odr-used in this Expr, and
771 /// we won't know until all lvalue-to-rvalue and discarded value conversions
772 /// have been applied to all subexpressions of the enclosing full expression.
773 /// This is cleared at the end of each full expression.
774 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
775 llvm::SmallPtrSet<Expr *, 4>>;
776 MaybeODRUseExprSet MaybeODRUseExprs;
777
778 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
779
780 /// Stack containing information about each of the nested
781 /// function, block, and method scopes that are currently active.
782 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
783
784 /// The index of the first FunctionScope that corresponds to the current
785 /// context.
786 unsigned FunctionScopesStart = 0;
787
788 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
789 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
790 FunctionScopes.end());
791 }
792
793 /// Stack containing information needed when in C++2a an 'auto' is encountered
794 /// in a function declaration parameter type specifier in order to invent a
795 /// corresponding template parameter in the enclosing abbreviated function
796 /// template. This information is also present in LambdaScopeInfo, stored in
797 /// the FunctionScopes stack.
798 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
799
800 /// The index of the first InventedParameterInfo that refers to the current
801 /// context.
802 unsigned InventedParameterInfosStart = 0;
803
804 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
805 return llvm::makeArrayRef(InventedParameterInfos.begin() +
806 InventedParameterInfosStart,
807 InventedParameterInfos.end());
808 }
809
810 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
811 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
812 ExtVectorDeclsType;
813
814 /// ExtVectorDecls - This is a list all the extended vector types. This allows
815 /// us to associate a raw vector type with one of the ext_vector type names.
816 /// This is only necessary for issuing pretty diagnostics.
817 ExtVectorDeclsType ExtVectorDecls;
818
819 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
820 std::unique_ptr<CXXFieldCollector> FieldCollector;
821
822 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
823
824 /// Set containing all declared private fields that are not used.
825 NamedDeclSetType UnusedPrivateFields;
826
827 /// Set containing all typedefs that are likely unused.
828 llvm::SmallSetVector<const TypedefNameDecl *, 4>
829 UnusedLocalTypedefNameCandidates;
830
831 /// Delete-expressions to be analyzed at the end of translation unit
832 ///
833 /// This list contains class members, and locations of delete-expressions
834 /// that could not be proven as to whether they mismatch with new-expression
835 /// used in initializer of the field.
836 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
837 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
838 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
839
840 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
841
842 /// PureVirtualClassDiagSet - a set of class declarations which we have
843 /// emitted a list of pure virtual functions. Used to prevent emitting the
844 /// same list more than once.
845 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
846
847 /// ParsingInitForAutoVars - a set of declarations with auto types for which
848 /// we are currently parsing the initializer.
849 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
850
851 /// Look for a locally scoped extern "C" declaration by the given name.
852 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
853
854 typedef LazyVector<VarDecl *, ExternalSemaSource,
855 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
856 TentativeDefinitionsType;
857
858 /// All the tentative definitions encountered in the TU.
859 TentativeDefinitionsType TentativeDefinitions;
860
861 /// All the external declarations encoutered and used in the TU.
862 SmallVector<VarDecl *, 4> ExternalDeclarations;
863
864 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
865 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
866 UnusedFileScopedDeclsType;
867
868 /// The set of file scoped decls seen so far that have not been used
869 /// and must warn if not used. Only contains the first declaration.
870 UnusedFileScopedDeclsType UnusedFileScopedDecls;
871
872 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
873 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
874 DelegatingCtorDeclsType;
875
876 /// All the delegating constructors seen so far in the file, used for
877 /// cycle detection at the end of the TU.
878 DelegatingCtorDeclsType DelegatingCtorDecls;
879
880 /// All the overriding functions seen during a class definition
881 /// that had their exception spec checks delayed, plus the overridden
882 /// function.
883 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
884 DelayedOverridingExceptionSpecChecks;
885
886 /// All the function redeclarations seen during a class definition that had
887 /// their exception spec checks delayed, plus the prior declaration they
888 /// should be checked against. Except during error recovery, the new decl
889 /// should always be a friend declaration, as that's the only valid way to
890 /// redeclare a special member before its class is complete.
891 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
892 DelayedEquivalentExceptionSpecChecks;
893
894 typedef llvm::MapVector<const FunctionDecl *,
895 std::unique_ptr<LateParsedTemplate>>
896 LateParsedTemplateMapT;
897 LateParsedTemplateMapT LateParsedTemplateMap;
898
899 /// Callback to the parser to parse templated functions when needed.
900 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
901 typedef void LateTemplateParserCleanupCB(void *P);
902 LateTemplateParserCB *LateTemplateParser;
903 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
904 void *OpaqueParser;
905
906 void SetLateTemplateParser(LateTemplateParserCB *LTP,
907 LateTemplateParserCleanupCB *LTPCleanup,
908 void *P) {
909 LateTemplateParser = LTP;
910 LateTemplateParserCleanup = LTPCleanup;
911 OpaqueParser = P;
912 }
913
914 class DelayedDiagnostics;
915
916 class DelayedDiagnosticsState {
917 sema::DelayedDiagnosticPool *SavedPool;
918 friend class Sema::DelayedDiagnostics;
919 };
920 typedef DelayedDiagnosticsState ParsingDeclState;
921 typedef DelayedDiagnosticsState ProcessingContextState;
922
923 /// A class which encapsulates the logic for delaying diagnostics
924 /// during parsing and other processing.
925 class DelayedDiagnostics {
926 /// The current pool of diagnostics into which delayed
927 /// diagnostics should go.
928 sema::DelayedDiagnosticPool *CurPool;
929
930 public:
931 DelayedDiagnostics() : CurPool(nullptr) {}
932
933 /// Adds a delayed diagnostic.
934 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
935
936 /// Determines whether diagnostics should be delayed.
937 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
938
939 /// Returns the current delayed-diagnostics pool.
940 sema::DelayedDiagnosticPool *getCurrentPool() const {
941 return CurPool;
942 }
943
944 /// Enter a new scope. Access and deprecation diagnostics will be
945 /// collected in this pool.
946 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
947 DelayedDiagnosticsState state;
948 state.SavedPool = CurPool;
949 CurPool = &pool;
950 return state;
951 }
952
953 /// Leave a delayed-diagnostic state that was previously pushed.
954 /// Do not emit any of the diagnostics. This is performed as part
955 /// of the bookkeeping of popping a pool "properly".
956 void popWithoutEmitting(DelayedDiagnosticsState state) {
957 CurPool = state.SavedPool;
958 }
959
960 /// Enter a new scope where access and deprecation diagnostics are
961 /// not delayed.
962 DelayedDiagnosticsState pushUndelayed() {
963 DelayedDiagnosticsState state;
964 state.SavedPool = CurPool;
965 CurPool = nullptr;
966 return state;
967 }
968
969 /// Undo a previous pushUndelayed().
970 void popUndelayed(DelayedDiagnosticsState state) {
971 assert(CurPool == nullptr);
972 CurPool = state.SavedPool;
973 }
974 } DelayedDiagnostics;
975
976 /// A RAII object to temporarily push a declaration context.
977 class ContextRAII {
978 private:
979 Sema &S;
980 DeclContext *SavedContext;
981 ProcessingContextState SavedContextState;
982 QualType SavedCXXThisTypeOverride;
983 unsigned SavedFunctionScopesStart;
984 unsigned SavedInventedParameterInfosStart;
985
986 public:
987 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
988 : S(S), SavedContext(S.CurContext),
989 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
990 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
991 SavedFunctionScopesStart(S.FunctionScopesStart),
992 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
993 {
994 assert(ContextToPush && "pushing null context");
995 S.CurContext = ContextToPush;
996 if (NewThisContext)
997 S.CXXThisTypeOverride = QualType();
998 // Any saved FunctionScopes do not refer to this context.
999 S.FunctionScopesStart = S.FunctionScopes.size();
1000 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1001 }
1002
1003 void pop() {
1004 if (!SavedContext) return;
1005 S.CurContext = SavedContext;
1006 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1007 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1008 S.FunctionScopesStart = SavedFunctionScopesStart;
1009 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1010 SavedContext = nullptr;
1011 }
1012
1013 ~ContextRAII() {
1014 pop();
1015 }
1016 };
1017
1018 /// Whether the AST is currently being rebuilt to correct immediate
1019 /// invocations. Immediate invocation candidates and references to consteval
1020 /// functions aren't tracked when this is set.
1021 bool RebuildingImmediateInvocation = false;
1022
1023 /// Used to change context to isConstantEvaluated without pushing a heavy
1024 /// ExpressionEvaluationContextRecord object.
1025 bool isConstantEvaluatedOverride;
1026
1027 bool isConstantEvaluated() {
1028 return ExprEvalContexts.back().isConstantEvaluated() ||
1029 isConstantEvaluatedOverride;
1030 }
1031
1032 /// RAII object to handle the state changes required to synthesize
1033 /// a function body.
1034 class SynthesizedFunctionScope {
1035 Sema &S;
1036 Sema::ContextRAII SavedContext;
1037 bool PushedCodeSynthesisContext = false;
1038
1039 public:
1040 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1041 : S(S), SavedContext(S, DC) {
1042 S.PushFunctionScope();
1043 S.PushExpressionEvaluationContext(
1044 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1045 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1046 FD->setWillHaveBody(true);
1047 else
1048 assert(isa<ObjCMethodDecl>(DC));
1049 }
1050
1051 void addContextNote(SourceLocation UseLoc) {
1052 assert(!PushedCodeSynthesisContext);
1053
1054 Sema::CodeSynthesisContext Ctx;
1055 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1056 Ctx.PointOfInstantiation = UseLoc;
1057 Ctx.Entity = cast<Decl>(S.CurContext);
1058 S.pushCodeSynthesisContext(Ctx);
1059
1060 PushedCodeSynthesisContext = true;
1061 }
1062
1063 ~SynthesizedFunctionScope() {
1064 if (PushedCodeSynthesisContext)
1065 S.popCodeSynthesisContext();
1066 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1067 FD->setWillHaveBody(false);
1068 S.PopExpressionEvaluationContext();
1069 S.PopFunctionScopeInfo();
1070 }
1071 };
1072
1073 /// WeakUndeclaredIdentifiers - Identifiers contained in
1074 /// \#pragma weak before declared. rare. may alias another
1075 /// identifier, declared or undeclared
1076 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
1077
1078 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1079 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1080 /// to define functions that occur in multiple standards to call the version
1081 /// in the currently selected standard.
1082 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1083
1084
1085 /// Load weak undeclared identifiers from the external source.
1086 void LoadExternalWeakUndeclaredIdentifiers();
1087
1088 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1089 /// \#pragma weak during processing of other Decls.
1090 /// I couldn't figure out a clean way to generate these in-line, so
1091 /// we store them here and handle separately -- which is a hack.
1092 /// It would be best to refactor this.
1093 SmallVector<Decl*,2> WeakTopLevelDecl;
1094
1095 IdentifierResolver IdResolver;
1096
1097 /// Translation Unit Scope - useful to Objective-C actions that need
1098 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1099 /// For example, user-defined classes, built-in "id" type, etc.
1100 Scope *TUScope;
1101
1102 /// The C++ "std" namespace, where the standard library resides.
1103 LazyDeclPtr StdNamespace;
1104
1105 /// The C++ "std::bad_alloc" class, which is defined by the C++
1106 /// standard library.
1107 LazyDeclPtr StdBadAlloc;
1108
1109 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1110 /// standard library.
1111 LazyDeclPtr StdAlignValT;
1112
1113 /// The C++ "std::experimental" namespace, where the experimental parts
1114 /// of the standard library resides.
1115 NamespaceDecl *StdExperimentalNamespaceCache;
1116
1117 /// The C++ "std::initializer_list" template, which is defined in
1118 /// \<initializer_list>.
1119 ClassTemplateDecl *StdInitializerList;
1120
1121 /// The C++ "std::coroutine_traits" template, which is defined in
1122 /// \<coroutine_traits>
1123 ClassTemplateDecl *StdCoroutineTraitsCache;
1124
1125 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1126 RecordDecl *CXXTypeInfoDecl;
1127
1128 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1129 RecordDecl *MSVCGuidDecl;
1130
1131 /// Caches identifiers/selectors for NSFoundation APIs.
1132 std::unique_ptr<NSAPI> NSAPIObj;
1133
1134 /// The declaration of the Objective-C NSNumber class.
1135 ObjCInterfaceDecl *NSNumberDecl;
1136
1137 /// The declaration of the Objective-C NSValue class.
1138 ObjCInterfaceDecl *NSValueDecl;
1139
1140 /// Pointer to NSNumber type (NSNumber *).
1141 QualType NSNumberPointer;
1142
1143 /// Pointer to NSValue type (NSValue *).
1144 QualType NSValuePointer;
1145
1146 /// The Objective-C NSNumber methods used to create NSNumber literals.
1147 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1148
1149 /// The declaration of the Objective-C NSString class.
1150 ObjCInterfaceDecl *NSStringDecl;
1151
1152 /// Pointer to NSString type (NSString *).
1153 QualType NSStringPointer;
1154
1155 /// The declaration of the stringWithUTF8String: method.
1156 ObjCMethodDecl *StringWithUTF8StringMethod;
1157
1158 /// The declaration of the valueWithBytes:objCType: method.
1159 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1160
1161 /// The declaration of the Objective-C NSArray class.
1162 ObjCInterfaceDecl *NSArrayDecl;
1163
1164 /// The declaration of the arrayWithObjects:count: method.
1165 ObjCMethodDecl *ArrayWithObjectsMethod;
1166
1167 /// The declaration of the Objective-C NSDictionary class.
1168 ObjCInterfaceDecl *NSDictionaryDecl;
1169
1170 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1171 ObjCMethodDecl *DictionaryWithObjectsMethod;
1172
1173 /// id<NSCopying> type.
1174 QualType QIDNSCopying;
1175
1176 /// will hold 'respondsToSelector:'
1177 Selector RespondsToSelectorSel;
1178
1179 /// A flag to remember whether the implicit forms of operator new and delete
1180 /// have been declared.
1181 bool GlobalNewDeleteDeclared;
1182
1183 /// Describes how the expressions currently being parsed are
1184 /// evaluated at run-time, if at all.
1185 enum class ExpressionEvaluationContext {
1186 /// The current expression and its subexpressions occur within an
1187 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1188 /// \c sizeof, where the type of the expression may be significant but
1189 /// no code will be generated to evaluate the value of the expression at
1190 /// run time.
1191 Unevaluated,
1192
1193 /// The current expression occurs within a braced-init-list within
1194 /// an unevaluated operand. This is mostly like a regular unevaluated
1195 /// context, except that we still instantiate constexpr functions that are
1196 /// referenced here so that we can perform narrowing checks correctly.
1197 UnevaluatedList,
1198
1199 /// The current expression occurs within a discarded statement.
1200 /// This behaves largely similarly to an unevaluated operand in preventing
1201 /// definitions from being required, but not in other ways.
1202 DiscardedStatement,
1203
1204 /// The current expression occurs within an unevaluated
1205 /// operand that unconditionally permits abstract references to
1206 /// fields, such as a SIZE operator in MS-style inline assembly.
1207 UnevaluatedAbstract,
1208
1209 /// The current context is "potentially evaluated" in C++11 terms,
1210 /// but the expression is evaluated at compile-time (like the values of
1211 /// cases in a switch statement).
1212 ConstantEvaluated,
1213
1214 /// The current expression is potentially evaluated at run time,
1215 /// which means that code may be generated to evaluate the value of the
1216 /// expression at run time.
1217 PotentiallyEvaluated,
1218
1219 /// The current expression is potentially evaluated, but any
1220 /// declarations referenced inside that expression are only used if
1221 /// in fact the current expression is used.
1222 ///
1223 /// This value is used when parsing default function arguments, for which
1224 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1225 /// through varargs) but do not want to mark declarations as "referenced"
1226 /// until the default argument is used.
1227 PotentiallyEvaluatedIfUsed
1228 };
1229
1230 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1231
1232 /// Data structure used to record current or nested
1233 /// expression evaluation contexts.
1234 struct ExpressionEvaluationContextRecord {
1235 /// The expression evaluation context.
1236 ExpressionEvaluationContext Context;
1237
1238 /// Whether the enclosing context needed a cleanup.
1239 CleanupInfo ParentCleanup;
1240
1241 /// The number of active cleanup objects when we entered
1242 /// this expression evaluation context.
1243 unsigned NumCleanupObjects;
1244
1245 /// The number of typos encountered during this expression evaluation
1246 /// context (i.e. the number of TypoExprs created).
1247 unsigned NumTypos;
1248
1249 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1250
1251 /// The lambdas that are present within this context, if it
1252 /// is indeed an unevaluated context.
1253 SmallVector<LambdaExpr *, 2> Lambdas;
1254
1255 /// The declaration that provides context for lambda expressions
1256 /// and block literals if the normal declaration context does not
1257 /// suffice, e.g., in a default function argument.
1258 Decl *ManglingContextDecl;
1259
1260 /// If we are processing a decltype type, a set of call expressions
1261 /// for which we have deferred checking the completeness of the return type.
1262 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1263
1264 /// If we are processing a decltype type, a set of temporary binding
1265 /// expressions for which we have deferred checking the destructor.
1266 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1267
1268 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1269
1270 /// Expressions appearing as the LHS of a volatile assignment in this
1271 /// context. We produce a warning for these when popping the context if
1272 /// they are not discarded-value expressions nor unevaluated operands.
1273 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1274
1275 /// Set of candidates for starting an immediate invocation.
1276 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1277
1278 /// Set of DeclRefExprs referencing a consteval function when used in a
1279 /// context not already known to be immediately invoked.
1280 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1281
1282 /// \brief Describes whether we are in an expression constext which we have
1283 /// to handle differently.
1284 enum ExpressionKind {
1285 EK_Decltype, EK_TemplateArgument, EK_Other
1286 } ExprContext;
1287
1288 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1289 unsigned NumCleanupObjects,
1290 CleanupInfo ParentCleanup,
1291 Decl *ManglingContextDecl,
1292 ExpressionKind ExprContext)
1293 : Context(Context), ParentCleanup(ParentCleanup),
1294 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1295 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1296
1297 bool isUnevaluated() const {
1298 return Context == ExpressionEvaluationContext::Unevaluated ||
1299 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1300 Context == ExpressionEvaluationContext::UnevaluatedList;
1301 }
1302 bool isConstantEvaluated() const {
1303 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1304 }
1305 };
1306
1307 /// A stack of expression evaluation contexts.
1308 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1309
1310 /// Emit a warning for all pending noderef expressions that we recorded.
1311 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1312
1313 /// Compute the mangling number context for a lambda expression or
1314 /// block literal. Also return the extra mangling decl if any.
1315 ///
1316 /// \param DC - The DeclContext containing the lambda expression or
1317 /// block literal.
1318 std::tuple<MangleNumberingContext *, Decl *>
1319 getCurrentMangleNumberContext(const DeclContext *DC);
1320
1321
1322 /// SpecialMemberOverloadResult - The overloading result for a special member
1323 /// function.
1324 ///
1325 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1326 /// integer are used to determine whether overload resolution succeeded.
1327 class SpecialMemberOverloadResult {
1328 public:
1329 enum Kind {
1330 NoMemberOrDeleted,
1331 Ambiguous,
1332 Success
1333 };
1334
1335 private:
1336 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1337
1338 public:
1339 SpecialMemberOverloadResult() : Pair() {}
1340 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1341 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1342
1343 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1344 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1345
1346 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1347 void setKind(Kind K) { Pair.setInt(K); }
1348 };
1349
1350 class SpecialMemberOverloadResultEntry
1351 : public llvm::FastFoldingSetNode,
1352 public SpecialMemberOverloadResult {
1353 public:
1354 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1355 : FastFoldingSetNode(ID)
1356 {}
1357 };
1358
1359 /// A cache of special member function overload resolution results
1360 /// for C++ records.
1361 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1362
1363 /// A cache of the flags available in enumerations with the flag_bits
1364 /// attribute.
1365 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1366
1367 /// The kind of translation unit we are processing.
1368 ///
1369 /// When we're processing a complete translation unit, Sema will perform
1370 /// end-of-translation-unit semantic tasks (such as creating
1371 /// initializers for tentative definitions in C) once parsing has
1372 /// completed. Modules and precompiled headers perform different kinds of
1373 /// checks.
1374 TranslationUnitKind TUKind;
1375
1376 llvm::BumpPtrAllocator BumpAlloc;
1377
1378 /// The number of SFINAE diagnostics that have been trapped.
1379 unsigned NumSFINAEErrors;
1380
1381 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1382 UnparsedDefaultArgInstantiationsMap;
1383
1384 /// A mapping from parameters with unparsed default arguments to the
1385 /// set of instantiations of each parameter.
1386 ///
1387 /// This mapping is a temporary data structure used when parsing
1388 /// nested class templates or nested classes of class templates,
1389 /// where we might end up instantiating an inner class before the
1390 /// default arguments of its methods have been parsed.
1391 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1392
1393 // Contains the locations of the beginning of unparsed default
1394 // argument locations.
1395 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1396
1397 /// UndefinedInternals - all the used, undefined objects which require a
1398 /// definition in this translation unit.
1399 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1400
1401 /// Determine if VD, which must be a variable or function, is an external
1402 /// symbol that nonetheless can't be referenced from outside this translation
1403 /// unit because its type has no linkage and it's not extern "C".
1404 bool isExternalWithNoLinkageType(ValueDecl *VD);
1405
1406 /// Obtain a sorted list of functions that are undefined but ODR-used.
1407 void getUndefinedButUsed(
1408 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1409
1410 /// Retrieves list of suspicious delete-expressions that will be checked at
1411 /// the end of translation unit.
1412 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1413 getMismatchingDeleteExpressions() const;
1414
1415 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1416 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1417
1418 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1419 /// We need to maintain a list, since selectors can have differing signatures
1420 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1421 /// of selectors are "overloaded").
1422 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1423 /// methods inside categories with a particular selector.
1424 GlobalMethodPool MethodPool;
1425
1426 /// Method selectors used in a \@selector expression. Used for implementation
1427 /// of -Wselector.
1428 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1429
1430 /// List of SourceLocations where 'self' is implicitly retained inside a
1431 /// block.
1432 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1433 ImplicitlyRetainedSelfLocs;
1434
1435 /// Kinds of C++ special members.
1436 enum CXXSpecialMember {
1437 CXXDefaultConstructor,
1438 CXXCopyConstructor,
1439 CXXMoveConstructor,
1440 CXXCopyAssignment,
1441 CXXMoveAssignment,
1442 CXXDestructor,
1443 CXXInvalid
1444 };
1445
1446 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1447 SpecialMemberDecl;
1448
1449 /// The C++ special members which we are currently in the process of
1450 /// declaring. If this process recursively triggers the declaration of the
1451 /// same special member, we should act as if it is not yet declared.
1452 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1453
1454 /// Kinds of defaulted comparison operator functions.
1455 enum class DefaultedComparisonKind : unsigned char {
1456 /// This is not a defaultable comparison operator.
1457 None,
1458 /// This is an operator== that should be implemented as a series of
1459 /// subobject comparisons.
1460 Equal,
1461 /// This is an operator<=> that should be implemented as a series of
1462 /// subobject comparisons.
1463 ThreeWay,
1464 /// This is an operator!= that should be implemented as a rewrite in terms
1465 /// of a == comparison.
1466 NotEqual,
1467 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1468 /// terms of a <=> comparison.
1469 Relational,
1470 };
1471
1472 /// The function definitions which were renamed as part of typo-correction
1473 /// to match their respective declarations. We want to keep track of them
1474 /// to ensure that we don't emit a "redefinition" error if we encounter a
1475 /// correctly named definition after the renamed definition.
1476 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1477
1478 /// Stack of types that correspond to the parameter entities that are
1479 /// currently being copy-initialized. Can be empty.
1480 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1481
1482 void ReadMethodPool(Selector Sel);
1483 void updateOutOfDateSelector(Selector Sel);
1484
1485 /// Private Helper predicate to check for 'self'.
1486 bool isSelfExpr(Expr *RExpr);
1487 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1488
1489 /// Cause the active diagnostic on the DiagosticsEngine to be
1490 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1491 /// should not be used elsewhere.
1492 void EmitCurrentDiagnostic(unsigned DiagID);
1493
1494 /// Records and restores the CurFPFeatures state on entry/exit of compound
1495 /// statements.
1496 class FPFeaturesStateRAII {
1497 public:
1498 FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1499 OldOverrides = S.FpPragmaStack.CurrentValue;
1500 }
1501 ~FPFeaturesStateRAII() {
1502 S.CurFPFeatures = OldFPFeaturesState;
1503 S.FpPragmaStack.CurrentValue = OldOverrides;
1504 }
1505 FPOptionsOverride getOverrides() { return OldOverrides; }
1506
1507 private:
1508 Sema& S;
1509 FPOptions OldFPFeaturesState;
1510 FPOptionsOverride OldOverrides;
1511 };
1512
1513 void addImplicitTypedef(StringRef Name, QualType T);
1514
1515 bool WarnedStackExhausted = false;
1516
1517public:
1518 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1519 TranslationUnitKind TUKind = TU_Complete,
1520 CodeCompleteConsumer *CompletionConsumer = nullptr);
1521 ~Sema();
1522
1523 /// Perform initialization that occurs after the parser has been
1524 /// initialized but before it parses anything.
1525 void Initialize();
1526
1527 /// This virtual key function only exists to limit the emission of debug info
1528 /// describing the Sema class. GCC and Clang only emit debug info for a class
1529 /// with a vtable when the vtable is emitted. Sema is final and not
1530 /// polymorphic, but the debug info size savings are so significant that it is
1531 /// worth adding a vtable just to take advantage of this optimization.
1532 virtual void anchor();
1533
1534 const LangOptions &getLangOpts() const { return LangOpts; }
1535 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1536 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1537
1538 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1539 SourceManager &getSourceManager() const { return SourceMgr; }
1540 Preprocessor &getPreprocessor() const { return PP; }
1541 ASTContext &getASTContext() const { return Context; }
1542 ASTConsumer &getASTConsumer() const { return Consumer; }
1543 ASTMutationListener *getASTMutationListener() const;
1544 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1545
1546 ///Registers an external source. If an external source already exists,
1547 /// creates a multiplex external source and appends to it.
1548 ///
1549 ///\param[in] E - A non-null external sema source.
1550 ///
1551 void addExternalSource(ExternalSemaSource *E);
1552
1553 void PrintStats() const;
1554
1555 /// Warn that the stack is nearly exhausted.
1556 void warnStackExhausted(SourceLocation Loc);
1557
1558 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1559 /// guaranteed). Produces a warning if we're low on stack space and allocates
1560 /// more in that case. Use this in code that may recurse deeply (for example,
1561 /// in template instantiation) to avoid stack overflow.
1562 void runWithSufficientStackSpace(SourceLocation Loc,
1563 llvm::function_ref<void()> Fn);
1564
1565 /// Helper class that creates diagnostics with optional
1566 /// template instantiation stacks.
1567 ///
1568 /// This class provides a wrapper around the basic DiagnosticBuilder
1569 /// class that emits diagnostics. ImmediateDiagBuilder is
1570 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1571 /// does) and, if the diagnostic comes from inside a template
1572 /// instantiation, printing the template instantiation stack as
1573 /// well.
1574 class ImmediateDiagBuilder : public DiagnosticBuilder {
1575 Sema &SemaRef;
1576 unsigned DiagID;
1577
1578 public:
1579 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1580 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1581 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1582 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1583
1584 // This is a cunning lie. DiagnosticBuilder actually performs move
1585 // construction in its copy constructor (but due to varied uses, it's not
1586 // possible to conveniently express this as actual move construction). So
1587 // the default copy ctor here is fine, because the base class disables the
1588 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1589 // in that case anwyay.
1590 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1591
1592 ~ImmediateDiagBuilder() {
1593 // If we aren't active, there is nothing to do.
1594 if (!isActive()) return;
1595
1596 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1597 // builder itself so it won't emit the diagnostic in its own destructor.
1598 //
1599 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1600 // do its own needless checks to see if the diagnostic needs to be
1601 // emitted. However, because we take care to ensure that the builder
1602 // objects never escape, a sufficiently smart compiler will be able to
1603 // eliminate that code.
1604 Clear();
1605
1606 // Dispatch to Sema to emit the diagnostic.
1607 SemaRef.EmitCurrentDiagnostic(DiagID);
1608 }
1609
1610 /// Teach operator<< to produce an object of the correct type.
1611 template <typename T>
1612 friend const ImmediateDiagBuilder &
1613 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1614 const DiagnosticBuilder &BaseDiag = Diag;
1615 BaseDiag << Value;
1616 return Diag;
1617 }
1618
1619 // It is necessary to limit this to rvalue reference to avoid calling this
1620 // function with a bitfield lvalue argument since non-const reference to
1621 // bitfield is not allowed.
1622 template <typename T, typename = typename std::enable_if<
1623 !std::is_lvalue_reference<T>::value>::type>
1624 const ImmediateDiagBuilder &operator<<(T &&V) const {
1625 const DiagnosticBuilder &BaseDiag = *this;
1626 BaseDiag << std::move(V);
1627 return *this;
1628 }
1629 };
1630
1631 /// A generic diagnostic builder for errors which may or may not be deferred.
1632 ///
1633 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1634 /// which are not allowed to appear inside __device__ functions and are
1635 /// allowed to appear in __host__ __device__ functions only if the host+device
1636 /// function is never codegen'ed.
1637 ///
1638 /// To handle this, we use the notion of "deferred diagnostics", where we
1639 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1640 ///
1641 /// This class lets you emit either a regular diagnostic, a deferred
1642 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1643 /// its constructor, thus simplifying the process of creating these "maybe
1644 /// deferred" diagnostics.
1645 class SemaDiagnosticBuilder {
1646 public:
1647 enum Kind {
1648 /// Emit no diagnostics.
1649 K_Nop,
1650 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1651 K_Immediate,
1652 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1653 /// emit a call stack showing how this function can be reached by an a
1654 /// priori known-emitted function.
1655 K_ImmediateWithCallStack,
1656 /// Create a deferred diagnostic, which is emitted only if the function
1657 /// it's attached to is codegen'ed. Also emit a call stack as with
1658 /// K_ImmediateWithCallStack.
1659 K_Deferred
1660 };
1661
1662 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1663 FunctionDecl *Fn, Sema &S);
1664 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1665 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1666 ~SemaDiagnosticBuilder();
1667
1668 bool isImmediate() const { return ImmediateDiag.hasValue(); }
1669
1670 /// Convertible to bool: True if we immediately emitted an error, false if
1671 /// we didn't emit an error or we created a deferred error.
1672 ///
1673 /// Example usage:
1674 ///
1675 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1676 /// return ExprError();
1677 ///
1678 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1679 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1680 operator bool() const { return isImmediate(); }
1681
1682 template <typename T>
1683 friend const SemaDiagnosticBuilder &
1684 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1685 if (Diag.ImmediateDiag.hasValue())
1686 *Diag.ImmediateDiag << Value;
1687 else if (Diag.PartialDiagId.hasValue())
1688 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1689 << Value;
1690 return Diag;
1691 }
1692
1693 // It is necessary to limit this to rvalue reference to avoid calling this
1694 // function with a bitfield lvalue argument since non-const reference to
1695 // bitfield is not allowed.
1696 template <typename T, typename = typename std::enable_if<
1697 !std::is_lvalue_reference<T>::value>::type>
1698 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1699 if (ImmediateDiag.hasValue())
1700 *ImmediateDiag << std::move(V);
1701 else if (PartialDiagId.hasValue())
1702 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1703 return *this;
1704 }
1705
1706 friend const SemaDiagnosticBuilder &
1707 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1708 if (Diag.ImmediateDiag.hasValue())
1709 PD.Emit(*Diag.ImmediateDiag);
1710 else if (Diag.PartialDiagId.hasValue())
1711 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1712 return Diag;
1713 }
1714
1715 void AddFixItHint(const FixItHint &Hint) const {
1716 if (ImmediateDiag.hasValue())
1717 ImmediateDiag->AddFixItHint(Hint);
1718 else if (PartialDiagId.hasValue())
1719 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1720 }
1721
1722 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1723 return ExprError();
1724 }
1725 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1726 return StmtError();
1727 }
1728 operator ExprResult() const { return ExprError(); }
1729 operator StmtResult() const { return StmtError(); }
1730 operator TypeResult() const { return TypeError(); }
1731 operator DeclResult() const { return DeclResult(true); }
1732 operator MemInitResult() const { return MemInitResult(true); }
1733
1734 private:
1735 Sema &S;
1736 SourceLocation Loc;
1737 unsigned DiagID;
1738 FunctionDecl *Fn;
1739 bool ShowCallStack;
1740
1741 // Invariant: At most one of these Optionals has a value.
1742 // FIXME: Switch these to a Variant once that exists.
1743 llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1744 llvm::Optional<unsigned> PartialDiagId;
1745 };
1746
1747 /// Is the last error level diagnostic immediate. This is used to determined
1748 /// whether the next info diagnostic should be immediate.
1749 bool IsLastErrorImmediate = true;
1750
1751 /// Emit a diagnostic.
1752 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1753 bool DeferHint = false);
1754
1755 /// Emit a partial diagnostic.
1756 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1757 bool DeferHint = false);
1758
1759 /// Build a partial diagnostic.
1760 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1761
1762 /// Whether uncompilable error has occurred. This includes error happens
1763 /// in deferred diagnostics.
1764 bool hasUncompilableErrorOccurred() const;
1765
1766 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1767
1768 /// Get a string to suggest for zero-initialization of a type.
1769 std::string
1770 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1771 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1772
1773 /// Calls \c Lexer::getLocForEndOfToken()
1774 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1775
1776 /// Retrieve the module loader associated with the preprocessor.
1777 ModuleLoader &getModuleLoader() const;
1778
1779 /// Invent a new identifier for parameters of abbreviated templates.
1780 IdentifierInfo *
1781 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1782 unsigned Index);
1783
1784 void emitAndClearUnusedLocalTypedefWarnings();
1785
1786 private:
1787 /// Function or variable declarations to be checked for whether the deferred
1788 /// diagnostics should be emitted.
1789 SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1790
1791 public:
1792 // Emit all deferred diagnostics.
1793 void emitDeferredDiags();
1794
1795 enum TUFragmentKind {
1796 /// The global module fragment, between 'module;' and a module-declaration.
1797 Global,
1798 /// A normal translation unit fragment. For a non-module unit, this is the
1799 /// entire translation unit. Otherwise, it runs from the module-declaration
1800 /// to the private-module-fragment (if any) or the end of the TU (if not).
1801 Normal,
1802 /// The private module fragment, between 'module :private;' and the end of
1803 /// the translation unit.
1804 Private
1805 };
1806
1807 void ActOnStartOfTranslationUnit();
1808 void ActOnEndOfTranslationUnit();
1809 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1810
1811 void CheckDelegatingCtorCycles();
1812
1813 Scope *getScopeForContext(DeclContext *Ctx);
1814
1815 void PushFunctionScope();
1816 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1817 sema::LambdaScopeInfo *PushLambdaScope();
1818
1819 /// This is used to inform Sema what the current TemplateParameterDepth
1820 /// is during Parsing. Currently it is used to pass on the depth
1821 /// when parsing generic lambda 'auto' parameters.
1822 void RecordParsingTemplateParameterDepth(unsigned Depth);
1823
1824 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1825 RecordDecl *RD, CapturedRegionKind K,
1826 unsigned OpenMPCaptureLevel = 0);
1827
1828 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1829 /// time after they've been popped.
1830 class PoppedFunctionScopeDeleter {
1831 Sema *Self;
1832
1833 public:
1834 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1835 void operator()(sema::FunctionScopeInfo *Scope) const;
1836 };
1837
1838 using PoppedFunctionScopePtr =
1839 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1840
1841 PoppedFunctionScopePtr
1842 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1843 const Decl *D = nullptr,
1844 QualType BlockType = QualType());
1845
1846 sema::FunctionScopeInfo *getCurFunction() const {
1847 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1848 }
1849
1850 sema::FunctionScopeInfo *getEnclosingFunction() const;
1851
1852 void setFunctionHasBranchIntoScope();
1853 void setFunctionHasBranchProtectedScope();
1854 void setFunctionHasIndirectGoto();
1855 void setFunctionHasMustTail();
1856
1857 void PushCompoundScope(bool IsStmtExpr);
1858 void PopCompoundScope();
1859
1860 sema::CompoundScopeInfo &getCurCompoundScope() const;
1861
1862 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1863
1864 /// Retrieve the current block, if any.
1865 sema::BlockScopeInfo *getCurBlock();
1866
1867 /// Get the innermost lambda enclosing the current location, if any. This
1868 /// looks through intervening non-lambda scopes such as local functions and
1869 /// blocks.
1870 sema::LambdaScopeInfo *getEnclosingLambda() const;
1871
1872 /// Retrieve the current lambda scope info, if any.
1873 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1874 /// lambda scope info ignoring all inner capturing scopes that are not
1875 /// lambda scopes.
1876 sema::LambdaScopeInfo *
1877 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1878
1879 /// Retrieve the current generic lambda info, if any.
1880 sema::LambdaScopeInfo *getCurGenericLambda();
1881
1882 /// Retrieve the current captured region, if any.
1883 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1884
1885 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1886 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1887
1888 /// Called before parsing a function declarator belonging to a function
1889 /// declaration.
1890 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1891 unsigned TemplateParameterDepth);
1892
1893 /// Called after parsing a function declarator belonging to a function
1894 /// declaration.
1895 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1896
1897 void ActOnComment(SourceRange Comment);
1898
1899 //===--------------------------------------------------------------------===//
1900 // Type Analysis / Processing: SemaType.cpp.
1901 //
1902
1903 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1904 const DeclSpec *DS = nullptr);
1905 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1906 const DeclSpec *DS = nullptr);
1907 QualType BuildPointerType(QualType T,
1908 SourceLocation Loc, DeclarationName Entity);
1909 QualType BuildReferenceType(QualType T, bool LValueRef,
1910 SourceLocation Loc, DeclarationName Entity);
1911 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1912 Expr *ArraySize, unsigned Quals,
1913 SourceRange Brackets, DeclarationName Entity);
1914 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1915 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1916 SourceLocation AttrLoc);
1917 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
1918 SourceLocation AttrLoc);
1919
1920 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1921 SourceLocation AttrLoc);
1922
1923 /// Same as above, but constructs the AddressSpace index if not provided.
1924 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1925 SourceLocation AttrLoc);
1926
1927 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1928
1929 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1930
1931 /// Build a function type.
1932 ///
1933 /// This routine checks the function type according to C++ rules and
1934 /// under the assumption that the result type and parameter types have
1935 /// just been instantiated from a template. It therefore duplicates
1936 /// some of the behavior of GetTypeForDeclarator, but in a much
1937 /// simpler form that is only suitable for this narrow use case.
1938 ///
1939 /// \param T The return type of the function.
1940 ///
1941 /// \param ParamTypes The parameter types of the function. This array
1942 /// will be modified to account for adjustments to the types of the
1943 /// function parameters.
1944 ///
1945 /// \param Loc The location of the entity whose type involves this
1946 /// function type or, if there is no such entity, the location of the
1947 /// type that will have function type.
1948 ///
1949 /// \param Entity The name of the entity that involves the function
1950 /// type, if known.
1951 ///
1952 /// \param EPI Extra information about the function type. Usually this will
1953 /// be taken from an existing function with the same prototype.
1954 ///
1955 /// \returns A suitable function type, if there are no errors. The
1956 /// unqualified type will always be a FunctionProtoType.
1957 /// Otherwise, returns a NULL type.
1958 QualType BuildFunctionType(QualType T,
1959 MutableArrayRef<QualType> ParamTypes,
1960 SourceLocation Loc, DeclarationName Entity,
1961 const FunctionProtoType::ExtProtoInfo &EPI);
1962
1963 QualType BuildMemberPointerType(QualType T, QualType Class,
1964 SourceLocation Loc,
1965 DeclarationName Entity);
1966 QualType BuildBlockPointerType(QualType T,
1967 SourceLocation Loc, DeclarationName Entity);
1968 QualType BuildParenType(QualType T);
1969 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1970 QualType BuildReadPipeType(QualType T,
1971 SourceLocation Loc);
1972 QualType BuildWritePipeType(QualType T,
1973 SourceLocation Loc);
1974 QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
1975
1976 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1977 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1978
1979 /// Package the given type and TSI into a ParsedType.
1980 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1981 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1982 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1983 static QualType GetTypeFromParser(ParsedType Ty,
1984 TypeSourceInfo **TInfo = nullptr);
1985 CanThrowResult canThrow(const Stmt *E);
1986 /// Determine whether the callee of a particular function call can throw.
1987 /// E, D and Loc are all optional.
1988 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
1989 SourceLocation Loc = SourceLocation());
1990 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1991 const FunctionProtoType *FPT);
1992 void UpdateExceptionSpec(FunctionDecl *FD,
1993 const FunctionProtoType::ExceptionSpecInfo &ESI);
1994 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1995 bool CheckDistantExceptionSpec(QualType T);
1996 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1997 bool CheckEquivalentExceptionSpec(
1998 const FunctionProtoType *Old, SourceLocation OldLoc,
1999 const FunctionProtoType *New, SourceLocation NewLoc);
2000 bool CheckEquivalentExceptionSpec(
2001 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2002 const FunctionProtoType *Old, SourceLocation OldLoc,
2003 const FunctionProtoType *New, SourceLocation NewLoc);
2004 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2005 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2006 const PartialDiagnostic &NestedDiagID,
2007 const PartialDiagnostic &NoteID,
2008 const PartialDiagnostic &NoThrowDiagID,
2009 const FunctionProtoType *Superset,
2010 SourceLocation SuperLoc,
2011 const FunctionProtoType *Subset,
2012 SourceLocation SubLoc);
2013 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2014 const PartialDiagnostic &NoteID,
2015 const FunctionProtoType *Target,
2016 SourceLocation TargetLoc,
2017 const FunctionProtoType *Source,
2018 SourceLocation SourceLoc);
2019
2020 TypeResult ActOnTypeName(Scope *S, Declarator &D);
2021
2022 /// The parser has parsed the context-sensitive type 'instancetype'
2023 /// in an Objective-C message declaration. Return the appropriate type.
2024 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2025
2026 /// Abstract class used to diagnose incomplete types.
2027 struct TypeDiagnoser {
2028 TypeDiagnoser() {}
2029
2030 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2031 virtual ~TypeDiagnoser() {}
2032 };
2033
2034 static int getPrintable(int I) { return I; }
2035 static unsigned getPrintable(unsigned I) { return I; }
2036 static bool getPrintable(bool B) { return B; }
2037 static const char * getPrintable(const char *S) { return S; }
2038 static StringRef getPrintable(StringRef S) { return S; }
2039 static const std::string &getPrintable(const std::string &S) { return S; }
2040 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2041 return II;
2042 }
2043 static DeclarationName getPrintable(DeclarationName N) { return N; }
2044 static QualType getPrintable(QualType T) { return T; }
2045 static SourceRange getPrintable(SourceRange R) { return R; }
2046 static SourceRange getPrintable(SourceLocation L) { return L; }
2047 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2048 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2049
2050 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2051 protected:
2052 unsigned DiagID;
2053 std::tuple<const Ts &...> Args;
2054
2055 template <std::size_t... Is>
2056 void emit(const SemaDiagnosticBuilder &DB,
2057 std::index_sequence<Is...>) const {
2058 // Apply all tuple elements to the builder in order.
2059 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2060 (void)Dummy;
2061 }
2062
2063 public:
2064 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2065 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2066 assert(DiagID != 0 && "no diagnostic for type diagnoser");
2067 }
2068
2069 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2070 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2071 emit(DB, std::index_sequence_for<Ts...>());
2072 DB << T;
2073 }
2074 };
2075
2076 /// Do a check to make sure \p Name looks like a legal argument for the
2077 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2078 /// is invalid for the given declaration.
2079 ///
2080 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2081 ///
2082 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2083 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2084 const ParsedAttr &AL, bool IsAsync);
2085
2086 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2087 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2088 /// For example, a diagnostic with no other parameters would generally have
2089 /// the form "...%select{incomplete|sizeless}0 type %1...".
2090 template <typename... Ts>
2091 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2092 public:
2093 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2094 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2095
2096 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2097 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2098 this->emit(DB, std::index_sequence_for<Ts...>());
2099 DB << T->isSizelessType() << T;
2100 }
2101 };
2102
2103 enum class CompleteTypeKind {
2104 /// Apply the normal rules for complete types. In particular,
2105 /// treat all sizeless types as incomplete.
2106 Normal,
2107
2108 /// Relax the normal rules for complete types so that they include
2109 /// sizeless built-in types.
2110 AcceptSizeless,
2111
2112 // FIXME: Eventually we should flip the default to Normal and opt in
2113 // to AcceptSizeless rather than opt out of it.
2114 Default = AcceptSizeless
2115 };
2116
2117private:
2118 /// Methods for marking which expressions involve dereferencing a pointer
2119 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2120 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2121 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2122 /// `*p`, but need to check that `address of` is called on it. This requires
2123 /// keeping a container of all pending expressions and checking if the address
2124 /// of them are eventually taken.
2125 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2126 void CheckAddressOfNoDeref(const Expr *E);
2127 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2128
2129 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2130 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2131
2132 struct ModuleScope {
2133 SourceLocation BeginLoc;
2134 clang::Module *Module = nullptr;
2135 bool ModuleInterface = false;
2136 bool ImplicitGlobalModuleFragment = false;
2137 VisibleModuleSet OuterVisibleModules;
2138 };
2139 /// The modules we're currently parsing.
2140 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2141
2142 /// Namespace definitions that we will export when they finish.
2143 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2144
2145 /// Get the module whose scope we are currently within.
2146 Module *getCurrentModule() const {
2147 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2148 }
2149
2150 VisibleModuleSet VisibleModules;
2151
2152public:
2153 /// Get the module owning an entity.
2154 Module *getOwningModule(const Decl *Entity) {
2155 return Entity->getOwningModule();
2156 }
2157
2158 /// Make a merged definition of an existing hidden definition \p ND
2159 /// visible at the specified location.
2160 void makeMergedDefinitionVisible(NamedDecl *ND);
2161
2162 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2163
2164 // When loading a non-modular PCH files, this is used to restore module
2165 // visibility.
2166 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2167 VisibleModules.setVisible(Mod, ImportLoc);
2168 }
2169
2170 /// Determine whether a declaration is visible to name lookup.
2171 bool isVisible(const NamedDecl *D) {
2172 return D->isUnconditionallyVisible() || isVisibleSlow(D);
2173 }
2174
2175 /// Determine whether any declaration of an entity is visible.
2176 bool
2177 hasVisibleDeclaration(const NamedDecl *D,
2178 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2179 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2180 }
2181 bool hasVisibleDeclarationSlow(const NamedDecl *D,
2182 llvm::SmallVectorImpl<Module *> *Modules);
2183
2184 bool hasVisibleMergedDefinition(NamedDecl *Def);
2185 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2186
2187 /// Determine if \p D and \p Suggested have a structurally compatible
2188 /// layout as described in C11 6.2.7/1.
2189 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2190
2191 /// Determine if \p D has a visible definition. If not, suggest a declaration
2192 /// that should be made visible to expose the definition.
2193 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2194 bool OnlyNeedComplete = false);
2195 bool hasVisibleDefinition(const NamedDecl *D) {
2196 NamedDecl *Hidden;
2197 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2198 }
2199
2200 /// Determine if the template parameter \p D has a visible default argument.
2201 bool
2202 hasVisibleDefaultArgument(const NamedDecl *D,
2203 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2204
2205 /// Determine if there is a visible declaration of \p D that is an explicit
2206 /// specialization declaration for a specialization of a template. (For a
2207 /// member specialization, use hasVisibleMemberSpecialization.)
2208 bool hasVisibleExplicitSpecialization(
2209 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2210
2211 /// Determine if there is a visible declaration of \p D that is a member
2212 /// specialization declaration (as opposed to an instantiated declaration).
2213 bool hasVisibleMemberSpecialization(
2214 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2215
2216 /// Determine if \p A and \p B are equivalent internal linkage declarations
2217 /// from different modules, and thus an ambiguity error can be downgraded to
2218 /// an extension warning.
2219 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2220 const NamedDecl *B);
2221 void diagnoseEquivalentInternalLinkageDeclarations(
2222 SourceLocation Loc, const NamedDecl *D,
2223 ArrayRef<const NamedDecl *> Equiv);
2224
2225 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2226
2227 bool isCompleteType(SourceLocation Loc, QualType T,
2228 CompleteTypeKind Kind = CompleteTypeKind::Default) {
2229 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2230 }
2231 bool RequireCompleteType(SourceLocation Loc, QualType T,
2232 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2233 bool RequireCompleteType(SourceLocation Loc, QualType T,
2234 CompleteTypeKind Kind, unsigned DiagID);
2235
2236 bool RequireCompleteType(SourceLocation Loc, QualType T,
2237 TypeDiagnoser &Diagnoser) {
2238 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2239 }
2240 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2241 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2242 }
2243
2244 template <typename... Ts>
2245 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2246 const Ts &...Args) {
2247 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2248 return RequireCompleteType(Loc, T, Diagnoser);
2249 }
2250
2251 template <typename... Ts>
2252 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2253 const Ts &... Args) {
2254 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2255 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2256 }
2257
2258 /// Get the type of expression E, triggering instantiation to complete the
2259 /// type if necessary -- that is, if the expression refers to a templated
2260 /// static data member of incomplete array type.
2261 ///
2262 /// May still return an incomplete type if instantiation was not possible or
2263 /// if the type is incomplete for a different reason. Use
2264 /// RequireCompleteExprType instead if a diagnostic is expected for an
2265 /// incomplete expression type.
2266 QualType getCompletedType(Expr *E);
2267
2268 void completeExprArrayBound(Expr *E);
2269 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2270 TypeDiagnoser &Diagnoser);
2271 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2272
2273 template <typename... Ts>
2274 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2275 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2276 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2277 }
2278
2279 template <typename... Ts>
2280 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2281 const Ts &... Args) {
2282 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2283 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2284 }
2285
2286 bool RequireLiteralType(SourceLocation Loc, QualType T,
2287 TypeDiagnoser &Diagnoser);
2288 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2289
2290 template <typename... Ts>
2291 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2292 const Ts &...Args) {
2293 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2294 return RequireLiteralType(Loc, T, Diagnoser);
2295 }
2296
2297 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2298 const CXXScopeSpec &SS, QualType T,
2299 TagDecl *OwnedTagDecl = nullptr);
2300
2301 QualType getDecltypeForParenthesizedExpr(Expr *E);
2302 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
2303 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2304 /// context, such as when building a type for decltype(auto).
2305 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
2306 bool AsUnevaluated = true);
2307 QualType BuildUnaryTransformType(QualType BaseType,
2308 UnaryTransformType::UTTKind UKind,
2309 SourceLocation Loc);
2310
2311 //===--------------------------------------------------------------------===//
2312 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2313 //
2314
2315 struct SkipBodyInfo {
2316 SkipBodyInfo()
2317 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2318 New(nullptr) {}
2319 bool ShouldSkip;
2320 bool CheckSameAsPrevious;
2321 NamedDecl *Previous;
2322 NamedDecl *New;
2323 };
2324
2325 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2326
2327 void DiagnoseUseOfUnimplementedSelectors();
2328
2329 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2330
2331 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2332 Scope *S, CXXScopeSpec *SS = nullptr,
2333 bool isClassName = false, bool HasTrailingDot = false,
2334 ParsedType ObjectType = nullptr,
2335 bool IsCtorOrDtorName = false,
2336 bool WantNontrivialTypeSourceInfo = false,
2337 bool IsClassTemplateDeductionContext = true,
2338 IdentifierInfo **CorrectedII = nullptr);
2339 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2340 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2341 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2342 SourceLocation IILoc,
2343 Scope *S,
2344 CXXScopeSpec *SS,
2345 ParsedType &SuggestedType,
2346 bool IsTemplateName = false);
2347
2348 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2349 /// type name has failed in a dependent context. In these situations, we
2350 /// automatically form a DependentTypeName that will retry lookup in a related
2351 /// scope during instantiation.
2352 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2353 SourceLocation NameLoc,
2354 bool IsTemplateTypeArg);
2355
2356 /// Describes the result of the name lookup and resolution performed
2357 /// by \c ClassifyName().
2358 enum NameClassificationKind {
2359 /// This name is not a type or template in this context, but might be
2360 /// something else.
2361 NC_Unknown,
2362 /// Classification failed; an error has been produced.
2363 NC_Error,
2364 /// The name has been typo-corrected to a keyword.
2365 NC_Keyword,
2366 /// The name was classified as a type.
2367 NC_Type,
2368 /// The name was classified as a specific non-type, non-template
2369 /// declaration. ActOnNameClassifiedAsNonType should be called to
2370 /// convert the declaration to an expression.
2371 NC_NonType,
2372 /// The name was classified as an ADL-only function name.
2373 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2374 /// result to an expression.
2375 NC_UndeclaredNonType,
2376 /// The name denotes a member of a dependent type that could not be
2377 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2378 /// convert the result to an expression.
2379 NC_DependentNonType,
2380 /// The name was classified as an overload set, and an expression
2381 /// representing that overload set has been formed.
2382 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2383 /// expression referencing the overload set.
2384 NC_OverloadSet,
2385 /// The name was classified as a template whose specializations are types.
2386 NC_TypeTemplate,
2387 /// The name was classified as a variable template name.
2388 NC_VarTemplate,
2389 /// The name was classified as a function template name.
2390 NC_FunctionTemplate,
2391 /// The name was classified as an ADL-only function template name.
2392 NC_UndeclaredTemplate,
2393 /// The name was classified as a concept name.
2394 NC_Concept,
2395 };
2396
2397 class NameClassification {
2398 NameClassificationKind Kind;
2399 union {
2400 ExprResult Expr;
2401 NamedDecl *NonTypeDecl;
2402 TemplateName Template;
2403 ParsedType Type;
2404 };
2405
2406 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2407
2408 public:
2409 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2410
2411 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2412
2413 static NameClassification Error() {
2414 return NameClassification(NC_Error);
2415 }
2416
2417 static NameClassification Unknown() {
2418 return NameClassification(NC_Unknown);
2419 }
2420
2421 static NameClassification OverloadSet(ExprResult E) {
2422 NameClassification Result(NC_OverloadSet);
2423 Result.Expr = E;
2424 return Result;
2425 }
2426
2427 static NameClassification NonType(NamedDecl *D) {
2428 NameClassification Result(NC_NonType);
2429 Result.NonTypeDecl = D;
2430 return Result;
2431 }
2432
2433 static NameClassification UndeclaredNonType() {
2434 return NameClassification(NC_UndeclaredNonType);
2435 }
2436
2437 static NameClassification DependentNonType() {
2438 return NameClassification(NC_DependentNonType);
2439 }
2440
2441 static NameClassification TypeTemplate(TemplateName Name) {
2442 NameClassification Result(NC_TypeTemplate);
2443 Result.Template = Name;
2444 return Result;
2445 }
2446
2447 static NameClassification VarTemplate(TemplateName Name) {
2448 NameClassification Result(NC_VarTemplate);
2449 Result.Template = Name;
2450 return Result;
2451 }
2452
2453 static NameClassification FunctionTemplate(TemplateName Name) {
2454 NameClassification Result(NC_FunctionTemplate);
2455 Result.Template = Name;
2456 return Result;
2457 }
2458
2459 static NameClassification Concept(TemplateName Name) {
2460 NameClassification Result(NC_Concept);
2461 Result.Template = Name;
2462 return Result;
2463 }
2464
2465 static NameClassification UndeclaredTemplate(TemplateName Name) {
2466 NameClassification Result(NC_UndeclaredTemplate);
2467 Result.Template = Name;
2468 return Result;
2469 }
2470
2471 NameClassificationKind getKind() const { return Kind; }
2472
2473 ExprResult getExpression() const {
2474 assert(Kind == NC_OverloadSet);
2475 return Expr;
2476 }
2477
2478 ParsedType getType() const {
2479 assert(Kind == NC_Type);
2480 return Type;
2481 }
2482
2483 NamedDecl *getNonTypeDecl() const {
2484 assert(Kind == NC_NonType);
2485 return NonTypeDecl;
2486 }
2487
2488 TemplateName getTemplateName() const {
2489 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2490 Kind == NC_VarTemplate || Kind == NC_Concept ||
2491 Kind == NC_UndeclaredTemplate);
2492 return Template;
2493 }
2494
2495 TemplateNameKind getTemplateNameKind() const {
2496 switch (Kind) {
2497 case NC_TypeTemplate:
2498 return TNK_Type_template;
2499 case NC_FunctionTemplate:
2500 return TNK_Function_template;
2501 case NC_VarTemplate:
2502 return TNK_Var_template;
2503 case NC_Concept:
2504 return TNK_Concept_template;
2505 case NC_UndeclaredTemplate:
2506 return TNK_Undeclared_template;
2507 default:
2508 llvm_unreachable("unsupported name classification.");
2509 }
2510 }
2511 };
2512
2513 /// Perform name lookup on the given name, classifying it based on
2514 /// the results of name lookup and the following token.
2515 ///
2516 /// This routine is used by the parser to resolve identifiers and help direct
2517 /// parsing. When the identifier cannot be found, this routine will attempt
2518 /// to correct the typo and classify based on the resulting name.
2519 ///
2520 /// \param S The scope in which we're performing name lookup.
2521 ///
2522 /// \param SS The nested-name-specifier that precedes the name.
2523 ///
2524 /// \param Name The identifier. If typo correction finds an alternative name,
2525 /// this pointer parameter will be updated accordingly.
2526 ///
2527 /// \param NameLoc The location of the identifier.
2528 ///
2529 /// \param NextToken The token following the identifier. Used to help
2530 /// disambiguate the name.
2531 ///
2532 /// \param CCC The correction callback, if typo correction is desired.
2533 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2534 IdentifierInfo *&Name, SourceLocation NameLoc,
2535 const Token &NextToken,
2536 CorrectionCandidateCallback *CCC = nullptr);
2537
2538 /// Act on the result of classifying a name as an undeclared (ADL-only)
2539 /// non-type declaration.
2540 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2541 SourceLocation NameLoc);
2542 /// Act on the result of classifying a name as an undeclared member of a
2543 /// dependent base class.
2544 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2545 IdentifierInfo *Name,
2546 SourceLocation NameLoc,
2547 bool IsAddressOfOperand);
2548 /// Act on the result of classifying a name as a specific non-type
2549 /// declaration.
2550 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2551 NamedDecl *Found,
2552 SourceLocation NameLoc,
2553 const Token &NextToken);
2554 /// Act on the result of classifying a name as an overload set.
2555 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2556
2557 /// Describes the detailed kind of a template name. Used in diagnostics.
2558 enum class TemplateNameKindForDiagnostics {
2559 ClassTemplate,
2560 FunctionTemplate,
2561 VarTemplate,
2562 AliasTemplate,
2563 TemplateTemplateParam,
2564 Concept,
2565 DependentTemplate
2566 };
2567 TemplateNameKindForDiagnostics
2568 getTemplateNameKindForDiagnostics(TemplateName Name);
2569
2570 /// Determine whether it's plausible that E was intended to be a
2571 /// template-name.
2572 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2573 if (!getLangOpts().CPlusPlus || E.isInvalid())
2574 return false;
2575 Dependent = false;
2576 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2577 return !DRE->hasExplicitTemplateArgs();
2578 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2579 return !ME->hasExplicitTemplateArgs();
2580 Dependent = true;
2581 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2582 return !DSDRE->hasExplicitTemplateArgs();
2583 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2584 return !DSME->hasExplicitTemplateArgs();
2585 // Any additional cases recognized here should also be handled by
2586 // diagnoseExprIntendedAsTemplateName.
2587 return false;
2588 }
2589 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2590 SourceLocation Less,
2591 SourceLocation Greater);
2592
2593 void warnOnReservedIdentifier(const NamedDecl *D);
2594
2595 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2596
2597 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2598 MultiTemplateParamsArg TemplateParameterLists);
2599 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2600 QualType &T, SourceLocation Loc,
2601 unsigned FailedFoldDiagID);
2602 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2603 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2604 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2605 DeclarationName Name, SourceLocation Loc,
2606 bool IsTemplateId);
2607 void
2608 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2609 SourceLocation FallbackLoc,
2610 SourceLocation ConstQualLoc = SourceLocation(),
2611 SourceLocation VolatileQualLoc = SourceLocation(),
2612 SourceLocation RestrictQualLoc = SourceLocation(),
2613 SourceLocation AtomicQualLoc = SourceLocation(),
2614 SourceLocation UnalignedQualLoc = SourceLocation());
2615
2616 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2617 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2618 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2619 const LookupResult &R);
2620 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2621 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2622 const LookupResult &R);
2623 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2624 const LookupResult &R);
2625 void CheckShadow(Scope *S, VarDecl *D);
2626
2627 /// Warn if 'E', which is an expression that is about to be modified, refers
2628 /// to a shadowing declaration.
2629 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2630
2631 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2632
2633private:
2634 /// Map of current shadowing declarations to shadowed declarations. Warn if
2635 /// it looks like the user is trying to modify the shadowing declaration.
2636 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2637
2638public:
2639 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2640 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2641 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2642 TypedefNameDecl *NewTD);
2643 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2644 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2645 TypeSourceInfo *TInfo,
2646 LookupResult &Previous);
2647 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2648 LookupResult &Previous, bool &Redeclaration);
2649 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2650 TypeSourceInfo *TInfo,
2651 LookupResult &Previous,
2652 MultiTemplateParamsArg TemplateParamLists,
2653 bool &AddToScope,
2654 ArrayRef<BindingDecl *> Bindings = None);
2655 NamedDecl *
2656 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2657 MultiTemplateParamsArg TemplateParamLists);
2658 // Returns true if the variable declaration is a redeclaration
2659 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2660 void CheckVariableDeclarationType(VarDecl *NewVD);
2661 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2662 Expr *Init);
2663 void CheckCompleteVariableDeclaration(VarDecl *VD);
2664 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2665 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2666
2667 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2668 TypeSourceInfo *TInfo,
2669 LookupResult &Previous,
2670 MultiTemplateParamsArg TemplateParamLists,
2671 bool &AddToScope);
2672 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2673
2674 enum class CheckConstexprKind {
2675 /// Diagnose issues that are non-constant or that are extensions.
2676 Diagnose,
2677 /// Identify whether this function satisfies the formal rules for constexpr
2678 /// functions in the current lanugage mode (with no extensions).
2679 CheckValid
2680 };
2681
2682 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2683 CheckConstexprKind Kind);
2684
2685 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2686 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2687 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2688 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2689 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2690 // Returns true if the function declaration is a redeclaration
2691 bool CheckFunctionDeclaration(Scope *S,
2692 FunctionDecl *NewFD, LookupResult &Previous,
2693 bool IsMemberSpecialization);
2694 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2695 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2696 QualType NewT, QualType OldT);
2697 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2698 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2699 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2700 bool IsDefinition);
2701 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2702 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2703 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2704 SourceLocation Loc,
2705 QualType T);
2706 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2707 SourceLocation NameLoc, IdentifierInfo *Name,
2708 QualType T, TypeSourceInfo *TSInfo,
2709 StorageClass SC);
2710 void ActOnParamDefaultArgument(Decl *param,
2711 SourceLocation EqualLoc,
2712 Expr *defarg);
2713 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2714 SourceLocation ArgLoc);
2715 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2716 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2717 SourceLocation EqualLoc);
2718 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2719 SourceLocation EqualLoc);
2720
2721 // Contexts where using non-trivial C union types can be disallowed. This is
2722 // passed to err_non_trivial_c_union_in_invalid_context.
2723 enum NonTrivialCUnionContext {
2724 // Function parameter.
2725 NTCUC_FunctionParam,
2726 // Function return.
2727 NTCUC_FunctionReturn,
2728 // Default-initialized object.
2729 NTCUC_DefaultInitializedObject,
2730 // Variable with automatic storage duration.
2731 NTCUC_AutoVar,
2732 // Initializer expression that might copy from another object.
2733 NTCUC_CopyInit,
2734 // Assignment.
2735 NTCUC_Assignment,
2736 // Compound literal.
2737 NTCUC_CompoundLiteral,
2738 // Block capture.
2739 NTCUC_BlockCapture,
2740 // lvalue-to-rvalue conversion of volatile type.
2741 NTCUC_LValueToRValueVolatile,
2742 };
2743
2744 /// Emit diagnostics if the initializer or any of its explicit or
2745 /// implicitly-generated subexpressions require copying or
2746 /// default-initializing a type that is or contains a C union type that is
2747 /// non-trivial to copy or default-initialize.
2748 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2749
2750 // These flags are passed to checkNonTrivialCUnion.
2751 enum NonTrivialCUnionKind {
2752 NTCUK_Init = 0x1,
2753 NTCUK_Destruct = 0x2,
2754 NTCUK_Copy = 0x4,
2755 };
2756
2757 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2758 /// a non-trivial C union is used in an invalid context.
2759 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2760 NonTrivialCUnionContext UseContext,
2761 unsigned NonTrivialKind);
2762
2763 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2764 void ActOnUninitializedDecl(Decl *dcl);
2765 void ActOnInitializerError(Decl *Dcl);
2766
2767 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2768 void ActOnCXXForRangeDecl(Decl *D);
2769 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2770 IdentifierInfo *Ident,
2771 ParsedAttributes &Attrs,
2772 SourceLocation AttrEnd);
2773 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2774 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2775 void CheckStaticLocalForDllExport(VarDecl *VD);
2776 void FinalizeDeclaration(Decl *D);
2777 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2778 ArrayRef<Decl *> Group);
2779 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2780
2781 /// Should be called on all declarations that might have attached
2782 /// documentation comments.
2783 void ActOnDocumentableDecl(Decl *D);
2784 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2785
2786 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2787 SourceLocation LocAfterDecls);
2788 void CheckForFunctionRedefinition(
2789 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2790 SkipBodyInfo *SkipBody = nullptr);
2791 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2792 MultiTemplateParamsArg TemplateParamLists,
2793 SkipBodyInfo *SkipBody = nullptr);
2794 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2795 SkipBodyInfo *SkipBody = nullptr);
2796 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2797 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2798 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
2799 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2800 bool isObjCMethodDecl(Decl *D) {
2801 return D && isa<ObjCMethodDecl>(D);
2802 }
2803
2804 /// Determine whether we can delay parsing the body of a function or
2805 /// function template until it is used, assuming we don't care about emitting
2806 /// code for that function.
2807 ///
2808 /// This will be \c false if we may need the body of the function in the
2809 /// middle of parsing an expression (where it's impractical to switch to
2810 /// parsing a different function), for instance, if it's constexpr in C++11
2811 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2812 bool canDelayFunctionBody(const Declarator &D);
2813
2814 /// Determine whether we can skip parsing the body of a function
2815 /// definition, assuming we don't care about analyzing its body or emitting
2816 /// code for that function.
2817 ///
2818 /// This will be \c false only if we may need the body of the function in
2819 /// order to parse the rest of the program (for instance, if it is
2820 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2821 bool canSkipFunctionBody(Decl *D);
2822
2823 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2824 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2825 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2826 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2827 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2828
2829 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2830 /// attribute for which parsing is delayed.
2831 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2832
2833 /// Diagnose any unused parameters in the given sequence of
2834 /// ParmVarDecl pointers.
2835 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2836
2837 /// Diagnose whether the size of parameters or return value of a
2838 /// function or obj-c method definition is pass-by-value and larger than a
2839 /// specified threshold.
2840 void
2841 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2842 QualType ReturnTy, NamedDecl *D);
2843
2844 void DiagnoseInvalidJumps(Stmt *Body);
2845 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2846 SourceLocation AsmLoc,
2847 SourceLocation RParenLoc);
2848
2849 /// Handle a C++11 empty-declaration and attribute-declaration.
2850 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2851 SourceLocation SemiLoc);
2852
2853 enum class ModuleDeclKind {
2854 Interface, ///< 'export module X;'
2855 Implementation, ///< 'module X;'
2856 };
2857
2858 /// The parser has processed a module-declaration that begins the definition
2859 /// of a module interface or implementation.
2860 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2861 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2862 ModuleIdPath Path, bool IsFirstDecl);
2863
2864 /// The parser has processed a global-module-fragment declaration that begins
2865 /// the definition of the global module fragment of the current module unit.
2866 /// \param ModuleLoc The location of the 'module' keyword.
2867 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2868
2869 /// The parser has processed a private-module-fragment declaration that begins
2870 /// the definition of the private module fragment of the current module unit.
2871 /// \param ModuleLoc The location of the 'module' keyword.
2872 /// \param PrivateLoc The location of the 'private' keyword.
2873 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2874 SourceLocation PrivateLoc);
2875
2876 /// The parser has processed a module import declaration.
2877 ///
2878 /// \param StartLoc The location of the first token in the declaration. This
2879 /// could be the location of an '@', 'export', or 'import'.
2880 /// \param ExportLoc The location of the 'export' keyword, if any.
2881 /// \param ImportLoc The location of the 'import' keyword.
2882 /// \param Path The module access path.
2883 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2884 SourceLocation ExportLoc,
2885 SourceLocation ImportLoc, ModuleIdPath Path);
2886 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2887 SourceLocation ExportLoc,
2888 SourceLocation ImportLoc, Module *M,
2889 ModuleIdPath Path = {});
2890
2891 /// The parser has processed a module import translated from a
2892 /// #include or similar preprocessing directive.
2893 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2894 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2895
2896 /// The parsed has entered a submodule.
2897 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2898 /// The parser has left a submodule.
2899 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2900
2901 /// Create an implicit import of the given module at the given
2902 /// source location, for error recovery, if possible.
2903 ///
2904 /// This routine is typically used when an entity found by name lookup
2905 /// is actually hidden within a module that we know about but the user
2906 /// has forgotten to import.
2907 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2908 Module *Mod);
2909
2910 /// Kinds of missing import. Note, the values of these enumerators correspond
2911 /// to %select values in diagnostics.
2912 enum class MissingImportKind {
2913 Declaration,
2914 Definition,
2915 DefaultArgument,
2916 ExplicitSpecialization,
2917 PartialSpecialization
2918 };
2919
2920 /// Diagnose that the specified declaration needs to be visible but
2921 /// isn't, and suggest a module import that would resolve the problem.
2922 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2923 MissingImportKind MIK, bool Recover = true);
2924 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2925 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2926 MissingImportKind MIK, bool Recover);
2927
2928 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2929 SourceLocation LBraceLoc);
2930 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2931 SourceLocation RBraceLoc);
2932
2933 /// We've found a use of a templated declaration that would trigger an
2934 /// implicit instantiation. Check that any relevant explicit specializations
2935 /// and partial specializations are visible, and diagnose if not.
2936 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2937
2938 /// Retrieve a suitable printing policy for diagnostics.
2939 PrintingPolicy getPrintingPolicy() const {
2940 return getPrintingPolicy(Context, PP);
2941 }
2942
2943 /// Retrieve a suitable printing policy for diagnostics.
2944 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2945 const Preprocessor &PP);
2946
2947 /// Scope actions.
2948 void ActOnPopScope(SourceLocation Loc, Scope *S);
2949 void ActOnTranslationUnitScope(Scope *S);
2950
2951 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2952 RecordDecl *&AnonRecord);
2953 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2954 MultiTemplateParamsArg TemplateParams,
2955 bool IsExplicitInstantiation,
2956 RecordDecl *&AnonRecord);
2957
2958 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2959 AccessSpecifier AS,
2960 RecordDecl *Record,
2961 const PrintingPolicy &Policy);
2962
2963 Decl *BuildMicrosoftCAnonymousStruct(