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

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/StmtOpenMP.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/TypeOrdering.h"
38#include "clang/Basic/BitmaskEnum.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/DarwinSDKInfo.h"
41#include "clang/Basic/ExpressionTraits.h"
42#include "clang/Basic/Module.h"
43#include "clang/Basic/OpenCLOptions.h"
44#include "clang/Basic/OpenMPKinds.h"
45#include "clang/Basic/PragmaKinds.h"
46#include "clang/Basic/Specifiers.h"
47#include "clang/Basic/TemplateKinds.h"
48#include "clang/Basic/TypeTraits.h"
49#include "clang/Sema/AnalysisBasedWarnings.h"
50#include "clang/Sema/CleanupInfo.h"
51#include "clang/Sema/DeclSpec.h"
52#include "clang/Sema/ExternalSemaSource.h"
53#include "clang/Sema/IdentifierResolver.h"
54#include "clang/Sema/ObjCMethodList.h"
55#include "clang/Sema/Ownership.h"
56#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaConcept.h"
58#include "clang/Sema/TypoCorrection.h"
59#include "clang/Sema/Weak.h"
60#include "llvm/ADT/ArrayRef.h"
61#include "llvm/ADT/SetVector.h"
62#include "llvm/ADT/SmallBitVector.h"
63#include "llvm/ADT/SmallPtrSet.h"
64#include "llvm/ADT/SmallSet.h"
65#include "llvm/ADT/SmallVector.h"
66#include "llvm/ADT/TinyPtrVector.h"
67#include "llvm/Frontend/OpenMP/OMPConstants.h"
68#include <deque>
69#include <memory>
70#include <optional>
71#include <string>
72#include <tuple>
73#include <vector>
74
75namespace llvm {
76 class APSInt;
77 template <typename ValueT, typename ValueInfoT> class DenseSet;
78 class SmallBitVector;
79 struct InlineAsmIdentifierInfo;
80}
81
82namespace clang {
83 class ADLResult;
84 class ASTConsumer;
85 class ASTContext;
86 class ASTMutationListener;
87 class ASTReader;
88 class ASTWriter;
89 class ArrayType;
90 class ParsedAttr;
91 class BindingDecl;
92 class BlockDecl;
93 class CapturedDecl;
94 class CXXBasePath;
95 class CXXBasePaths;
96 class CXXBindTemporaryExpr;
97 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98 class CXXConstructorDecl;
99 class CXXConversionDecl;
100 class CXXDeleteExpr;
101 class CXXDestructorDecl;
102 class CXXFieldCollector;
103 class CXXMemberCallExpr;
104 class CXXMethodDecl;
105 class CXXScopeSpec;
106 class CXXTemporary;
107 class CXXTryStmt;
108 class CallExpr;
109 class ClassTemplateDecl;
110 class ClassTemplatePartialSpecializationDecl;
111 class ClassTemplateSpecializationDecl;
112 class VarTemplatePartialSpecializationDecl;
113 class CodeCompleteConsumer;
114 class CodeCompletionAllocator;
115 class CodeCompletionTUInfo;
116 class CodeCompletionResult;
117 class CoroutineBodyStmt;
118 class Decl;
119 class DeclAccessPair;
120 class DeclContext;
121 class DeclRefExpr;
122 class DeclaratorDecl;
123 class DeducedTemplateArgument;
124 class DependentDiagnostic;
125 class DesignatedInitExpr;
126 class Designation;
127 class EnableIfAttr;
128 class EnumConstantDecl;
129 class Expr;
130 class ExtVectorType;
131 class FormatAttr;
132 class FriendDecl;
133 class FunctionDecl;
134 class FunctionProtoType;
135 class FunctionTemplateDecl;
136 class ImplicitConversionSequence;
137 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138 class InitListExpr;
139 class InitializationKind;
140 class InitializationSequence;
141 class InitializedEntity;
142 class IntegerLiteral;
143 class LabelStmt;
144 class LambdaExpr;
145 class LangOptions;
146 class LocalInstantiationScope;
147 class LookupResult;
148 class MacroInfo;
149 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150 class ModuleLoader;
151 class MultiLevelTemplateArgumentList;
152 class NamedDecl;
153 class ObjCCategoryDecl;
154 class ObjCCategoryImplDecl;
155 class ObjCCompatibleAliasDecl;
156 class ObjCContainerDecl;
157 class ObjCImplDecl;
158 class ObjCImplementationDecl;
159 class ObjCInterfaceDecl;
160 class ObjCIvarDecl;
161 template <class T> class ObjCList;
162 class ObjCMessageExpr;
163 class ObjCMethodDecl;
164 class ObjCPropertyDecl;
165 class ObjCProtocolDecl;
166 class OMPThreadPrivateDecl;
167 class OMPRequiresDecl;
168 class OMPDeclareReductionDecl;
169 class OMPDeclareSimdDecl;
170 class OMPClause;
171 struct OMPVarListLocTy;
172 struct OverloadCandidate;
173 enum class OverloadCandidateParamOrder : char;
174 enum OverloadCandidateRewriteKind : unsigned;
175 class OverloadCandidateSet;
176 class OverloadExpr;
177 class ParenListExpr;
178 class ParmVarDecl;
179 class Preprocessor;
180 class PseudoDestructorTypeStorage;
181 class PseudoObjectExpr;
182 class QualType;
183 class StandardConversionSequence;
184 class Stmt;
185 class StringLiteral;
186 class SwitchStmt;
187 class TemplateArgument;
188 class TemplateArgumentList;
189 class TemplateArgumentLoc;
190 class TemplateDecl;
191 class TemplateInstantiationCallback;
192 class TemplateParameterList;
193 class TemplatePartialOrderingContext;
194 class TemplateTemplateParmDecl;
195 class Token;
196 class TypeAliasDecl;
197 class TypedefDecl;
198 class TypedefNameDecl;
199 class TypeLoc;
200 class TypoCorrectionConsumer;
201 class UnqualifiedId;
202 class UnresolvedLookupExpr;
203 class UnresolvedMemberExpr;
204 class UnresolvedSetImpl;
205 class UnresolvedSetIterator;
206 class UsingDecl;
207 class UsingShadowDecl;
208 class ValueDecl;
209 class VarDecl;
210 class VarTemplateSpecializationDecl;
211 class VisibilityAttr;
212 class VisibleDeclConsumer;
213 class IndirectFieldDecl;
214 struct DeductionFailureInfo;
215 class TemplateSpecCandidateSet;
216
217namespace sema {
218 class AccessedEntity;
219 class BlockScopeInfo;
220 class Capture;
221 class CapturedRegionScopeInfo;
222 class CapturingScopeInfo;
223 class CompoundScopeInfo;
224 class DelayedDiagnostic;
225 class DelayedDiagnosticPool;
226 class FunctionScopeInfo;
227 class LambdaScopeInfo;
228 class PossiblyUnreachableDiag;
229 class RISCVIntrinsicManager;
230 class SemaPPCallbacks;
231 class TemplateDeductionInfo;
232}
233
234namespace threadSafety {
235 class BeforeSet;
236 void threadSafetyCleanup(BeforeSet* Cache);
237}
238
239// FIXME: No way to easily map from TemplateTypeParmTypes to
240// TemplateTypeParmDecls, so we have this horrible PointerUnion.
241typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
242 SourceLocation>
243 UnexpandedParameterPack;
244
245/// Describes whether we've seen any nullability information for the given
246/// file.
247struct FileNullability {
248 /// The first pointer declarator (of any pointer kind) in the file that does
249 /// not have a corresponding nullability annotation.
250 SourceLocation PointerLoc;
251
252 /// The end location for the first pointer declarator in the file. Used for
253 /// placing fix-its.
254 SourceLocation PointerEndLoc;
255
256 /// Which kind of pointer declarator we saw.
257 uint8_t PointerKind;
258
259 /// Whether we saw any type nullability annotations in the given file.
260 bool SawTypeNullability = false;
261};
262
263/// A mapping from file IDs to a record of whether we've seen nullability
264/// information in that file.
265class FileNullabilityMap {
266 /// A mapping from file IDs to the nullability information for each file ID.
267 llvm::DenseMap<FileID, FileNullability> Map;
268
269 /// A single-element cache based on the file ID.
270 struct {
271 FileID File;
272 FileNullability Nullability;
273 } Cache;
274
275public:
276 FileNullability &operator[](FileID file) {
277 // Check the single-element cache.
278 if (file == Cache.File)
279 return Cache.Nullability;
280
281 // It's not in the single-element cache; flush the cache if we have one.
282 if (!Cache.File.isInvalid()) {
283 Map[Cache.File] = Cache.Nullability;
284 }
285
286 // Pull this entry into the cache.
287 Cache.File = file;
288 Cache.Nullability = Map[file];
289 return Cache.Nullability;
290 }
291};
292
293/// Tracks expected type during expression parsing, for use in code completion.
294/// The type is tied to a particular token, all functions that update or consume
295/// the type take a start location of the token they are looking at as a
296/// parameter. This avoids updating the type on hot paths in the parser.
297class PreferredTypeBuilder {
298public:
299 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
300
301 void enterCondition(Sema &S, SourceLocation Tok);
302 void enterReturn(Sema &S, SourceLocation Tok);
303 void enterVariableInit(SourceLocation Tok, Decl *D);
304 /// Handles e.g. BaseType{ .D = Tok...
305 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
306 const Designation &D);
307 /// Computing a type for the function argument may require running
308 /// overloading, so we postpone its computation until it is actually needed.
309 ///
310 /// Clients should be very careful when using this function, as it stores a
311 /// function_ref, clients should make sure all calls to get() with the same
312 /// location happen while function_ref is alive.
313 ///
314 /// The callback should also emit signature help as a side-effect, but only
315 /// if the completion point has been reached.
316 void enterFunctionArgument(SourceLocation Tok,
317 llvm::function_ref<QualType()> ComputeType);
318
319 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
320 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
321 SourceLocation OpLoc);
322 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
323 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
324 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
325 /// Handles all type casts, including C-style cast, C++ casts, etc.
326 void enterTypeCast(SourceLocation Tok, QualType CastType);
327
328 /// Get the expected type associated with this location, if any.
329 ///
330 /// If the location is a function argument, determining the expected type
331 /// involves considering all function overloads and the arguments so far.
332 /// In this case, signature help for these function overloads will be reported
333 /// as a side-effect (only if the completion point has been reached).
334 QualType get(SourceLocation Tok) const {
335 if (!Enabled || Tok != ExpectedLoc)
336 return QualType();
337 if (!Type.isNull())
338 return Type;
339 if (ComputeType)
340 return ComputeType();
341 return QualType();
342 }
343
344private:
345 bool Enabled;
346 /// Start position of a token for which we store expected type.
347 SourceLocation ExpectedLoc;
348 /// Expected type for a token starting at ExpectedLoc.
349 QualType Type;
350 /// A function to compute expected type at ExpectedLoc. It is only considered
351 /// if Type is null.
352 llvm::function_ref<QualType()> ComputeType;
353};
354
355/// Sema - This implements semantic analysis and AST building for C.
356class Sema final {
357 Sema(const Sema &) = delete;
358 void operator=(const Sema &) = delete;
359
360 ///Source of additional semantic information.
361 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
362
363 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
364
365 /// Determine whether two declarations should be linked together, given that
366 /// the old declaration might not be visible and the new declaration might
367 /// not have external linkage.
368 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
369 const NamedDecl *New) {
370 if (isVisible(Old))
371 return true;
372 // See comment in below overload for why it's safe to compute the linkage
373 // of the new declaration here.
374 if (New->isExternallyDeclarable()) {
375 assert(Old->isExternallyDeclarable() &&
376 "should not have found a non-externally-declarable previous decl");
377 return true;
378 }
379 return false;
380 }
381 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
382
383 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
384 QualType ResultTy,
385 ArrayRef<QualType> Args);
386
387public:
388 /// The maximum alignment, same as in llvm::Value. We duplicate them here
389 /// because that allows us not to duplicate the constants in clang code,
390 /// which we must to since we can't directly use the llvm constants.
391 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
392 ///
393 /// This is the greatest alignment value supported by load, store, and alloca
394 /// instructions, and global values.
395 static const unsigned MaxAlignmentExponent = 32;
396 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
397
398 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
399 typedef OpaquePtr<TemplateName> TemplateTy;
400 typedef OpaquePtr<QualType> TypeTy;
401
402 OpenCLOptions OpenCLFeatures;
403 FPOptions CurFPFeatures;
404
405 const LangOptions &LangOpts;
406 Preprocessor &PP;
407 ASTContext &Context;
408 ASTConsumer &Consumer;
409 DiagnosticsEngine &Diags;
410 SourceManager &SourceMgr;
411
412 /// Flag indicating whether or not to collect detailed statistics.
413 bool CollectStats;
414
415 /// Code-completion consumer.
416 CodeCompleteConsumer *CodeCompleter;
417
418 /// CurContext - This is the current declaration context of parsing.
419 DeclContext *CurContext;
420
421 /// Generally null except when we temporarily switch decl contexts,
422 /// like in \see ActOnObjCTemporaryExitContainerContext.
423 DeclContext *OriginalLexicalContext;
424
425 /// VAListTagName - The declaration name corresponding to __va_list_tag.
426 /// This is used as part of a hack to omit that class from ADL results.
427 DeclarationName VAListTagName;
428
429 bool MSStructPragmaOn; // True when \#pragma ms_struct on
430
431 /// Controls member pointer representation format under the MS ABI.
432 LangOptions::PragmaMSPointersToMembersKind
433 MSPointerToMemberRepresentationMethod;
434
435 /// Stack of active SEH __finally scopes. Can be empty.
436 SmallVector<Scope*, 2> CurrentSEHFinally;
437
438 /// Source location for newly created implicit MSInheritanceAttrs
439 SourceLocation ImplicitMSInheritanceAttrLoc;
440
441 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
442 /// `TransformTypos` in order to keep track of any TypoExprs that are created
443 /// recursively during typo correction and wipe them away if the correction
444 /// fails.
445 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
446
447 /// pragma clang section kind
448 enum PragmaClangSectionKind {
449 PCSK_Invalid = 0,
450 PCSK_BSS = 1,
451 PCSK_Data = 2,
452 PCSK_Rodata = 3,
453 PCSK_Text = 4,
454 PCSK_Relro = 5
455 };
456
457 enum PragmaClangSectionAction {
458 PCSA_Set = 0,
459 PCSA_Clear = 1
460 };
461
462 struct PragmaClangSection {
463 std::string SectionName;
464 bool Valid = false;
465 SourceLocation PragmaLocation;
466 };
467
468 PragmaClangSection PragmaClangBSSSection;
469 PragmaClangSection PragmaClangDataSection;
470 PragmaClangSection PragmaClangRodataSection;
471 PragmaClangSection PragmaClangRelroSection;
472 PragmaClangSection PragmaClangTextSection;
473
474 enum PragmaMsStackAction {
475 PSK_Reset = 0x0, // #pragma ()
476 PSK_Set = 0x1, // #pragma (value)
477 PSK_Push = 0x2, // #pragma (push[, id])
478 PSK_Pop = 0x4, // #pragma (pop[, id])
479 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
480 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
481 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
482 };
483
484 struct PragmaPackInfo {
485 PragmaMsStackAction Action;
486 StringRef SlotLabel;
487 Token Alignment;
488 };
489
490 // #pragma pack and align.
491 class AlignPackInfo {
492 public:
493 // `Native` represents default align mode, which may vary based on the
494 // platform.
495 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
496
497 // #pragma pack info constructor
498 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
499 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
500 assert(Num == PackNumber && "The pack number has been truncated.");
501 }
502
503 // #pragma align info constructor
504 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
505 : PackAttr(false), AlignMode(M),
506 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
507
508 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
509
510 AlignPackInfo() : AlignPackInfo(Native, false) {}
511
512 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
513 // integer encoding for it. This should only be passed to
514 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
515 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
516 std::uint32_t Encoding{};
517 if (Info.IsXLStack())
518 Encoding |= IsXLMask;
519
520 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
521
522 if (Info.IsPackAttr())
523 Encoding |= PackAttrMask;
524
525 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
526
527 return Encoding;
528 }
529
530 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
531 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
532 AlignPackInfo::Mode M =
533 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
534 int PackNumber = (Encoding & PackNumMask) >> 4;
535
536 if (Encoding & PackAttrMask)
537 return AlignPackInfo(M, PackNumber, IsXL);
538
539 return AlignPackInfo(M, IsXL);
540 }
541
542 bool IsPackAttr() const { return PackAttr; }
543
544 bool IsAlignAttr() const { return !PackAttr; }
545
546 Mode getAlignMode() const { return AlignMode; }
547
548 unsigned getPackNumber() const { return PackNumber; }
549
550 bool IsPackSet() const {
551 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
552 // attriute on a decl.
553 return PackNumber != UninitPackVal && PackNumber != 0;
554 }
555
556 bool IsXLStack() const { return XLStack; }
557
558 bool operator==(const AlignPackInfo &Info) const {
559 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
560 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
561 Info.XLStack);
562 }
563
564 bool operator!=(const AlignPackInfo &Info) const {
565 return !(*this == Info);
566 }
567
568 private:
569 /// \brief True if this is a pragma pack attribute,
570 /// not a pragma align attribute.
571 bool PackAttr;
572
573 /// \brief The alignment mode that is in effect.
574 Mode AlignMode;
575
576 /// \brief The pack number of the stack.
577 unsigned char PackNumber;
578
579 /// \brief True if it is a XL #pragma align/pack stack.
580 bool XLStack;
581
582 /// \brief Uninitialized pack value.
583 static constexpr unsigned char UninitPackVal = -1;
584
585 // Masks to encode and decode an AlignPackInfo.
586 static constexpr uint32_t IsXLMask{0x0000'0001};
587 static constexpr uint32_t AlignModeMask{0x0000'0006};
588 static constexpr uint32_t PackAttrMask{0x00000'0008};
589 static constexpr uint32_t PackNumMask{0x0000'01F0};
590 };
591
592 template<typename ValueType>
593 struct PragmaStack {
594 struct Slot {
595 llvm::StringRef StackSlotLabel;
596 ValueType Value;
597 SourceLocation PragmaLocation;
598 SourceLocation PragmaPushLocation;
599 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
600 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
601 : StackSlotLabel(StackSlotLabel), Value(Value),
602 PragmaLocation(PragmaLocation),
603 PragmaPushLocation(PragmaPushLocation) {}
604 };
605
606 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
607 llvm::StringRef StackSlotLabel, ValueType Value) {
608 if (Action == PSK_Reset) {
609 CurrentValue = DefaultValue;
610 CurrentPragmaLocation = PragmaLocation;
611 return;
612 }
613 if (Action & PSK_Push)
614 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
615 PragmaLocation);
616 else if (Action & PSK_Pop) {
617 if (!StackSlotLabel.empty()) {
618 // If we've got a label, try to find it and jump there.
619 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
620 return x.StackSlotLabel == StackSlotLabel;
621 });
622 // If we found the label so pop from there.
623 if (I != Stack.rend()) {
624 CurrentValue = I->Value;
625 CurrentPragmaLocation = I->PragmaLocation;
626 Stack.erase(std::prev(I.base()), Stack.end());
627 }
628 } else if (!Stack.empty()) {
629 // We do not have a label, just pop the last entry.
630 CurrentValue = Stack.back().Value;
631 CurrentPragmaLocation = Stack.back().PragmaLocation;
632 Stack.pop_back();
633 }
634 }
635 if (Action & PSK_Set) {
636 CurrentValue = Value;
637 CurrentPragmaLocation = PragmaLocation;
638 }
639 }
640
641 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
642 // method body to restore the stacks on exit, so it works like this:
643 //
644 // struct S {
645 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
646 // void Method {}
647 // #pragma <name>(pop, InternalPragmaSlot)
648 // };
649 //
650 // It works even with #pragma vtordisp, although MSVC doesn't support
651 // #pragma vtordisp(push [, id], n)
652 // syntax.
653 //
654 // Push / pop a named sentinel slot.
655 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
656 assert((Action == PSK_Push || Action == PSK_Pop) &&
657 "Can only push / pop #pragma stack sentinels!");
658 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
659 }
660
661 // Constructors.
662 explicit PragmaStack(const ValueType &Default)
663 : DefaultValue(Default), CurrentValue(Default) {}
664
665 bool hasValue() const { return CurrentValue != DefaultValue; }
666
667 SmallVector<Slot, 2> Stack;
668 ValueType DefaultValue; // Value used for PSK_Reset action.
669 ValueType CurrentValue;
670 SourceLocation CurrentPragmaLocation;
671 };
672 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
673 // we shouldn't do so if they're in a module).
674
675 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
676 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
677 ///
678 /// 0: Suppress all vtordisps
679 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
680 /// structors
681 /// 2: Always insert vtordisps to support RTTI on partially constructed
682 /// objects
683 PragmaStack<MSVtorDispMode> VtorDispStack;
684 PragmaStack<AlignPackInfo> AlignPackStack;
685 // The current #pragma align/pack values and locations at each #include.
686 struct AlignPackIncludeState {
687 AlignPackInfo CurrentValue;
688 SourceLocation CurrentPragmaLocation;
689 bool HasNonDefaultValue, ShouldWarnOnInclude;
690 };
691 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
692 // Segment #pragmas.
693 PragmaStack<StringLiteral *> DataSegStack;
694 PragmaStack<StringLiteral *> BSSSegStack;
695 PragmaStack<StringLiteral *> ConstSegStack;
696 PragmaStack<StringLiteral *> CodeSegStack;
697
698 // #pragma strict_gs_check.
699 PragmaStack<bool> StrictGuardStackCheckStack;
700
701 // This stack tracks the current state of Sema.CurFPFeatures.
702 PragmaStack<FPOptionsOverride> FpPragmaStack;
703 FPOptionsOverride CurFPFeatureOverrides() {
704 FPOptionsOverride result;
705 if (!FpPragmaStack.hasValue()) {
706 result = FPOptionsOverride();
707 } else {
708 result = FpPragmaStack.CurrentValue;
709 }
710 return result;
711 }
712
713 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
714 // Actions should be performed only if we enter / exit a C++ method body.
715 class PragmaStackSentinelRAII {
716 public:
717 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
718 ~PragmaStackSentinelRAII();
719
720 private:
721 Sema &S;
722 StringRef SlotLabel;
723 bool ShouldAct;
724 };
725
726 /// A mapping that describes the nullability we've seen in each header file.
727 FileNullabilityMap NullabilityMap;
728
729 /// Last section used with #pragma init_seg.
730 StringLiteral *CurInitSeg;
731 SourceLocation CurInitSegLoc;
732
733 /// Sections used with #pragma alloc_text.
734 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
735
736 /// VisContext - Manages the stack for \#pragma GCC visibility.
737 void *VisContext; // Really a "PragmaVisStack*"
738
739 /// This an attribute introduced by \#pragma clang attribute.
740 struct PragmaAttributeEntry {
741 SourceLocation Loc;
742 ParsedAttr *Attribute;
743 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
744 bool IsUsed;
745 };
746
747 /// A push'd group of PragmaAttributeEntries.
748 struct PragmaAttributeGroup {
749 /// The location of the push attribute.
750 SourceLocation Loc;
751 /// The namespace of this push group.
752 const IdentifierInfo *Namespace;
753 SmallVector<PragmaAttributeEntry, 2> Entries;
754 };
755
756 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
757
758 /// The declaration that is currently receiving an attribute from the
759 /// #pragma attribute stack.
760 const Decl *PragmaAttributeCurrentTargetDecl;
761
762 /// This represents the last location of a "#pragma clang optimize off"
763 /// directive if such a directive has not been closed by an "on" yet. If
764 /// optimizations are currently "on", this is set to an invalid location.
765 SourceLocation OptimizeOffPragmaLocation;
766
767 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
768 /// whether the optimizations in the list passed to the pragma should be
769 /// turned off or on. This boolean is true by default because command line
770 /// options are honored when `#pragma optimize("", on)`.
771 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
772 bool MSPragmaOptimizeIsOn = true;
773
774 /// Set of no-builtin functions listed by \#pragma function.
775 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
776
777 /// Flag indicating if Sema is building a recovery call expression.
778 ///
779 /// This flag is used to avoid building recovery call expressions
780 /// if Sema is already doing so, which would cause infinite recursions.
781 bool IsBuildingRecoveryCallExpr;
782
783 /// Used to control the generation of ExprWithCleanups.
784 CleanupInfo Cleanup;
785
786 /// ExprCleanupObjects - This is the stack of objects requiring
787 /// cleanup that are created by the current full expression.
788 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
789
790 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
791 /// to a variable (constant) that may or may not be odr-used in this Expr, and
792 /// we won't know until all lvalue-to-rvalue and discarded value conversions
793 /// have been applied to all subexpressions of the enclosing full expression.
794 /// This is cleared at the end of each full expression.
795 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
796 llvm::SmallPtrSet<Expr *, 4>>;
797 MaybeODRUseExprSet MaybeODRUseExprs;
798
799 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
800
801 /// Stack containing information about each of the nested
802 /// function, block, and method scopes that are currently active.
803 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
804
805 /// The index of the first FunctionScope that corresponds to the current
806 /// context.
807 unsigned FunctionScopesStart = 0;
808
809 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
810 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
811 FunctionScopes.end());
812 }
813
814 /// Stack containing information needed when in C++2a an 'auto' is encountered
815 /// in a function declaration parameter type specifier in order to invent a
816 /// corresponding template parameter in the enclosing abbreviated function
817 /// template. This information is also present in LambdaScopeInfo, stored in
818 /// the FunctionScopes stack.
819 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
820
821 /// The index of the first InventedParameterInfo that refers to the current
822 /// context.
823 unsigned InventedParameterInfosStart = 0;
824
825 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
826 return llvm::ArrayRef(InventedParameterInfos.begin() +
827 InventedParameterInfosStart,
828 InventedParameterInfos.end());
829 }
830
831 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
832 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
833 ExtVectorDeclsType;
834
835 /// ExtVectorDecls - This is a list all the extended vector types. This allows
836 /// us to associate a raw vector type with one of the ext_vector type names.
837 /// This is only necessary for issuing pretty diagnostics.
838 ExtVectorDeclsType ExtVectorDecls;
839
840 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
841 std::unique_ptr<CXXFieldCollector> FieldCollector;
842
843 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
844
845 /// Set containing all declared private fields that are not used.
846 NamedDeclSetType UnusedPrivateFields;
847
848 /// Set containing all typedefs that are likely unused.
849 llvm::SmallSetVector<const TypedefNameDecl *, 4>
850 UnusedLocalTypedefNameCandidates;
851
852 /// Delete-expressions to be analyzed at the end of translation unit
853 ///
854 /// This list contains class members, and locations of delete-expressions
855 /// that could not be proven as to whether they mismatch with new-expression
856 /// used in initializer of the field.
857 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
858 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
859 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
860
861 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
862
863 /// PureVirtualClassDiagSet - a set of class declarations which we have
864 /// emitted a list of pure virtual functions. Used to prevent emitting the
865 /// same list more than once.
866 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
867
868 /// ParsingInitForAutoVars - a set of declarations with auto types for which
869 /// we are currently parsing the initializer.
870 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
871
872 /// Look for a locally scoped extern "C" declaration by the given name.
873 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
874
875 typedef LazyVector<VarDecl *, ExternalSemaSource,
876 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
877 TentativeDefinitionsType;
878
879 /// All the tentative definitions encountered in the TU.
880 TentativeDefinitionsType TentativeDefinitions;
881
882 /// All the external declarations encoutered and used in the TU.
883 SmallVector<VarDecl *, 4> ExternalDeclarations;
884
885 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
886 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
887 UnusedFileScopedDeclsType;
888
889 /// The set of file scoped decls seen so far that have not been used
890 /// and must warn if not used. Only contains the first declaration.
891 UnusedFileScopedDeclsType UnusedFileScopedDecls;
892
893 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
894 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
895 DelegatingCtorDeclsType;
896
897 /// All the delegating constructors seen so far in the file, used for
898 /// cycle detection at the end of the TU.
899 DelegatingCtorDeclsType DelegatingCtorDecls;
900
901 /// All the overriding functions seen during a class definition
902 /// that had their exception spec checks delayed, plus the overridden
903 /// function.
904 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
905 DelayedOverridingExceptionSpecChecks;
906
907 /// All the function redeclarations seen during a class definition that had
908 /// their exception spec checks delayed, plus the prior declaration they
909 /// should be checked against. Except during error recovery, the new decl
910 /// should always be a friend declaration, as that's the only valid way to
911 /// redeclare a special member before its class is complete.
912 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
913 DelayedEquivalentExceptionSpecChecks;
914
915 typedef llvm::MapVector<const FunctionDecl *,
916 std::unique_ptr<LateParsedTemplate>>
917 LateParsedTemplateMapT;
918 LateParsedTemplateMapT LateParsedTemplateMap;
919
920 /// Callback to the parser to parse templated functions when needed.
921 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
922 typedef void LateTemplateParserCleanupCB(void *P);
923 LateTemplateParserCB *LateTemplateParser;
924 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
925 void *OpaqueParser;
926
927 void SetLateTemplateParser(LateTemplateParserCB *LTP,
928 LateTemplateParserCleanupCB *LTPCleanup,
929 void *P) {
930 LateTemplateParser = LTP;
931 LateTemplateParserCleanup = LTPCleanup;
932 OpaqueParser = P;
933 }
934
935 class DelayedDiagnostics;
936
937 class DelayedDiagnosticsState {
938 sema::DelayedDiagnosticPool *SavedPool;
939 friend class Sema::DelayedDiagnostics;
940 };
941 typedef DelayedDiagnosticsState ParsingDeclState;
942 typedef DelayedDiagnosticsState ProcessingContextState;
943
944 /// A class which encapsulates the logic for delaying diagnostics
945 /// during parsing and other processing.
946 class DelayedDiagnostics {
947 /// The current pool of diagnostics into which delayed
948 /// diagnostics should go.
949 sema::DelayedDiagnosticPool *CurPool = nullptr;
950
951 public:
952 DelayedDiagnostics() = default;
953
954 /// Adds a delayed diagnostic.
955 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
956
957 /// Determines whether diagnostics should be delayed.
958 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
959
960 /// Returns the current delayed-diagnostics pool.
961 sema::DelayedDiagnosticPool *getCurrentPool() const {
962 return CurPool;
963 }
964
965 /// Enter a new scope. Access and deprecation diagnostics will be
966 /// collected in this pool.
967 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
968 DelayedDiagnosticsState state;
969 state.SavedPool = CurPool;
970 CurPool = &pool;
971 return state;
972 }
973
974 /// Leave a delayed-diagnostic state that was previously pushed.
975 /// Do not emit any of the diagnostics. This is performed as part
976 /// of the bookkeeping of popping a pool "properly".
977 void popWithoutEmitting(DelayedDiagnosticsState state) {
978 CurPool = state.SavedPool;
979 }
980
981 /// Enter a new scope where access and deprecation diagnostics are
982 /// not delayed.
983 DelayedDiagnosticsState pushUndelayed() {
984 DelayedDiagnosticsState state;
985 state.SavedPool = CurPool;
986 CurPool = nullptr;
987 return state;
988 }
989
990 /// Undo a previous pushUndelayed().
991 void popUndelayed(DelayedDiagnosticsState state) {
992 assert(CurPool == nullptr);
993 CurPool = state.SavedPool;
994 }
995 } DelayedDiagnostics;
996
997 /// A RAII object to temporarily push a declaration context.
998 class ContextRAII {
999 private:
1000 Sema &S;
1001 DeclContext *SavedContext;
1002 ProcessingContextState SavedContextState;
1003 QualType SavedCXXThisTypeOverride;
1004 unsigned SavedFunctionScopesStart;
1005 unsigned SavedInventedParameterInfosStart;
1006
1007 public:
1008 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1009 : S(S), SavedContext(S.CurContext),
1010 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1011 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1012 SavedFunctionScopesStart(S.FunctionScopesStart),
1013 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1014 {
1015 assert(ContextToPush && "pushing null context");
1016 S.CurContext = ContextToPush;
1017 if (NewThisContext)
1018 S.CXXThisTypeOverride = QualType();
1019 // Any saved FunctionScopes do not refer to this context.
1020 S.FunctionScopesStart = S.FunctionScopes.size();
1021 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1022 }
1023
1024 void pop() {
1025 if (!SavedContext) return;
1026 S.CurContext = SavedContext;
1027 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1028 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1029 S.FunctionScopesStart = SavedFunctionScopesStart;
1030 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1031 SavedContext = nullptr;
1032 }
1033
1034 ~ContextRAII() {
1035 pop();
1036 }
1037 };
1038
1039 /// Whether the AST is currently being rebuilt to correct immediate
1040 /// invocations. Immediate invocation candidates and references to consteval
1041 /// functions aren't tracked when this is set.
1042 bool RebuildingImmediateInvocation = false;
1043
1044 /// Used to change context to isConstantEvaluated without pushing a heavy
1045 /// ExpressionEvaluationContextRecord object.
1046 bool isConstantEvaluatedOverride;
1047
1048 bool isConstantEvaluated() const {
1049 return ExprEvalContexts.back().isConstantEvaluated() ||
1050 isConstantEvaluatedOverride;
1051 }
1052
1053 /// RAII object to handle the state changes required to synthesize
1054 /// a function body.
1055 class SynthesizedFunctionScope {
1056 Sema &S;
1057 Sema::ContextRAII SavedContext;
1058 bool PushedCodeSynthesisContext = false;
1059
1060 public:
1061 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1062 : S(S), SavedContext(S, DC) {
1063 S.PushFunctionScope();
1064 S.PushExpressionEvaluationContext(
1065 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1066 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1067 FD->setWillHaveBody(true);
1068 else
1069 assert(isa<ObjCMethodDecl>(DC));
1070 }
1071
1072 void addContextNote(SourceLocation UseLoc) {
1073 assert(!PushedCodeSynthesisContext);
1074
1075 Sema::CodeSynthesisContext Ctx;
1076 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1077 Ctx.PointOfInstantiation = UseLoc;
1078 Ctx.Entity = cast<Decl>(S.CurContext);
1079 S.pushCodeSynthesisContext(Ctx);
1080
1081 PushedCodeSynthesisContext = true;
1082 }
1083
1084 ~SynthesizedFunctionScope() {
1085 if (PushedCodeSynthesisContext)
1086 S.popCodeSynthesisContext();
1087 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1088 FD->setWillHaveBody(false);
1089 S.PopExpressionEvaluationContext();
1090 S.PopFunctionScopeInfo();
1091 }
1092 };
1093
1094 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1095 /// declared. Rare. May alias another identifier, declared or undeclared.
1096 ///
1097 /// For aliases, the target identifier is used as a key for eventual
1098 /// processing when the target is declared. For the single-identifier form,
1099 /// the sole identifier is used as the key. Each entry is a `SetVector`
1100 /// (ordered by parse order) of aliases (identified by the alias name) in case
1101 /// of multiple aliases to the same undeclared identifier.
1102 llvm::MapVector<
1103 IdentifierInfo *,
1104 llvm::SetVector<
1105 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
1106 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1107 WeakUndeclaredIdentifiers;
1108
1109 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1110 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1111 /// to define functions that occur in multiple standards to call the version
1112 /// in the currently selected standard.
1113 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1114
1115
1116 /// Load weak undeclared identifiers from the external source.
1117 void LoadExternalWeakUndeclaredIdentifiers();
1118
1119 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1120 /// \#pragma weak during processing of other Decls.
1121 /// I couldn't figure out a clean way to generate these in-line, so
1122 /// we store them here and handle separately -- which is a hack.
1123 /// It would be best to refactor this.
1124 SmallVector<Decl*,2> WeakTopLevelDecl;
1125
1126 IdentifierResolver IdResolver;
1127
1128 /// Translation Unit Scope - useful to Objective-C actions that need
1129 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1130 /// For example, user-defined classes, built-in "id" type, etc.
1131 Scope *TUScope;
1132
1133 /// The C++ "std" namespace, where the standard library resides.
1134 LazyDeclPtr StdNamespace;
1135
1136 /// The C++ "std::bad_alloc" class, which is defined by the C++
1137 /// standard library.
1138 LazyDeclPtr StdBadAlloc;
1139
1140 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1141 /// standard library.
1142 LazyDeclPtr StdAlignValT;
1143
1144 /// The C++ "std::initializer_list" template, which is defined in
1145 /// \<initializer_list>.
1146 ClassTemplateDecl *StdInitializerList;
1147
1148 /// The C++ "std::coroutine_traits" template, which is defined in
1149 /// \<coroutine_traits>
1150 ClassTemplateDecl *StdCoroutineTraitsCache;
1151
1152 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1153 RecordDecl *CXXTypeInfoDecl;
1154
1155 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1156 RecordDecl *MSVCGuidDecl;
1157
1158 /// The C++ "std::source_location::__impl" struct, defined in
1159 /// \<source_location>.
1160 RecordDecl *StdSourceLocationImplDecl;
1161
1162 /// Caches identifiers/selectors for NSFoundation APIs.
1163 std::unique_ptr<NSAPI> NSAPIObj;
1164
1165 /// The declaration of the Objective-C NSNumber class.
1166 ObjCInterfaceDecl *NSNumberDecl;
1167
1168 /// The declaration of the Objective-C NSValue class.
1169 ObjCInterfaceDecl *NSValueDecl;
1170
1171 /// Pointer to NSNumber type (NSNumber *).
1172 QualType NSNumberPointer;
1173
1174 /// Pointer to NSValue type (NSValue *).
1175 QualType NSValuePointer;
1176
1177 /// The Objective-C NSNumber methods used to create NSNumber literals.
1178 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1179
1180 /// The declaration of the Objective-C NSString class.
1181 ObjCInterfaceDecl *NSStringDecl;
1182
1183 /// Pointer to NSString type (NSString *).
1184 QualType NSStringPointer;
1185
1186 /// The declaration of the stringWithUTF8String: method.
1187 ObjCMethodDecl *StringWithUTF8StringMethod;
1188
1189 /// The declaration of the valueWithBytes:objCType: method.
1190 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1191
1192 /// The declaration of the Objective-C NSArray class.
1193 ObjCInterfaceDecl *NSArrayDecl;
1194
1195 /// The declaration of the arrayWithObjects:count: method.
1196 ObjCMethodDecl *ArrayWithObjectsMethod;
1197
1198 /// The declaration of the Objective-C NSDictionary class.
1199 ObjCInterfaceDecl *NSDictionaryDecl;
1200
1201 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1202 ObjCMethodDecl *DictionaryWithObjectsMethod;
1203
1204 /// id<NSCopying> type.
1205 QualType QIDNSCopying;
1206
1207 /// will hold 'respondsToSelector:'
1208 Selector RespondsToSelectorSel;
1209
1210 /// A flag to remember whether the implicit forms of operator new and delete
1211 /// have been declared.
1212 bool GlobalNewDeleteDeclared;
1213
1214 /// Describes how the expressions currently being parsed are
1215 /// evaluated at run-time, if at all.
1216 enum class ExpressionEvaluationContext {
1217 /// The current expression and its subexpressions occur within an
1218 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1219 /// \c sizeof, where the type of the expression may be significant but
1220 /// no code will be generated to evaluate the value of the expression at
1221 /// run time.
1222 Unevaluated,
1223
1224 /// The current expression occurs within a braced-init-list within
1225 /// an unevaluated operand. This is mostly like a regular unevaluated
1226 /// context, except that we still instantiate constexpr functions that are
1227 /// referenced here so that we can perform narrowing checks correctly.
1228 UnevaluatedList,
1229
1230 /// The current expression occurs within a discarded statement.
1231 /// This behaves largely similarly to an unevaluated operand in preventing
1232 /// definitions from being required, but not in other ways.
1233 DiscardedStatement,
1234
1235 /// The current expression occurs within an unevaluated
1236 /// operand that unconditionally permits abstract references to
1237 /// fields, such as a SIZE operator in MS-style inline assembly.
1238 UnevaluatedAbstract,
1239
1240 /// The current context is "potentially evaluated" in C++11 terms,
1241 /// but the expression is evaluated at compile-time (like the values of
1242 /// cases in a switch statement).
1243 ConstantEvaluated,
1244
1245 /// In addition of being constant evaluated, the current expression
1246 /// occurs in an immediate function context - either a consteval function
1247 /// or a consteval if function.
1248 ImmediateFunctionContext,
1249
1250 /// The current expression is potentially evaluated at run time,
1251 /// which means that code may be generated to evaluate the value of the
1252 /// expression at run time.
1253 PotentiallyEvaluated,
1254
1255 /// The current expression is potentially evaluated, but any
1256 /// declarations referenced inside that expression are only used if
1257 /// in fact the current expression is used.
1258 ///
1259 /// This value is used when parsing default function arguments, for which
1260 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1261 /// through varargs) but do not want to mark declarations as "referenced"
1262 /// until the default argument is used.
1263 PotentiallyEvaluatedIfUsed
1264 };
1265
1266 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1267
1268 /// Data structure used to record current or nested
1269 /// expression evaluation contexts.
1270 struct ExpressionEvaluationContextRecord {
1271 /// The expression evaluation context.
1272 ExpressionEvaluationContext Context;
1273
1274 /// Whether the enclosing context needed a cleanup.
1275 CleanupInfo ParentCleanup;
1276
1277 /// The number of active cleanup objects when we entered
1278 /// this expression evaluation context.
1279 unsigned NumCleanupObjects;
1280
1281 /// The number of typos encountered during this expression evaluation
1282 /// context (i.e. the number of TypoExprs created).
1283 unsigned NumTypos;
1284
1285 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1286
1287 /// The lambdas that are present within this context, if it
1288 /// is indeed an unevaluated context.
1289 SmallVector<LambdaExpr *, 2> Lambdas;
1290
1291 /// The declaration that provides context for lambda expressions
1292 /// and block literals if the normal declaration context does not
1293 /// suffice, e.g., in a default function argument.
1294 Decl *ManglingContextDecl;
1295
1296 /// If we are processing a decltype type, a set of call expressions
1297 /// for which we have deferred checking the completeness of the return type.
1298 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1299
1300 /// If we are processing a decltype type, a set of temporary binding
1301 /// expressions for which we have deferred checking the destructor.
1302 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1303
1304 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1305
1306 /// Expressions appearing as the LHS of a volatile assignment in this
1307 /// context. We produce a warning for these when popping the context if
1308 /// they are not discarded-value expressions nor unevaluated operands.
1309 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1310
1311 /// Set of candidates for starting an immediate invocation.
1312 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1313
1314 /// Set of DeclRefExprs referencing a consteval function when used in a
1315 /// context not already known to be immediately invoked.
1316 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1317
1318 /// \brief Describes whether we are in an expression constext which we have
1319 /// to handle differently.
1320 enum ExpressionKind {
1321 EK_Decltype, EK_TemplateArgument, EK_Other
1322 } ExprContext;
1323
1324 // A context can be nested in both a discarded statement context and
1325 // an immediate function context, so they need to be tracked independently.
1326 bool InDiscardedStatement;
1327 bool InImmediateFunctionContext;
1328
1329 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
1330
1331 // When evaluating immediate functions in the initializer of a default
1332 // argument or default member initializer, this is the declaration whose
1333 // default initializer is being evaluated and the location of the call
1334 // or constructor definition.
1335 struct InitializationContext {
1336 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
1337 DeclContext *Context)
1338 : Loc(Loc), Decl(Decl), Context(Context) {
1339 assert(Decl && Context && "invalid initialization context");
1340 }
1341
1342 SourceLocation Loc;
1343 ValueDecl *Decl = nullptr;
1344 DeclContext *Context = nullptr;
1345 };
1346 std::optional<InitializationContext> DelayedDefaultInitializationContext;
1347
1348 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1349 unsigned NumCleanupObjects,
1350 CleanupInfo ParentCleanup,
1351 Decl *ManglingContextDecl,
1352 ExpressionKind ExprContext)
1353 : Context(Context), ParentCleanup(ParentCleanup),
1354 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1355 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1356 InDiscardedStatement(false), InImmediateFunctionContext(false) {}
1357
1358 bool isUnevaluated() const {
1359 return Context == ExpressionEvaluationContext::Unevaluated ||
1360 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1361 Context == ExpressionEvaluationContext::UnevaluatedList;
1362 }
1363
1364 bool isConstantEvaluated() const {
1365 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1366 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1367 }
1368
1369 bool isImmediateFunctionContext() const {
1370 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1371 (Context == ExpressionEvaluationContext::DiscardedStatement &&
1372 InImmediateFunctionContext) ||
1373 // C++2b [expr.const]p14:
1374 // An expression or conversion is in an immediate function
1375 // context if it is potentially evaluated and either:
1376 // * its innermost enclosing non-block scope is a function
1377 // parameter scope of an immediate function, or
1378 // * its enclosing statement is enclosed by the compound-
1379 // statement of a consteval if statement.
1380 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
1381 InImmediateFunctionContext);
1382 }
1383
1384 bool isDiscardedStatementContext() const {
1385 return Context == ExpressionEvaluationContext::DiscardedStatement ||
1386 (Context ==
1387 ExpressionEvaluationContext::ImmediateFunctionContext &&
1388 InDiscardedStatement);
1389 }
1390 };
1391
1392 /// A stack of expression evaluation contexts.
1393 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1394
1395 // Set of failed immediate invocations to avoid double diagnosing.
1396 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
1397
1398 /// Emit a warning for all pending noderef expressions that we recorded.
1399 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1400
1401 /// Compute the mangling number context for a lambda expression or
1402 /// block literal. Also return the extra mangling decl if any.
1403 ///
1404 /// \param DC - The DeclContext containing the lambda expression or
1405 /// block literal.
1406 std::tuple<MangleNumberingContext *, Decl *>
1407 getCurrentMangleNumberContext(const DeclContext *DC);
1408
1409
1410 /// SpecialMemberOverloadResult - The overloading result for a special member
1411 /// function.
1412 ///
1413 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1414 /// integer are used to determine whether overload resolution succeeded.
1415 class SpecialMemberOverloadResult {
1416 public:
1417 enum Kind {
1418 NoMemberOrDeleted,
1419 Ambiguous,
1420 Success
1421 };
1422
1423 private:
1424 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1425
1426 public:
1427 SpecialMemberOverloadResult() {}
1428 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1429 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1430
1431 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1432 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1433
1434 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1435 void setKind(Kind K) { Pair.setInt(K); }
1436 };
1437
1438 class SpecialMemberOverloadResultEntry
1439 : public llvm::FastFoldingSetNode,
1440 public SpecialMemberOverloadResult {
1441 public:
1442 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1443 : FastFoldingSetNode(ID)
1444 {}
1445 };
1446
1447 /// A cache of special member function overload resolution results
1448 /// for C++ records.
1449 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1450
1451 /// A cache of the flags available in enumerations with the flag_bits
1452 /// attribute.
1453 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1454
1455 /// The kind of translation unit we are processing.
1456 ///
1457 /// When we're processing a complete translation unit, Sema will perform
1458 /// end-of-translation-unit semantic tasks (such as creating
1459 /// initializers for tentative definitions in C) once parsing has
1460 /// completed. Modules and precompiled headers perform different kinds of
1461 /// checks.
1462 const TranslationUnitKind TUKind;
1463
1464 llvm::BumpPtrAllocator BumpAlloc;
1465
1466 /// The number of SFINAE diagnostics that have been trapped.
1467 unsigned NumSFINAEErrors;
1468
1469 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1470 UnparsedDefaultArgInstantiationsMap;
1471
1472 /// A mapping from parameters with unparsed default arguments to the
1473 /// set of instantiations of each parameter.
1474 ///
1475 /// This mapping is a temporary data structure used when parsing
1476 /// nested class templates or nested classes of class templates,
1477 /// where we might end up instantiating an inner class before the
1478 /// default arguments of its methods have been parsed.
1479 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1480
1481 // Contains the locations of the beginning of unparsed default
1482 // argument locations.
1483 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1484
1485 /// UndefinedInternals - all the used, undefined objects which require a
1486 /// definition in this translation unit.
1487 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1488
1489 /// Determine if VD, which must be a variable or function, is an external
1490 /// symbol that nonetheless can't be referenced from outside this translation
1491 /// unit because its type has no linkage and it's not extern "C".
1492 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
1493
1494 /// Obtain a sorted list of functions that are undefined but ODR-used.
1495 void getUndefinedButUsed(
1496 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1497
1498 /// Retrieves list of suspicious delete-expressions that will be checked at
1499 /// the end of translation unit.
1500 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1501 getMismatchingDeleteExpressions() const;
1502
1503 class GlobalMethodPool {
1504 public:
1505 using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1506 using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1507 iterator begin() { return Methods.begin(); }
1508 iterator end() { return Methods.end(); }
1509 iterator find(Selector Sel) { return Methods.find(Sel); }
1510 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1511 return Methods.insert(Val);
1512 }
1513 int count(Selector Sel) const { return Methods.count(Sel); }
1514 bool empty() const { return Methods.empty(); }
1515
1516 private:
1517 llvm::DenseMap<Selector, Lists> Methods;
1518 };
1519
1520 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1521 /// We need to maintain a list, since selectors can have differing signatures
1522 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1523 /// of selectors are "overloaded").
1524 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1525 /// methods inside categories with a particular selector.
1526 GlobalMethodPool MethodPool;
1527
1528 /// Method selectors used in a \@selector expression. Used for implementation
1529 /// of -Wselector.
1530 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1531
1532 /// List of SourceLocations where 'self' is implicitly retained inside a
1533 /// block.
1534 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1535 ImplicitlyRetainedSelfLocs;
1536
1537 /// Kinds of C++ special members.
1538 enum CXXSpecialMember {
1539 CXXDefaultConstructor,
1540 CXXCopyConstructor,
1541 CXXMoveConstructor,
1542 CXXCopyAssignment,
1543 CXXMoveAssignment,
1544 CXXDestructor,
1545 CXXInvalid
1546 };
1547
1548 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1549 SpecialMemberDecl;
1550
1551 /// The C++ special members which we are currently in the process of
1552 /// declaring. If this process recursively triggers the declaration of the
1553 /// same special member, we should act as if it is not yet declared.
1554 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1555
1556 /// Kinds of defaulted comparison operator functions.
1557 enum class DefaultedComparisonKind : unsigned char {
1558 /// This is not a defaultable comparison operator.
1559 None,
1560 /// This is an operator== that should be implemented as a series of
1561 /// subobject comparisons.
1562 Equal,
1563 /// This is an operator<=> that should be implemented as a series of
1564 /// subobject comparisons.
1565 ThreeWay,
1566 /// This is an operator!= that should be implemented as a rewrite in terms
1567 /// of a == comparison.
1568 NotEqual,
1569 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1570 /// terms of a <=> comparison.
1571 Relational,
1572 };
1573
1574 /// The function definitions which were renamed as part of typo-correction
1575 /// to match their respective declarations. We want to keep track of them
1576 /// to ensure that we don't emit a "redefinition" error if we encounter a
1577 /// correctly named definition after the renamed definition.
1578 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1579
1580 /// Stack of types that correspond to the parameter entities that are
1581 /// currently being copy-initialized. Can be empty.
1582 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1583
1584 void ReadMethodPool(Selector Sel);
1585 void updateOutOfDateSelector(Selector Sel);
1586
1587 /// Private Helper predicate to check for 'self'.
1588 bool isSelfExpr(Expr *RExpr);
1589 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1590
1591 /// Cause the active diagnostic on the DiagosticsEngine to be
1592 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1593 /// should not be used elsewhere.
1594 void EmitCurrentDiagnostic(unsigned DiagID);
1595
1596 /// Records and restores the CurFPFeatures state on entry/exit of compound
1597 /// statements.
1598 class FPFeaturesStateRAII {
1599 public:
1600 FPFeaturesStateRAII(Sema &S);
1601 ~FPFeaturesStateRAII();
1602 FPOptionsOverride getOverrides() { return OldOverrides; }
1603
1604 private:
1605 Sema& S;
1606 FPOptions OldFPFeaturesState;
1607 FPOptionsOverride OldOverrides;
1608 LangOptions::FPEvalMethodKind OldEvalMethod;
1609 SourceLocation OldFPPragmaLocation;
1610 };
1611
1612 void addImplicitTypedef(StringRef Name, QualType T);
1613
1614 bool WarnedStackExhausted = false;
1615
1616 /// Increment when we find a reference; decrement when we find an ignored
1617 /// assignment. Ultimately the value is 0 if every reference is an ignored
1618 /// assignment.
1619 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1620
1621 /// Indicate RISC-V vector builtin functions enabled or not.
1622 bool DeclareRISCVVBuiltins = false;
1623
1624private:
1625 std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1626
1627 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1628
1629 bool WarnedDarwinSDKInfoMissing = false;
1630
1631public:
1632 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1633 TranslationUnitKind TUKind = TU_Complete,
1634 CodeCompleteConsumer *CompletionConsumer = nullptr);
1635 ~Sema();
1636
1637 /// Perform initialization that occurs after the parser has been
1638 /// initialized but before it parses anything.
1639 void Initialize();
1640
1641 /// This virtual key function only exists to limit the emission of debug info
1642 /// describing the Sema class. GCC and Clang only emit debug info for a class
1643 /// with a vtable when the vtable is emitted. Sema is final and not
1644 /// polymorphic, but the debug info size savings are so significant that it is
1645 /// worth adding a vtable just to take advantage of this optimization.
1646 virtual void anchor();
1647
1648 const LangOptions &getLangOpts() const { return LangOpts; }
1649 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1650 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1651
1652 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1653 SourceManager &getSourceManager() const { return SourceMgr; }
1654 Preprocessor &getPreprocessor() const { return PP; }
1655 ASTContext &getASTContext() const { return Context; }
1656 ASTConsumer &getASTConsumer() const { return Consumer; }
1657 ASTMutationListener *getASTMutationListener() const;
1658 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
1659
1660 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1661 StringRef Platform);
1662 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
1663
1664 ///Registers an external source. If an external source already exists,
1665 /// creates a multiplex external source and appends to it.
1666 ///
1667 ///\param[in] E - A non-null external sema source.
1668 ///
1669 void addExternalSource(ExternalSemaSource *E);
1670
1671 void PrintStats() const;
1672
1673 /// Warn that the stack is nearly exhausted.
1674 void warnStackExhausted(SourceLocation Loc);
1675
1676 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1677 /// guaranteed). Produces a warning if we're low on stack space and allocates
1678 /// more in that case. Use this in code that may recurse deeply (for example,
1679 /// in template instantiation) to avoid stack overflow.
1680 void runWithSufficientStackSpace(SourceLocation Loc,
1681 llvm::function_ref<void()> Fn);
1682
1683 /// Helper class that creates diagnostics with optional
1684 /// template instantiation stacks.
1685 ///
1686 /// This class provides a wrapper around the basic DiagnosticBuilder
1687 /// class that emits diagnostics. ImmediateDiagBuilder is
1688 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1689 /// does) and, if the diagnostic comes from inside a template
1690 /// instantiation, printing the template instantiation stack as
1691 /// well.
1692 class ImmediateDiagBuilder : public DiagnosticBuilder {
1693 Sema &SemaRef;
1694 unsigned DiagID;
1695
1696 public:
1697 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1698 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1699 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1700 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1701
1702 // This is a cunning lie. DiagnosticBuilder actually performs move
1703 // construction in its copy constructor (but due to varied uses, it's not
1704 // possible to conveniently express this as actual move construction). So
1705 // the default copy ctor here is fine, because the base class disables the
1706 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1707 // in that case anwyay.
1708 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1709
1710 ~ImmediateDiagBuilder() {
1711 // If we aren't active, there is nothing to do.
1712 if (!isActive()) return;
1713
1714 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1715 // builder itself so it won't emit the diagnostic in its own destructor.
1716 //
1717 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1718 // do its own needless checks to see if the diagnostic needs to be
1719 // emitted. However, because we take care to ensure that the builder
1720 // objects never escape, a sufficiently smart compiler will be able to
1721 // eliminate that code.
1722 Clear();
1723
1724 // Dispatch to Sema to emit the diagnostic.
1725 SemaRef.EmitCurrentDiagnostic(DiagID);
1726 }
1727
1728 /// Teach operator<< to produce an object of the correct type.
1729 template <typename T>
1730 friend const ImmediateDiagBuilder &
1731 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1732 const DiagnosticBuilder &BaseDiag = Diag;
1733 BaseDiag << Value;
1734 return Diag;
1735 }
1736
1737 // It is necessary to limit this to rvalue reference to avoid calling this
1738 // function with a bitfield lvalue argument since non-const reference to
1739 // bitfield is not allowed.
1740 template <typename T,
1741 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1742 const ImmediateDiagBuilder &operator<<(T &&V) const {
1743 const DiagnosticBuilder &BaseDiag = *this;
1744 BaseDiag << std::move(V);
1745 return *this;
1746 }
1747 };
1748
1749 /// A generic diagnostic builder for errors which may or may not be deferred.
1750 ///
1751 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1752 /// which are not allowed to appear inside __device__ functions and are
1753 /// allowed to appear in __host__ __device__ functions only if the host+device
1754 /// function is never codegen'ed.
1755 ///
1756 /// To handle this, we use the notion of "deferred diagnostics", where we
1757 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1758 ///
1759 /// This class lets you emit either a regular diagnostic, a deferred
1760 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1761 /// its constructor, thus simplifying the process of creating these "maybe
1762 /// deferred" diagnostics.
1763 class SemaDiagnosticBuilder {
1764 public:
1765 enum Kind {
1766 /// Emit no diagnostics.
1767 K_Nop,
1768 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1769 K_Immediate,
1770 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1771 /// emit a call stack showing how this function can be reached by an a
1772 /// priori known-emitted function.
1773 K_ImmediateWithCallStack,
1774 /// Create a deferred diagnostic, which is emitted only if the function
1775 /// it's attached to is codegen'ed. Also emit a call stack as with
1776 /// K_ImmediateWithCallStack.
1777 K_Deferred
1778 };
1779
1780 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1781 const FunctionDecl *Fn, Sema &S);
1782 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1783 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1784 ~SemaDiagnosticBuilder();
1785
1786 bool isImmediate() const { return ImmediateDiag.has_value(); }
1787
1788 /// Convertible to bool: True if we immediately emitted an error, false if
1789 /// we didn't emit an error or we created a deferred error.
1790 ///
1791 /// Example usage:
1792 ///
1793 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1794 /// return ExprError();
1795 ///
1796 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1797 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1798 operator bool() const { return isImmediate(); }
1799
1800 template <typename T>
1801 friend const SemaDiagnosticBuilder &
1802 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1803 if (Diag.ImmediateDiag)
1804 *Diag.ImmediateDiag << Value;
1805 else if (Diag.PartialDiagId)
1806 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1807 << Value;
1808 return Diag;
1809 }
1810
1811 // It is necessary to limit this to rvalue reference to avoid calling this
1812 // function with a bitfield lvalue argument since non-const reference to
1813 // bitfield is not allowed.
1814 template <typename T,
1815 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1816 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1817 if (ImmediateDiag)
1818 *ImmediateDiag << std::move(V);
1819 else if (PartialDiagId)
1820 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1821 return *this;
1822 }
1823
1824 friend const SemaDiagnosticBuilder &
1825 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1826 if (Diag.ImmediateDiag)
1827 PD.Emit(*Diag.ImmediateDiag);
1828 else if (Diag.PartialDiagId)
1829 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1830 return Diag;
1831 }
1832
1833 void AddFixItHint(const FixItHint &Hint) const {
1834 if (ImmediateDiag)
1835 ImmediateDiag->AddFixItHint(Hint);
1836 else if (PartialDiagId)
1837 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1838 }
1839
1840 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1841 return ExprError();
1842 }
1843 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1844 return StmtError();
1845 }
1846 operator ExprResult() const { return ExprError(); }
1847 operator StmtResult() const { return StmtError(); }
1848 operator TypeResult() const { return TypeError(); }
1849 operator DeclResult() const { return DeclResult(true); }
1850 operator MemInitResult() const { return MemInitResult(true); }
1851
1852 private:
1853 Sema &S;
1854 SourceLocation Loc;
1855 unsigned DiagID;
1856 const FunctionDecl *Fn;
1857 bool ShowCallStack;
1858
1859 // Invariant: At most one of these Optionals has a value.
1860 // FIXME: Switch these to a Variant once that exists.
1861 std::optional<ImmediateDiagBuilder> ImmediateDiag;
1862 std::optional<unsigned> PartialDiagId;
1863 };
1864
1865 /// Is the last error level diagnostic immediate. This is used to determined
1866 /// whether the next info diagnostic should be immediate.
1867 bool IsLastErrorImmediate = true;
1868
1869 /// Emit a diagnostic.
1870 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1871 bool DeferHint = false);
1872
1873 /// Emit a partial diagnostic.
1874 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1875 bool DeferHint = false);
1876
1877 /// Build a partial diagnostic.
1878 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1879
1880 /// Whether deferrable diagnostics should be deferred.
1881 bool DeferDiags = false;
1882
1883 /// RAII class to control scope of DeferDiags.
1884 class DeferDiagsRAII {
1885 Sema &S;
1886 bool SavedDeferDiags = false;
1887
1888 public:
1889 DeferDiagsRAII(Sema &S, bool DeferDiags)
1890 : S(S), SavedDeferDiags(S.DeferDiags) {
1891 S.DeferDiags = DeferDiags;
1892 }
1893 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1894 };
1895
1896 /// Whether uncompilable error has occurred. This includes error happens
1897 /// in deferred diagnostics.
1898 bool hasUncompilableErrorOccurred() const;
1899
1900 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1901
1902 /// Get a string to suggest for zero-initialization of a type.
1903 std::string
1904 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1905 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1906
1907 /// Calls \c Lexer::getLocForEndOfToken()
1908 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1909
1910 /// Retrieve the module loader associated with the preprocessor.
1911 ModuleLoader &getModuleLoader() const;
1912
1913 /// Invent a new identifier for parameters of abbreviated templates.
1914 IdentifierInfo *
1915 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1916 unsigned Index);
1917
1918 void emitAndClearUnusedLocalTypedefWarnings();
1919
1920 private:
1921 /// Function or variable declarations to be checked for whether the deferred
1922 /// diagnostics should be emitted.
1923 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1924
1925 public:
1926 // Emit all deferred diagnostics.
1927 void emitDeferredDiags();
1928
1929 enum TUFragmentKind {
1930 /// The global module fragment, between 'module;' and a module-declaration.
1931 Global,
1932 /// A normal translation unit fragment. For a non-module unit, this is the
1933 /// entire translation unit. Otherwise, it runs from the module-declaration
1934 /// to the private-module-fragment (if any) or the end of the TU (if not).
1935 Normal,
1936 /// The private module fragment, between 'module :private;' and the end of
1937 /// the translation unit.
1938 Private
1939 };
1940
1941 void ActOnStartOfTranslationUnit();
1942 void ActOnEndOfTranslationUnit();
1943 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1944
1945 void CheckDelegatingCtorCycles();
1946
1947 Scope *getScopeForContext(DeclContext *Ctx);
1948
1949 void PushFunctionScope();
1950 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1951 sema::LambdaScopeInfo *PushLambdaScope();
1952
1953 /// This is used to inform Sema what the current TemplateParameterDepth
1954 /// is during Parsing. Currently it is used to pass on the depth
1955 /// when parsing generic lambda 'auto' parameters.
1956 void RecordParsingTemplateParameterDepth(unsigned Depth);
1957
1958 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1959 RecordDecl *RD, CapturedRegionKind K,
1960 unsigned OpenMPCaptureLevel = 0);
1961
1962 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1963 /// time after they've been popped.
1964 class PoppedFunctionScopeDeleter {
1965 Sema *Self;
1966
1967 public:
1968 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1969 void operator()(sema::FunctionScopeInfo *Scope) const;
1970 };
1971
1972 using PoppedFunctionScopePtr =
1973 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1974
1975 PoppedFunctionScopePtr
1976 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1977 const Decl *D = nullptr,
1978 QualType BlockType = QualType());
1979
1980 sema::FunctionScopeInfo *getCurFunction() const {
1981 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1982 }
1983
1984 sema::FunctionScopeInfo *getEnclosingFunction() const;
1985
1986 void setFunctionHasBranchIntoScope();
1987 void setFunctionHasBranchProtectedScope();
1988 void setFunctionHasIndirectGoto();
1989 void setFunctionHasMustTail();
1990
1991 void PushCompoundScope(bool IsStmtExpr);
1992 void PopCompoundScope();
1993
1994 sema::CompoundScopeInfo &getCurCompoundScope() const;
1995
1996 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1997
1998 /// Retrieve the current block, if any.
1999 sema::BlockScopeInfo *getCurBlock();
2000
2001 /// Get the innermost lambda enclosing the current location, if any. This
2002 /// looks through intervening non-lambda scopes such as local functions and
2003 /// blocks.
2004 sema::LambdaScopeInfo *getEnclosingLambda() const;
2005
2006 /// Retrieve the current lambda scope info, if any.
2007 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
2008 /// lambda scope info ignoring all inner capturing scopes that are not
2009 /// lambda scopes.
2010 sema::LambdaScopeInfo *
2011 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
2012
2013 /// Retrieve the current generic lambda info, if any.
2014 sema::LambdaScopeInfo *getCurGenericLambda();
2015
2016 /// Retrieve the current captured region, if any.
2017 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
2018
2019 /// Retrieve the current function, if any, that should be analyzed for
2020 /// potential availability violations.
2021 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2022
2023 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
2024 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
2025
2026 /// Called before parsing a function declarator belonging to a function
2027 /// declaration.
2028 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
2029 unsigned TemplateParameterDepth);
2030
2031 /// Called after parsing a function declarator belonging to a function
2032 /// declaration.
2033 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
2034
2035 void ActOnComment(SourceRange Comment);
2036
2037 //===--------------------------------------------------------------------===//
2038 // Type Analysis / Processing: SemaType.cpp.
2039 //
2040
2041 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
2042 const DeclSpec *DS = nullptr);
2043 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2044 const DeclSpec *DS = nullptr);
2045 QualType BuildPointerType(QualType T,
2046 SourceLocation Loc, DeclarationName Entity);
2047 QualType BuildReferenceType(QualType T, bool LValueRef,
2048 SourceLocation Loc, DeclarationName Entity);
2049 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2050 Expr *ArraySize, unsigned Quals,
2051 SourceRange Brackets, DeclarationName Entity);
2052 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2053 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2054 SourceLocation AttrLoc);
2055 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2056 SourceLocation AttrLoc);
2057
2058 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2059 SourceLocation AttrLoc);
2060
2061 /// Same as above, but constructs the AddressSpace index if not provided.
2062 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
2063 SourceLocation AttrLoc);
2064
2065 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
2066
2067 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
2068
2069 /// Build a function type.
2070 ///
2071 /// This routine checks the function type according to C++ rules and
2072 /// under the assumption that the result type and parameter types have
2073 /// just been instantiated from a template. It therefore duplicates
2074 /// some of the behavior of GetTypeForDeclarator, but in a much
2075 /// simpler form that is only suitable for this narrow use case.
2076 ///
2077 /// \param T The return type of the function.
2078 ///
2079 /// \param ParamTypes The parameter types of the function. This array
2080 /// will be modified to account for adjustments to the types of the
2081 /// function parameters.
2082 ///
2083 /// \param Loc The location of the entity whose type involves this
2084 /// function type or, if there is no such entity, the location of the
2085 /// type that will have function type.
2086 ///
2087 /// \param Entity The name of the entity that involves the function
2088 /// type, if known.
2089 ///
2090 /// \param EPI Extra information about the function type. Usually this will
2091 /// be taken from an existing function with the same prototype.
2092 ///
2093 /// \returns A suitable function type, if there are no errors. The
2094 /// unqualified type will always be a FunctionProtoType.
2095 /// Otherwise, returns a NULL type.
2096 QualType BuildFunctionType(QualType T,
2097 MutableArrayRef<QualType> ParamTypes,
2098 SourceLocation Loc, DeclarationName Entity,
2099 const FunctionProtoType::ExtProtoInfo &EPI);
2100
2101 QualType BuildMemberPointerType(QualType T, QualType Class,
2102 SourceLocation Loc,
2103 DeclarationName Entity);
2104 QualType BuildBlockPointerType(QualType T,
2105 SourceLocation Loc, DeclarationName Entity);
2106 QualType BuildParenType(QualType T);
2107 QualType BuildAtomicType(QualType T, SourceLocation Loc);
2108 QualType BuildReadPipeType(QualType T,
2109 SourceLocation Loc);
2110 QualType BuildWritePipeType(QualType T,
2111 SourceLocation Loc);
2112 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2113
2114 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2115 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2116
2117 /// Package the given type and TSI into a ParsedType.
2118 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2119 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2120 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2121 static QualType GetTypeFromParser(ParsedType Ty,
2122 TypeSourceInfo **TInfo = nullptr);
2123 CanThrowResult canThrow(const Stmt *E);
2124 /// Determine whether the callee of a particular function call can throw.
2125 /// E, D and Loc are all optional.
2126 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2127 SourceLocation Loc = SourceLocation());
2128 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2129 const FunctionProtoType *FPT);
2130 void UpdateExceptionSpec(FunctionDecl *FD,
2131 const FunctionProtoType::ExceptionSpecInfo &ESI);
2132 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2133 bool CheckDistantExceptionSpec(QualType T);
2134 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2135 bool CheckEquivalentExceptionSpec(
2136 const FunctionProtoType *Old, SourceLocation OldLoc,
2137 const FunctionProtoType *New, SourceLocation NewLoc);
2138 bool CheckEquivalentExceptionSpec(
2139 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2140 const FunctionProtoType *Old, SourceLocation OldLoc,
2141 const FunctionProtoType *New, SourceLocation NewLoc);
2142 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2143 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2144 const PartialDiagnostic &NestedDiagID,
2145 const PartialDiagnostic &NoteID,
2146 const PartialDiagnostic &NoThrowDiagID,
2147 const FunctionProtoType *Superset,
2148 SourceLocation SuperLoc,
2149 const FunctionProtoType *Subset,
2150 SourceLocation SubLoc);
2151 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2152 const PartialDiagnostic &NoteID,
2153 const FunctionProtoType *Target,
2154 SourceLocation TargetLoc,
2155 const FunctionProtoType *Source,
2156 SourceLocation SourceLoc);
2157
2158 TypeResult ActOnTypeName(Scope *S, Declarator &D);
2159
2160 /// The parser has parsed the context-sensitive type 'instancetype'
2161 /// in an Objective-C message declaration. Return the appropriate type.
2162 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2163
2164 /// Abstract class used to diagnose incomplete types.
2165 struct TypeDiagnoser {
2166 TypeDiagnoser() {}
2167
2168 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2169 virtual ~TypeDiagnoser() {}
2170 };
2171
2172 static int getPrintable(int I) { return I; }
2173 static unsigned getPrintable(unsigned I) { return I; }
2174 static bool getPrintable(bool B) { return B; }
2175 static const char * getPrintable(const char *S) { return S; }
2176 static StringRef getPrintable(StringRef S) { return S; }
2177 static const std::string &getPrintable(const std::string &S) { return S; }
2178 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2179 return II;
2180 }
2181 static DeclarationName getPrintable(DeclarationName N) { return N; }
2182 static QualType getPrintable(QualType T) { return T; }
2183 static SourceRange getPrintable(SourceRange R) { return R; }
2184 static SourceRange getPrintable(SourceLocation L) { return L; }
2185 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2186 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2187
2188 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2189 protected:
2190 unsigned DiagID;
2191 std::tuple<const Ts &...> Args;
2192
2193 template <std::size_t... Is>
2194 void emit(const SemaDiagnosticBuilder &DB,
2195 std::index_sequence<Is...>) const {
2196 // Apply all tuple elements to the builder in order.
2197 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2198 (void)Dummy;
2199 }
2200
2201 public:
2202 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2203 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2204 assert(DiagID != 0 && "no diagnostic for type diagnoser");
2205 }
2206
2207 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2208 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2209 emit(DB, std::index_sequence_for<Ts...>());
2210 DB << T;
2211 }
2212 };
2213
2214 /// Do a check to make sure \p Name looks like a legal argument for the
2215 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2216 /// is invalid for the given declaration.
2217 ///
2218 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2219 ///
2220 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2221 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2222 const ParsedAttr &AL, bool IsAsync);
2223
2224 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2225 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2226 /// For example, a diagnostic with no other parameters would generally have
2227 /// the form "...%select{incomplete|sizeless}0 type %1...".
2228 template <typename... Ts>
2229 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2230 public:
2231 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2232 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2233
2234 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2235 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2236 this->emit(DB, std::index_sequence_for<Ts...>());
2237 DB << T->isSizelessType() << T;
2238 }
2239 };
2240
2241 enum class CompleteTypeKind {
2242 /// Apply the normal rules for complete types. In particular,
2243 /// treat all sizeless types as incomplete.
2244 Normal,
2245
2246 /// Relax the normal rules for complete types so that they include
2247 /// sizeless built-in types.
2248 AcceptSizeless,
2249
2250 // FIXME: Eventually we should flip the default to Normal and opt in
2251 // to AcceptSizeless rather than opt out of it.
2252 Default = AcceptSizeless
2253 };
2254
2255 enum class AcceptableKind { Visible, Reachable };
2256
2257private:
2258 /// Methods for marking which expressions involve dereferencing a pointer
2259 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2260 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2261 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2262 /// `*p`, but need to check that `address of` is called on it. This requires
2263 /// keeping a container of all pending expressions and checking if the address
2264 /// of them are eventually taken.
2265 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2266 void CheckAddressOfNoDeref(const Expr *E);
2267 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2268
2269 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2270 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2271
2272 struct ModuleScope {
2273 SourceLocation BeginLoc;
2274 clang::Module *Module = nullptr;
2275 bool ModuleInterface = false;
2276 VisibleModuleSet OuterVisibleModules;
2277 };
2278 /// The modules we're currently parsing.
2279 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2280
2281 /// For an interface unit, this is the implicitly imported interface unit.
2282 clang::Module *ThePrimaryInterface = nullptr;
2283
2284 /// The explicit global module fragment of the current translation unit.
2285 /// The explicit Global Module Fragment, as specified in C++
2286 /// [module.global.frag].
2287 clang::Module *TheGlobalModuleFragment = nullptr;
2288
2289 /// The implicit global module fragments of the current translation unit.
2290 /// We would only create at most two implicit global module fragments to
2291 /// avoid performance penalties when there are many language linkage
2292 /// exports.
2293 ///
2294 /// The contents in the implicit global module fragment can't be discarded
2295 /// no matter if it is exported or not.
2296 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
2297 clang::Module *TheExportedImplicitGlobalModuleFragment = nullptr;
2298
2299 /// Namespace definitions that we will export when they finish.
2300 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2301
2302 /// In a C++ standard module, inline declarations require a definition to be
2303 /// present at the end of a definition domain. This set holds the decls to
2304 /// be checked at the end of the TU.
2305 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
2306
2307 /// Helper function to judge if we are in module purview.
2308 /// Return false if we are not in a module.
2309 bool isCurrentModulePurview() const {
2310 return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2311 }
2312
2313 /// Enter the scope of the explicit global module fragment.
2314 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
2315 /// Leave the scope of the explicit global module fragment.
2316 void PopGlobalModuleFragment();
2317
2318 /// Enter the scope of an implicit global module fragment.
2319 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc,
2320 bool IsExported);
2321 /// Leave the scope of an implicit global module fragment.
2322 void PopImplicitGlobalModuleFragment();
2323
2324 VisibleModuleSet VisibleModules;
2325
2326 /// Cache for module units which is usable for current module.
2327 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2328
2329 bool isUsableModule(const Module *M);
2330
2331 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2332
2333public:
2334 /// Get the module unit whose scope we are currently within.
2335 Module *getCurrentModule() const {
2336 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2337 }
2338
2339 /// Is the module scope we are an interface?
2340 bool currentModuleIsInterface() const {
2341 return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
2342 }
2343
2344 /// Is the module scope we are in a C++ Header Unit?
2345 bool currentModuleIsHeaderUnit() const {
2346 return ModuleScopes.empty() ? false
2347 : ModuleScopes.back().Module->isHeaderUnit();
2348 }
2349
2350 /// Get the module owning an entity.
2351 Module *getOwningModule(const Decl *Entity) {
2352 return Entity->getOwningModule();
2353 }
2354
2355 // Determine whether the module M belongs to the current TU.
2356 bool isModuleUnitOfCurrentTU(const Module *M) const;
2357
2358 /// Make a merged definition of an existing hidden definition \p ND
2359 /// visible at the specified location.
2360 void makeMergedDefinitionVisible(NamedDecl *ND);
2361
2362 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2363
2364 // When loading a non-modular PCH files, this is used to restore module
2365 // visibility.
2366 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2367 VisibleModules.setVisible(Mod, ImportLoc);
2368 }
2369
2370 /// Determine whether a declaration is visible to name lookup.
2371 bool isVisible(const NamedDecl *D) {
2372 return D->isUnconditionallyVisible() ||
2373 isAcceptableSlow(D, AcceptableKind::Visible);
2374 }
2375
2376 /// Determine whether a declaration is reachable.
2377 bool isReachable(const NamedDecl *D) {
2378 // All visible declarations are reachable.
2379 return D->isUnconditionallyVisible() ||
2380 isAcceptableSlow(D, AcceptableKind::Reachable);
2381 }
2382
2383 /// Determine whether a declaration is acceptable (visible/reachable).
2384 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
2385 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2386 }
2387
2388 /// Determine whether any declaration of an entity is visible.
2389 bool
2390 hasVisibleDeclaration(const NamedDecl *D,
2391 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2392 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2393 }
2394
2395 bool hasVisibleDeclarationSlow(const NamedDecl *D,
2396 llvm::SmallVectorImpl<Module *> *Modules);
2397 /// Determine whether any declaration of an entity is reachable.
2398 bool
2399 hasReachableDeclaration(const NamedDecl *D,
2400 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2401 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2402 }
2403 bool hasReachableDeclarationSlow(
2404 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2405
2406 bool hasVisibleMergedDefinition(const NamedDecl *Def);
2407 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
2408
2409 /// Determine if \p D and \p Suggested have a structurally compatible
2410 /// layout as described in C11 6.2.7/1.
2411 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2412
2413 /// Determine if \p D has a visible definition. If not, suggest a declaration
2414 /// that should be made visible to expose the definition.
2415 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2416 bool OnlyNeedComplete = false);
2417 bool hasVisibleDefinition(const NamedDecl *D) {
2418 NamedDecl *Hidden;
2419 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2420 }
2421
2422 /// Determine if \p D has a reachable definition. If not, suggest a
2423 /// declaration that should be made reachable to expose the definition.
2424 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2425 bool OnlyNeedComplete = false);
2426 bool hasReachableDefinition(NamedDecl *D) {
2427 NamedDecl *Hidden;
2428 return hasReachableDefinition(D, &Hidden);
2429 }
2430
2431 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2432 AcceptableKind Kind,
2433 bool OnlyNeedComplete = false);
2434 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
2435 NamedDecl *Hidden;
2436 return hasAcceptableDefinition(D, &Hidden, Kind);
2437 }
2438
2439 /// Determine if the template parameter \p D has a visible default argument.
2440 bool
2441 hasVisibleDefaultArgument(const NamedDecl *D,
2442 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2443 /// Determine if the template parameter \p D has a reachable default argument.
2444 bool hasReachableDefaultArgument(
2445 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2446 /// Determine if the template parameter \p D has a reachable default argument.
2447 bool hasAcceptableDefaultArgument(const NamedDecl *D,
2448 llvm::SmallVectorImpl<Module *> *Modules,
2449 Sema::AcceptableKind Kind);
2450
2451 /// Determine if there is a visible declaration of \p D that is an explicit
2452 /// specialization declaration for a specialization of a template. (For a
2453 /// member specialization, use hasVisibleMemberSpecialization.)
2454 bool hasVisibleExplicitSpecialization(
2455 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2456 /// Determine if there is a reachable declaration of \p D that is an explicit
2457 /// specialization declaration for a specialization of a template. (For a
2458 /// member specialization, use hasReachableMemberSpecialization.)
2459 bool hasReachableExplicitSpecialization(
2460 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2461
2462 /// Determine if there is a visible declaration of \p D that is a member
2463 /// specialization declaration (as opposed to an instantiated declaration).
2464 bool hasVisibleMemberSpecialization(
2465 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2466 /// Determine if there is a reachable declaration of \p D that is a member
2467 /// specialization declaration (as opposed to an instantiated declaration).
2468 bool hasReachableMemberSpecialization(
2469 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2470
2471 /// Determine if \p A and \p B are equivalent internal linkage declarations
2472 /// from different modules, and thus an ambiguity error can be downgraded to
2473 /// an extension warning.
2474 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2475 const NamedDecl *B);
2476 void diagnoseEquivalentInternalLinkageDeclarations(
2477 SourceLocation Loc, const NamedDecl *D,
2478 ArrayRef<const NamedDecl *> Equiv);
2479
2480 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2481
2482 // Check whether the size of array element of type \p EltTy is a multiple of
2483 // its alignment and return false if it isn't.
2484 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
2485
2486 bool isCompleteType(SourceLocation Loc, QualType T,
2487 CompleteTypeKind Kind = CompleteTypeKind::Default) {
2488 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2489 }
2490 bool RequireCompleteType(SourceLocation Loc, QualType T,
2491 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2492 bool RequireCompleteType(SourceLocation Loc, QualType T,
2493 CompleteTypeKind Kind, unsigned DiagID);
2494
2495 bool RequireCompleteType(SourceLocation Loc, QualType T,
2496 TypeDiagnoser &Diagnoser) {
2497 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2498 }
2499 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2500 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2501 }
2502
2503 template <typename... Ts>
2504 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2505 const Ts &...Args) {
2506 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2507 return RequireCompleteType(Loc, T, Diagnoser);
2508 }
2509
2510 template <typename... Ts>
2511 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2512 const Ts &... Args) {
2513 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2514 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2515 }
2516
2517 /// Get the type of expression E, triggering instantiation to complete the
2518 /// type if necessary -- that is, if the expression refers to a templated
2519 /// static data member of incomplete array type.
2520 ///
2521 /// May still return an incomplete type if instantiation was not possible or
2522 /// if the type is incomplete for a different reason. Use
2523 /// RequireCompleteExprType instead if a diagnostic is expected for an
2524 /// incomplete expression type.
2525 QualType getCompletedType(Expr *E);
2526
2527 void completeExprArrayBound(Expr *E);
2528 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2529 TypeDiagnoser &Diagnoser);
2530 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2531
2532 template <typename... Ts>
2533 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2534 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2535 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2536 }
2537
2538 template <typename... Ts>
2539 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2540 const Ts &... Args) {
2541 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2542 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2543 }
2544
2545 bool RequireLiteralType(SourceLocation Loc, QualType T,
2546 TypeDiagnoser &Diagnoser);
2547 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2548
2549 template <typename... Ts>
2550 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2551 const Ts &...Args) {
2552 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2553 return RequireLiteralType(Loc, T, Diagnoser);
2554 }
2555
2556 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2557 const CXXScopeSpec &SS, QualType T,
2558 TagDecl *OwnedTagDecl = nullptr);
2559
2560 // Returns the underlying type of a decltype with the given expression.
2561 QualType getDecltypeForExpr(Expr *E);
2562
2563 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
2564 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2565 /// context, such as when building a type for decltype(auto).
2566 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2567
2568 using UTTKind = UnaryTransformType::UTTKind;
2569 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
2570 SourceLocation Loc);
2571 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
2572 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
2573 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
2574 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
2575 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
2576 SourceLocation Loc);
2577 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
2578 SourceLocation Loc);
2579 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
2580 SourceLocation Loc);
2581 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
2582 SourceLocation Loc);
2583 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
2584 SourceLocation Loc);
2585
2586 //===--------------------------------------------------------------------===//
2587 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2588 //
2589
2590 struct SkipBodyInfo {
2591 SkipBodyInfo() = default;
2592 bool ShouldSkip = false;
2593 bool CheckSameAsPrevious = false;
2594 NamedDecl *Previous = nullptr;
2595 NamedDecl *New = nullptr;
2596 };
2597
2598 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2599
2600 void DiagnoseUseOfUnimplementedSelectors();
2601
2602 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2603
2604 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2605 Scope *S, CXXScopeSpec *SS = nullptr,
2606 bool isClassName = false, bool HasTrailingDot = false,
2607 ParsedType ObjectType = nullptr,
2608 bool IsCtorOrDtorName = false,
2609 bool WantNontrivialTypeSourceInfo = false,
2610 bool IsClassTemplateDeductionContext = true,
2611 ImplicitTypenameContext AllowImplicitTypename =
2612 ImplicitTypenameContext::No,
2613 IdentifierInfo **CorrectedII = nullptr);
2614 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2615 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2616 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2617 SourceLocation IILoc,
2618 Scope *S,
2619 CXXScopeSpec *SS,
2620 ParsedType &SuggestedType,
2621 bool IsTemplateName = false);
2622
2623 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2624 /// type name has failed in a dependent context. In these situations, we
2625 /// automatically form a DependentTypeName that will retry lookup in a related
2626 /// scope during instantiation.
2627 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2628 SourceLocation NameLoc,
2629 bool IsTemplateTypeArg);
2630
2631 /// Describes the result of the name lookup and resolution performed
2632 /// by \c ClassifyName().
2633 enum NameClassificationKind {
2634 /// This name is not a type or template in this context, but might be
2635 /// something else.
2636 NC_Unknown,
2637 /// Classification failed; an error has been produced.
2638 NC_Error,
2639 /// The name has been typo-corrected to a keyword.
2640 NC_Keyword,
2641 /// The name was classified as a type.
2642 NC_Type,
2643 /// The name was classified as a specific non-type, non-template
2644 /// declaration. ActOnNameClassifiedAsNonType should be called to
2645 /// convert the declaration to an expression.
2646 NC_NonType,
2647 /// The name was classified as an ADL-only function name.
2648 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2649 /// result to an expression.
2650 NC_UndeclaredNonType,
2651 /// The name denotes a member of a dependent type that could not be
2652 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2653 /// convert the result to an expression.
2654 NC_DependentNonType,
2655 /// The name was classified as an overload set, and an expression
2656 /// representing that overload set has been formed.
2657 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2658 /// expression referencing the overload set.
2659 NC_OverloadSet,
2660 /// The name was classified as a template whose specializations are types.
2661 NC_TypeTemplate,
2662 /// The name was classified as a variable template name.
2663 NC_VarTemplate,
2664 /// The name was classified as a function template name.
2665 NC_FunctionTemplate,
2666 /// The name was classified as an ADL-only function template name.
2667 NC_UndeclaredTemplate,
2668 /// The name was classified as a concept name.
2669 NC_Concept,
2670 };
2671
2672 class NameClassification {
2673 NameClassificationKind Kind;
2674 union {
2675 ExprResult Expr;
2676 NamedDecl *NonTypeDecl;
2677 TemplateName Template;
2678 ParsedType Type;
2679 };
2680
2681 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2682
2683 public:
2684 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2685
2686 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2687
2688 static NameClassification Error() {
2689 return NameClassification(NC_Error);
2690 }
2691
2692 static NameClassification Unknown() {
2693 return NameClassification(NC_Unknown);
2694 }
2695
2696 static NameClassification OverloadSet(ExprResult E) {
2697 NameClassification Result(NC_OverloadSet);
2698 Result.Expr = E;
2699 return Result;
2700 }
2701
2702 static NameClassification NonType(NamedDecl *D) {
2703 NameClassification Result(NC_NonType);
2704 Result.NonTypeDecl = D;
2705 return Result;
2706 }
2707
2708 static NameClassification UndeclaredNonType() {
2709 return NameClassification(NC_UndeclaredNonType);
2710 }
2711
2712 static NameClassification DependentNonType() {
2713 return NameClassification(NC_DependentNonType);
2714 }
2715
2716 static NameClassification TypeTemplate(TemplateName Name) {
2717 NameClassification Result(NC_TypeTemplate);
2718 Result.Template = Name;
2719 return Result;
2720 }
2721
2722 static NameClassification VarTemplate(TemplateName Name) {
2723 NameClassification Result(NC_VarTemplate);
2724 Result.Template = Name;
2725 return Result;
2726 }
2727
2728 static NameClassification FunctionTemplate(TemplateName Name) {
2729 NameClassification Result(NC_FunctionTemplate);
2730 Result.Template = Name;
2731 return Result;
2732 }
2733
2734 static NameClassification Concept(TemplateName Name) {
2735 NameClassification Result(NC_Concept);
2736 Result.Template = Name;
2737 return Result;
2738 }
2739
2740 static NameClassification UndeclaredTemplate(TemplateName Name) {
2741 NameClassification Result(NC_UndeclaredTemplate);
2742 Result.Template = Name;
2743 return Result;
2744 }
2745
2746 NameClassificationKind getKind() const { return Kind; }
2747
2748 ExprResult getExpression() const {
2749 assert(Kind == NC_OverloadSet);
2750 return Expr;
2751 }
2752
2753 ParsedType getType() const {
2754 assert(Kind == NC_Type);
2755 return Type;
2756 }
2757
2758 NamedDecl *getNonTypeDecl() const {
2759 assert(Kind == NC_NonType);
2760 return NonTypeDecl;
2761 }
2762
2763 TemplateName getTemplateName() const {
2764 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2765 Kind == NC_VarTemplate || Kind == NC_Concept ||
2766 Kind == NC_UndeclaredTemplate);
2767 return Template;
2768 }
2769
2770 TemplateNameKind getTemplateNameKind() const {
2771 switch (Kind) {
2772 case NC_TypeTemplate:
2773 return TNK_Type_template;
2774 case NC_FunctionTemplate:
2775 return TNK_Function_template;
2776 case NC_VarTemplate:
2777 return TNK_Var_template;
2778 case NC_Concept:
2779 return TNK_Concept_template;
2780 case NC_UndeclaredTemplate:
2781 return TNK_Undeclared_template;
2782 default:
2783 llvm_unreachable("unsupported name classification.");
2784 }
2785 }
2786 };
2787
2788 /// Perform name lookup on the given name, classifying it based on
2789 /// the results of name lookup and the following token.
2790 ///
2791 /// This routine is used by the parser to resolve identifiers and help direct
2792 /// parsing. When the identifier cannot be found, this routine will attempt
2793 /// to correct the typo and classify based on the resulting name.
2794 ///
2795 /// \param S The scope in which we're performing name lookup.
2796 ///
2797 /// \param SS The nested-name-specifier that precedes the name.
2798 ///
2799 /// \param Name The identifier. If typo correction finds an alternative name,
2800 /// this pointer parameter will be updated accordingly.
2801 ///
2802 /// \param NameLoc The location of the identifier.
2803 ///
2804 /// \param NextToken The token following the identifier. Used to help
2805 /// disambiguate the name.
2806 ///
2807 /// \param CCC The correction callback, if typo correction is desired.
2808 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2809 IdentifierInfo *&Name, SourceLocation NameLoc,
2810 const Token &NextToken,
2811 CorrectionCandidateCallback *CCC = nullptr);
2812
2813 /// Act on the result of classifying a name as an undeclared (ADL-only)
2814 /// non-type declaration.
2815 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2816 SourceLocation NameLoc);
2817 /// Act on the result of classifying a name as an undeclared member of a
2818 /// dependent base class.
2819 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2820 IdentifierInfo *Name,
2821 SourceLocation NameLoc,
2822 bool IsAddressOfOperand);
2823 /// Act on the result of classifying a name as a specific non-type
2824 /// declaration.
2825 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2826 NamedDecl *Found,
2827 SourceLocation NameLoc,
2828 const Token &NextToken);
2829 /// Act on the result of classifying a name as an overload set.
2830 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2831
2832 /// Describes the detailed kind of a template name. Used in diagnostics.
2833 enum class TemplateNameKindForDiagnostics {
2834 ClassTemplate,
2835 FunctionTemplate,
2836 VarTemplate,
2837 AliasTemplate,
2838 TemplateTemplateParam,
2839 Concept,
2840 DependentTemplate
2841 };
2842 TemplateNameKindForDiagnostics
2843 getTemplateNameKindForDiagnostics(TemplateName Name);
2844
2845 /// Determine whether it's plausible that E was intended to be a
2846 /// template-name.
2847 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2848 if (!getLangOpts().CPlusPlus || E.isInvalid())
2849 return false;
2850 Dependent = false;
2851 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2852 return !DRE->hasExplicitTemplateArgs();
2853 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2854 return !ME->hasExplicitTemplateArgs();
2855 Dependent = true;
2856 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2857 return !DSDRE->hasExplicitTemplateArgs();
2858 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2859 return !DSME->hasExplicitTemplateArgs();
2860 // Any additional cases recognized here should also be handled by
2861 // diagnoseExprIntendedAsTemplateName.
2862 return false;
2863 }
2864 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2865 SourceLocation Less,
2866 SourceLocation Greater);
2867
2868 void warnOnReservedIdentifier(const NamedDecl *D);
2869
2870 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2871
2872 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2873 MultiTemplateParamsArg TemplateParameterLists);
2874 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2875 QualType &T, SourceLocation Loc,
2876 unsigned FailedFoldDiagID);
2877 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2878 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2879 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2880 DeclarationName Name, SourceLocation Loc,
2881 bool IsTemplateId);
2882 void
2883 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2884 SourceLocation FallbackLoc,
2885 SourceLocation ConstQualLoc = SourceLocation(),
2886 SourceLocation VolatileQualLoc = SourceLocation(),
2887 SourceLocation RestrictQualLoc = SourceLocation(),
2888 SourceLocation AtomicQualLoc = SourceLocation(),
2889 SourceLocation UnalignedQualLoc = SourceLocation());
2890
2891 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2892 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2893 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2894 const LookupResult &R);
2895 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2896 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2897 const LookupResult &R);
2898 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2899 const LookupResult &R);
2900 void CheckShadow(Scope *S, VarDecl *D);
2901
2902 /// Warn if 'E', which is an expression that is about to be modified, refers
2903 /// to a shadowing declaration.
2904 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2905
2906 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2907
2908private:
2909 /// Map of current shadowing declarations to shadowed declarations. Warn if
2910 /// it looks like the user is trying to modify the shadowing declaration.
2911 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2912
2913public:
2914 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2915 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2916 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2917 TypedefNameDecl *NewTD);
2918 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2919 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2920 TypeSourceInfo *TInfo,
2921 LookupResult &Previous);
2922 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2923 LookupResult &Previous, bool &Redeclaration);
2924 NamedDecl *ActOnVariableDeclarator(
2925 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
2926 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
2927 bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt);
2928 NamedDecl *
2929 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2930 MultiTemplateParamsArg TemplateParamLists);
2931 // Returns true if the variable declaration is a redeclaration
2932 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2933 void CheckVariableDeclarationType(VarDecl *NewVD);
2934 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2935 Expr *Init);
2936 void CheckCompleteVariableDeclaration(VarDecl *VD);
2937 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2938 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2939
2940 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2941 TypeSourceInfo *TInfo,
2942 LookupResult &Previous,
2943 MultiTemplateParamsArg TemplateParamLists,
2944 bool &AddToScope);
2945 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2946
2947 enum class CheckConstexprKind {
2948 /// Diagnose issues that are non-constant or that are extensions.
2949 Diagnose,
2950 /// Identify whether this function satisfies the formal rules for constexpr
2951 /// functions in the current lanugage mode (with no extensions).
2952 CheckValid
2953 };
2954
2955 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2956 CheckConstexprKind Kind);
2957
2958 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2959 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2960 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2961 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2962 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2963 // Returns true if the function declaration is a redeclaration
2964 bool CheckFunctionDeclaration(Scope *S,
2965 FunctionDecl *NewFD, LookupResult &Previous,
2966 bool IsMemberSpecialization, bool DeclIsDefn);
2967 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2968 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2969 QualType NewT, QualType OldT);
2970 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2971 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2972 void CheckHLSLEntryPoint(FunctionDecl *FD);
2973 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2974 bool IsDefinition);
2975 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2976 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2977 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2978 SourceLocation Loc,
2979 QualType T);
2980 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2981 SourceLocation NameLoc, IdentifierInfo *Name,
2982 QualType T, TypeSourceInfo *TSInfo,
2983 StorageClass SC);
2984 void ActOnParamDefaultArgument(Decl *param,
2985 SourceLocation EqualLoc,
2986 Expr *defarg);
2987 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2988 SourceLocation ArgLoc);
2989 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2990 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2991 SourceLocation EqualLoc);
2992 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2993 SourceLocation EqualLoc);
2994
2995 // Contexts where using non-trivial C union types can be disallowed. This is
2996 // passed to err_non_trivial_c_union_in_invalid_context.
2997 enum NonTrivialCUnionContext {
2998 // Function parameter.
2999 NTCUC_FunctionParam,
3000 // Function return.
3001 NTCUC_FunctionReturn,
3002 // Default-initialized object.
3003 NTCUC_DefaultInitializedObject,
3004 // Variable with automatic storage duration.
3005 NTCUC_AutoVar,
3006 // Initializer expression that might copy from another object.
3007 NTCUC_CopyInit,
3008 // Assignment.
3009 NTCUC_Assignment,
3010 // Compound literal.
3011 NTCUC_CompoundLiteral,
3012 // Block capture.
3013 NTCUC_BlockCapture,
3014 // lvalue-to-rvalue conversion of volatile type.
3015 NTCUC_LValueToRValueVolatile,
3016 };
3017
3018 /// Emit diagnostics if the initializer or any of its explicit or
3019 /// implicitly-generated subexpressions require copying or
3020 /// default-initializing a type that is or contains a C union type that is
3021 /// non-trivial to copy or default-initialize.
3022 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
3023
3024 // These flags are passed to checkNonTrivialCUnion.
3025 enum NonTrivialCUnionKind {
3026 NTCUK_Init = 0x1,
3027 NTCUK_Destruct = 0x2,
3028 NTCUK_Copy = 0x4,
3029 };
3030
3031 /// Emit diagnostics if a non-trivial C union type or a struct that contains
3032 /// a non-trivial C union is used in an invalid context.
3033 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
3034 NonTrivialCUnionContext UseContext,
3035 unsigned NonTrivialKind);
3036
3037 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3038 void ActOnUninitializedDecl(Decl *dcl);
3039 void ActOnInitializerError(Decl *Dcl);
3040
3041 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
3042 void ActOnCXXForRangeDecl(Decl *D);
3043 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
3044 IdentifierInfo *Ident,
3045 ParsedAttributes &Attrs);
3046 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
3047 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
3048 void CheckStaticLocalForDllExport(VarDecl *VD);
3049 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
3050 void FinalizeDeclaration(Decl *D);
3051 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3052 ArrayRef<Decl *> Group);
3053 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
3054
3055 /// Should be called on all declarations that might have attached
3056 /// documentation comments.
3057 void ActOnDocumentableDecl(Decl *D);
3058 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
3059
3060 enum class FnBodyKind {
3061 /// C++ [dcl.fct.def.general]p1
3062 /// function-body:
3063 /// ctor-initializer[opt] compound-statement
3064 /// function-try-block
3065 Other,
3066 /// = default ;
3067 Default,
3068 /// = delete ;
3069 Delete
3070 };
3071
3072 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3073 SourceLocation LocAfterDecls);
3074 void CheckForFunctionRedefinition(
3075 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3076 SkipBodyInfo *SkipBody = nullptr);
3077 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
3078 MultiTemplateParamsArg TemplateParamLists,
3079 SkipBodyInfo *SkipBody = nullptr,
3080 FnBodyKind BodyKind = FnBodyKind::Other);
3081 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
3082 SkipBodyInfo *SkipBody = nullptr,
3083 FnBodyKind BodyKind = FnBodyKind::Other);
3084 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3085 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
3086 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
3087 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
3088 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
3089 bool isObjCMethodDecl(Decl *D) {
3090 return D && isa<ObjCMethodDecl>(D);
3091 }
3092
3093 /// Determine whether we can delay parsing the body of a function or
3094 /// function template until it is used, assuming we don't care about emitting
3095 /// code for that function.
3096 ///
3097 /// This will be \c false if we may need the body of the function in the
3098 /// middle of parsing an expression (where it's impractical to switch to
3099 /// parsing a different function), for instance, if it's constexpr in C++11
3100 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3101 bool canDelayFunctionBody(const Declarator &D);
3102
3103 /// Determine whether we can skip parsing the body of a function
3104 /// definition, assuming we don't care about analyzing its body or emitting
3105 /// code for that function.
3106 ///
3107 /// This will be \c false only if we may need the body of the function in
3108 /// order to parse the rest of the program (for instance, if it is
3109 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3110 bool canSkipFunctionBody(Decl *D);
3111
3112 /// Determine whether \param D is function like (function or function
3113 /// template) for parsing.
3114 bool isDeclaratorFunctionLike(Declarator &D);
3115
3116 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
3117 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
3118 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3119 Decl *ActOnSkippedFunctionBody(Decl *Decl);
3120 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
3121
3122 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3123 /// attribute for which parsing is delayed.
3124 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
3125
3126 /// Diagnose any unused parameters in the given sequence of
3127 /// ParmVarDecl pointers.
3128 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
3129
3130 /// Diagnose whether the size of parameters or return value of a
3131 /// function or obj-c method definition is pass-by-value and larger than a
3132 /// specified threshold.
3133 void
3134 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
3135 QualType ReturnTy, NamedDecl *D);
3136
3137 void DiagnoseInvalidJumps(Stmt *Body);
3138 Decl *ActOnFileScopeAsmDecl(Expr *expr,
3139 SourceLocation AsmLoc,
3140 SourceLocation RParenLoc);
3141
3142 Decl *ActOnTopLevelStmtDecl(Stmt *Statement);
3143
3144 /// Handle a C++11 empty-declaration and attribute-declaration.
3145 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
3146 SourceLocation SemiLoc);
3147
3148 enum class ModuleDeclKind {
3149 Interface, ///< 'export module X;'
3150 Implementation, ///< 'module X;'
3151 PartitionInterface, ///< 'export module X:Y;'
3152 PartitionImplementation, ///< 'module X:Y;'
3153 };
3154
3155 /// An enumeration to represent the transition of states in parsing module
3156 /// fragments and imports. If we are not parsing a C++20 TU, or we find
3157 /// an error in state transition, the state is set to NotACXX20Module.
3158 enum class ModuleImportState {
3159 FirstDecl, ///< Parsing the first decl in a TU.
3160 GlobalFragment, ///< after 'module;' but before 'module X;'
3161 ImportAllowed, ///< after 'module X;' but before any non-import decl.
3162 ImportFinished, ///< after any non-import decl.
3163 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
3164 ///< non-import decl.
3165 PrivateFragmentImportFinished, ///< after 'module :private;' but a
3166 ///< non-import decl has already been seen.
3167 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3168 };
3169
3170private:
3171 /// The parser has begun a translation unit to be compiled as a C++20
3172 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3173 void HandleStartOfHeaderUnit();
3174
3175public:
3176 /// The parser has processed a module-declaration that begins the definition
3177 /// of a module interface or implementation.
3178 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
3179 SourceLocation ModuleLoc, ModuleDeclKind MDK,
3180 ModuleIdPath Path, ModuleIdPath Partition,
3181 ModuleImportState &ImportState);
3182
3183 /// The parser has processed a global-module-fragment declaration that begins
3184 /// the definition of the global module fragment of the current module unit.
3185 /// \param ModuleLoc The location of the 'module' keyword.
3186 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
3187
3188 /// The parser has processed a private-module-fragment declaration that begins
3189 /// the definition of the private module fragment of the current module unit.
3190 /// \param ModuleLoc The location of the 'module' keyword.
3191 /// \param PrivateLoc The location of the 'private' keyword.
3192 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
3193 SourceLocation PrivateLoc);
3194
3195 /// The parser has processed a module import declaration.
3196 ///
3197 /// \param StartLoc The location of the first token in the declaration. This
3198 /// could be the location of an '@', 'export', or 'import'.
3199 /// \param ExportLoc The location of the 'export' keyword, if any.
3200 /// \param ImportLoc The location of the 'import' keyword.
3201 /// \param Path The module toplevel name as an access path.
3202 /// \param IsPartition If the name is for a partition.
3203 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3204 SourceLocation ExportLoc,
3205 SourceLocation ImportLoc, ModuleIdPath Path,
3206 bool IsPartition = false);
3207 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3208 SourceLocation ExportLoc,
3209 SourceLocation ImportLoc, Module *M,
3210 ModuleIdPath Path = {});
3211
3212 /// The parser has processed a module import translated from a
3213 /// #include or similar preprocessing directive.
3214 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3215 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3216
3217 /// The parsed has entered a submodule.
3218 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3219 /// The parser has left a submodule.
3220 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3221
3222 /// Create an implicit import of the given module at the given
3223 /// source location, for error recovery, if possible.
3224 ///
3225 /// This routine is typically used when an entity found by name lookup
3226 /// is actually hidden within a module that we know about but the user
3227 /// has forgotten to import.
3228 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3229 Module *Mod);
3230
3231 /// Kinds of missing import. Note, the values of these enumerators correspond
3232 /// to %select values in diagnostics.
3233 enum class MissingImportKind {
3234 Declaration,
3235 Definition,
3236 DefaultArgument,
3237 ExplicitSpecialization,
3238 PartialSpecialization
3239 };
3240
3241 /// Diagnose that the specified declaration needs to be visible but
3242 /// isn't, and suggest a module import that would resolve the problem.
3243 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
3244 MissingImportKind MIK, bool Recover = true);
3245 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
3246 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3247 MissingImportKind MIK, bool Recover);
3248
3249 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
3250 SourceLocation LBraceLoc);
3251 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
3252 SourceLocation RBraceLoc);
3253
3254 /// We've found a use of a templated declaration that would trigger an
3255 /// implicit instantiation. Check that any relevant explicit specializations
3256 /// and partial specializations are visible/reachable, and diagnose if not.
3257 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
3258 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
3259
3260 /// Retrieve a suitable printing policy for diagnostics.
3261 PrintingPolicy getPrintingPolicy() const {
3262 return getPrintingPolicy(Context, PP);
3263 }
3264
3265 /// Retrieve a suitable printing policy for diagnostics.
3266 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3267 const Preprocessor &PP);
3268
3269 /// Scope actions.
3270 void ActOnPopScope(SourceLocation Loc, Scope *S);
3271 void ActOnTranslationUnitScope(Scope *S);
3272
3273 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3274 const ParsedAttributesView &DeclAttrs,
3275 RecordDecl *&AnonRecord);
3276 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3277 const ParsedAttributesView &DeclAttrs,
3278 MultiTemplateParamsArg TemplateParams,
3279 bool IsExplicitInstantiation,
3280 RecordDecl *&AnonRecord);
3281
3282 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3283 AccessSpecifier AS,
3284 RecordDecl *Record,
3285 const PrintingPolicy &Policy);
3286
3287 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3288 RecordDecl *Record);
3289
3290 /// Common ways to introduce type names without a tag for use in diagnostics.
3291 /// Keep in sync with err_tag_reference_non_tag.
3292 enum NonTagKind {
3293 NTK_NonStruct,
3294 NTK_NonClass,
3295 NTK_NonUnion,
3296 NTK_NonEnum,
3297 NTK_Typedef,
3298 NTK_TypeAlias,
3299 NTK_Template,
3300 NTK_TypeAliasTemplate,
3301 NTK_TemplateTemplateArgument,
3302 };
3303
3304 /// Given a non-tag type declaration, returns an enum useful for indicating
3305 /// what kind of non-tag type this is.
3306 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3307
3308 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3309 TagTypeKind NewTag, bool isDefinition,
3310 SourceLocation NewTagLoc,
3311 const IdentifierInfo *Name);
3312
3313 enum TagUseKind {
3314 TUK_Reference, // Reference to a tag: 'struct foo *X;'
3315 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3316 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3317 TUK_Friend // Friend declaration: 'friend struct foo;'
3318 };
3319
3320 enum OffsetOfKind {
3321 // Not parsing a type within __builtin_offsetof.
3322 OOK_Outside,
3323 // Parsing a type within __builtin_offsetof.
3324 OOK_Builtin,
3325 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3326 // To improve our diagnostic message.
3327 OOK_Macro,
3328 };
3329
3330 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3331 SourceLocation KWLoc, CXXScopeSpec &SS,
3332 IdentifierInfo *Name, SourceLocation NameLoc,
3333 const ParsedAttributesView &Attr, AccessSpecifier AS,
3334 SourceLocation ModulePrivateLoc,
3335 MultiTemplateParamsArg TemplateParameterLists,
3336 bool &OwnedDecl, bool &IsDependent,
3337 SourceLocation ScopedEnumKWLoc,
3338 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3339 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3340 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3341
3342 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3343 unsigned TagSpec, SourceLocation TagLoc,
3344 CXXScopeSpec &SS, IdentifierInfo *Name,
3345 SourceLocation NameLoc,
3346 const ParsedAttributesView &Attr,
3347 MultiTemplateParamsArg TempParamLists);
3348
3349 TypeResult ActOnDependentTag(Scope *S,
3350 unsigned TagSpec,
3351 TagUseKind TUK,
3352 const CXXScopeSpec &SS,
3353 IdentifierInfo *Name,
3354 SourceLocation TagLoc,
3355 SourceLocation NameLoc);
3356
3357 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3358 IdentifierInfo *ClassName,
3359 SmallVectorImpl<Decl *> &Decls);
3360 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3361 Declarator &D, Expr *BitfieldWidth);
3362
3363 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3364 Declarator &D, Expr *BitfieldWidth,
3365 InClassInitStyle InitStyle,
3366 AccessSpecifier AS);
3367 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3368 SourceLocation DeclStart, Declarator &D,
3369 Expr *BitfieldWidth,
3370 InClassInitStyle InitStyle,
3371 AccessSpecifier AS,
3372 const ParsedAttr &MSPropertyAttr);
3373
3374 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3375 TypeSourceInfo *TInfo,
3376 RecordDecl *Record, SourceLocation Loc,
3377 bool Mutable, Expr *BitfieldWidth,
3378 InClassInitStyle InitStyle,
3379 SourceLocation TSSL,
3380 AccessSpecifier AS, NamedDecl *PrevDecl,
3381 Declarator *D = nullptr);
3382
3383 bool CheckNontrivialField(FieldDecl *FD);
3384 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3385
3386 enum TrivialABIHandling {
3387 /// The triviality of a method unaffected by "trivial_abi".
3388 TAH_IgnoreTrivialABI,
3389
3390 /// The triviality of a method affected by "trivial_abi".
3391 TAH_ConsiderTrivialABI
3392 };
3393
3394 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3395 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3396 bool Diagnose = false);
3397
3398 /// For a defaulted function, the kind of defaulted function that it is.
3399 class DefaultedFunctionKind {
3400 CXXSpecialMember SpecialMember : 8;
3401 DefaultedComparisonKind Comparison : 8;
3402
3403 public:
3404 DefaultedFunctionKind()
3405 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3406 }
3407 DefaultedFunctionKind(CXXSpecialMember CSM)
3408 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3409 DefaultedFunctionKind(DefaultedComparisonKind Comp)
3410 : SpecialMember(CXXInvalid), Comparison(Comp) {}
3411
3412 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3413 bool isComparison() const {
3414 return Comparison != DefaultedComparisonKind::None;
3415 }
3416
3417 explicit operator bool() const {
3418 return isSpecialMember() || isComparison();
3419 }
3420
3421 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3422 DefaultedComparisonKind asComparison() const { return Comparison; }
3423
3424 /// Get the index of this function kind for use in diagnostics.
3425 unsigned getDiagnosticIndex() const {
3426 static_assert(CXXInvalid > CXXDestructor,
3427 "invalid should have highest index");
3428 static_assert((unsigned)DefaultedComparisonKind::None == 0,
3429 "none should be equal to zero");
3430 return SpecialMember + (unsigned)Comparison;
3431 }
3432 };
3433
3434 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3435
3436 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3437 return getDefaultedFunctionKind(MD).asSpecialMember();
3438 }
3439 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3440 return getDefaultedFunctionKind(FD).asComparison();
3441 }
3442
3443 void ActOnLastBitfield(SourceLocation DeclStart,
3444 SmallVectorImpl<Decl *> &AllIvarDecls);
3445 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3446 Declarator &D, Expr *BitfieldWidth,
3447 tok::ObjCKeywordKind visibility);
3448
3449 // This is used for both record definitions and ObjC interface declarations.
3450 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3451 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3452 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3453
3454 /// ActOnTagStartDefinition - Invoked when we have entered the
3455 /// scope of a tag's definition (e.g., for an enumeration, class,
3456 /// struct, or union).
3457 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3458
3459 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3460 /// Differently from C++, actually parse the body and reject / error out
3461 /// in case of a structural mismatch.
3462 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3463
3464 /// Check ODR hashes for C/ObjC when merging types from modules.
3465 /// Differently from C++, actually parse the body and reject in case
3466 /// of a mismatch.
3467 template <typename T,
3468 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
3469 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
3470 if (Duplicate->getODRHash() != Previous->getODRHash())
3471 return false;
3472
3473 // Make the previous decl visible.
3474 makeMergedDefinitionVisible(Previous);
3475 return true;
3476 }
3477
3478 typedef void *SkippedDefinitionContext;
3479
3480 /// Invoked when we enter a tag definition that we're skipping.
3481 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3482
3483 void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl);
3484
3485 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3486 /// C++ record definition's base-specifiers clause and are starting its
3487 /// member declarations.
3488 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3489 SourceLocation FinalLoc,
3490 bool IsFinalSpelledSealed,
3491 bool IsAbstract,
3492 SourceLocation LBraceLoc);
3493
3494 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3495 /// the definition of a tag (enumeration, class, struct, or union).
3496 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3497 SourceRange BraceRange);
3498
3499 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3500
3501 void ActOnObjCContainerFinishDefinition();
3502
3503 /// Invoked when we must temporarily exit the objective-c container
3504 /// scope for parsing/looking-up C constructs.
3505 ///
3506 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3507 void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx);
3508 void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx);
3509
3510 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3511 /// error parsing the definition of a tag.
3512 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3513
3514 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3515 EnumConstantDecl *LastEnumConst,
3516 SourceLocation IdLoc,
3517 IdentifierInfo *Id,
3518 Expr *val);
3519 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3520 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3521 QualType EnumUnderlyingTy, bool IsFixed,
3522 const EnumDecl *Prev);
3523
3524 /// Determine whether the body of an anonymous enumeration should be skipped.
3525 /// \param II The name of the first enumerator.
3526 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3527 SourceLocation IILoc);
3528
3529 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3530 SourceLocation IdLoc, IdentifierInfo *Id,
3531 const ParsedAttributesView &Attrs,
3532 SourceLocation EqualLoc, Expr *Val);
3533 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3534 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3535 const ParsedAttributesView &Attr);
3536
3537 /// Set the current declaration context until it gets popped.
3538 void PushDeclContext(Scope *S, DeclContext *DC);
3539 void PopDeclContext();
3540
3541 /// EnterDeclaratorContext - Used when we must lookup names in the context
3542 /// of a declarator's nested name specifier.
3543 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3544 void ExitDeclaratorContext(Scope *S);
3545
3546 /// Enter a template parameter scope, after it's been associated with a particular
3547 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3548 /// in the correct order.
3549 void EnterTemplatedContext(Scope *S, DeclContext *DC);
3550
3551 /// Push the parameters of D, which must be a function, into scope.
3552 void ActOnReenterFunctionContext(Scope* S, Decl* D);
3553 void ActOnExitFunctionContext();
3554
3555 /// If \p AllowLambda is true, treat lambda as function.
3556 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
3557
3558 /// Returns a pointer to the innermost enclosing function, or nullptr if the
3559 /// current context is not inside a function. If \p AllowLambda is true,
3560 /// this can return the call operator of an enclosing lambda, otherwise
3561 /// lambdas are skipped when looking for an enclosing function.
3562 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
3563
3564 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3565 /// the method decl for the method being parsed. If we're currently
3566 /// in a 'block', this returns the containing context.
3567 ObjCMethodDecl *getCurMethodDecl();
3568
3569 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3570 /// or C function we're in, otherwise return null. If we're currently
3571 /// in a 'block', this returns the containing context.
3572 NamedDecl *getCurFunctionOrMethodDecl() const;
3573
3574 /// Add this decl to the scope shadowed decl chains.
3575 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3576
3577 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3578 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3579 /// true if 'D' belongs to the given declaration context.
3580 ///
3581 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3582 /// enclosing namespace set of the context, rather than contained
3583 /// directly within it.
3584 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3585 bool AllowInlineNamespace = false) const;
3586
3587 /// Finds the scope corresponding to the given decl context, if it
3588 /// happens to be an enclosing scope. Otherwise return NULL.
3589 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3590
3591 /// Subroutines of ActOnDeclarator().
3592 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3593 TypeSourceInfo *TInfo);
3594 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3595
3596 /// Describes the kind of merge to perform for availability
3597 /// attributes (including "deprecated", "unavailable", and "availability").
3598 enum AvailabilityMergeKind {
3599 /// Don't merge availability attributes at all.
3600 AMK_None,
3601 /// Merge availability attributes for a redeclaration, which requires
3602 /// an exact match.
3603 AMK_Redeclaration,
3604 /// Merge availability attributes for an override, which requires
3605 /// an exact match or a weakening of constraints.
3606 AMK_Override,
3607 /// Merge availability attributes for an implementation of
3608 /// a protocol requirement.
3609 AMK_ProtocolImplementation,
3610 /// Merge availability attributes for an implementation of
3611 /// an optional protocol requirement.
3612 AMK_OptionalProtocolImplementation
3613 };
3614
3615 /// Describes the kind of priority given to an availability attribute.
3616 ///
3617 /// The sum of priorities deteremines the final priority of the attribute.
3618 /// The final priority determines how the attribute will be merged.
3619 /// An attribute with a lower priority will always remove higher priority
3620 /// attributes for the specified platform when it is being applied. An
3621 /// attribute with a higher priority will not be applied if the declaration
3622 /// already has an availability attribute with a lower priority for the
3623 /// specified platform. The final prirority values are not expected to match
3624 /// the values in this enumeration, but instead should be treated as a plain
3625 /// integer value. This enumeration just names the priority weights that are
3626 /// used to calculate that final vaue.
3627 enum AvailabilityPriority : int {
3628 /// The availability attribute was specified explicitly next to the
3629 /// declaration.
3630 AP_Explicit = 0,
3631
3632 /// The availability attribute was applied using '#pragma clang attribute'.
3633 AP_PragmaClangAttribute = 1,
3634
3635 /// The availability attribute for a specific platform was inferred from
3636 /// an availability attribute for another platform.
3637 AP_InferredFromOtherPlatform = 2
3638 };
3639
3640 /// Attribute merging methods. Return true if a new attribute was added.
3641 AvailabilityAttr *
3642 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3643 IdentifierInfo *Platform, bool Implicit,
3644 VersionTuple Introduced, VersionTuple Deprecated,
3645 VersionTuple Obsoleted, bool IsUnavailable,
3646 StringRef Message, bool IsStrict, StringRef Replacement,
3647 AvailabilityMergeKind AMK, int Priority);
3648 TypeVisibilityAttr *
3649 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3650 TypeVisibilityAttr::VisibilityType Vis);
3651 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3652 VisibilityAttr::VisibilityType Vis);
3653 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3654 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3655 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3656 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3657 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3658 const AttributeCommonInfo &CI,
3659 bool BestCase,
3660 MSInheritanceModel Model);
3661 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3662 StringRef NewUserDiagnostic);
3663 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3664 IdentifierInfo *Format, int FormatIdx,
3665 int FirstArg);
3666 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3667 StringRef Name);
3668 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3669 StringRef Name);
3670 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3671 const AttributeCommonInfo &CI,
3672 const IdentifierInfo *Ident);
3673 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3674 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3675 StringRef Name);
3676 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3677 const AttributeCommonInfo &CI);
3678 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3679 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3680 const InternalLinkageAttr &AL);
3681 WebAssemblyImportNameAttr *mergeImportNameAttr(
3682 Decl *D, const WebAssemblyImportNameAttr &AL);
3683 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3684 Decl *D, const WebAssemblyImportModuleAttr &AL);
3685 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3686 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3687 const EnforceTCBLeafAttr &AL);
3688 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3689 HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3690 const AttributeCommonInfo &AL,
3691 int X, int Y, int Z);
3692 HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3693 HLSLShaderAttr::ShaderType ShaderType);
3694
3695 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3696 AvailabilityMergeKind AMK = AMK_Redeclaration);
3697 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3698 LookupResult &OldDecls);
3699 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3700 bool MergeTypeWithOld, bool NewDeclIsDefn);
3701 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3702 Scope *S, bool MergeTypeWithOld);
3703 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3704 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3705 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3706 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3707 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3708 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3709 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3710
3711 // AssignmentAction - This is used by all the assignment diagnostic functions
3712 // to represent what is actually causing the operation
3713 enum AssignmentAction {
3714 AA_Assigning,
3715 AA_Passing,
3716 AA_Returning,
3717 AA_Converting,
3718 AA_Initializing,
3719 AA_Sending,
3720 AA_Casting,
3721 AA_Passing_CFAudited
3722 };
3723
3724 /// C++ Overloading.
3725 enum OverloadKind {
3726 /// This is a legitimate overload: the existing declarations are
3727 /// functions or function templates with different signatures.
3728 Ovl_Overload,
3729
3730 /// This is not an overload because the signature exactly matches
3731 /// an existing declaration.
3732 Ovl_Match,
3733
3734 /// This is not an overload because the lookup results contain a
3735 /// non-function.
3736 Ovl_NonFunction
3737 };
3738 OverloadKind CheckOverload(Scope *S,
3739 FunctionDecl *New,
3740 const LookupResult &OldDecls,
3741 NamedDecl *&OldDecl,
3742 bool UseMemberUsingDeclRules);
3743 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
3744 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true,
3745 bool ConsiderRequiresClauses = true);
3746
3747 // Calculates whether the expression Constraint depends on an enclosing
3748 // template, for the purposes of [temp.friend] p9.
3749 // TemplateDepth is the 'depth' of the friend function, which is used to
3750 // compare whether a declaration reference is referring to a containing
3751 // template, or just the current friend function. A 'lower' TemplateDepth in
3752 // the AST refers to a 'containing' template. As the constraint is
3753 // uninstantiated, this is relative to the 'top' of the TU.
3754 bool
3755 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
3756 unsigned TemplateDepth,
3757 const Expr *Constraint);
3758
3759 // Calculates whether the friend function depends on an enclosing template for
3760 // the purposes of [temp.friend] p9.
3761 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
3762
3763 // Calculates whether two constraint expressions are equal irrespective of a
3764 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
3765 // 'New', which are the "source" of the constraint, since this is necessary
3766 // for figuring out the relative 'depth' of the constraint. The depth of the
3767 // 'primary template' and the 'instantiated from' templates aren't necessarily
3768 // the same, such as a case when one is a 'friend' defined in a class.
3769 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
3770 const Expr *OldConstr,
3771 const NamedDecl *New,
3772 const Expr *NewConstr);
3773
3774 enum class AllowedExplicit {
3775 /// Allow no explicit functions to be used.
3776 None,
3777 /// Allow explicit conversion functions but not explicit constructors.
3778 Conversions,
3779 /// Allow both explicit conversion functions and explicit constructors.
3780 All
3781 };
3782
3783 ImplicitConversionSequence
3784 TryImplicitConversion(Expr *From, QualType ToType,
3785 bool SuppressUserConversions,
3786 AllowedExplicit AllowExplicit,
3787 bool InOverloadResolution,
3788 bool CStyle,
3789 bool AllowObjCWritebackConversion);
3790
3791 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3792 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3793 bool IsComplexPromotion(QualType FromType, QualType ToType);
3794 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3795 bool InOverloadResolution,
3796 QualType& ConvertedType, bool &IncompatibleObjC);
3797 bool isObjCPointerConversion(QualType FromType, QualType ToType,
3798 QualType& ConvertedType, bool &IncompatibleObjC);
3799 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3800 QualType &ConvertedType);
3801 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3802 QualType& ConvertedType);
3803 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3804 const FunctionProtoType *NewType,
3805 unsigned *ArgPos = nullptr,
3806 bool Reversed = false);
3807 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3808 QualType FromType, QualType ToType);
3809
3810 void maybeExtendBlockObject(ExprResult &E);
3811 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3812 bool CheckPointerConversion(Expr *From, QualType ToType,
3813 CastKind &Kind,
3814 CXXCastPath& BasePath,
3815 bool IgnoreBaseAccess,
3816 bool Diagnose = true);
3817 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3818 bool InOverloadResolution,
3819 QualType &ConvertedType);
3820 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3821 CastKind &Kind,
3822 CXXCastPath &BasePath,
3823 bool IgnoreBaseAccess);
3824 bool IsQualificationConversion(QualType FromType, QualType ToType,
3825 bool CStyle, bool &ObjCLifetimeConversion);
3826 bool IsFunctionConversion(QualType FromType, QualType ToType,
3827 QualType &ResultTy);
3828 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3829 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
3830
3831 bool CanPerformAggregateInitializationForOverloadResolution(
3832 const InitializedEntity &Entity, InitListExpr *From);
3833
3834 bool IsStringInit(Expr *Init, const ArrayType *AT);
3835
3836 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3837 ExprResult Init);
3838 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3839 SourceLocation EqualLoc,
3840 ExprResult Init,
3841 bool TopLevelOfInitList = false,
3842 bool AllowExplicit = false);
3843 ExprResult PerformObjectArgumentInitialization(Expr *From,
3844 NestedNameSpecifier *Qualifier,
3845 NamedDecl *FoundDecl,
3846 CXXMethodDecl *Method);
3847
3848 /// Check that the lifetime of the initializer (and its subobjects) is
3849 /// sufficient for initializing the entity, and perform lifetime extension
3850 /// (when permitted) if not.
3851 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3852
3853 ExprResult PerformContextuallyConvertToBool(Expr *From);
3854 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3855
3856 /// Contexts in which a converted constant expression is required.
3857 enum CCEKind {
3858 CCEK_CaseValue, ///< Expression in a case label.
3859 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3860 CCEK_TemplateArg, ///< Value of a non-type template parameter.
3861 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3862 CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3863 CCEK_Noexcept ///< Condition in a noexcept(bool) specifier.
3864 };
3865 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3866 llvm::APSInt &Value, CCEKind CCE);
3867 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3868 APValue &Value, CCEKind CCE,
3869 NamedDecl *Dest = nullptr);
3870
3871 /// Abstract base class used to perform a contextual implicit
3872 /// conversion from an expression to any type passing a filter.
3873 class ContextualImplicitConverter {
3874 public:
3875 bool Suppress;
3876 bool SuppressConversion;
3877
3878 ContextualImplicitConverter(bool Suppress = false,
3879 bool SuppressConversion = false)
3880 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3881
3882 /// Determine whether the specified type is a valid destination type
3883 /// for this conversion.
3884 virtual bool match(QualType T) = 0;
3885
3886 /// Emits a diagnostic complaining that the expression does not have
3887 /// integral or enumeration type.
3888 virtual SemaDiagnosticBuilder
3889 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3890
3891 /// Emits a diagnostic when the expression has incomplete class type.
3892 virtual SemaDiagnosticBuilder
3893 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3894
3895 /// Emits a diagnostic when the only matching conversion function
3896 /// is explicit.
3897 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3898 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3899
3900 /// Emits a note for the explicit conversion function.
3901 virtual SemaDiagnosticBuilder
3902 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3903
3904 /// Emits a diagnostic when there are multiple possible conversion
3905 /// functions.
3906 virtual SemaDiagnosticBuilder
3907 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3908
3909 /// Emits a note for one of the candidate conversions.
3910 virtual SemaDiagnosticBuilder
3911 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3912
3913 /// Emits a diagnostic when we picked a conversion function
3914 /// (for cases when we are not allowed to pick a conversion function).
3915 virtual SemaDiagnosticBuilder diagnoseConversion(
3916 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3917
3918 virtual ~ContextualImplicitConverter() {}
3919 };
3920
3921 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3922 bool AllowScopedEnumerations;
3923
3924 public:
3925 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3926 bool Suppress, bool SuppressConversion)
3927 : ContextualImplicitConverter(Suppress, SuppressConversion),
3928 AllowScopedEnumerations(AllowScopedEnumerations) {}
3929
3930 /// Match an integral or (possibly scoped) enumeration type.
3931 bool match(QualType T) override;
3932
3933 SemaDiagnosticBuilder
3934 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3935 return diagnoseNotInt(S, Loc, T);
3936 }
3937
3938 /// Emits a diagnostic complaining that the expression does not have
3939 /// integral or enumeration type.
3940 virtual SemaDiagnosticBuilder
3941 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3942 };
3943
3944 /// Perform a contextual implicit conversion.
3945 ExprResult PerformContextualImplicitConversion(
3946 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3947
3948
3949 enum ObjCSubscriptKind {
3950 OS_Array,
3951 OS_Dictionary,
3952 OS_Error
3953 };
3954 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3955
3956 // Note that LK_String is intentionally after the other literals, as
3957 // this is used for diagnostics logic.
3958 enum ObjCLiteralKind {
3959 LK_Array,
3960 LK_Dictionary,
3961 LK_Numeric,
3962 LK_Boxed,
3963 LK_String,
3964 LK_Block,
3965 LK_None
3966 };
3967 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3968
3969 ExprResult PerformObjectMemberConversion(Expr *From,
3970 NestedNameSpecifier *Qualifier,
3971 NamedDecl *FoundDecl,
3972 NamedDecl *Member);
3973
3974 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3975 // TODO: make this is a typesafe union.
3976 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3977 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3978
3979 using ADLCallKind = CallExpr::ADLCallKind;
3980
3981 void AddOverloadCandidate(
3982 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
3983 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3984 bool PartialOverloading = false, bool AllowExplicit = true,
3985 bool AllowExplicitConversion = false,
3986 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3987 ConversionSequenceList EarlyConversions = std::nullopt,
3988 OverloadCandidateParamOrder PO = {});
3989 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3990 ArrayRef<Expr *> Args,
3991 OverloadCandidateSet &CandidateSet,
3992 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3993 bool SuppressUserConversions = false,
3994 bool PartialOverloading = false,
3995 bool FirstArgumentIsBase = false);
3996 void AddMethodCandidate(DeclAccessPair FoundDecl,
3997 QualType ObjectType,
3998 Expr::Classification ObjectClassification,
3999 ArrayRef<Expr *> Args,
4000 OverloadCandidateSet& CandidateSet,
4001 bool SuppressUserConversion = false,
4002 OverloadCandidateParamOrder PO = {});
4003 void
4004 AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
4005 CXXRecordDecl *ActingContext, QualType ObjectType,
4006 Expr::Classification ObjectClassification,
4007 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4008 bool SuppressUserConversions = false,
4009 bool PartialOverloading = false,
4010 ConversionSequenceList EarlyConversions = std::nullopt,
4011 OverloadCandidateParamOrder PO = {});
4012 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
4013 DeclAccessPair FoundDecl,
4014 CXXRecordDecl *ActingContext,
4015 TemplateArgumentListInfo *ExplicitTemplateArgs,
4016 QualType ObjectType,
4017 Expr::Classification ObjectClassification,
4018 ArrayRef<Expr *> Args,
4019 OverloadCandidateSet& CandidateSet,
4020 bool SuppressUserConversions = false,
4021 bool PartialOverloading = false,
4022 OverloadCandidateParamOrder PO = {});
4023 void AddTemplateOverloadCandidate(
4024 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4025 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4026 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
4027 bool PartialOverloading = false, bool AllowExplicit = true,
4028 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
4029 OverloadCandidateParamOrder PO = {});
4030 bool CheckNonDependentConversions(
4031 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
4032 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4033 ConversionSequenceList &Conversions, bool SuppressUserConversions,
4034 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
4035 Expr::Classification ObjectClassification = {},
4036 OverloadCandidateParamOrder PO = {});
4037 void AddConversionCandidate(
4038 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
4039 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4040 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4041 bool AllowExplicit, bool AllowResultConversion = true);
4042 void AddTemplateConversionCandidate(
4043 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4044 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4045 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4046 bool AllowExplicit, bool AllowResultConversion = true);
4047 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
4048 DeclAccessPair FoundDecl,
4049 CXXRecordDecl *ActingContext,
4050 const FunctionProtoType *Proto,
4051 Expr *Object, ArrayRef<Expr *> Args,
4052 OverloadCandidateSet& CandidateSet);
4053 void AddNonMemberOperatorCandidates(
4054 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
4055 OverloadCandidateSet &CandidateSet,
4056 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4057 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4058 SourceLocation OpLoc, ArrayRef<Expr *> Args,
4059 OverloadCandidateSet &CandidateSet,
4060 OverloadCandidateParamOrder PO = {});
4061 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
4062 OverloadCandidateSet& CandidateSet,
4063 bool IsAssignmentOperator = false,
4064 unsigned NumContextualBoolArguments = 0);
4065 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
4066 SourceLocation OpLoc, ArrayRef<Expr *> Args,
4067 OverloadCandidateSet& CandidateSet);
4068 void AddArgumentDependentLookupCandidates(DeclarationName Name,
4069 SourceLocation Loc,
4070 ArrayRef<Expr *> Args,
4071 TemplateArgumentListInfo *ExplicitTemplateArgs,
4072 OverloadCandidateSet& CandidateSet,
4073 bool PartialOverloading = false);
4074
4075 // Emit as a 'note' the specific overload candidate
4076 void NoteOverloadCandidate(
4077 const NamedDecl *Found, const FunctionDecl *Fn,
4078 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
4079 QualType DestType = QualType(), bool TakingAddress = false);
4080
4081 // Emit as a series of 'note's all template and non-templates identified by
4082 // the expression Expr
4083 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
4084 bool TakingAddress = false);
4085
4086 /// Check the enable_if expressions on the given function. Returns the first
4087 /// failing attribute, or NULL if they were all successful.
4088 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
4089 ArrayRef<Expr *> Args,
4090 bool MissingImplicitThis = false);
4091
4092 /// Find the failed Boolean condition within a given Boolean
4093 /// constant expression, and describe it with a string.
4094 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
4095
4096 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4097 /// non-ArgDependent DiagnoseIfAttrs.
4098 ///
4099 /// Argument-dependent diagnose_if attributes should be checked each time a
4100 /// function is used as a direct callee of a function call.
4101 ///
4102 /// Returns true if any errors were emitted.
4103 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
4104 const Expr *ThisArg,
4105 ArrayRef<const Expr *> Args,
4106 SourceLocation Loc);
4107
4108 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4109 /// ArgDependent DiagnoseIfAttrs.
4110 ///
4111 /// Argument-independent diagnose_if attributes should be checked on every use
4112 /// of a function.
4113 ///
4114 /// Returns true if any errors were emitted.
4115 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
4116 SourceLocation Loc);
4117
4118 /// Returns whether the given function's address can be taken or not,
4119 /// optionally emitting a diagnostic if the address can't be taken.
4120 ///
4121 /// Returns false if taking the address of the function is illegal.
4122 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
4123 bool Complain = false,
4124 SourceLocation Loc = SourceLocation());
4125
4126 // [PossiblyAFunctionType] --> [Return]
4127 // NonFunctionType --> NonFunctionType
4128 // R (A) --> R(A)
4129 // R (*)(A) --> R (A)
4130 // R (&)(A) --> R (A)
4131 // R (S::*)(A) --> R (A)
4132 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
4133
4134 FunctionDecl *
4135 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
4136 QualType TargetType,
4137 bool Complain,
4138 DeclAccessPair &Found,
4139 bool *pHadMultipleCandidates = nullptr);
4140
4141 FunctionDecl *
4142 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
4143
4144 bool resolveAndFixAddressOfSingleOverloadCandidate(
4145 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
4146
4147 FunctionDecl *
4148 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
4149 bool Complain = false,
4150 DeclAccessPair *Found = nullptr);
4151
4152 bool ResolveAndFixSingleFunctionTemplateSpecialization(
4153 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
4154 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
4155 QualType DestTypeForComplaining = QualType(),
4156 unsigned DiagIDForComplaining = 0);
4157
4158 Expr *FixOverloadedFunctionReference(Expr *E,
4159 DeclAccessPair FoundDecl,
4160 FunctionDecl *Fn);
4161 ExprResult FixOverloadedFunctionReference(ExprResult,
4162 DeclAccessPair FoundDecl,
4163 FunctionDecl *Fn);
4164
4165 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
4166 ArrayRef<Expr *> Args,
4167 OverloadCandidateSet &CandidateSet,
4168 bool PartialOverloading = false);
4169 void AddOverloadedCallCandidates(
4170 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
4171 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
4172
4173 // An enum used to represent the different possible results of building a
4174 // range-based for loop.
4175 enum ForRangeStatus {
4176 FRS_Success,
4177 FRS_NoViableFunction,
4178 FRS_DiagnosticIssued
4179 };
4180
4181 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
4182 SourceLocation RangeLoc,
4183 const DeclarationNameInfo &NameInfo,
4184 LookupResult &MemberLookup,
4185 OverloadCandidateSet *CandidateSet,
4186 Expr *Range, ExprResult *CallExpr);
4187
4188 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
4189 UnresolvedLookupExpr *ULE,
4190 SourceLocation LParenLoc,
4191 MultiExprArg Args,
4192 SourceLocation RParenLoc,
4193 Expr *ExecConfig,
4194 bool AllowTypoCorrection=true,
4195 bool CalleesAddressIsTaken=false);
4196
4197 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
4198 MultiExprArg Args, SourceLocation RParenLoc,
4199 OverloadCandidateSet *CandidateSet,
4200 ExprResult *Result);
4201
4202 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
4203 NestedNameSpecifierLoc NNSLoc,
4204 DeclarationNameInfo DNI,
4205 const UnresolvedSetImpl &Fns,
4206 bool PerformADL = true);
4207
4208 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
4209 UnaryOperatorKind Opc,
4210 const UnresolvedSetImpl &Fns,
4211 Expr *input, bool RequiresADL = true);
4212
4213 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
4214 OverloadedOperatorKind Op,
4215 const UnresolvedSetImpl &Fns,
4216 ArrayRef<Expr *> Args, bool RequiresADL = true);
4217 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
4218 BinaryOperatorKind Opc,
4219 const UnresolvedSetImpl &Fns,
4220 Expr *LHS, Expr *RHS,
4221 bool RequiresADL = true,
4222 bool AllowRewrittenCandidates = true,
4223 FunctionDecl *DefaultedFn = nullptr);
4224 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
4225 const UnresolvedSetImpl &Fns,
4226 Expr *LHS, Expr *RHS,
4227 FunctionDecl *DefaultedFn);
4228
4229 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4230 SourceLocation RLoc, Expr *Base,
4231 MultiExprArg Args);
4232
4233 ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
4234 SourceLocation LParenLoc,
4235 MultiExprArg Args,
4236 SourceLocation RParenLoc,
4237 Expr *ExecConfig = nullptr,
4238 bool IsExecConfig = false,
4239 bool AllowRecovery = false);
4240 ExprResult
4241 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
4242 MultiExprArg Args,
4243 SourceLocation RParenLoc);
4244
4245 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
4246 SourceLocation OpLoc,
4247 bool *NoArrowOperatorFound = nullptr);
4248
4249 /// CheckCallReturnType - Checks that a call expression's return type is
4250 /// complete. Returns true on failure. The location passed in is the location
4251 /// that best represents the call.
4252 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4253 CallExpr *CE, FunctionDecl *FD);
4254
4255 /// Helpers for dealing with blocks and functions.
4256 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
4257 bool CheckParameterNames);
4258 void CheckCXXDefaultArguments(FunctionDecl *FD);
4259 void CheckExtraCXXDefaultArguments(Declarator &D);
4260 Scope *getNonFieldDeclScope(Scope *S);
4261
4262 /// \name Name lookup
4263 ///
4264 /// These routines provide name lookup that is used during semantic
4265 /// analysis to resolve the various kinds of names (identifiers,
4266 /// overloaded operator names, constructor names, etc.) into zero or
4267 /// more declarations within a particular scope. The major entry
4268 /// points are LookupName, which performs unqualified name lookup,
4269 /// and LookupQualifiedName, which performs qualified name lookup.
4270 ///
4271 /// All name lookup is performed based on some specific criteria,
4272 /// which specify what names will be visible to name lookup and how
4273 /// far name lookup should work. These criteria are important both
4274 /// for capturing language semantics (certain lookups will ignore
4275 /// certain names, for example) and for performance, since name
4276 /// lookup is often a bottleneck in the compilation of C++. Name
4277 /// lookup criteria is specified via the LookupCriteria enumeration.
4278 ///
4279 /// The results of name lookup can vary based on the kind of name
4280 /// lookup performed, the current language, and the translation
4281 /// unit. In C, for example, name lookup will either return nothing
4282 /// (no entity found) or a single declaration. In C++, name lookup
4283 /// can additionally refer to a set of overloaded functions or
4284 /// result in an ambiguity. All of the possible results of name
4285 /// lookup are captured by the LookupResult class, which provides
4286 /// the ability to distinguish among them.
4287 //@{
4288
4289 /// Describes the kind of name lookup to perform.
4290 enum LookupNameKind {
4291 /// Ordinary name lookup, which finds ordinary names (functions,
4292 /// variables, typedefs, etc.) in C and most kinds of names
4293 /// (functions, variables, members, types, etc.) in C++.
4294 LookupOrdinaryName = 0,
4295 /// Tag name lookup, which finds the names of enums, classes,
4296 /// structs, and unions.
4297 LookupTagName,
4298 /// Label name lookup.
4299 LookupLabel,
4300 /// Member name lookup, which finds the names of
4301 /// class/struct/union members.
4302 LookupMemberName,
4303 /// Look up of an operator name (e.g., operator+) for use with
4304 /// operator overloading. This lookup is similar to ordinary name
4305 /// lookup, but will ignore any declarations that are class members.
4306 LookupOperatorName,
4307 /// Look up a name following ~ in a destructor name. This is an ordinary
4308 /// lookup, but prefers tags to typedefs.
4309 LookupDestructorName,
4310 /// Look up of a name that precedes the '::' scope resolution
4311 /// operator in C++. This lookup completely ignores operator, object,
4312 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4313 LookupNestedNameSpecifierName,
4314 /// Look up a namespace name within a C++ using directive or
4315 /// namespace alias definition, ignoring non-namespace names (C++
4316 /// [basic.lookup.udir]p1).
4317 LookupNamespaceName,
4318 /// Look up all declarations in a scope with the given name,
4319 /// including resolved using declarations. This is appropriate
4320 /// for checking redeclarations for a using declaration.
4321 LookupUsingDeclName,
4322 /// Look up an ordinary name that is going to be redeclared as a
4323 /// name with linkage. This lookup ignores any declarations that
4324 /// are outside of the current scope unless they have linkage. See
4325 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4326 LookupRedeclarationWithLinkage,
4327 /// Look up a friend of a local class. This lookup does not look
4328 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4329 LookupLocalFriendName,
4330 /// Look up the name of an Objective-C protocol.
4331 LookupObjCProtocolName,
4332 /// Look up implicit 'self' parameter of an objective-c method.
4333 LookupObjCImplicitSelfParam,
4334 /// Look up the name of an OpenMP user-defined reduction operation.
4335 LookupOMPReductionName,
4336 /// Look up the name of an OpenMP user-defined mapper.
4337 LookupOMPMapperName,
4338 /// Look up any declaration with any name.
4339 LookupAnyName
4340 };
4341
4342 /// Specifies whether (or how) name lookup is being performed for a
4343 /// redeclaration (vs. a reference).
4344 enum RedeclarationKind {
4345 /// The lookup is a reference to this name that is not for the
4346 /// purpose of redeclaring the name.
4347 NotForRedeclaration = 0,
4348 /// The lookup results will be used for redeclaration of a name,
4349 /// if an entity by that name already exists and is visible.
4350 ForVisibleRedeclaration,
4351 /// The lookup results will be used for redeclaration of a name
4352 /// with external linkage; non-visible lookup results with external linkage
4353 /// may also be found.
4354 ForExternalRedeclaration
4355 };
4356
4357 RedeclarationKind forRedeclarationInCurContext() const {
4358 // A declaration with an owning module for linkage can never link against
4359 // anything that is not visible. We don't need to check linkage here; if
4360 // the context has internal linkage, redeclaration lookup won't find things
4361 // from other TUs, and we can't safely compute linkage yet in general.
4362 if (cast<Decl>(CurContext)
4363 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4364 return ForVisibleRedeclaration;
4365 return ForExternalRedeclaration;
4366 }
4367
4368 /// The possible outcomes of name lookup for a literal operator.
4369 enum LiteralOperatorLookupResult {
4370 /// The lookup resulted in an error.
4371 LOLR_Error,
4372 /// The lookup found no match but no diagnostic was issued.
4373 LOLR_ErrorNoDiagnostic,
4374 /// The lookup found a single 'cooked' literal operator, which
4375 /// expects a normal literal to be built and passed to it.
4376 LOLR_Cooked,
4377 /// The lookup found a single 'raw' literal operator, which expects
4378 /// a string literal containing the spelling of the literal token.
4379 LOLR_Raw,
4380 /// The lookup found an overload set of literal operator templates,
4381 /// which expect the characters of the spelling of the literal token to be
4382 /// passed as a non-type template argument pack.
4383 LOLR_Template,
4384 /// The lookup found an overload set of literal operator templates,
4385 /// which expect the character type and characters of the spelling of the
4386 /// string literal token to be passed as template arguments.
4387 LOLR_StringTemplatePack,
4388 };
4389
4390 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4391 CXXSpecialMember SM,
4392 bool ConstArg,
4393 bool VolatileArg,
4394 bool RValueThis,
4395 bool ConstThis,
4396 bool VolatileThis);
4397
4398 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4399 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4400 TypoRecoveryCallback;
4401
4402private:
4403 bool CppLookupName(LookupResult &R, Scope *S);
4404
4405 struct TypoExprState {
4406 std::unique_ptr<TypoCorrectionConsumer> Consumer;
4407 TypoDiagnosticGenerator DiagHandler;
4408 TypoRecoveryCallback RecoveryHandler;
4409 TypoExprState();
4410 TypoExprState(TypoExprState &&other) noexcept;
4411 TypoExprState &operator=(TypoExprState &&other) noexcept;
4412 };
4413
4414 /// The set of unhandled TypoExprs and their associated state.
4415 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4416
4417 /// Creates a new TypoExpr AST node.
4418 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4419 TypoDiagnosticGenerator TDG,
4420 TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4421
4422 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4423 //
4424 // The boolean value will be true to indicate that the namespace was loaded
4425 // from an AST/PCH file, or false otherwise.
4426 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4427
4428 /// Whether we have already loaded known namespaces from an extenal
4429 /// source.
4430 bool LoadedExternalKnownNamespaces;
4431
4432 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4433 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4434 /// should be skipped entirely.
4435 std::unique_ptr<TypoCorrectionConsumer>
4436 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4437 Sema::LookupNameKind LookupKind, Scope *S,
4438 CXXScopeSpec *SS,
4439 CorrectionCandidateCallback &CCC,
4440 DeclContext *MemberContext, bool EnteringContext,
4441 const ObjCObjectPointerType *OPT,
4442 bool ErrorRecovery);
4443
4444public:
4445 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4446
4447 /// Clears the state of the given TypoExpr.
4448 void clearDelayedTypo(TypoExpr *TE);
4449
4450 /// Look up a name, looking for a single declaration. Return
4451 /// null if the results were absent, ambiguous, or overloaded.
4452 ///
4453 /// It is preferable to use the elaborated form and explicitly handle
4454 /// ambiguity and overloaded.
4455 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
4456 SourceLocation Loc,
4457 LookupNameKind NameKind,
4458 RedeclarationKind Redecl
4459 = NotForRedeclaration);
4460 bool LookupBuiltin(LookupResult &R);
4461 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4462 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
4463 bool ForceNoCPlusPlus = false);
4464 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4465 bool InUnqualifiedLookup = false);
4466 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4467 CXXScopeSpec &SS);
4468 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
4469 bool AllowBuiltinCreation = false,
4470 bool EnteringContext = false);
4471 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
4472 RedeclarationKind Redecl
4473 = NotForRedeclaration);
4474 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4475
4476 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
4477 UnresolvedSetImpl &Functions);
4478
4479 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
4480 SourceLocation GnuLabelLoc = SourceLocation());
4481
4482 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
4483 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
4484 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
4485 unsigned Quals);
4486 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4487 bool RValueThis, unsigned ThisQuals);
4488 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
4489 unsigned Quals);
4490 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4491 bool RValueThis, unsigned ThisQuals);
4492 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
4493
4494 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4495 bool IsUDSuffix);
4496 LiteralOperatorLookupResult
4497 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4498 bool AllowRaw, bool AllowTemplate,
4499 bool AllowStringTemplate, bool DiagnoseMissing,
4500 StringLiteral *StringLit = nullptr);
4501 bool isKnownName(StringRef name);
4502
4503 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4504 enum class FunctionEmissionStatus {
4505 Emitted,
4506 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4507 OMPDiscarded, // Discarded due to OpenMP hostness
4508 TemplateDiscarded, // Discarded due to uninstantiated templates
4509 Unknown,
4510 };
4511 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4512 bool Final = false);
4513
4514 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4515 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4516
4517 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4518 ArrayRef<Expr *> Args, ADLResult &Functions);
4519
4520 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4521 VisibleDeclConsumer &Consumer,
4522 bool IncludeGlobalScope = true,
4523 bool LoadExternal = true);
4524 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4525 VisibleDeclConsumer &Consumer,
4526 bool IncludeGlobalScope = true,
4527 bool IncludeDependentBases = false,
4528 bool LoadExternal = true);
4529
4530 enum CorrectTypoKind {
4531 CTK_NonError, // CorrectTypo used in a non error recovery situation.
4532 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4533 };
4534
4535 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4536 Sema::LookupNameKind LookupKind,
4537 Scope *S, CXXScopeSpec *SS,
4538 CorrectionCandidateCallback &CCC,
4539 CorrectTypoKind Mode,
4540 DeclContext *MemberContext = nullptr,
4541 bool EnteringContext = false,
4542 const ObjCObjectPointerType *OPT = nullptr,
4543 bool RecordFailure = true);
4544
4545 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4546 Sema::LookupNameKind LookupKind, Scope *S,
4547 CXXScopeSpec *SS,
4548 CorrectionCandidateCallback &CCC,
4549 TypoDiagnosticGenerator TDG,
4550 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4551 DeclContext *MemberContext = nullptr,
4552 bool EnteringContext = false,
4553 const ObjCObjectPointerType *OPT = nullptr);
4554
4555 /// Process any TypoExprs in the given Expr and its children,
4556 /// generating diagnostics as appropriate and returning a new Expr if there
4557 /// were typos that were all successfully corrected and ExprError if one or
4558 /// more typos could not be corrected.
4559 ///
4560 /// \param E The Expr to check for TypoExprs.
4561 ///
4562 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4563 /// initializer.
4564 ///
4565 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4566 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4567 ///
4568 /// \param Filter A function applied to a newly rebuilt Expr to determine if
4569 /// it is an acceptable/usable result from a single combination of typo
4570 /// corrections. As long as the filter returns ExprError, different
4571 /// combinations of corrections will be tried until all are exhausted.
4572 ExprResult CorrectDelayedTyposInExpr(
4573 Expr *E, VarDecl *InitDecl = nullptr,
4574 bool RecoverUncorrectedTypos = false,
4575 llvm::function_ref<ExprResult(Expr *)> Filter =
4576 [](Expr *E) -> ExprResult { return E; });
4577
4578 ExprResult CorrectDelayedTyposInExpr(
4579 ExprResult ER, VarDecl *InitDecl = nullptr,
4580 bool RecoverUncorrectedTypos = false,
4581 llvm::function_ref<ExprResult(Expr *)> Filter =
4582 [](Expr *E) -> ExprResult { return E; }) {
4583 return ER.isInvalid()
4584 ? ER
4585 : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4586 RecoverUncorrectedTypos, Filter);
4587 }
4588
4589 void diagnoseTypo(const TypoCorrection &Correction,
4590 const PartialDiagnostic &TypoDiag,
4591 bool ErrorRecovery = true);
4592
4593 void diagnoseTypo(const TypoCorrection &Correction,
4594 const PartialDiagnostic &TypoDiag,
4595 const PartialDiagnostic &PrevNote,
4596 bool ErrorRecovery = true);
4597
4598 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4599
4600 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4601 ArrayRef<Expr *> Args,
4602 AssociatedNamespaceSet &AssociatedNamespaces,
4603 AssociatedClassSet &AssociatedClasses);
4604
4605 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4606 bool ConsiderLinkage, bool AllowInlineNamespace);
4607
4608 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4609 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4610 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4611 bool IsRedefinitionInModule(const NamedDecl *New,
4612 const NamedDecl *Old) const;
4613
4614 void DiagnoseAmbiguousLookup(LookupResult &Result);
4615 //@}
4616
4617 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4618 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4619 ArrayRef<Expr *> SubExprs,
4620 QualType T = QualType());
4621
4622 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4623 SourceLocation IdLoc,
4624 bool TypoCorrection = false);
4625 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4626 SourceLocation Loc);
4627 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4628 Scope *S, bool ForRedeclaration,
4629 SourceLocation Loc);
4630 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4631 Scope *S);
4632 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4633 FunctionDecl *FD);
4634 void AddKnownFunctionAttributes(FunctionDecl *FD);
4635
4636 // More parsing and symbol table subroutines.
4637
4638 void ProcessPragmaWeak(Scope *S, Decl *D);
4639 // Decl attributes - this routine is the top level dispatcher.
4640 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4641 // Helper for delayed processing of attributes.
4642 void ProcessDeclAttributeDelayed(Decl *D,
4643 const ParsedAttributesView &AttrList);
4644
4645 // Options for ProcessDeclAttributeList().
4646 struct ProcessDeclAttributeOptions {
4647 ProcessDeclAttributeOptions()
4648 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
4649
4650 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
4651 ProcessDeclAttributeOptions Result = *this;
4652 Result.IncludeCXX11Attributes = Val;
4653 return Result;
4654 }
4655
4656 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
4657 ProcessDeclAttributeOptions Result = *this;
4658 Result.IgnoreTypeAttributes = Val;
4659 return Result;
4660 }
4661
4662 // Should C++11 attributes be processed?
4663 bool IncludeCXX11Attributes;
4664
4665 // Should any type attributes encountered be ignored?
4666 // If this option is false, a diagnostic will be emitted for any type
4667 // attributes of a kind that does not "slide" from the declaration to
4668 // the decl-specifier-seq.
4669 bool IgnoreTypeAttributes;
4670 };
4671
4672 void ProcessDeclAttributeList(Scope *S, Decl *D,
4673 const ParsedAttributesView &AttrList,
4674 const ProcessDeclAttributeOptions &Options =
4675 ProcessDeclAttributeOptions());
4676 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4677 const ParsedAttributesView &AttrList);
4678
4679 void checkUnusedDeclAttributes(Declarator &D);
4680
4681 /// Handles semantic checking for features that are common to all attributes,
4682 /// such as checking whether a parameter was properly specified, or the
4683 /// correct number of arguments were passed, etc. Returns true if the
4684 /// attribute has been diagnosed.
4685 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
4686 bool SkipArgCountCheck = false);
4687 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
4688 bool SkipArgCountCheck = false);
4689
4690 /// Determine if type T is a valid subject for a nonnull and similar
4691 /// attributes. By default, we look through references (the behavior used by
4692 /// nonnull), but if the second parameter is true, then we treat a reference
4693 /// type as valid.
4694 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4695
4696 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4697 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4698 const FunctionDecl *FD = nullptr);
4699 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4700 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4701 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4702 const Expr *E, StringRef &Str,
4703 SourceLocation *ArgLocation = nullptr);
4704 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4705 StringRef &Str,
4706 SourceLocation *ArgLocation = nullptr);
4707 llvm::Error isValidSectionSpecifier(StringRef Str);
4708 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4709 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4710 bool checkTargetVersionAttr(SourceLocation LiteralLoc, StringRef &Str,
4711 bool &isDefault);
4712 bool
4713 checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
4714 const StringLiteral *Literal, bool &HasDefault,
4715 bool &HasCommas, bool &HasNotDefault,
4716 SmallVectorImpl<SmallString<64>> &StringsBuffer);
4717 bool checkMSInheritanceAttrOnDefinition(
4718 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4719 MSInheritanceModel SemanticSpelling);
4720
4721 void CheckAlignasUnderalignment(Decl *D);
4722
4723 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
4724 const AttributeCommonInfo &A);
4725 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
4726 const AttributeCommonInfo &A);
4727
4728 /// Adjust the calling convention of a method to be the ABI default if it
4729 /// wasn't specified explicitly. This handles method types formed from
4730 /// function type typedefs and typename template arguments.
4731 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4732 SourceLocation Loc);
4733
4734 // Check if there is an explicit attribute, but only look through parens.
4735 // The intent is to look for an attribute on the current declarator, but not
4736 // one that came from a typedef.
4737 bool hasExplicitCallingConv(QualType T);
4738
4739 /// Get the outermost AttributedType node that sets a calling convention.
4740 /// Valid types should not have multiple attributes with different CCs.
4741 const AttributedType *getCallingConvAttributedType(QualType T) const;
4742
4743 /// Process the attributes before creating an attributed statement. Returns
4744 /// the semantic attributes that have been processed.
4745 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
4746 SmallVectorImpl<const Attr *> &OutAttrs);
4747
4748 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4749 ObjCMethodDecl *MethodDecl,
4750 bool IsProtocolMethodDecl);
4751
4752 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4753 ObjCMethodDecl *Overridden,
4754 bool IsProtocolMethodDecl);
4755
4756 /// WarnExactTypedMethods - This routine issues a warning if method
4757 /// implementation declaration matches exactly that of its declaration.
4758 void WarnExactTypedMethods(ObjCMethodDecl *Method,
4759 ObjCMethodDecl *MethodDecl,
4760 bool IsProtocolMethodDecl);
4761
4762 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4763
4764 /// CheckImplementationIvars - This routine checks if the instance variables
4765 /// listed in the implelementation match those listed in the interface.
4766 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4767 ObjCIvarDecl **Fields, unsigned nIvars,
4768 SourceLocation Loc);
4769
4770 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4771 /// remains unimplemented in the class or category \@implementation.
4772 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4773 ObjCContainerDecl* IDecl,
4774 bool IncompleteImpl = false);
4775
4776 /// DiagnoseUnimplementedProperties - This routine warns on those properties
4777 /// which must be implemented by this implementation.
4778 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4779 ObjCContainerDecl *CDecl,
4780 bool SynthesizeProperties);
4781
4782 /// Diagnose any null-resettable synthesized setters.
4783 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4784
4785 /// DefaultSynthesizeProperties - This routine default synthesizes all
4786 /// properties which must be synthesized in the class's \@implementation.
4787 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4788 ObjCInterfaceDecl *IDecl,
4789 SourceLocation AtEnd);
4790 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4791
4792 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4793 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4794 /// declared in class 'IFace'.
4795 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4796 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4797
4798 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4799 /// backs the property is not used in the property's accessor.
4800 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4801 const ObjCImplementationDecl *ImplD);
4802
4803 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4804 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4805 /// It also returns ivar's property on success.
4806 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4807 const ObjCPropertyDecl *&PDecl) const;
4808
4809 /// Called by ActOnProperty to handle \@property declarations in
4810 /// class extensions.
4811 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4812 SourceLocation AtLoc,
4813 SourceLocation LParenLoc,
4814 FieldDeclarator &FD,
4815 Selector GetterSel,
4816 SourceLocation GetterNameLoc,
4817 Selector SetterSel,
4818 SourceLocation SetterNameLoc,
4819 const bool isReadWrite,
4820 unsigned &Attributes,
4821 const unsigned AttributesAsWritten,
4822 QualType T,
4823 TypeSourceInfo *TSI,
4824 tok::ObjCKeywordKind MethodImplKind);
4825
4826 /// Called by ActOnProperty and HandlePropertyInClassExtension to
4827 /// handle creating the ObjcPropertyDecl for a category or \@interface.
4828 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4829 ObjCContainerDecl *CDecl,
4830 SourceLocation AtLoc,
4831 SourceLocation LParenLoc,
4832 FieldDeclarator &FD,
4833 Selector GetterSel,
4834 SourceLocation GetterNameLoc,
4835 Selector SetterSel,
4836 SourceLocation SetterNameLoc,
4837 const bool isReadWrite,
4838 const unsigned Attributes,
4839 const unsigned AttributesAsWritten,
4840 QualType T,
4841 TypeSourceInfo *TSI,
4842 tok::ObjCKeywordKind MethodImplKind,
4843 DeclContext *lexicalDC = nullptr);
4844
4845 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4846 /// warning) when atomic property has one but not the other user-declared
4847 /// setter or getter.
4848 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4849 ObjCInterfaceDecl* IDecl);
4850
4851 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4852
4853 void DiagnoseMissingDesignatedInitOverrides(
4854 const ObjCImplementationDecl *ImplD,
4855 const ObjCInterfaceDecl *IFD);
4856
4857 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4858
4859 enum MethodMatchStrategy {
4860 MMS_loose,
4861 MMS_strict
4862 };
4863
4864 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4865 /// true, or false, accordingly.
4866 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4867 const ObjCMethodDecl *PrevMethod,
4868 MethodMatchStrategy strategy = MMS_strict);
4869
4870 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4871 /// or protocol against those declared in their implementations.
4872 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4873 const SelectorSet &ClsMap,
4874 SelectorSet &InsMapSeen,
4875 SelectorSet &ClsMapSeen,
4876 ObjCImplDecl* IMPDecl,
4877 ObjCContainerDecl* IDecl,
4878 bool &IncompleteImpl,
4879 bool ImmediateClass,
4880 bool WarnCategoryMethodImpl=false);
4881
4882 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4883 /// category matches with those implemented in its primary class and
4884 /// warns each time an exact match is found.
4885 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4886
4887 /// Add the given method to the list of globally-known methods.
4888 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4889
4890 /// Returns default addr space for method qualifiers.
4891 LangAS getDefaultCXXMethodAddrSpace() const;
4892
4893private:
4894 /// AddMethodToGlobalPool - Add an instance or factory method to the global
4895 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4896 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4897
4898 /// LookupMethodInGlobalPool - Returns the instance or factory method and
4899 /// optionally warns if there are multiple signatures.
4900 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4901 bool receiverIdOrClass,
4902 bool instance);
4903
4904public:
4905 /// - Returns instance or factory methods in global method pool for
4906 /// given selector. It checks the desired kind first, if none is found, and
4907 /// parameter checkTheOther is set, it then checks the other kind. If no such
4908 /// method or only one method is found, function returns false; otherwise, it
4909 /// returns true.
4910 bool
4911 CollectMultipleMethodsInGlobalPool(Selector Sel,
4912 SmallVectorImpl<ObjCMethodDecl*>& Methods,
4913 bool InstanceFirst, bool CheckTheOther,
4914 const ObjCObjectType *TypeBound = nullptr);
4915
4916 bool
4917 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4918 SourceRange R, bool receiverIdOrClass,
4919 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4920
4921 void
4922 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4923 Selector Sel, SourceRange R,
4924 bool receiverIdOrClass);
4925
4926private:
4927 /// - Returns a selector which best matches given argument list or
4928 /// nullptr if none could be found
4929 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4930 bool IsInstance,
4931 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4932
4933
4934 /// Record the typo correction failure and return an empty correction.
4935 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4936 bool RecordFailure = true) {
4937 if (RecordFailure)
4938 TypoCorrectionFailures[Typo].insert(TypoLoc);
4939 return TypoCorrection();
4940 }
4941
4942public:
4943 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4944 /// unit are added to a global pool. This allows us to efficiently associate
4945 /// a selector with a method declaraation for purposes of typechecking
4946 /// messages sent to "id" (where the class of the object is unknown).
4947 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4948 AddMethodToGlobalPool(Method, impl, /*instance*/true);
4949 }
4950
4951 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4952 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4953 AddMethodToGlobalPool(Method, impl, /*instance*/false);
4954 }
4955
4956 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4957 /// pool.
4958 void AddAnyMethodToGlobalPool(Decl *D);
4959
4960 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4961 /// there are multiple signatures.
4962 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4963 bool receiverIdOrClass=false) {
4964 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4965 /*instance*/true);
4966 }
4967
4968 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4969 /// there are multiple signatures.
4970 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4971 bool receiverIdOrClass=false) {
4972 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4973 /*instance*/false);
4974 }
4975
4976 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4977 QualType ObjectType=QualType());
4978 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4979 /// implementation.
4980 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4981
4982 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4983 /// initialization.
4984 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4985 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4986
4987 //===--------------------------------------------------------------------===//
4988 // Statement Parsing Callbacks: SemaStmt.cpp.
4989public:
4990 class FullExprArg {
4991 public:
4992 FullExprArg() : E(nullptr) { }
4993 FullExprArg(Sema &actions) : E(nullptr) { }
4994
4995 ExprResult release() {
4996 return E;
4997 }
4998
4999 Expr *get() const { return E; }
5000
5001 Expr *operator->() {
5002 return E;
5003 }
5004
5005 private:
5006 // FIXME: No need to make the entire Sema class a friend when it's just
5007 // Sema::MakeFullExpr that needs access to the constructor below.
5008 friend class Sema;
5009
5010 explicit FullExprArg(Expr *expr) : E(expr) {}
5011
5012 Expr *E;
5013 };
5014
5015 FullExprArg MakeFullExpr(Expr *Arg) {
5016 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
5017 }
5018 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
5019 return FullExprArg(
5020 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
5021 }
5022 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
5023 ExprResult FE =
5024 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
5025 /*DiscardedValue*/ true);
5026 return FullExprArg(FE.get());
5027 }
5028
5029 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
5030 StmtResult ActOnExprStmtError();
5031
5032 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
5033 bool HasLeadingEmptyMacro = false);
5034
5035 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
5036 void ActOnAfterCompoundStatementLeadingPragmas();
5037 void ActOnFinishOfCompoundStmt();
5038 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
5039 ArrayRef<Stmt *> Elts, bool isStmtExpr);
5040
5041 /// A RAII object to enter scope of a compound statement.
5042 class CompoundScopeRAII {
5043 public:
5044 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
5045 S.ActOnStartOfCompoundStmt(IsStmtExpr);
5046 }
5047
5048 ~CompoundScopeRAII() {
5049 S.ActOnFinishOfCompoundStmt();
5050 }
5051
5052 private:
5053 Sema &S;
5054 };
5055
5056 /// An RAII helper that pops function a function scope on exit.
5057 struct FunctionScopeRAII {
5058 Sema &S;
5059 bool Active;
5060 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
5061 ~FunctionScopeRAII() {
5062 if (Active)
5063 S.PopFunctionScopeInfo();
5064 }
5065 void disable() { Active = false; }
5066 };
5067
5068 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
5069 SourceLocation StartLoc,
5070 SourceLocation EndLoc);
5071 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
5072 StmtResult ActOnForEachLValueExpr(Expr *E);
5073 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
5074 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
5075 SourceLocation DotDotDotLoc, ExprResult RHS,
5076 SourceLocation ColonLoc);
5077 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
5078
5079 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
5080 SourceLocation ColonLoc,
5081 Stmt *SubStmt, Scope *CurScope);
5082 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
5083 SourceLocation ColonLoc, Stmt *SubStmt);
5084
5085 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
5086 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
5087 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
5088 Stmt *SubStmt);
5089
5090 class ConditionResult;
5091
5092 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
5093 SourceLocation LParenLoc, Stmt *InitStmt,
5094 ConditionResult Cond, SourceLocation RParenLoc,
5095 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
5096 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
5097 SourceLocation LParenLoc, Stmt *InitStmt,
5098 ConditionResult Cond, SourceLocation RParenLoc,
5099 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
5100 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
5101 SourceLocation LParenLoc, Stmt *InitStmt,
5102 ConditionResult Cond,
5103 SourceLocation RParenLoc);
5104 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
5105 Stmt *Switch, Stmt *Body);
5106 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
5107 ConditionResult Cond, SourceLocation RParenLoc,
5108 Stmt *Body);
5109 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
5110 SourceLocation WhileLoc, SourceLocation CondLParen,
5111 Expr *Cond, SourceLocation CondRParen);
5112
5113 StmtResult ActOnForStmt(SourceLocation ForLoc,
5114 SourceLocation LParenLoc,
5115 Stmt *First,
5116 ConditionResult Second,
5117 FullExprArg Third,
5118 SourceLocation RParenLoc,
5119 Stmt *Body);
5120 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
5121 Expr *collection);
5122 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
5123 Stmt *First, Expr *collection,
5124 SourceLocation RParenLoc);
5125 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
5126
5127 enum BuildForRangeKind {
5128 /// Initial building of a for-range statement.
5129 BFRK_Build,
5130 /// Instantiation or recovery rebuild of a for-range statement. Don't
5131 /// attempt any typo-correction.
5132 BFRK_Rebuild,
5133 /// Determining whether a for-range statement could be built. Avoid any
5134 /// unnecessary or irreversible actions.
5135 BFRK_Check
5136 };
5137
5138 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
5139 SourceLocation CoawaitLoc,
5140 Stmt *InitStmt,
5141 Stmt *LoopVar,
5142 SourceLocation ColonLoc, Expr *Collection,
5143 SourceLocation RParenLoc,
5144 BuildForRangeKind Kind);
5145 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
5146 SourceLocation CoawaitLoc,
5147 Stmt *InitStmt,
5148 SourceLocation ColonLoc,
5149 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
5150 Expr *Cond, Expr *Inc,
5151 Stmt *LoopVarDecl,
5152 SourceLocation RParenLoc,
5153 BuildForRangeKind Kind);
5154 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
5155
5156 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
5157 SourceLocation LabelLoc,
5158 LabelDecl *TheDecl);
5159 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
5160 SourceLocation StarLoc,
5161 Expr *DestExp);
5162 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
5163 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
5164
5165 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
5166 CapturedRegionKind Kind, unsigned NumParams);
5167 typedef std::pair<StringRef, QualType> CapturedParamNameType;
5168 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
5169 CapturedRegionKind Kind,
5170 ArrayRef<CapturedParamNameType> Params,
5171 unsigned OpenMPCaptureLevel = 0);
5172 StmtResult ActOnCapturedRegionEnd(Stmt *S);
5173 void ActOnCapturedRegionError();
5174 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
5175 SourceLocation Loc,
5176 unsigned NumParams);
5177
5178 struct NamedReturnInfo {
5179 const VarDecl *Candidate;
5180
5181 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
5182 Status S;
5183
5184 bool isMoveEligible() const { return S != None; };
5185 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
5186 };
5187 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
5188 NamedReturnInfo getNamedReturnInfo(
5189 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
5190 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
5191 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
5192 QualType ReturnType);
5193
5194 ExprResult
5195 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
5196 const NamedReturnInfo &NRInfo, Expr *Value,
5197 bool SupressSimplerImplicitMoves = false);
5198
5199 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5200 Scope *CurScope);
5201 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5202 bool AllowRecovery = false);
5203 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5204 NamedReturnInfo &NRInfo,
5205 bool SupressSimplerImplicitMoves);
5206
5207 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
5208 bool IsVolatile, unsigned NumOutputs,
5209 unsigned NumInputs, IdentifierInfo **Names,
5210 MultiExprArg Constraints, MultiExprArg Exprs,
5211 Expr *AsmString, MultiExprArg Clobbers,
5212 unsigned NumLabels,
5213 SourceLocation RParenLoc);
5214
5215 void FillInlineAsmIdentifierInfo(Expr *Res,
5216 llvm::InlineAsmIdentifierInfo &Info);
5217 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
5218 SourceLocation TemplateKWLoc,
5219 UnqualifiedId &Id,
5220 bool IsUnevaluatedContext);
5221 bool LookupInlineAsmField(StringRef Base, StringRef Member,
5222 unsigned &Offset, SourceLocation AsmLoc);
5223 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
5224 SourceLocation AsmLoc);
5225 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
5226 ArrayRef<Token> AsmToks,
5227 StringRef AsmString,
5228 unsigned NumOutputs, unsigned NumInputs,
5229 ArrayRef<StringRef> Constraints,
5230 ArrayRef<StringRef> Clobbers,
5231 ArrayRef<Expr*> Exprs,
5232 SourceLocation EndLoc);
5233 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
5234 SourceLocation Location,
5235 bool AlwaysCreate);
5236
5237 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
5238 SourceLocation StartLoc,
5239 SourceLocation IdLoc, IdentifierInfo *Id,
5240 bool Invalid = false);
5241
5242 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
5243
5244 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
5245 Decl *Parm, Stmt *Body);
5246
5247 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
5248
5249 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
5250 MultiStmtArg Catch, Stmt *Finally);
5251
5252 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
5253 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
5254 Scope *CurScope);
5255 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
5256 Expr *operand);
5257 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
5258 Expr *SynchExpr,
5259 Stmt *SynchBody);
5260
5261 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
5262
5263 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
5264 SourceLocation StartLoc,
5265 SourceLocation IdLoc,
5266 IdentifierInfo *Id);
5267
5268 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
5269
5270 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
5271 Decl *ExDecl, Stmt *HandlerBlock);
5272 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
5273 ArrayRef<Stmt *> Handlers);
5274
5275 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
5276 SourceLocation TryLoc, Stmt *TryBlock,
5277 Stmt *Handler);
5278 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
5279 Expr *FilterExpr,
5280 Stmt *Block);
5281 void ActOnStartSEHFinallyBlock();
5282 void ActOnAbortSEHFinallyBlock();
5283 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
5284 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
5285
5286 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
5287
5288 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
5289
5290 /// If it's a file scoped decl that must warn if not used, keep track
5291 /// of it.
5292 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
5293
5294 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
5295 DiagReceiverTy;
5296
5297 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
5298 /// whose result is unused, warn.
5299 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
5300 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
5301 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
5302 DiagReceiverTy DiagReceiver);
5303 void DiagnoseUnusedDecl(const NamedDecl *ND);
5304 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
5305
5306 /// If VD is set but not otherwise used, diagnose, for a parameter or a
5307 /// variable.
5308 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
5309
5310 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
5311 /// statement as a \p Body, and it is located on the same line.
5312 ///
5313 /// This helps prevent bugs due to typos, such as:
5314 /// if (condition);
5315 /// do_stuff();
5316 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5317 const Stmt *Body,
5318 unsigned DiagID);
5319
5320 /// Warn if a for/while loop statement \p S, which is followed by
5321 /// \p PossibleBody, has a suspicious null statement as a body.
5322 void DiagnoseEmptyLoopBody(const Stmt *S,
5323 const Stmt *PossibleBody);
5324
5325 /// Warn if a value is moved to itself.
5326 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
5327 SourceLocation OpLoc);
5328
5329 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
5330 /// SelfAssigned when inside a CXXMethodDecl.
5331 const FieldDecl *
5332 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
5333
5334 /// Warn if we're implicitly casting from a _Nullable pointer type to a
5335 /// _Nonnull one.
5336 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
5337 SourceLocation Loc);
5338
5339 /// Warn when implicitly casting 0 to nullptr.
5340 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
5341
5342 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
5343 return DelayedDiagnostics.push(pool);
5344 }
5345 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5346
5347 typedef ProcessingContextState ParsingClassState;
5348 ParsingClassState PushParsingClass() {
5349 ParsingClassDepth++;
5350 return DelayedDiagnostics.pushUndelayed();
5351 }
5352 void PopParsingClass(ParsingClassState state) {
5353 ParsingClassDepth--;
5354 DelayedDiagnostics.popUndelayed(state);
5355 }
5356
5357 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5358
5359 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5360 const ObjCInterfaceDecl *UnknownObjCClass,
5361 bool ObjCPropertyAccess,
5362 bool AvoidPartialAvailabilityChecks = false,
5363 ObjCInterfaceDecl *ClassReceiver = nullptr);
5364
5365 bool makeUnavailableInSystemHeader(SourceLocation loc,
5366 UnavailableAttr::ImplicitReason reason);
5367
5368 /// Issue any -Wunguarded-availability warnings in \c FD
5369 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
5370
5371 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5372
5373 //===--------------------------------------------------------------------===//
5374 // Expression Parsing Callbacks: SemaExpr.cpp.
5375
5376 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
5377 // A version of DiagnoseUseOfDecl that should be used if overload resolution
5378 // has been used to find this declaration, which means we don't have to bother
5379 // checking the trailing requires clause.
5380 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
5381 return DiagnoseUseOfDecl(
5382 D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false,
5383 /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr,
5384 /*SkipTrailingRequiresClause=*/true);
5385 }
5386
5387 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5388 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
5389 bool ObjCPropertyAccess = false,
5390 bool AvoidPartialAvailabilityChecks = false,
5391 ObjCInterfaceDecl *ClassReciever = nullptr,
5392 bool SkipTrailingRequiresClause = false);
5393 void NoteDeletedFunction(FunctionDecl *FD);
5394 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
5395 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
5396 ObjCMethodDecl *Getter,
5397 SourceLocation Loc);
5398 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
5399 ArrayRef<Expr *> Args);
5400
5401 void PushExpressionEvaluationContext(
5402 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
5403 ExpressionEvaluationContextRecord::ExpressionKind Type =
5404 ExpressionEvaluationContextRecord::EK_Other);
5405 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
5406 void PushExpressionEvaluationContext(
5407 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
5408 ExpressionEvaluationContextRecord::ExpressionKind Type =
5409 ExpressionEvaluationContextRecord::EK_Other);
5410 void PopExpressionEvaluationContext();
5411
5412 void DiscardCleanupsInEvaluationContext();
5413
5414 ExprResult TransformToPotentiallyEvaluated(Expr *E);
5415 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
5416 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
5417
5418 ExprResult CheckUnevaluatedOperand(Expr *E);
5419 void CheckUnusedVolatileAssignment(Expr *E);
5420
5421 ExprResult ActOnConstantExpression(ExprResult Res);
5422
5423 // Functions for marking a declaration referenced. These functions also
5424 // contain the relevant logic for marking if a reference to a function or
5425 // variable is an odr-use (in the C++11 sense). There are separate variants
5426 // for expressions referring to a decl; these exist because odr-use marking
5427 // needs to be delayed for some constant variables when we build one of the
5428 // named expressions.
5429 //
5430 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
5431 // should usually be true. This only needs to be set to false if the lack of
5432 // odr-use cannot be determined from the current context (for instance,
5433 // because the name denotes a virtual function and was written without an
5434 // explicit nested-name-specifier).
5435 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
5436 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
5437 bool MightBeOdrUse = true);
5438 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
5439 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
5440 void MarkMemberReferenced(MemberExpr *E);
5441 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
5442 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
5443 unsigned CapturingScopeIndex);
5444
5445 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
5446 void CleanupVarDeclMarking();
5447
5448 enum TryCaptureKind {
5449 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
5450 };
5451
5452 /// Try to capture the given variable.
5453 ///
5454 /// \param Var The variable to capture.
5455 ///
5456 /// \param Loc The location at which the capture occurs.
5457 ///
5458 /// \param Kind The kind of capture, which may be implicit (for either a
5459 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
5460 ///
5461 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
5462 /// an explicit lambda capture.
5463 ///
5464 /// \param BuildAndDiagnose Whether we are actually supposed to add the
5465 /// captures or diagnose errors. If false, this routine merely check whether
5466 /// the capture can occur without performing the capture itself or complaining
5467 /// if the variable cannot be captured.
5468 ///
5469 /// \param CaptureType Will be set to the type of the field used to capture
5470 /// this variable in the innermost block or lambda. Only valid when the
5471 /// variable can be captured.
5472 ///
5473 /// \param DeclRefType Will be set to the type of a reference to the capture
5474 /// from within the current scope. Only valid when the variable can be
5475 /// captured.
5476 ///
5477 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5478 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5479 /// This is useful when enclosing lambdas must speculatively capture
5480 /// variables that may or may not be used in certain specializations of
5481 /// a nested generic lambda.
5482 ///
5483 /// \returns true if an error occurred (i.e., the variable cannot be
5484 /// captured) and false if the capture succeeded.
5485 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
5486 TryCaptureKind Kind, SourceLocation EllipsisLoc,
5487 bool BuildAndDiagnose, QualType &CaptureType,
5488 QualType &DeclRefType,
5489 const unsigned *const FunctionScopeIndexToStopAt);
5490
5491 /// Try to capture the given variable.
5492 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
5493 TryCaptureKind Kind = TryCapture_Implicit,
5494 SourceLocation EllipsisLoc = SourceLocation());
5495
5496 /// Checks if the variable must be captured.
5497 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
5498
5499 /// Given a variable, determine the type that a reference to that
5500 /// variable will have in the given scope.
5501 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
5502
5503 /// Mark all of the declarations referenced within a particular AST node as
5504 /// referenced. Used when template instantiation instantiates a non-dependent
5505 /// type -- entities referenced by the type are now referenced.
5506 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
5507 void MarkDeclarationsReferencedInExpr(
5508 Expr *E, bool SkipLocalVariables = false,
5509 ArrayRef<const Expr *> StopAt = std::nullopt);
5510
5511 /// Try to recover by turning the given expression into a
5512 /// call. Returns true if recovery was attempted or an error was
5513 /// emitted; this may also leave the ExprResult invalid.
5514 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
5515 bool ForceComplain = false,
5516 bool (*IsPlausibleResult)(QualType) = nullptr);
5517
5518 /// Figure out if an expression could be turned into a call.
5519 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
5520 UnresolvedSetImpl &NonTemplateOverloads);
5521
5522 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
5523 /// conversion.
5524 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
5525
5526 /// Conditionally issue a diagnostic based on the statements's reachability
5527 /// analysis.
5528 ///
5529 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
5530 /// the function body is parsed, and then do a basic reachability analysis to
5531 /// determine if the statement is reachable. If it is unreachable, the
5532 /// diagnostic will not be emitted.
5533 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
5534 const PartialDiagnostic &PD);
5535
5536 /// Conditionally issue a diagnostic based on the current
5537 /// evaluation context.
5538 ///
5539 /// \param Statement If Statement is non-null, delay reporting the
5540 /// diagnostic until the function body is parsed, and then do a basic
5541 /// reachability analysis to determine if the statement is reachable.
5542 /// If it is unreachable, the diagnostic will not be emitted.
5543 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
5544 const PartialDiagnostic &PD);
5545 /// Similar, but diagnostic is only produced if all the specified statements
5546 /// are reachable.
5547 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
5548 const PartialDiagnostic &PD);
5549
5550 // Primary Expressions.
5551 SourceRange getExprRange(Expr *E) const;
5552
5553 ExprResult ActOnIdExpression(
5554 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5555 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
5556 CorrectionCandidateCallback *CCC = nullptr,
5557 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
5558
5559 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
5560 TemplateArgumentListInfo &Buffer,
5561 DeclarationNameInfo &NameInfo,
5562 const TemplateArgumentListInfo *&TemplateArgs);
5563
5564 bool DiagnoseDependentMemberLookup(const LookupResult &R);
5565
5566 bool
5567 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
5568 CorrectionCandidateCallback &CCC,
5569 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
5570 ArrayRef<Expr *> Args = std::nullopt,
5571 TypoExpr **Out = nullptr);
5572
5573 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
5574 IdentifierInfo *II);
5575 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
5576
5577 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
5578 IdentifierInfo *II,
5579 bool AllowBuiltinCreation=false);
5580
5581 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
5582 SourceLocation TemplateKWLoc,
5583 const DeclarationNameInfo &NameInfo,
5584 bool isAddressOfOperand,
5585 const TemplateArgumentListInfo *TemplateArgs);
5586
5587 /// If \p D cannot be odr-used in the current expression evaluation context,
5588 /// return a reason explaining why. Otherwise, return NOUR_None.
5589 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
5590
5591 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5592 SourceLocation Loc,
5593 const CXXScopeSpec *SS = nullptr);
5594 DeclRefExpr *
5595 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5596 const DeclarationNameInfo &NameInfo,
5597 const CXXScopeSpec *SS = nullptr,
5598 NamedDecl *FoundD = nullptr,
5599 SourceLocation TemplateKWLoc = SourceLocation(),
5600 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5601 DeclRefExpr *
5602 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5603 const DeclarationNameInfo &NameInfo,
5604 NestedNameSpecifierLoc NNS,
5605 NamedDecl *FoundD = nullptr,
5606 SourceLocation TemplateKWLoc = SourceLocation(),
5607 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5608
5609 ExprResult
5610 BuildAnonymousStructUnionMemberReference(
5611 const CXXScopeSpec &SS,
5612 SourceLocation nameLoc,
5613 IndirectFieldDecl *indirectField,
5614 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5615 Expr *baseObjectExpr = nullptr,
5616 SourceLocation opLoc = SourceLocation());
5617
5618 ExprResult BuildPossibleImplicitMemberExpr(
5619 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5620 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5621 UnresolvedLookupExpr *AsULE = nullptr);
5622 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5623 SourceLocation TemplateKWLoc,
5624 LookupResult &R,
5625 const TemplateArgumentListInfo *TemplateArgs,
5626 bool IsDefiniteInstance,
5627 const Scope *S);
5628 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5629 const LookupResult &R,
5630 bool HasTrailingLParen);
5631
5632 ExprResult
5633 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5634 const DeclarationNameInfo &NameInfo,
5635 bool IsAddressOfOperand, const Scope *S,
5636 TypeSourceInfo **RecoveryTSI = nullptr);
5637
5638 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5639 SourceLocation TemplateKWLoc,
5640 const DeclarationNameInfo &NameInfo,
5641 const TemplateArgumentListInfo *TemplateArgs);
5642
5643 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5644 LookupResult &R,
5645 bool NeedsADL,
5646 bool AcceptInvalidDecl = false);
5647 ExprResult BuildDeclarationNameExpr(
5648 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5649 NamedDecl *FoundD = nullptr,
5650 const TemplateArgumentListInfo *TemplateArgs = nullptr,
5651 bool AcceptInvalidDecl = false);
5652
5653 ExprResult BuildLiteralOperatorCall(LookupResult &R,
5654 DeclarationNameInfo &SuffixInfo,
5655 ArrayRef<Expr *> Args,
5656 SourceLocation LitEndLoc,
5657 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5658
5659 ExprResult BuildPredefinedExpr(SourceLocation Loc,
5660 PredefinedExpr::IdentKind IK);
5661 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5662 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5663
5664 ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5665 SourceLocation LParen,
5666 SourceLocation RParen,
5667 TypeSourceInfo *TSI);
5668 ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5669 SourceLocation LParen,
5670 SourceLocation RParen,
5671 ParsedType ParsedTy);
5672
5673 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5674
5675 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5676 ExprResult ActOnCharacterConstant(const Token &Tok,
5677 Scope *UDLScope = nullptr);
5678 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5679 ExprResult ActOnParenListExpr(SourceLocation L,
5680 SourceLocation R,
5681 MultiExprArg Val);
5682
5683 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5684 /// fragments (e.g. "foo" "bar" L"baz").
5685 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5686 Scope *UDLScope = nullptr);
5687
5688 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5689 SourceLocation DefaultLoc,
5690 SourceLocation RParenLoc,
5691 Expr *ControllingExpr,
5692 ArrayRef<ParsedType> ArgTypes,
5693 ArrayRef<Expr *> ArgExprs);
5694 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5695 SourceLocation DefaultLoc,
5696 SourceLocation RParenLoc,
5697 Expr *ControllingExpr,
5698 ArrayRef<TypeSourceInfo *> Types,
5699 ArrayRef<Expr *> Exprs);
5700
5701 // Binary/Unary Operators. 'Tok' is the token for the operator.
5702 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5703 Expr *InputExpr, bool IsAfterAmp = false);
5704 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
5705 Expr *Input, bool IsAfterAmp = false);
5706 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
5707 Expr *Input, bool IsAfterAmp = false);
5708
5709 bool isQualifiedMemberAccess(Expr *E);
5710 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5711
5712 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
5713
5714 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5715 SourceLocation OpLoc,
5716 UnaryExprOrTypeTrait ExprKind,
5717 SourceRange R);
5718 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5719 UnaryExprOrTypeTrait ExprKind);
5720 ExprResult
5721 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5722 UnaryExprOrTypeTrait ExprKind,
5723 bool IsType, void *TyOrEx,
5724 SourceRange ArgRange);
5725
5726 ExprResult CheckPlaceholderExpr(Expr *E);
5727 bool CheckVecStepExpr(Expr *E);
5728
5729 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5730 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5731 SourceRange ExprRange,
5732 UnaryExprOrTypeTrait ExprKind);
5733 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5734 SourceLocation OpLoc,
5735 IdentifierInfo &Name,
5736 SourceLocation NameLoc,
5737 SourceLocation RParenLoc);
5738 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5739 tok::TokenKind Kind, Expr *Input);
5740
5741 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5742 MultiExprArg ArgExprs,
5743 SourceLocation RLoc);
5744 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5745 Expr *Idx, SourceLocation RLoc);
5746
5747 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5748 Expr *ColumnIdx,
5749 SourceLocation RBLoc);
5750
5751 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5752 Expr *LowerBound,
5753 SourceLocation ColonLocFirst,
5754 SourceLocation ColonLocSecond,
5755 Expr *Length, Expr *Stride,
5756 SourceLocation RBLoc);
5757 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5758 SourceLocation RParenLoc,
5759 ArrayRef<Expr *> Dims,
5760 ArrayRef<SourceRange> Brackets);
5761
5762 /// Data structure for iterator expression.
5763 struct OMPIteratorData {
5764 IdentifierInfo *DeclIdent = nullptr;
5765 SourceLocation DeclIdentLoc;
5766 ParsedType Type;
5767 OMPIteratorExpr::IteratorRange Range;
5768 SourceLocation AssignLoc;
5769 SourceLocation ColonLoc;
5770 SourceLocation SecColonLoc;
5771 };
5772
5773 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5774 SourceLocation LLoc, SourceLocation RLoc,
5775 ArrayRef<OMPIteratorData> Data);
5776
5777 // This struct is for use by ActOnMemberAccess to allow
5778 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5779 // changing the access operator from a '.' to a '->' (to see if that is the
5780 // change needed to fix an error about an unknown member, e.g. when the class
5781 // defines a custom operator->).
5782 struct ActOnMemberAccessExtraArgs {
5783 Scope *S;
5784 UnqualifiedId &Id;
5785 Decl *ObjCImpDecl;
5786 };
5787
5788 ExprResult BuildMemberReferenceExpr(
5789 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5790 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5791 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5792 const TemplateArgumentListInfo *TemplateArgs,
5793 const Scope *S,
5794 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5795
5796 ExprResult
5797 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5798 bool IsArrow, const CXXScopeSpec &SS,
5799 SourceLocation TemplateKWLoc,
5800 NamedDecl *FirstQualifierInScope, LookupResult &R,
5801 const TemplateArgumentListInfo *TemplateArgs,
5802 const Scope *S,
5803 bool SuppressQualifierCheck = false,
5804 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5805
5806 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5807 SourceLocation OpLoc,
5808 const CXXScopeSpec &SS, FieldDecl *Field,
5809 DeclAccessPair FoundDecl,
5810 const DeclarationNameInfo &MemberNameInfo);
5811
5812 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5813
5814 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5815 const CXXScopeSpec &SS,
5816 const LookupResult &R);
5817
5818 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5819 bool IsArrow, SourceLocation OpLoc,
5820 const CXXScopeSpec &SS,
5821 SourceLocation TemplateKWLoc,
5822 NamedDecl *FirstQualifierInScope,
5823 const DeclarationNameInfo &NameInfo,
5824 const TemplateArgumentListInfo *TemplateArgs);
5825
5826 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5827 SourceLocation OpLoc,
5828 tok::TokenKind OpKind,
5829 CXXScopeSpec &SS,
5830 SourceLocation TemplateKWLoc,
5831 UnqualifiedId &Member,
5832 Decl *ObjCImpDecl);
5833
5834 MemberExpr *
5835 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5836 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5837 ValueDecl *Member, DeclAccessPair FoundDecl,
5838 bool HadMultipleCandidates,
5839 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5840 ExprValueKind VK, ExprObjectKind OK,
5841 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5842 MemberExpr *
5843 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5844 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5845 ValueDecl *Member, DeclAccessPair FoundDecl,
5846 bool HadMultipleCandidates,
5847 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5848 ExprValueKind VK, ExprObjectKind OK,
5849 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5850
5851 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5852 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5853 FunctionDecl *FDecl,
5854 const FunctionProtoType *Proto,
5855 ArrayRef<Expr *> Args,
5856 SourceLocation RParenLoc,
5857 bool ExecConfig = false);
5858 void CheckStaticArrayArgument(SourceLocation CallLoc,
5859 ParmVarDecl *Param,
5860 const Expr *ArgExpr);
5861
5862 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5863 /// This provides the location of the left/right parens and a list of comma
5864 /// locations.
5865 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5866 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5867 Expr *ExecConfig = nullptr);
5868 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5869 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5870 Expr *ExecConfig = nullptr,
5871 bool IsExecConfig = false,
5872 bool AllowRecovery = false);
5873 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
5874 MultiExprArg CallArgs);
5875 enum class AtomicArgumentOrder { API, AST };
5876 ExprResult
5877 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5878 SourceLocation RParenLoc, MultiExprArg Args,
5879 AtomicExpr::AtomicOp Op,
5880 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5881 ExprResult
5882 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5883 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5884 Expr *Config = nullptr, bool IsExecConfig = false,
5885 ADLCallKind UsesADL = ADLCallKind::NotADL);
5886
5887 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5888 MultiExprArg ExecConfig,
5889 SourceLocation GGGLoc);
5890
5891 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5892 Declarator &D, ParsedType &Ty,
5893 SourceLocation RParenLoc, Expr *CastExpr);
5894 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5895 TypeSourceInfo *Ty,
5896 SourceLocation RParenLoc,
5897 Expr *Op);
5898 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5899
5900 /// Build an altivec or OpenCL literal.
5901 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5902 SourceLocation RParenLoc, Expr *E,
5903 TypeSourceInfo *TInfo);
5904
5905 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5906
5907 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5908 ParsedType Ty,
5909 SourceLocation RParenLoc,
5910 Expr *InitExpr);
5911
5912 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5913 TypeSourceInfo *TInfo,
5914 SourceLocation RParenLoc,
5915 Expr *LiteralExpr);
5916
5917 ExprResult ActOnInitList(SourceLocation LBraceLoc,
5918 MultiExprArg InitArgList,
5919 SourceLocation RBraceLoc);
5920
5921 ExprResult BuildInitList(SourceLocation LBraceLoc,
5922 MultiExprArg InitArgList,
5923 SourceLocation RBraceLoc);
5924
5925 ExprResult ActOnDesignatedInitializer(Designation &Desig,
5926 SourceLocation EqualOrColonLoc,
5927 bool GNUSyntax,
5928 ExprResult Init);
5929
5930private:
5931 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5932
5933public:
5934 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5935 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5936 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5937 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5938 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5939 Expr *LHSExpr, Expr *RHSExpr);
5940 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
5941 UnresolvedSetImpl &Functions);
5942
5943 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5944
5945 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5946 /// in the case of a the GNU conditional expr extension.
5947 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5948 SourceLocation ColonLoc,
5949 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5950
5951 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5952 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5953 LabelDecl *TheDecl);
5954
5955 void ActOnStartStmtExpr();
5956 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5957 SourceLocation RPLoc);
5958 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5959 SourceLocation RPLoc, unsigned TemplateDepth);
5960 // Handle the final expression in a statement expression.
5961 ExprResult ActOnStmtExprResult(ExprResult E);
5962 void ActOnStmtExprError();
5963
5964 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5965 struct OffsetOfComponent {
5966 SourceLocation LocStart, LocEnd;
5967 bool isBrackets; // true if [expr], false if .ident
5968 union {
5969 IdentifierInfo *IdentInfo;
5970 Expr *E;
5971 } U;
5972 };
5973
5974 /// __builtin_offsetof(type, a.b[123][456].c)
5975 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5976 TypeSourceInfo *TInfo,
5977 ArrayRef<OffsetOfComponent> Components,
5978 SourceLocation RParenLoc);
5979 ExprResult ActOnBuiltinOffsetOf(Scope *S,
5980 SourceLocation BuiltinLoc,
5981 SourceLocation TypeLoc,
5982 ParsedType ParsedArgTy,
5983 ArrayRef<OffsetOfComponent> Components,
5984 SourceLocation RParenLoc);
5985
5986 // __builtin_choose_expr(constExpr, expr1, expr2)
5987 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5988 Expr *CondExpr, Expr *LHSExpr,
5989 Expr *RHSExpr, SourceLocation RPLoc);
5990
5991 // __builtin_va_arg(expr, type)
5992 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5993 SourceLocation RPLoc);
5994 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5995 TypeSourceInfo *TInfo, SourceLocation RPLoc);
5996
5997 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5998 // __builtin_COLUMN(), __builtin_source_location()
5999 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
6000 SourceLocation BuiltinLoc,
6001 SourceLocation RPLoc);
6002
6003 // Build a potentially resolved SourceLocExpr.
6004 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
6005 QualType ResultTy, SourceLocation BuiltinLoc,
6006 SourceLocation RPLoc,
6007 DeclContext *ParentContext);
6008
6009 // __null
6010 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
6011
6012 bool CheckCaseExpression(Expr *E);
6013
6014 /// Describes the result of an "if-exists" condition check.
6015 enum IfExistsResult {
6016 /// The symbol exists.
6017 IER_Exists,
6018
6019 /// The symbol does not exist.
6020 IER_DoesNotExist,
6021
6022 /// The name is a dependent name, so the results will differ
6023 /// from one instantiation to the next.
6024 IER_Dependent,
6025
6026 /// An error occurred.
6027 IER_Error
6028 };
6029
6030 IfExistsResult
6031 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
6032 const DeclarationNameInfo &TargetNameInfo);
6033
6034 IfExistsResult
6035 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6036 bool IsIfExists, CXXScopeSpec &SS,
6037 UnqualifiedId &Name);
6038
6039 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
6040 bool IsIfExists,
6041 NestedNameSpecifierLoc QualifierLoc,
6042 DeclarationNameInfo NameInfo,
6043 Stmt *Nested);
6044 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
6045 bool IsIfExists,
6046 CXXScopeSpec &SS, UnqualifiedId &Name,
6047 Stmt *Nested);
6048
6049 //===------------------------- "Block" Extension ------------------------===//
6050
6051 /// ActOnBlockStart - This callback is invoked when a block literal is
6052 /// started.
6053 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
6054
6055 /// ActOnBlockArguments - This callback allows processing of block arguments.
6056 /// If there are no arguments, this is still invoked.
6057 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
6058 Scope *CurScope);
6059
6060 /// ActOnBlockError - If there is an error parsing a block, this callback
6061 /// is invoked to pop the information about the block from the action impl.
6062 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
6063
6064 /// ActOnBlockStmtExpr - This is called when the body of a block statement
6065 /// literal was successfully completed. ^(int x){...}
6066 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
6067 Scope *CurScope);
6068
6069 //===---------------------------- Clang Extensions ----------------------===//
6070
6071 /// __builtin_convertvector(...)
6072 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6073 SourceLocation BuiltinLoc,
6074 SourceLocation RParenLoc);
6075
6076 //===---------------------------- OpenCL Features -----------------------===//
6077
6078 /// __builtin_astype(...)
6079 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6080 SourceLocation BuiltinLoc,
6081 SourceLocation RParenLoc);
6082 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
6083 SourceLocation BuiltinLoc,
6084 SourceLocation RParenLoc);
6085
6086 //===---------------------------- HLSL Features -------------------------===//
6087 Decl *ActOnStartHLSLBuffer(Scope *BufferScope, bool CBuffer,
6088 SourceLocation KwLoc, IdentifierInfo *Ident,
6089 SourceLocation IdentLoc, SourceLocation LBrace);
6090 void ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace);
6091
6092 //===---------------------------- C++ Features --------------------------===//
6093
6094 // Act on C++ namespaces
6095 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
6096 SourceLocation NamespaceLoc,
6097 SourceLocation IdentLoc, IdentifierInfo *Ident,
6098 SourceLocation LBrace,
6099 const ParsedAttributesView &AttrList,
6100 UsingDirectiveDecl *&UsingDecl, bool IsNested);
6101 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
6102
6103 NamespaceDecl *getStdNamespace() const;
6104 NamespaceDecl *getOrCreateStdNamespace();
6105
6106 CXXRecordDecl *getStdBadAlloc() const;
6107 EnumDecl *getStdAlignValT() const;
6108
6109private:
6110 // A cache representing if we've fully checked the various comparison category
6111 // types stored in ASTContext. The bit-index corresponds to the integer value
6112 // of a ComparisonCategoryType enumerator.
6113 llvm::SmallBitVector FullyCheckedComparisonCategories;
6114
6115 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6116 CXXScopeSpec &SS,
6117 ParsedType TemplateTypeTy,
6118 IdentifierInfo *MemberOrBase);
6119
6120public:
6121 enum class ComparisonCategoryUsage {
6122 /// The '<=>' operator was used in an expression and a builtin operator
6123 /// was selected.
6124 OperatorInExpression,
6125 /// A defaulted 'operator<=>' needed the comparison category. This
6126 /// typically only applies to 'std::strong_ordering', due to the implicit
6127 /// fallback return value.
6128 DefaultedOperator,
6129 };
6130
6131 /// Lookup the specified comparison category types in the standard
6132 /// library, an check the VarDecls possibly returned by the operator<=>
6133 /// builtins for that type.
6134 ///
6135 /// \return The type of the comparison category type corresponding to the
6136 /// specified Kind, or a null type if an error occurs
6137 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
6138 SourceLocation Loc,
6139 ComparisonCategoryUsage Usage);
6140
6141 /// Tests whether Ty is an instance of std::initializer_list and, if
6142 /// it is and Element is not NULL, assigns the element type to Element.
6143 bool isStdInitializerList(QualType Ty, QualType *Element);
6144
6145 /// Looks for the std::initializer_list template and instantiates it
6146 /// with Element, or emits an error if it's not found.
6147 ///
6148 /// \returns The instantiated template, or null on error.
6149 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
6150
6151 /// Determine whether Ctor is an initializer-list constructor, as
6152 /// defined in [dcl.init.list]p2.
6153 bool isInitListConstructor(const FunctionDecl *Ctor);
6154
6155 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
6156 SourceLocation NamespcLoc, CXXScopeSpec &SS,
6157 SourceLocation IdentLoc,
6158 IdentifierInfo *NamespcName,
6159 const ParsedAttributesView &AttrList);
6160
6161 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
6162
6163 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
6164 SourceLocation NamespaceLoc,
6165 SourceLocation AliasLoc,
6166 IdentifierInfo *Alias,
6167 CXXScopeSpec &SS,
6168 SourceLocation IdentLoc,
6169 IdentifierInfo *Ident);
6170
6171 void FilterUsingLookup(Scope *S, LookupResult &lookup);
6172 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
6173 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
6174 const LookupResult &PreviousDecls,
6175 UsingShadowDecl *&PrevShadow);
6176 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
6177 NamedDecl *Target,
6178 UsingShadowDecl *PrevDecl);
6179
6180 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6181 bool HasTypenameKeyword,
6182 const CXXScopeSpec &SS,
6183 SourceLocation NameLoc,
6184 const LookupResult &Previous);
6185 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
6186 const CXXScopeSpec &SS,
6187 const DeclarationNameInfo &NameInfo,
6188 SourceLocation NameLoc,
6189 const LookupResult *R = nullptr,
6190 const UsingDecl *UD = nullptr);
6191
6192 NamedDecl *BuildUsingDeclaration(
6193 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
6194 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
6195 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
6196 const ParsedAttributesView &AttrList, bool IsInstantiation,
6197 bool IsUsingIfExists);
6198 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
6199 SourceLocation UsingLoc,
6200 SourceLocation EnumLoc,
6201 SourceLocation NameLoc,
6202 TypeSourceInfo *EnumType, EnumDecl *ED);
6203 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
6204 ArrayRef<NamedDecl *> Expansions);
6205
6206 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
6207
6208 /// Given a derived-class using shadow declaration for a constructor and the
6209 /// correspnding base class constructor, find or create the implicit
6210 /// synthesized derived class constructor to use for this initialization.
6211 CXXConstructorDecl *
6212 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
6213 ConstructorUsingShadowDecl *DerivedShadow);
6214
6215 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
6216 SourceLocation UsingLoc,
6217 SourceLocation TypenameLoc, CXXScopeSpec &SS,
6218 UnqualifiedId &Name, SourceLocation EllipsisLoc,
6219 const ParsedAttributesView &AttrList);
6220 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
6221 SourceLocation UsingLoc,
6222 SourceLocation EnumLoc,
6223 SourceLocation IdentLoc, IdentifierInfo &II,
6224 CXXScopeSpec *SS = nullptr);
6225 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
6226 MultiTemplateParamsArg TemplateParams,
6227 SourceLocation UsingLoc, UnqualifiedId &Name,
6228 const ParsedAttributesView &AttrList,
6229 TypeResult Type, Decl *DeclFromDeclSpec);
6230
6231 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
6232 /// including handling of its default argument expressions.
6233 ///
6234 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
6235 ExprResult
6236 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6237 NamedDecl *FoundDecl,
6238 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
6239 bool HadMultipleCandidates, bool IsListInitialization,
6240 bool IsStdInitListInitialization,
6241 bool RequiresZeroInit, unsigned ConstructKind,
6242 SourceRange ParenRange);
6243
6244 /// Build a CXXConstructExpr whose constructor has already been resolved if
6245 /// it denotes an inherited constructor.
6246 ExprResult
6247 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6248 CXXConstructorDecl *Constructor, bool Elidable,
6249 MultiExprArg Exprs,
6250 bool HadMultipleCandidates, bool IsListInitialization,
6251 bool IsStdInitListInitialization,
6252 bool RequiresZeroInit, unsigned ConstructKind,
6253 SourceRange ParenRange);
6254
6255 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
6256 // the constructor can be elidable?
6257 ExprResult
6258 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6259 NamedDecl *FoundDecl,
6260 CXXConstructorDecl *Constructor, bool Elidable,
6261 MultiExprArg Exprs, bool HadMultipleCandidates,
6262 bool IsListInitialization,
6263 bool IsStdInitListInitialization, bool RequiresZeroInit,
6264 unsigned ConstructKind, SourceRange ParenRange);
6265
6266 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
6267 SourceLocation InitLoc);
6268
6269 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
6270
6271
6272 /// Instantiate or parse a C++ default argument expression as necessary.
6273 /// Return true on error.
6274 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6275 ParmVarDecl *Param, Expr *Init = nullptr,
6276 bool SkipImmediateInvocations = true);
6277
6278 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
6279 /// the default expr if needed.
6280 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6281 ParmVarDecl *Param, Expr *Init = nullptr);
6282
6283 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
6284 /// constructed variable.
6285 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
6286
6287 /// Helper class that collects exception specifications for
6288 /// implicitly-declared special member functions.
6289 class ImplicitExceptionSpecification {
6290 // Pointer to allow copying
6291 Sema *Self;
6292 // We order exception specifications thus:
6293 // noexcept is the most restrictive, but is only used in C++11.
6294 // throw() comes next.
6295 // Then a throw(collected exceptions)
6296 // Finally no specification, which is expressed as noexcept(false).
6297 // throw(...) is used instead if any called function uses it.
6298 ExceptionSpecificationType ComputedEST;
6299 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
6300 SmallVector<QualType, 4> Exceptions;
6301
6302 void ClearExceptions() {
6303 ExceptionsSeen.clear();
6304 Exceptions.clear();
6305 }
6306
6307 public:
6308 explicit ImplicitExceptionSpecification(Sema &Self)
6309 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
6310 if (!Self.getLangOpts().CPlusPlus11)
6311 ComputedEST = EST_DynamicNone;
6312 }
6313
6314 /// Get the computed exception specification type.
6315 ExceptionSpecificationType getExceptionSpecType() const {
6316 assert(!isComputedNoexcept(ComputedEST) &&
6317 "noexcept(expr) should not be a possible result");
6318 return ComputedEST;
6319 }
6320
6321 /// The number of exceptions in the exception specification.
6322 unsigned size() const { return Exceptions.size(); }
6323
6324 /// The set of exceptions in the exception specification.
6325 const QualType *data() const { return Exceptions.data(); }
6326
6327 /// Integrate another called method into the collected data.
6328 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
6329
6330 /// Integrate an invoked expression into the collected data.
6331 void CalledExpr(Expr *E) { CalledStmt(E); }
6332
6333 /// Integrate an invoked statement into the collected data.
6334 void CalledStmt(Stmt *S);
6335
6336 /// Overwrite an EPI's exception specification with this
6337 /// computed exception specification.
6338 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
6339 FunctionProtoType::ExceptionSpecInfo ESI;
6340 ESI.Type = getExceptionSpecType();
6341 if (ESI.Type == EST_Dynamic) {
6342 ESI.Exceptions = Exceptions;
6343 } else if (ESI.Type == EST_None) {
6344 /// C++11 [except.spec]p14:
6345 /// The exception-specification is noexcept(false) if the set of
6346 /// potential exceptions of the special member function contains "any"
6347 ESI.Type = EST_NoexceptFalse;
6348 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
6349 tok::kw_false).get();
6350 }
6351 return ESI;
6352 }
6353 };
6354
6355 /// Evaluate the implicit exception specification for a defaulted
6356 /// special member function.
6357 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
6358
6359 /// Check the given noexcept-specifier, convert its expression, and compute
6360 /// the appropriate ExceptionSpecificationType.
6361 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6362 ExceptionSpecificationType &EST);
6363
6364 /// Check the given exception-specification and update the
6365 /// exception specification information with the results.
6366 void checkExceptionSpecification(bool IsTopLevel,
6367 ExceptionSpecificationType EST,
6368 ArrayRef<ParsedType> DynamicExceptions,
6369 ArrayRef<SourceRange> DynamicExceptionRanges,
6370 Expr *NoexceptExpr,
6371 SmallVectorImpl<QualType> &Exceptions,
6372 FunctionProtoType::ExceptionSpecInfo &ESI);
6373
6374 /// Determine if we're in a case where we need to (incorrectly) eagerly
6375 /// parse an exception specification to work around a libstdc++ bug.
6376 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6377
6378 /// Add an exception-specification to the given member function
6379 /// (or member function template). The exception-specification was parsed
6380 /// after the method itself was declared.
6381 void actOnDelayedExceptionSpecification(Decl *Method,
6382 ExceptionSpecificationType EST,
6383 SourceRange SpecificationRange,
6384 ArrayRef<ParsedType> DynamicExceptions,
6385 ArrayRef<SourceRange> DynamicExceptionRanges,
6386 Expr *NoexceptExpr);
6387
6388 class InheritedConstructorInfo;
6389
6390 /// Determine if a special member function should have a deleted
6391 /// definition when it is defaulted.
6392 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6393 InheritedConstructorInfo *ICI = nullptr,
6394 bool Diagnose = false);
6395
6396 /// Produce notes explaining why a defaulted function was defined as deleted.
6397 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
6398
6399 /// Declare the implicit default constructor for the given class.
6400 ///
6401 /// \param ClassDecl The class declaration into which the implicit
6402 /// default constructor will be added.
6403 ///
6404 /// \returns The implicitly-declared default constructor.
6405 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
6406 CXXRecordDecl *ClassDecl);
6407
6408 /// DefineImplicitDefaultConstructor - Checks for feasibility of
6409 /// defining this constructor as the default constructor.
6410 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6411 CXXConstructorDecl *Constructor);
6412
6413 /// Declare the implicit destructor for the given class.
6414 ///
6415 /// \param ClassDecl The class declaration into which the implicit
6416 /// destructor will be added.
6417 ///
6418 /// \returns The implicitly-declared destructor.
6419 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
6420
6421 /// DefineImplicitDestructor - Checks for feasibility of
6422 /// defining this destructor as the default destructor.
6423 void DefineImplicitDestructor(SourceLocation CurrentLocation,
6424 CXXDestructorDecl *Destructor);
6425
6426 /// Build an exception spec for destructors that don't have one.
6427 ///
6428 /// C++11 says that user-defined destructors with no exception spec get one
6429 /// that looks as if the destructor was implicitly declared.
6430 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
6431
6432 /// Define the specified inheriting constructor.
6433 void DefineInheritingConstructor(SourceLocation UseLoc,
6434 CXXConstructorDecl *Constructor);
6435
6436 /// Declare the implicit copy constructor for the given class.
6437 ///
6438 /// \param ClassDecl The class declaration into which the implicit
6439 /// copy constructor will be added.
6440 ///
6441 /// \returns The implicitly-declared copy constructor.
6442 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
6443
6444 /// DefineImplicitCopyConstructor - Checks for feasibility of
6445 /// defining this constructor as the copy constructor.
6446 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6447 CXXConstructorDecl *Constructor);
6448
6449 /// Declare the implicit move constructor for the given class.
6450 ///
6451 /// \param ClassDecl The Class declaration into which the implicit
6452 /// move constructor will be added.
6453 ///
6454 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
6455 /// declared.
6456 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
6457
6458 /// DefineImplicitMoveConstructor - Checks for feasibility of
6459 /// defining this constructor as the move constructor.
6460 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
6461 CXXConstructorDecl *Constructor);
6462
6463 /// Declare the implicit copy assignment operator for the given class.
6464 ///
6465 /// \param ClassDecl The class declaration into which the implicit
6466 /// copy assignment operator will be added.
6467 ///
6468 /// \returns The implicitly-declared copy assignment operator.
6469 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
6470
6471 /// Defines an implicitly-declared copy assignment operator.
6472 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6473 CXXMethodDecl *MethodDecl);
6474
6475 /// Declare the implicit move assignment operator for the given class.
6476 ///
6477 /// \param ClassDecl The Class declaration into which the implicit
6478 /// move assignment operator will be added.
6479 ///
6480 /// \returns The implicitly-declared move assignment operator, or NULL if it
6481 /// wasn't declared.
6482 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
6483
6484 /// Defines an implicitly-declared move assignment operator.
6485 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
6486 CXXMethodDecl *MethodDecl);
6487
6488 /// Force the declaration of any implicitly-declared members of this
6489 /// class.
6490 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
6491
6492 /// Check a completed declaration of an implicit special member.
6493 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
6494
6495 /// Determine whether the given function is an implicitly-deleted
6496 /// special member function.
6497 bool isImplicitlyDeleted(FunctionDecl *FD);
6498
6499 /// Check whether 'this' shows up in the type of a static member
6500 /// function after the (naturally empty) cv-qualifier-seq would be.
6501 ///
6502 /// \returns true if an error occurred.
6503 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
6504
6505 /// Whether this' shows up in the exception specification of a static
6506 /// member function.
6507 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
6508
6509 /// Check whether 'this' shows up in the attributes of the given
6510 /// static member function.
6511 ///
6512 /// \returns true if an error occurred.
6513 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
6514
6515 /// MaybeBindToTemporary - If the passed in expression has a record type with
6516 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
6517 /// it simply returns the passed in expression.
6518 ExprResult MaybeBindToTemporary(Expr *E);
6519
6520 /// Wrap the expression in a ConstantExpr if it is a potential immediate
6521 /// invocation.
6522 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
6523
6524 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
6525 QualType DeclInitType, MultiExprArg ArgsPtr,
6526 SourceLocation Loc,
6527 SmallVectorImpl<Expr *> &ConvertedArgs,
6528 bool AllowExplicit = false,
6529 bool IsListInitialization = false);
6530
6531 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
6532 SourceLocation NameLoc,
6533 IdentifierInfo &Name);
6534
6535 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
6536 Scope *S, CXXScopeSpec &SS,
6537 bool EnteringContext);
6538 ParsedType getDestructorName(SourceLocation TildeLoc,
6539 IdentifierInfo &II, SourceLocation NameLoc,
6540 Scope *S, CXXScopeSpec &SS,
6541 ParsedType ObjectType,
6542 bool EnteringContext);
6543
6544 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
6545 ParsedType ObjectType);
6546
6547 // Checks that reinterpret casts don't have undefined behavior.
6548 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
6549 bool IsDereference, SourceRange Range);
6550
6551 // Checks that the vector type should be initialized from a scalar
6552 // by splatting the value rather than populating a single element.
6553 // This is the case for AltiVecVector types as well as with
6554 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
6555 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
6556
6557 // Checks if the -faltivec-src-compat=gcc option is specified.
6558 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
6559 // treated the same way as they are when trying to initialize
6560 // these vectors on gcc (an error is emitted).
6561 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
6562 QualType SrcTy);
6563
6564 /// ActOnCXXNamedCast - Parse
6565 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
6566 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
6567 tok::TokenKind Kind,
6568 SourceLocation LAngleBracketLoc,
6569 Declarator &D,
6570 SourceLocation RAngleBracketLoc,
6571 SourceLocation LParenLoc,
6572 Expr *E,
6573 SourceLocation RParenLoc);
6574
6575 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
6576 tok::TokenKind Kind,
6577 TypeSourceInfo *Ty,
6578 Expr *E,
6579 SourceRange AngleBrackets,
6580 SourceRange Parens);
6581
6582 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
6583 ExprResult Operand,
6584 SourceLocation RParenLoc);
6585
6586 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
6587 Expr *Operand, SourceLocation RParenLoc);
6588
6589 ExprResult BuildCXXTypeId(QualType TypeInfoType,
6590 SourceLocation TypeidLoc,
6591 TypeSourceInfo *Operand,
6592 SourceLocation RParenLoc);
6593 ExprResult BuildCXXTypeId(QualType TypeInfoType,
6594 SourceLocation TypeidLoc,
6595 Expr *Operand,
6596 SourceLocation RParenLoc);
6597
6598 /// ActOnCXXTypeid - Parse typeid( something ).
6599 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
6600 SourceLocation LParenLoc, bool isType,
6601 void *TyOrExpr,
6602 SourceLocation RParenLoc);
6603
6604 ExprResult BuildCXXUuidof(QualType TypeInfoType,
6605 SourceLocation TypeidLoc,
6606 TypeSourceInfo *Operand,
6607 SourceLocation RParenLoc);
6608 ExprResult BuildCXXUuidof(QualType TypeInfoType,
6609 SourceLocation TypeidLoc,
6610 Expr *Operand,
6611 SourceLocation RParenLoc);
6612
6613 /// ActOnCXXUuidof - Parse __uuidof( something ).
6614 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
6615 SourceLocation LParenLoc, bool isType,
6616 void *TyOrExpr,
6617 SourceLocation RParenLoc);
6618
6619 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6620 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6621 tok::TokenKind Operator,
6622 SourceLocation EllipsisLoc, Expr *RHS,
6623 SourceLocation RParenLoc);
6624 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6625 SourceLocation LParenLoc, Expr *LHS,
6626 BinaryOperatorKind Operator,
6627 SourceLocation EllipsisLoc, Expr *RHS,
6628 SourceLocation RParenLoc,
6629 std::optional<unsigned> NumExpansions);
6630 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6631 BinaryOperatorKind Operator);
6632
6633 //// ActOnCXXThis - Parse 'this' pointer.
6634 ExprResult ActOnCXXThis(SourceLocation loc);
6635
6636 /// Build a CXXThisExpr and mark it referenced in the current context.
6637 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6638 void MarkThisReferenced(CXXThisExpr *This);
6639
6640 /// Try to retrieve the type of the 'this' pointer.
6641 ///
6642 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6643 QualType getCurrentThisType();
6644
6645 /// When non-NULL, the C++ 'this' expression is allowed despite the
6646 /// current context not being a non-static member function. In such cases,
6647 /// this provides the type used for 'this'.
6648 QualType CXXThisTypeOverride;
6649
6650 /// RAII object used to temporarily allow the C++ 'this' expression
6651 /// to be used, with the given qualifiers on the current class type.
6652 class CXXThisScopeRAII {
6653 Sema &S;
6654 QualType OldCXXThisTypeOverride;
6655 bool Enabled;
6656
6657 public:
6658 /// Introduce a new scope where 'this' may be allowed (when enabled),
6659 /// using the given declaration (which is either a class template or a
6660 /// class) along with the given qualifiers.
6661 /// along with the qualifiers placed on '*this'.
6662 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6663 bool Enabled = true);
6664
6665 ~CXXThisScopeRAII();
6666 };
6667
6668 /// Make sure the value of 'this' is actually available in the current
6669 /// context, if it is a potentially evaluated context.
6670 ///
6671 /// \param Loc The location at which the capture of 'this' occurs.
6672 ///
6673 /// \param Explicit Whether 'this' is explicitly captured in a lambda
6674 /// capture list.
6675 ///
6676 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6677 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6678 /// This is useful when enclosing lambdas must speculatively capture
6679 /// 'this' that may or may not be used in certain specializations of
6680 /// a nested generic lambda (depending on whether the name resolves to
6681 /// a non-static member function or a static function).
6682 /// \return returns 'true' if failed, 'false' if success.
6683 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6684 bool BuildAndDiagnose = true,
6685 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6686 bool ByCopy = false);
6687
6688 /// Determine whether the given type is the type of *this that is used
6689 /// outside of the body of a member function for a type that is currently
6690 /// being defined.
6691 bool isThisOutsideMemberFunctionBody(QualType BaseType);
6692
6693 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6694 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6695
6696
6697 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6698 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6699
6700 ExprResult
6701 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6702 SourceLocation AtLoc, SourceLocation RParen);
6703
6704 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6705 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6706
6707 //// ActOnCXXThrow - Parse throw expressions.
6708 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6709 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6710 bool IsThrownVarInScope);
6711 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6712
6713 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6714 /// Can be interpreted either as function-style casting ("int(x)")
6715 /// or class type construction ("ClassType(x,y,z)")
6716 /// or creation of a value-initialized type ("int()").
6717 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6718 SourceLocation LParenOrBraceLoc,
6719 MultiExprArg Exprs,
6720 SourceLocation RParenOrBraceLoc,
6721 bool ListInitialization);
6722
6723 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6724 SourceLocation LParenLoc,
6725 MultiExprArg Exprs,
6726 SourceLocation RParenLoc,
6727 bool ListInitialization);
6728
6729 /// ActOnCXXNew - Parsed a C++ 'new' expression.
6730 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6731 SourceLocation PlacementLParen,
6732 MultiExprArg PlacementArgs,
6733 SourceLocation PlacementRParen,
6734 SourceRange TypeIdParens, Declarator &D,
6735 Expr *Initializer);
6736 ExprResult
6737 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
6738 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
6739 SourceRange TypeIdParens, QualType AllocType,
6740 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
6741 SourceRange DirectInitRange, Expr *Initializer);
6742
6743 /// Determine whether \p FD is an aligned allocation or deallocation
6744 /// function that is unavailable.
6745 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6746
6747 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6748 /// function that is unavailable.
6749 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6750 SourceLocation Loc);
6751
6752 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6753 SourceRange R);
6754
6755 /// The scope in which to find allocation functions.
6756 enum AllocationFunctionScope {
6757 /// Only look for allocation functions in the global scope.
6758 AFS_Global,
6759 /// Only look for allocation functions in the scope of the
6760 /// allocated class.
6761 AFS_Class,
6762 /// Look for allocation functions in both the global scope
6763 /// and in the scope of the allocated class.
6764 AFS_Both
6765 };
6766
6767 /// Finds the overloads of operator new and delete that are appropriate
6768 /// for the allocation.
6769 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6770 AllocationFunctionScope NewScope,
6771 AllocationFunctionScope DeleteScope,
6772 QualType AllocType, bool IsArray,
6773 bool &PassAlignment, MultiExprArg PlaceArgs,
6774 FunctionDecl *&OperatorNew,
6775 FunctionDecl *&OperatorDelete,
6776 bool Diagnose = true);
6777 void DeclareGlobalNewDelete();
6778 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6779 ArrayRef<QualType> Params);
6780
6781 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6782 DeclarationName Name, FunctionDecl *&Operator,
6783 bool Diagnose = true, bool WantSize = false,
6784 bool WantAligned = false);
6785 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6786 bool CanProvideSize,
6787 bool Overaligned,
6788 DeclarationName Name);
6789 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6790 CXXRecordDecl *RD);
6791
6792 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6793 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6794 bool UseGlobal, bool ArrayForm,
6795 Expr *Operand);
6796 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6797 bool IsDelete, bool CallCanBeVirtual,
6798 bool WarnOnNonAbstractTypes,
6799 SourceLocation DtorLoc);
6800
6801 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6802 Expr *Operand, SourceLocation RParen);
6803 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6804 SourceLocation RParen);
6805
6806 /// Parsed one of the type trait support pseudo-functions.
6807 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6808 ArrayRef<ParsedType> Args,
6809 SourceLocation RParenLoc);
6810 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6811 ArrayRef<TypeSourceInfo *> Args,
6812 SourceLocation RParenLoc);
6813
6814 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6815 /// pseudo-functions.
6816 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6817 SourceLocation KWLoc,
6818 ParsedType LhsTy,
6819 Expr *DimExpr,
6820 SourceLocation RParen);
6821
6822 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6823 SourceLocation KWLoc,
6824 TypeSourceInfo *TSInfo,
6825 Expr *DimExpr,
6826 SourceLocation RParen);
6827
6828 /// ActOnExpressionTrait - Parsed one of the unary type trait support
6829 /// pseudo-functions.
6830 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6831 SourceLocation KWLoc,
6832 Expr *Queried,
6833 SourceLocation RParen);
6834
6835 ExprResult BuildExpressionTrait(ExpressionTrait OET,
6836 SourceLocation KWLoc,
6837 Expr *Queried,
6838 SourceLocation RParen);
6839
6840 ExprResult ActOnStartCXXMemberReference(Scope *S,
6841 Expr *Base,
6842 SourceLocation OpLoc,
6843 tok::TokenKind OpKind,
6844 ParsedType &ObjectType,
6845 bool &MayBePseudoDestructor);
6846
6847 ExprResult BuildPseudoDestructorExpr(Expr *Base,
6848 SourceLocation OpLoc,
6849 tok::TokenKind OpKind,
6850 const CXXScopeSpec &SS,
6851 TypeSourceInfo *ScopeType,
6852 SourceLocation CCLoc,
6853 SourceLocation TildeLoc,
6854 PseudoDestructorTypeStorage DestroyedType);
6855
6856 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6857 SourceLocation OpLoc,
6858 tok::TokenKind OpKind,
6859 CXXScopeSpec &SS,
6860 UnqualifiedId &FirstTypeName,
6861 SourceLocation CCLoc,
6862 SourceLocation TildeLoc,
6863 UnqualifiedId &SecondTypeName);
6864
6865 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6866 SourceLocation OpLoc,
6867 tok::TokenKind OpKind,
6868 SourceLocation TildeLoc,
6869 const DeclSpec& DS);
6870
6871 /// MaybeCreateExprWithCleanups - If the current full-expression
6872 /// requires any cleanups, surround it with a ExprWithCleanups node.
6873 /// Otherwise, just returns the passed-in expression.
6874 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6875 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6876 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6877
6878 MaterializeTemporaryExpr *
6879 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6880 bool BoundToLvalueReference);
6881
6882 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6883 return ActOnFinishFullExpr(
6884 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6885 }
6886 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6887 bool DiscardedValue, bool IsConstexpr = false,
6888 bool IsTemplateArgument = false);
6889 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6890
6891 // Marks SS invalid if it represents an incomplete type.
6892 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6893 // Complete an enum decl, maybe without a scope spec.
6894 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
6895 CXXScopeSpec *SS = nullptr);
6896
6897 DeclContext *computeDeclContext(QualType T);
6898 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6899 bool EnteringContext = false);
6900 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6901 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6902
6903 /// The parser has parsed a global nested-name-specifier '::'.
6904 ///
6905 /// \param CCLoc The location of the '::'.
6906 ///
6907 /// \param SS The nested-name-specifier, which will be updated in-place
6908 /// to reflect the parsed nested-name-specifier.
6909 ///
6910 /// \returns true if an error occurred, false otherwise.
6911 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6912
6913 /// The parser has parsed a '__super' nested-name-specifier.
6914 ///
6915 /// \param SuperLoc The location of the '__super' keyword.
6916 ///
6917 /// \param ColonColonLoc The location of the '::'.
6918 ///
6919 /// \param SS The nested-name-specifier, which will be updated in-place
6920 /// to reflect the parsed nested-name-specifier.
6921 ///
6922 /// \returns true if an error occurred, false otherwise.
6923 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6924 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6925
6926 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6927 bool *CanCorrect = nullptr);
6928 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6929
6930 /// Keeps information about an identifier in a nested-name-spec.
6931 ///
6932 struct NestedNameSpecInfo {
6933 /// The type of the object, if we're parsing nested-name-specifier in
6934 /// a member access expression.
6935 ParsedType ObjectType;
6936
6937 /// The identifier preceding the '::'.
6938 IdentifierInfo *Identifier;
6939
6940 /// The location of the identifier.
6941 SourceLocation IdentifierLoc;
6942
6943 /// The location of the '::'.
6944 SourceLocation CCLoc;
6945
6946 /// Creates info object for the most typical case.
6947 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6948 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
6949 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6950 CCLoc(ColonColonLoc) {
6951 }
6952
6953 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6954 SourceLocation ColonColonLoc, QualType ObjectType)
6955 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6956 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6957 }
6958 };
6959
6960 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6961 NestedNameSpecInfo &IdInfo);
6962
6963 bool BuildCXXNestedNameSpecifier(Scope *S,
6964 NestedNameSpecInfo &IdInfo,
6965 bool EnteringContext,
6966 CXXScopeSpec &SS,
6967 NamedDecl *ScopeLookupResult,
6968 bool ErrorRecoveryLookup,
6969 bool *IsCorrectedToColon = nullptr,
6970 bool OnlyNamespace = false);
6971
6972 /// The parser has parsed a nested-name-specifier 'identifier::'.
6973 ///
6974 /// \param S The scope in which this nested-name-specifier occurs.
6975 ///
6976 /// \param IdInfo Parser information about an identifier in the
6977 /// nested-name-spec.
6978 ///
6979 /// \param EnteringContext Whether we're entering the context nominated by
6980 /// this nested-name-specifier.
6981 ///
6982 /// \param SS The nested-name-specifier, which is both an input
6983 /// parameter (the nested-name-specifier before this type) and an
6984 /// output parameter (containing the full nested-name-specifier,
6985 /// including this new type).
6986 ///
6987 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6988 /// are allowed. The bool value pointed by this parameter is set to 'true'
6989 /// if the identifier is treated as if it was followed by ':', not '::'.
6990 ///
6991 /// \param OnlyNamespace If true, only considers namespaces in lookup.
6992 ///
6993 /// \returns true if an error occurred, false otherwise.
6994 bool ActOnCXXNestedNameSpecifier(Scope *S,
6995 NestedNameSpecInfo &IdInfo,
6996 bool EnteringContext,
6997 CXXScopeSpec &SS,
6998 bool *IsCorrectedToColon = nullptr,
6999 bool OnlyNamespace = false);
7000
7001 ExprResult ActOnDecltypeExpression(Expr *E);
7002
7003 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
7004 const DeclSpec &DS,
7005 SourceLocation ColonColonLoc);
7006
7007 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
7008 NestedNameSpecInfo &IdInfo,
7009 bool EnteringContext);
7010
7011 /// The parser has parsed a nested-name-specifier
7012 /// 'template[opt] template-name < template-args >::'.
7013 ///
7014 /// \param S The scope in which this nested-name-specifier occurs.
7015 ///
7016 /// \param SS The nested-name-specifier, which is both an input
7017 /// parameter (the nested-name-specifier before this type) and an
7018 /// output parameter (containing the full nested-name-specifier,
7019 /// including this new type).
7020 ///
7021 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
7022 /// \param TemplateName the template name.
7023 /// \param TemplateNameLoc The location of the template name.
7024 /// \param LAngleLoc The location of the opening angle bracket ('<').
7025 /// \param TemplateArgs The template arguments.
7026 /// \param RAngleLoc The location of the closing angle bracket ('>').
7027 /// \param CCLoc The location of the '::'.
7028 ///
7029 /// \param EnteringContext Whether we're entering the context of the
7030 /// nested-name-specifier.
7031 ///
7032 ///
7033 /// \returns true if an error occurred, false otherwise.
7034 bool ActOnCXXNestedNameSpecifier(Scope *S,
7035 CXXScopeSpec &SS,
7036 SourceLocation TemplateKWLoc,
7037 TemplateTy TemplateName,
7038 SourceLocation TemplateNameLoc,
7039 SourceLocation LAngleLoc,
7040 ASTTemplateArgsPtr TemplateArgs,
7041 SourceLocation RAngleLoc,
7042 SourceLocation CCLoc,
7043 bool EnteringContext);
7044
7045 /// Given a C++ nested-name-specifier, produce an annotation value
7046 /// that the parser can use later to reconstruct the given
7047 /// nested-name-specifier.
7048 ///
7049 /// \param SS A nested-name-specifier.
7050 ///
7051 /// \returns A pointer containing all of the information in the
7052 /// nested-name-specifier \p SS.
7053 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
7054
7055 /// Given an annotation pointer for a nested-name-specifier, restore
7056 /// the nested-name-specifier structure.
7057 ///
7058 /// \param Annotation The annotation pointer, produced by
7059 /// \c SaveNestedNameSpecifierAnnotation().
7060 ///
7061 /// \param AnnotationRange The source range corresponding to the annotation.
7062 ///
7063 /// \param SS The nested-name-specifier that will be updated with the contents
7064 /// of the annotation pointer.
7065 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
7066 SourceRange AnnotationRange,
7067 CXXScopeSpec &SS);
7068
7069 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
7070
7071 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
7072 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
7073 /// After this method is called, according to [C++ 3.4.3p3], names should be
7074 /// looked up in the declarator-id's scope, until the declarator is parsed and
7075 /// ActOnCXXExitDeclaratorScope is called.
7076 /// The 'SS' should be a non-empty valid CXXScopeSpec.
7077 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
7078
7079 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
7080 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
7081 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
7082 /// Used to indicate that names should revert to being looked up in the
7083 /// defining scope.
7084 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
7085
7086 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
7087 /// initializer for the declaration 'Dcl'.
7088 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7089 /// static data member of class X, names should be looked up in the scope of
7090 /// class X.
7091 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
7092
7093 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
7094 /// initializer for the declaration 'Dcl'.
7095 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
7096
7097 /// Create a new lambda closure type.
7098 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
7099 TypeSourceInfo *Info,
7100 unsigned LambdaDependencyKind,
7101 LambdaCaptureDefault CaptureDefault);
7102
7103 /// Start the definition of a lambda expression.
7104 CXXMethodDecl *
7105 startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange,
7106 TypeSourceInfo *MethodType, SourceLocation EndLoc,
7107 ArrayRef<ParmVarDecl *> Params,
7108 ConstexprSpecKind ConstexprKind, StorageClass SC,
7109 Expr *TrailingRequiresClause);
7110
7111 /// Number lambda for linkage purposes if necessary.
7112 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
7113 std::optional<CXXRecordDecl::LambdaNumbering>
7114 NumberingOverride = std::nullopt);
7115
7116 /// Endow the lambda scope info with the relevant properties.
7117 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
7118 SourceRange IntroducerRange,
7119 LambdaCaptureDefault CaptureDefault,
7120 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
7121 bool Mutable);
7122
7123 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
7124 CXXRecordDecl *Class);
7125 void CompleteLambdaCallOperator(
7126 CXXMethodDecl *Method, SourceLocation LambdaLoc,
7127 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,
7128 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
7129 StorageClass SC, ArrayRef<ParmVarDecl *> Params,
7130 bool HasExplicitResultType);
7131
7132 /// Perform initialization analysis of the init-capture and perform
7133 /// any implicit conversions such as an lvalue-to-rvalue conversion if
7134 /// not being used to initialize a reference.
7135 ParsedType actOnLambdaInitCaptureInitialization(
7136 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
7137 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
7138 return ParsedType::make(buildLambdaInitCaptureInitialization(
7139 Loc, ByRef, EllipsisLoc, std::nullopt, Id,
7140 InitKind != LambdaCaptureInitKind::CopyInit, Init));
7141 }
7142 QualType buildLambdaInitCaptureInitialization(
7143 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
7144 std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
7145 bool DirectInit, Expr *&Init);
7146
7147 /// Create a dummy variable within the declcontext of the lambda's
7148 /// call operator, for name lookup purposes for a lambda init capture.
7149 ///
7150 /// CodeGen handles emission of lambda captures, ignoring these dummy
7151 /// variables appropriately.
7152 VarDecl *createLambdaInitCaptureVarDecl(
7153 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
7154 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
7155
7156 /// Add an init-capture to a lambda scope.
7157 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var,
7158 bool isReferenceType);
7159
7160 /// Note that we have finished the explicit captures for the
7161 /// given lambda.
7162 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
7163
7164 /// Deduce a block or lambda's return type based on the return
7165 /// statements present in the body.
7166 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
7167
7168 /// Once the Lambdas capture are known, we can start to create the closure,
7169 /// call operator method, and keep track of the captures.
7170 /// We do the capture lookup here, but they are not actually captured until
7171 /// after we know what the qualifiers of the call operator are.
7172 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
7173 Scope *CurContext);
7174
7175 /// This is called after parsing the explicit template parameter list
7176 /// on a lambda (if it exists) in C++2a.
7177 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
7178 SourceLocation LAngleLoc,
7179 ArrayRef<NamedDecl *> TParams,
7180 SourceLocation RAngleLoc,
7181 ExprResult RequiresClause);
7182
7183 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
7184 SourceLocation MutableLoc);
7185
7186 void ActOnLambdaClosureParameters(
7187 Scope *LambdaScope,
7188 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
7189
7190 /// ActOnStartOfLambdaDefinition - This is called just before we start
7191 /// parsing the body of a lambda; it analyzes the explicit captures and
7192 /// arguments, and sets up various data-structures for the body of the
7193 /// lambda.
7194 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
7195 Declarator &ParamInfo, const DeclSpec &DS);
7196
7197 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
7198 /// is invoked to pop the information about the lambda.
7199 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
7200 bool IsInstantiation = false);
7201
7202 /// ActOnLambdaExpr - This is called when the body of a lambda expression
7203 /// was successfully completed.
7204 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
7205 Scope *CurScope);
7206
7207 /// Does copying/destroying the captured variable have side effects?
7208 bool CaptureHasSideEffects(const sema::Capture &From);
7209
7210 /// Diagnose if an explicit lambda capture is unused. Returns true if a
7211 /// diagnostic is emitted.
7212 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
7213 const sema::Capture &From);
7214
7215 /// Build a FieldDecl suitable to hold the given capture.
7216 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
7217
7218 /// Initialize the given capture with a suitable expression.
7219 ExprResult BuildCaptureInit(const sema::Capture &Capture,
7220 SourceLocation ImplicitCaptureLoc,
7221 bool IsOpenMPMapping = false);
7222
7223 /// Complete a lambda-expression having processed and attached the
7224 /// lambda body.
7225 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
7226 sema::LambdaScopeInfo *LSI);
7227
7228 /// Get the return type to use for a lambda's conversion function(s) to
7229 /// function pointer type, given the type of the call operator.
7230 QualType
7231 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
7232 CallingConv CC);
7233
7234 /// Define the "body" of the conversion from a lambda object to a
7235 /// function pointer.
7236 ///
7237 /// This routine doesn't actually define a sensible body; rather, it fills
7238 /// in the initialization expression needed to copy the lambda object into
7239 /// the block, and IR generation actually generates the real body of the
7240 /// block pointer conversion.
7241 void DefineImplicitLambdaToFunctionPointerConversion(
7242 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
7243
7244 /// Define the "body" of the conversion from a lambda object to a
7245 /// block pointer.
7246 ///
7247 /// This routine doesn't actually define a sensible body; rather, it fills
7248 /// in the initialization expression needed to copy the lambda object into
7249 /// the block, and IR generation actually generates the real body of the
7250 /// block pointer conversion.
7251 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
7252 CXXConversionDecl *Conv);
7253
7254 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
7255 SourceLocation ConvLocation,
7256 CXXConversionDecl *Conv,
7257 Expr *Src);
7258
7259 /// Check whether the given expression is a valid constraint expression.
7260 /// A diagnostic is emitted if it is not, false is returned, and
7261 /// PossibleNonPrimary will be set to true if the failure might be due to a
7262 /// non-primary expression being used as an atomic constraint.
7263 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
7264 bool *PossibleNonPrimary = nullptr,
7265 bool IsTrailingRequiresClause = false);
7266
7267private:
7268 /// Caches pairs of template-like decls whose associated constraints were
7269 /// checked for subsumption and whether or not the first's constraints did in
7270 /// fact subsume the second's.
7271 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
7272 /// Caches the normalized associated constraints of declarations (concepts or
7273 /// constrained declarations). If an error occurred while normalizing the
7274 /// associated constraints of the template or concept, nullptr will be cached
7275 /// here.
7276 llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
7277 NormalizationCache;
7278
7279 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
7280 SatisfactionCache;
7281
7282 /// Introduce the instantiated function parameters into the local
7283 /// instantiation scope, and set the parameter names to those used
7284 /// in the template.
7285 bool addInstantiatedParametersToScope(
7286 FunctionDecl *Function, const FunctionDecl *PatternDecl,
7287 LocalInstantiationScope &Scope,
7288 const MultiLevelTemplateArgumentList &TemplateArgs);
7289
7290 /// Introduce the instantiated captures of the lambda into the local
7291 /// instantiation scope.
7292 bool addInstantiatedCapturesToScope(
7293 FunctionDecl *Function, const FunctionDecl *PatternDecl,
7294 LocalInstantiationScope &Scope,
7295 const MultiLevelTemplateArgumentList &TemplateArgs);
7296
7297 /// used by SetupConstraintCheckingTemplateArgumentsAndScope to recursively(in
7298 /// the case of lambdas) set up the LocalInstantiationScope of the current
7299 /// function.
7300 bool SetupConstraintScope(
7301 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
7302 MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope);
7303
7304 /// Used during constraint checking, sets up the constraint template argument
7305 /// lists, and calls SetupConstraintScope to set up the
7306 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
7307 std::optional<MultiLevelTemplateArgumentList>
7308 SetupConstraintCheckingTemplateArgumentsAndScope(
7309 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
7310 LocalInstantiationScope &Scope);
7311
7312private:
7313 // The current stack of constraint satisfactions, so we can exit-early.
7314 using SatisfactionStackEntryTy =
7315 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
7316 llvm::SmallVector<SatisfactionStackEntryTy, 10>
7317 SatisfactionStack;
7318
7319public:
7320 void PushSatisfactionStackEntry(const NamedDecl *D,
7321 const llvm::FoldingSetNodeID &ID) {
7322 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
7323 SatisfactionStack.emplace_back(Can, ID);
7324 }
7325
7326 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
7327
7328 bool SatisfactionStackContains(const NamedDecl *D,
7329 const llvm::FoldingSetNodeID &ID) const {
7330 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
7331 return llvm::find(SatisfactionStack,
7332 SatisfactionStackEntryTy{Can, ID}) !=
7333 SatisfactionStack.end();
7334 }
7335
7336 // Resets the current SatisfactionStack for cases where we are instantiating
7337 // constraints as a 'side effect' of normal instantiation in a way that is not
7338 // indicative of recursive definition.
7339 class SatisfactionStackResetRAII {
7340 llvm::SmallVector<SatisfactionStackEntryTy, 10>
7341 BackupSatisfactionStack;
7342 Sema &SemaRef;
7343
7344 public:
7345 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
7346 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
7347 }
7348
7349 ~SatisfactionStackResetRAII() {
7350 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
7351 }
7352 };
7353
7354 void SwapSatisfactionStack(
7355 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
7356 SatisfactionStack.swap(NewSS);
7357 }
7358
7359 const NormalizedConstraint *
7360 getNormalizedAssociatedConstraints(
7361 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
7362
7363 /// \brief Check whether the given declaration's associated constraints are
7364 /// at least as constrained than another declaration's according to the
7365 /// partial ordering of constraints.
7366 ///
7367 /// \param Result If no error occurred, receives the result of true if D1 is
7368 /// at least constrained than D2, and false otherwise.
7369 ///
7370 /// \returns true if an error occurred, false otherwise.
7371 bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef<const Expr *> AC1,
7372 NamedDecl *D2, MutableArrayRef<const Expr *> AC2,
7373 bool &Result);
7374
7375 /// If D1 was not at least as constrained as D2, but would've been if a pair
7376 /// of atomic constraints involved had been declared in a concept and not
7377 /// repeated in two separate places in code.
7378 /// \returns true if such a diagnostic was emitted, false otherwise.
7379 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
7380 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
7381
7382 /// \brief Check whether the given list of constraint expressions are
7383 /// satisfied (as if in a 'conjunction') given template arguments.
7384 /// \param Template the template-like entity that triggered the constraints
7385 /// check (either a concept or a constrained entity).
7386 /// \param ConstraintExprs a list of constraint expressions, treated as if
7387 /// they were 'AND'ed together.
7388 /// \param TemplateArgLists the list of template arguments to substitute into
7389 /// the constraint expression.
7390 /// \param TemplateIDRange The source range of the template id that
7391 /// caused the constraints check.
7392 /// \param Satisfaction if true is returned, will contain details of the
7393 /// satisfaction, with enough information to diagnose an unsatisfied
7394 /// expression.
7395 /// \returns true if an error occurred and satisfaction could not be checked,
7396 /// false otherwise.
7397 bool CheckConstraintSatisfaction(
7398 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
7399 const MultiLevelTemplateArgumentList &TemplateArgLists,
7400 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) {
7401 llvm::SmallVector<Expr *, 4> Converted;
7402 return CheckConstraintSatisfaction(Template, ConstraintExprs, Converted,
7403 TemplateArgLists, TemplateIDRange,
7404 Satisfaction);
7405 }
7406
7407 /// \brief Check whether the given list of constraint expressions are
7408 /// satisfied (as if in a 'conjunction') given template arguments.
7409 /// Additionally, takes an empty list of Expressions which is populated with
7410 /// the instantiated versions of the ConstraintExprs.
7411 /// \param Template the template-like entity that triggered the constraints
7412 /// check (either a concept or a constrained entity).
7413 /// \param ConstraintExprs a list of constraint expressions, treated as if
7414 /// they were 'AND'ed together.
7415 /// \param ConvertedConstraints a out parameter that will get populated with
7416 /// the instantiated version of the ConstraintExprs if we successfully checked
7417 /// satisfaction.
7418 /// \param TemplateArgList the multi-level list of template arguments to
7419 /// substitute into the constraint expression. This should be relative to the
7420 /// top-level (hence multi-level), since we need to instantiate fully at the
7421 /// time of checking.
7422 /// \param TemplateIDRange The source range of the template id that
7423 /// caused the constraints check.
7424 /// \param Satisfaction if true is returned, will contain details of the
7425 /// satisfaction, with enough information to diagnose an unsatisfied
7426 /// expression.
7427 /// \returns true if an error occurred and satisfaction could not be checked,
7428 /// false otherwise.
7429 bool CheckConstraintSatisfaction(
7430 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
7431 llvm::SmallVectorImpl<Expr *> &ConvertedConstraints,
7432 const MultiLevelTemplateArgumentList &TemplateArgList,
7433 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
7434
7435 /// \brief Check whether the given non-dependent constraint expression is
7436 /// satisfied. Returns false and updates Satisfaction with the satisfaction
7437 /// verdict if successful, emits a diagnostic and returns true if an error
7438 /// occurred and satisfaction could not be determined.
7439 ///
7440 /// \returns true if an error occurred, false otherwise.
7441 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
7442 ConstraintSatisfaction &Satisfaction);
7443
7444 /// Check whether the given function decl's trailing requires clause is
7445 /// satisfied, if any. Returns false and updates Satisfaction with the
7446 /// satisfaction verdict if successful, emits a diagnostic and returns true if
7447 /// an error occurred and satisfaction could not be determined.
7448 ///
7449 /// \returns true if an error occurred, false otherwise.
7450 bool CheckFunctionConstraints(const FunctionDecl *FD,
7451 ConstraintSatisfaction &Satisfaction,
7452 SourceLocation UsageLoc = SourceLocation(),
7453 bool ForOverloadResolution = false);
7454
7455 /// \brief Ensure that the given template arguments satisfy the constraints
7456 /// associated with the given template, emitting a diagnostic if they do not.
7457 ///
7458 /// \param Template The template to which the template arguments are being
7459 /// provided.
7460 ///
7461 /// \param TemplateArgs The converted, canonicalized template arguments.
7462 ///
7463 /// \param TemplateIDRange The source range of the template id that
7464 /// caused the constraints check.
7465 ///
7466 /// \returns true if the constrains are not satisfied or could not be checked
7467 /// for satisfaction, false if the constraints are satisfied.
7468 bool EnsureTemplateArgumentListConstraints(
7469 TemplateDecl *Template,
7470 const MultiLevelTemplateArgumentList &TemplateArgs,
7471 SourceRange TemplateIDRange);
7472
7473 /// \brief Emit diagnostics explaining why a constraint expression was deemed
7474 /// unsatisfied.
7475 /// \param First whether this is the first time an unsatisfied constraint is
7476 /// diagnosed for this error.
7477 void
7478 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
7479 bool First = true);
7480
7481 /// \brief Emit diagnostics explaining why a constraint expression was deemed
7482 /// unsatisfied.
7483 void
7484 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
7485 bool First = true);
7486
7487 // ParseObjCStringLiteral - Parse Objective-C string literals.
7488 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
7489 ArrayRef<Expr *> Strings);
7490
7491 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
7492
7493 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
7494 /// numeric literal expression. Type of the expression will be "NSNumber *"
7495 /// or "id" if NSNumber is unavailable.
7496 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
7497 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
7498 bool Value);
7499 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
7500
7501 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
7502 /// '@' prefixed parenthesized expression. The type of the expression will
7503 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
7504 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
7505 /// "const char *" or C structure with attribute 'objc_boxable'.
7506 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
7507
7508 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
7509 Expr *IndexExpr,
7510 ObjCMethodDecl *getterMethod,
7511 ObjCMethodDecl *setterMethod);
7512
7513 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
7514 MutableArrayRef<ObjCDictionaryElement> Elements);
7515
7516 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
7517 TypeSourceInfo *EncodedTypeInfo,
7518 SourceLocation RParenLoc);
7519 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
7520 CXXConversionDecl *Method,
7521 bool HadMultipleCandidates);
7522
7523 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
7524 SourceLocation EncodeLoc,
7525 SourceLocation LParenLoc,
7526 ParsedType Ty,
7527 SourceLocation RParenLoc);
7528
7529 /// ParseObjCSelectorExpression - Build selector expression for \@selector
7530 ExprResult ParseObjCSelectorExpression(Selector Sel,
7531 SourceLocation AtLoc,
7532 SourceLocation SelLoc,
7533 SourceLocation LParenLoc,
7534 SourceLocation RParenLoc,
7535 bool WarnMultipleSelectors);
7536
7537 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
7538 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
7539 SourceLocation AtLoc,
7540 SourceLocation ProtoLoc,
7541 SourceLocation LParenLoc,
7542 SourceLocation ProtoIdLoc,
7543 SourceLocation RParenLoc);
7544
7545 //===--------------------------------------------------------------------===//
7546 // C++ Declarations
7547 //
7548 Decl *ActOnStartLinkageSpecification(Scope *S,
7549 SourceLocation ExternLoc,
7550 Expr *LangStr,
7551 SourceLocation LBraceLoc);
7552 Decl *ActOnFinishLinkageSpecification(Scope *S,
7553 Decl *LinkageSpec,
7554 SourceLocation RBraceLoc);
7555
7556
7557 //===--------------------------------------------------------------------===//
7558 // C++ Classes
7559 //
7560 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
7561 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
7562 const CXXScopeSpec *SS = nullptr);
7563 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
7564
7565 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
7566 SourceLocation ColonLoc,
7567 const ParsedAttributesView &Attrs);
7568
7569 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
7570 Declarator &D,
7571 MultiTemplateParamsArg TemplateParameterLists,
7572 Expr *BitfieldWidth, const VirtSpecifiers &VS,
7573 InClassInitStyle InitStyle);
7574
7575 void ActOnStartCXXInClassMemberInitializer();
7576 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
7577 SourceLocation EqualLoc,
7578 Expr *Init);
7579
7580 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7581 Scope *S,
7582 CXXScopeSpec &SS,
7583 IdentifierInfo *MemberOrBase,
7584 ParsedType TemplateTypeTy,
7585 const DeclSpec &DS,
7586 SourceLocation IdLoc,
7587 SourceLocation LParenLoc,
7588 ArrayRef<Expr *> Args,
7589 SourceLocation RParenLoc,
7590 SourceLocation EllipsisLoc);
7591
7592 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7593 Scope *S,
7594 CXXScopeSpec &SS,
7595 IdentifierInfo *MemberOrBase,
7596 ParsedType TemplateTypeTy,
7597 const DeclSpec &DS,
7598 SourceLocation IdLoc,
7599 Expr *InitList,
7600 SourceLocation EllipsisLoc);
7601
7602 MemInitResult BuildMemInitializer(Decl *ConstructorD,
7603 Scope *S,
7604 CXXScopeSpec &SS,
7605 IdentifierInfo *MemberOrBase,
7606 ParsedType TemplateTypeTy,
7607 const DeclSpec &DS,
7608 SourceLocation IdLoc,
7609 Expr *Init,
7610 SourceLocation EllipsisLoc);
7611
7612 MemInitResult BuildMemberInitializer(ValueDecl *Member,
7613 Expr *Init,
7614 SourceLocation IdLoc);
7615
7616 MemInitResult BuildBaseInitializer(QualType BaseType,
7617 TypeSourceInfo *BaseTInfo,
7618 Expr *Init,
7619 CXXRecordDecl *ClassDecl,
7620 SourceLocation EllipsisLoc);
7621
7622 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
7623 Expr *Init,
7624 CXXRecordDecl *ClassDecl);
7625
7626 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
7627 CXXCtorInitializer *Initializer);
7628
7629 bool SetCtorInitializers(
7630 CXXConstructorDecl *Constructor, bool AnyErrors,
7631 ArrayRef<CXXCtorInitializer *> Initializers = std::nullopt);
7632
7633 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
7634
7635
7636 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
7637 /// mark all the non-trivial destructors of its members and bases as
7638 /// referenced.
7639 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
7640 CXXRecordDecl *Record);
7641
7642 /// Mark destructors of virtual bases of this class referenced. In the Itanium
7643 /// C++ ABI, this is done when emitting a destructor for any non-abstract
7644 /// class. In the Microsoft C++ ABI, this is done any time a class's
7645 /// destructor is referenced.
7646 void MarkVirtualBaseDestructorsReferenced(
7647 SourceLocation Location, CXXRecordDecl *ClassDecl,
7648 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
7649
7650 /// Do semantic checks to allow the complete destructor variant to be emitted
7651 /// when the destructor is defined in another translation unit. In the Itanium
7652 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
7653 /// can be emitted in separate TUs. To emit the complete variant, run a subset
7654 /// of the checks performed when emitting a regular destructor.
7655 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
7656 CXXDestructorDecl *Dtor);
7657
7658 /// The list of classes whose vtables have been used within
7659 /// this translation unit, and the source locations at which the
7660 /// first use occurred.
7661 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
7662
7663 /// The list of vtables that are required but have not yet been
7664 /// materialized.
7665 SmallVector<VTableUse, 16> VTableUses;
7666
7667 /// The set of classes whose vtables have been used within
7668 /// this translation unit, and a bit that will be true if the vtable is
7669 /// required to be emitted (otherwise, it should be emitted only if needed
7670 /// by code generation).
7671 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
7672
7673 /// Load any externally-stored vtable uses.
7674 void LoadExternalVTableUses();
7675
7676 /// Note that the vtable for the given class was used at the
7677 /// given location.
7678 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7679 bool DefinitionRequired = false);
7680
7681 /// Mark the exception specifications of all virtual member functions
7682 /// in the given class as needed.
7683 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
7684 const CXXRecordDecl *RD);
7685
7686 /// MarkVirtualMembersReferenced - Will mark all members of the given
7687 /// CXXRecordDecl referenced.
7688 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
7689 bool ConstexprOnly = false);
7690
7691 /// Define all of the vtables that have been used in this
7692 /// translation unit and reference any virtual members used by those
7693 /// vtables.
7694 ///
7695 /// \returns true if any work was done, false otherwise.
7696 bool DefineUsedVTables();
7697
7698 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
7699
7700 void ActOnMemInitializers(Decl *ConstructorDecl,
7701 SourceLocation ColonLoc,
7702 ArrayRef<CXXCtorInitializer*> MemInits,
7703 bool AnyErrors);
7704
7705 /// Check class-level dllimport/dllexport attribute. The caller must
7706 /// ensure that referenceDLLExportedClassMethods is called some point later
7707 /// when all outer classes of Class are complete.
7708 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
7709 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
7710
7711 void referenceDLLExportedClassMethods();
7712
7713 void propagateDLLAttrToBaseClassTemplate(
7714 CXXRecordDecl *Class, Attr *ClassAttr,
7715 ClassTemplateSpecializationDecl *BaseTemplateSpec,
7716 SourceLocation BaseLoc);
7717
7718 /// Add gsl::Pointer attribute to std::container::iterator
7719 /// \param ND The declaration that introduces the name
7720 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
7721 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
7722
7723 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
7724 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
7725
7726 /// Add [[gsl::Pointer]] attributes for std:: types.
7727 void inferGslPointerAttribute(TypedefNameDecl *TD);
7728
7729 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
7730
7731 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
7732 /// conditions that are needed for the attribute to have an effect.
7733 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7734
7735 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7736 Decl *TagDecl, SourceLocation LBrac,
7737 SourceLocation RBrac,
7738 const ParsedAttributesView &AttrList);
7739 void ActOnFinishCXXMemberDecls();
7740 void ActOnFinishCXXNonNestedClass();
7741
7742 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7743 unsigned ActOnReenterTemplateScope(Decl *Template,
7744 llvm::function_ref<Scope *()> EnterScope);
7745 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7746 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7747 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7748 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7749 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7750 void ActOnFinishDelayedMemberInitializers(Decl *Record);
7751 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7752 CachedTokens &Toks);
7753 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7754 bool IsInsideALocalClassWithinATemplateFunction();
7755
7756 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7757 Expr *AssertExpr,
7758 Expr *AssertMessageExpr,
7759 SourceLocation RParenLoc);
7760 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7761 Expr *AssertExpr,
7762 StringLiteral *AssertMessageExpr,
7763 SourceLocation RParenLoc,
7764 bool Failed);
7765 void DiagnoseStaticAssertDetails(const Expr *E);
7766
7767 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7768 SourceLocation FriendLoc,
7769 TypeSourceInfo *TSInfo);
7770 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7771 MultiTemplateParamsArg TemplateParams);
7772 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7773 MultiTemplateParamsArg TemplateParams);
7774
7775 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7776 StorageClass& SC);
7777 void CheckConstructor(CXXConstructorDecl *Constructor);
7778 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7779 StorageClass& SC);
7780 bool CheckDestructor(CXXDestructorDecl *Destructor);
7781 void CheckConversionDeclarator(Declarator &D, QualType &R,
7782 StorageClass& SC);
7783 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7784 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7785 StorageClass &SC);
7786 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7787
7788 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7789
7790 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7791 CXXSpecialMember CSM,
7792 SourceLocation DefaultLoc);
7793 void CheckDelayedMemberExceptionSpecs();
7794
7795 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7796 DefaultedComparisonKind DCK);
7797 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7798 FunctionDecl *Spaceship);
7799 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7800 DefaultedComparisonKind DCK);
7801
7802 //===--------------------------------------------------------------------===//
7803 // C++ Derived Classes
7804 //
7805
7806 /// ActOnBaseSpecifier - Parsed a base specifier
7807 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7808 SourceRange SpecifierRange,
7809 bool Virtual, AccessSpecifier Access,
7810 TypeSourceInfo *TInfo,
7811 SourceLocation EllipsisLoc);
7812
7813 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
7814 const ParsedAttributesView &Attrs, bool Virtual,
7815 AccessSpecifier Access, ParsedType basetype,
7816 SourceLocation BaseLoc,
7817 SourceLocation EllipsisLoc);
7818
7819 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7820 MutableArrayRef<CXXBaseSpecifier *> Bases);
7821 void ActOnBaseSpecifiers(Decl *ClassDecl,
7822 MutableArrayRef<CXXBaseSpecifier *> Bases);
7823
7824 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7825 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7826 CXXBasePaths &Paths);
7827
7828 // FIXME: I don't like this name.
7829 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7830
7831 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7832 SourceLocation Loc, SourceRange Range,
7833 CXXCastPath *BasePath = nullptr,
7834 bool IgnoreAccess = false);
7835 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7836 unsigned InaccessibleBaseID,
7837 unsigned AmbiguousBaseConvID,
7838 SourceLocation Loc, SourceRange Range,
7839 DeclarationName Name,
7840 CXXCastPath *BasePath,
7841 bool IgnoreAccess = false);
7842
7843 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7844
7845 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7846 const CXXMethodDecl *Old);
7847
7848 /// CheckOverridingFunctionReturnType - Checks whether the return types are
7849 /// covariant, according to C++ [class.virtual]p5.
7850 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7851 const CXXMethodDecl *Old);
7852
7853 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7854 /// spec is a subset of base spec.
7855 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7856 const CXXMethodDecl *Old);
7857
7858 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7859
7860 /// CheckOverrideControl - Check C++11 override control semantics.
7861 void CheckOverrideControl(NamedDecl *D);
7862
7863 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7864 /// not used in the declaration of an overriding method.
7865 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7866
7867 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7868 /// overrides a virtual member function marked 'final', according to
7869 /// C++11 [class.virtual]p4.
7870 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7871 const CXXMethodDecl *Old);
7872
7873
7874 //===--------------------------------------------------------------------===//
7875 // C++ Access Control
7876 //
7877
7878 enum AccessResult {
7879 AR_accessible,
7880 AR_inaccessible,
7881 AR_dependent,
7882 AR_delayed
7883 };
7884
7885 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7886 NamedDecl *PrevMemberDecl,
7887 AccessSpecifier LexicalAS);
7888
7889 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7890 DeclAccessPair FoundDecl);
7891 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7892 DeclAccessPair FoundDecl);
7893 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7894 SourceRange PlacementRange,
7895 CXXRecordDecl *NamingClass,
7896 DeclAccessPair FoundDecl,
7897 bool Diagnose = true);
7898 AccessResult CheckConstructorAccess(SourceLocation Loc,
7899 CXXConstructorDecl *D,
7900 DeclAccessPair FoundDecl,
7901 const InitializedEntity &Entity,
7902 bool IsCopyBindingRefToTemp = false);
7903 AccessResult CheckConstructorAccess(SourceLocation Loc,
7904 CXXConstructorDecl *D,
7905 DeclAccessPair FoundDecl,
7906 const InitializedEntity &Entity,
7907 const PartialDiagnostic &PDiag);
7908 AccessResult CheckDestructorAccess(SourceLocation Loc,
7909 CXXDestructorDecl *Dtor,
7910 const PartialDiagnostic &PDiag,
7911 QualType objectType = QualType());
7912 AccessResult CheckFriendAccess(NamedDecl *D);
7913 AccessResult CheckMemberAccess(SourceLocation UseLoc,
7914 CXXRecordDecl *NamingClass,
7915 DeclAccessPair Found);
7916 AccessResult
7917 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7918 CXXRecordDecl *DecomposedClass,
7919 DeclAccessPair Field);
7920 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7921 const SourceRange &,
7922 DeclAccessPair FoundDecl);
7923 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7924 Expr *ObjectExpr,
7925 Expr *ArgExpr,
7926 DeclAccessPair FoundDecl);
7927 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7928 ArrayRef<Expr *> ArgExprs,
7929 DeclAccessPair FoundDecl);
7930 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7931 DeclAccessPair FoundDecl);
7932 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7933 QualType Base, QualType Derived,
7934 const CXXBasePath &Path,
7935 unsigned DiagID,
7936 bool ForceCheck = false,
7937 bool ForceUnprivileged = false);
7938 void CheckLookupAccess(const LookupResult &R);
7939 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7940 QualType BaseType);
7941 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7942 DeclAccessPair Found, QualType ObjectType,
7943 SourceLocation Loc,
7944 const PartialDiagnostic &Diag);
7945 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7946 DeclAccessPair Found,
7947 QualType ObjectType) {
7948 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7949 SourceLocation(), PDiag());
7950 }
7951
7952 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7953 const MultiLevelTemplateArgumentList &TemplateArgs);
7954 void PerformDependentDiagnostics(const DeclContext *Pattern,
7955 const MultiLevelTemplateArgumentList &TemplateArgs);
7956
7957 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7958
7959 /// When true, access checking violations are treated as SFINAE
7960 /// failures rather than hard errors.
7961 bool AccessCheckingSFINAE;
7962
7963 enum AbstractDiagSelID {
7964 AbstractNone = -1,
7965 AbstractReturnType,
7966 AbstractParamType,
7967 AbstractVariableType,
7968 AbstractFieldType,
7969 AbstractIvarType,
7970 AbstractSynthesizedIvarType,
7971 AbstractArrayType
7972 };
7973
7974 bool isAbstractType(SourceLocation Loc, QualType T);
7975 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7976 TypeDiagnoser &Diagnoser);
7977 template <typename... Ts>
7978 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7979 const Ts &...Args) {
7980 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7981 return RequireNonAbstractType(Loc, T, Diagnoser);
7982 }
7983
7984 void DiagnoseAbstractType(const CXXRecordDecl *RD);
7985
7986 //===--------------------------------------------------------------------===//
7987 // C++ Overloaded Operators [C++ 13.5]
7988 //
7989
7990 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7991
7992 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7993
7994 //===--------------------------------------------------------------------===//
7995 // C++ Templates [C++ 14]
7996 //
7997 void FilterAcceptableTemplateNames(LookupResult &R,
7998 bool AllowFunctionTemplates = true,
7999 bool AllowDependent = true);
8000 bool hasAnyAcceptableTemplateNames(LookupResult &R,
8001 bool AllowFunctionTemplates = true,
8002 bool AllowDependent = true,
8003 bool AllowNonTemplateFunctions = false);
8004 /// Try to interpret the lookup result D as a template-name.
8005 ///
8006 /// \param D A declaration found by name lookup.
8007 /// \param AllowFunctionTemplates Whether function templates should be
8008 /// considered valid results.
8009 /// \param AllowDependent Whether unresolved using declarations (that might
8010 /// name templates) should be considered valid results.
8011 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
8012 bool AllowFunctionTemplates = true,
8013 bool AllowDependent = true);
8014
8015 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
8016 /// Whether and why a template name is required in this lookup.
8017 class RequiredTemplateKind {
8018 public:
8019 /// Template name is required if TemplateKWLoc is valid.
8020 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
8021 : TemplateKW(TemplateKWLoc) {}
8022 /// Template name is unconditionally required.
8023 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
8024
8025 SourceLocation getTemplateKeywordLoc() const {
8026 return TemplateKW.value_or(SourceLocation());
8027 }
8028 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
8029 bool isRequired() const { return TemplateKW != SourceLocation(); }
8030 explicit operator bool() const { return isRequired(); }
8031
8032 private:
8033 std::optional<SourceLocation> TemplateKW;
8034 };
8035
8036 enum class AssumedTemplateKind {
8037 /// This is not assumed to be a template name.
8038 None,
8039 /// This is assumed to be a template name because lookup found nothing.
8040 FoundNothing,
8041 /// This is assumed to be a template name because lookup found one or more
8042 /// functions (but no function templates).
8043 FoundFunctions,
8044 };
8045 bool LookupTemplateName(
8046 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
8047 bool EnteringContext, bool &MemberOfUnknownSpecialization,
8048 RequiredTemplateKind RequiredTemplate = SourceLocation(),
8049 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
8050
8051 TemplateNameKind isTemplateName(Scope *S,
8052 CXXScopeSpec &SS,
8053 bool hasTemplateKeyword,
8054 const UnqualifiedId &Name,
8055 ParsedType ObjectType,
8056 bool EnteringContext,
8057 TemplateTy &Template,
8058 bool &MemberOfUnknownSpecialization,
8059 bool Disambiguation = false);
8060
8061 /// Try to resolve an undeclared template name as a type template.
8062 ///
8063 /// Sets II to the identifier corresponding to the template name, and updates
8064 /// Name to a corresponding (typo-corrected) type template name and TNK to
8065 /// the corresponding kind, if possible.
8066 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
8067 TemplateNameKind &TNK,
8068 SourceLocation NameLoc,
8069 IdentifierInfo *&II);
8070
8071 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
8072 SourceLocation NameLoc,
8073 bool Diagnose = true);
8074
8075 /// Determine whether a particular identifier might be the name in a C++1z
8076 /// deduction-guide declaration.
8077 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
8078 SourceLocation NameLoc,
8079 ParsedTemplateTy *Template = nullptr);
8080
8081 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
8082 SourceLocation IILoc,
8083 Scope *S,
8084 const CXXScopeSpec *SS,
8085 TemplateTy &SuggestedTemplate,
8086 TemplateNameKind &SuggestedKind);
8087
8088 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
8089 NamedDecl *Instantiation,
8090 bool InstantiatedFromMember,
8091 const NamedDecl *Pattern,
8092 const NamedDecl *PatternDef,
8093 TemplateSpecializationKind TSK,
8094 bool Complain = true);
8095
8096 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
8097 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
8098
8099 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
8100 SourceLocation EllipsisLoc,
8101 SourceLocation KeyLoc,
8102 IdentifierInfo *ParamName,
8103 SourceLocation ParamNameLoc,
8104 unsigned Depth, unsigned Position,
8105 SourceLocation EqualLoc,
8106 ParsedType DefaultArg, bool HasTypeConstraint);
8107
8108 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
8109
8110 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
8111 TemplateIdAnnotation *TypeConstraint,
8112 TemplateTypeParmDecl *ConstrainedParameter,
8113 SourceLocation EllipsisLoc);
8114 bool BuildTypeConstraint(const CXXScopeSpec &SS,
8115 TemplateIdAnnotation *TypeConstraint,
8116 TemplateTypeParmDecl *ConstrainedParameter,
8117 SourceLocation EllipsisLoc,
8118 bool AllowUnexpandedPack);
8119
8120 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
8121 DeclarationNameInfo NameInfo,
8122 ConceptDecl *NamedConcept,
8123 const TemplateArgumentListInfo *TemplateArgs,
8124 TemplateTypeParmDecl *ConstrainedParameter,
8125 SourceLocation EllipsisLoc);
8126
8127 bool AttachTypeConstraint(AutoTypeLoc TL,
8128 NonTypeTemplateParmDecl *NewConstrainedParm,
8129 NonTypeTemplateParmDecl *OrigConstrainedParm,
8130 SourceLocation EllipsisLoc);
8131
8132 bool RequireStructuralType(QualType T, SourceLocation Loc);
8133
8134 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
8135 SourceLocation Loc);
8136 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
8137
8138 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
8139 unsigned Depth,
8140 unsigned Position,
8141 SourceLocation EqualLoc,
8142 Expr *DefaultArg);
8143 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
8144 SourceLocation TmpLoc,
8145 TemplateParameterList *Params,
8146 SourceLocation EllipsisLoc,
8147 IdentifierInfo *ParamName,
8148 SourceLocation ParamNameLoc,
8149 unsigned Depth,
8150 unsigned Position,
8151 SourceLocation EqualLoc,
8152 ParsedTemplateArgument DefaultArg);
8153
8154 TemplateParameterList *
8155 ActOnTemplateParameterList(unsigned Depth,
8156 SourceLocation ExportLoc,
8157 SourceLocation TemplateLoc,
8158 SourceLocation LAngleLoc,
8159 ArrayRef<NamedDecl *> Params,
8160 SourceLocation RAngleLoc,
8161 Expr *RequiresClause);
8162
8163 /// The context in which we are checking a template parameter list.
8164 enum TemplateParamListContext {
8165 TPC_ClassTemplate,
8166 TPC_VarTemplate,
8167 TPC_FunctionTemplate,
8168 TPC_ClassTemplateMember,
8169 TPC_FriendClassTemplate,
8170 TPC_FriendFunctionTemplate,
8171 TPC_FriendFunctionTemplateDefinition,
8172 TPC_TypeAliasTemplate
8173 };
8174
8175 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
8176 TemplateParameterList *OldParams,
8177 TemplateParamListContext TPC,
8178 SkipBodyInfo *SkipBody = nullptr);
8179 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
8180 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
8181 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
8182 ArrayRef<TemplateParameterList *> ParamLists,
8183 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
8184 bool SuppressDiagnostic = false);
8185
8186 DeclResult CheckClassTemplate(
8187 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8188 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
8189 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
8190 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
8191 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
8192 TemplateParameterList **OuterTemplateParamLists,
8193 SkipBodyInfo *SkipBody = nullptr);
8194
8195 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
8196 QualType NTTPType,
8197 SourceLocation Loc);
8198
8199 /// Get a template argument mapping the given template parameter to itself,
8200 /// e.g. for X in \c template<int X>, this would return an expression template
8201 /// argument referencing X.
8202 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
8203 SourceLocation Location);
8204
8205 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
8206 TemplateArgumentListInfo &Out);
8207
8208 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
8209
8210 void NoteAllFoundTemplates(TemplateName Name);
8211
8212 QualType CheckTemplateIdType(TemplateName Template,
8213 SourceLocation TemplateLoc,
8214 TemplateArgumentListInfo &TemplateArgs);
8215
8216 TypeResult
8217 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8218 TemplateTy Template, IdentifierInfo *TemplateII,
8219 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
8220 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
8221 bool IsCtorOrDtorName = false, bool IsClassName = false,
8222 ImplicitTypenameContext AllowImplicitTypename =
8223 ImplicitTypenameContext::No);
8224
8225 /// Parsed an elaborated-type-specifier that refers to a template-id,
8226 /// such as \c class T::template apply<U>.
8227 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
8228 TypeSpecifierType TagSpec,
8229 SourceLocation TagLoc,
8230 CXXScopeSpec &SS,
8231 SourceLocation TemplateKWLoc,
8232 TemplateTy TemplateD,
8233 SourceLocation TemplateLoc,
8234 SourceLocation LAngleLoc,
8235 ASTTemplateArgsPtr TemplateArgsIn,
8236 SourceLocation RAngleLoc);
8237
8238 DeclResult ActOnVarTemplateSpecialization(
8239 Scope *S, Declarator &D, TypeSourceInfo *DI,
8240 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
8241 StorageClass SC, bool IsPartialSpecialization);
8242
8243 /// Get the specialization of the given variable template corresponding to
8244 /// the specified argument list, or a null-but-valid result if the arguments
8245 /// are dependent.
8246 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
8247 SourceLocation TemplateLoc,
8248 SourceLocation TemplateNameLoc,
8249 const TemplateArgumentListInfo &TemplateArgs);
8250
8251 /// Form a reference to the specialization of the given variable template
8252 /// corresponding to the specified argument list, or a null-but-valid result
8253 /// if the arguments are dependent.
8254 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
8255 const DeclarationNameInfo &NameInfo,
8256 VarTemplateDecl *Template,
8257 SourceLocation TemplateLoc,
8258 const TemplateArgumentListInfo *TemplateArgs);
8259
8260 ExprResult
8261 CheckConceptTemplateId(const CXXScopeSpec &SS,
8262 SourceLocation TemplateKWLoc,
8263 const DeclarationNameInfo &ConceptNameInfo,
8264 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
8265 const TemplateArgumentListInfo *TemplateArgs);
8266
8267 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
8268
8269 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
8270 SourceLocation TemplateKWLoc,
8271 LookupResult &R,
8272 bool RequiresADL,
8273 const TemplateArgumentListInfo *TemplateArgs);
8274
8275 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
8276 SourceLocation TemplateKWLoc,
8277 const DeclarationNameInfo &NameInfo,
8278 const TemplateArgumentListInfo *TemplateArgs);
8279
8280 TemplateNameKind ActOnTemplateName(
8281 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8282 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
8283 TemplateTy &Template, bool AllowInjectedClassName = false);
8284
8285 DeclResult ActOnClassTemplateSpecialization(
8286 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8287 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8288 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8289 MultiTemplateParamsArg TemplateParameterLists,
8290 SkipBodyInfo *SkipBody = nullptr);
8291
8292 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
8293 TemplateDecl *PrimaryTemplate,
8294 unsigned NumExplicitArgs,
8295 ArrayRef<TemplateArgument> Args);
8296 void CheckTemplatePartialSpecialization(
8297 ClassTemplatePartialSpecializationDecl *Partial);
8298 void CheckTemplatePartialSpecialization(
8299 VarTemplatePartialSpecializationDecl *Partial);
8300
8301 Decl *ActOnTemplateDeclarator(Scope *S,
8302 MultiTemplateParamsArg TemplateParameterLists,
8303 Declarator &D);
8304
8305 bool
8306 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8307 TemplateSpecializationKind NewTSK,
8308 NamedDecl *PrevDecl,
8309 TemplateSpecializationKind PrevTSK,
8310 SourceLocation PrevPtOfInstantiation,
8311 bool &SuppressNew);
8312
8313 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8314 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8315 LookupResult &Previous);
8316
8317 bool CheckFunctionTemplateSpecialization(
8318 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8319 LookupResult &Previous, bool QualifiedFriend = false);
8320 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
8321 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
8322
8323 DeclResult ActOnExplicitInstantiation(
8324 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8325 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8326 TemplateTy Template, SourceLocation TemplateNameLoc,
8327 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
8328 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
8329
8330 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8331 SourceLocation TemplateLoc,
8332 unsigned TagSpec, SourceLocation KWLoc,
8333 CXXScopeSpec &SS, IdentifierInfo *Name,
8334 SourceLocation NameLoc,
8335 const ParsedAttributesView &Attr);
8336
8337 DeclResult ActOnExplicitInstantiation(Scope *S,
8338 SourceLocation ExternLoc,
8339 SourceLocation TemplateLoc,
8340 Declarator &D);
8341
8342 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
8343 TemplateDecl *Template, SourceLocation TemplateLoc,
8344 SourceLocation RAngleLoc, Decl *Param,
8345 ArrayRef<TemplateArgument> SugaredConverted,
8346 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
8347
8348 /// Specifies the context in which a particular template
8349 /// argument is being checked.
8350 enum CheckTemplateArgumentKind {
8351 /// The template argument was specified in the code or was
8352 /// instantiated with some deduced template arguments.
8353 CTAK_Specified,
8354
8355 /// The template argument was deduced via template argument
8356 /// deduction.
8357 CTAK_Deduced,
8358
8359 /// The template argument was deduced from an array bound
8360 /// via template argument deduction.
8361 CTAK_DeducedFromArrayBound
8362 };
8363
8364 bool
8365 CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
8366 NamedDecl *Template, SourceLocation TemplateLoc,
8367 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
8368 SmallVectorImpl<TemplateArgument> &SugaredConverted,
8369 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
8370 CheckTemplateArgumentKind CTAK);
8371
8372 /// Check that the given template arguments can be provided to
8373 /// the given template, converting the arguments along the way.
8374 ///
8375 /// \param Template The template to which the template arguments are being
8376 /// provided.
8377 ///
8378 /// \param TemplateLoc The location of the template name in the source.
8379 ///
8380 /// \param TemplateArgs The list of template arguments. If the template is
8381 /// a template template parameter, this function may extend the set of
8382 /// template arguments to also include substituted, defaulted template
8383 /// arguments.
8384 ///
8385 /// \param PartialTemplateArgs True if the list of template arguments is
8386 /// intentionally partial, e.g., because we're checking just the initial
8387 /// set of template arguments.
8388 ///
8389 /// \param Converted Will receive the converted, canonicalized template
8390 /// arguments.
8391 ///
8392 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
8393 /// contain the converted forms of the template arguments as written.
8394 /// Otherwise, \p TemplateArgs will not be modified.
8395 ///
8396 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
8397 /// receive true if the cause for the error is the associated constraints of
8398 /// the template not being satisfied by the template arguments.
8399 ///
8400 /// \returns true if an error occurred, false otherwise.
8401 bool CheckTemplateArgumentList(
8402 TemplateDecl *Template, SourceLocation TemplateLoc,
8403 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
8404 SmallVectorImpl<TemplateArgument> &SugaredConverted,
8405 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
8406 bool UpdateArgsWithConversions = true,
8407 bool *ConstraintsNotSatisfied = nullptr);
8408
8409 bool CheckTemplateTypeArgument(
8410 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
8411 SmallVectorImpl<TemplateArgument> &SugaredConverted,
8412 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
8413
8414 bool CheckTemplateArgument(TypeSourceInfo *Arg);
8415 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
8416 QualType InstantiatedParamType, Expr *Arg,
8417 TemplateArgument &SugaredConverted,
8418 TemplateArgument &CanonicalConverted,
8419 CheckTemplateArgumentKind CTAK);
8420 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
8421 TemplateParameterList *Params,
8422 TemplateArgumentLoc &Arg);
8423
8424 ExprResult
8425 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
8426 QualType ParamType,
8427 SourceLocation Loc);
8428 ExprResult
8429 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
8430 SourceLocation Loc);
8431
8432 /// Enumeration describing how template parameter lists are compared
8433 /// for equality.
8434 enum TemplateParameterListEqualKind {
8435 /// We are matching the template parameter lists of two templates
8436 /// that might be redeclarations.
8437 ///
8438 /// \code
8439 /// template<typename T> struct X;
8440 /// template<typename T> struct X;
8441 /// \endcode
8442 TPL_TemplateMatch,
8443
8444 /// We are matching the template parameter lists of two template
8445 /// template parameters as part of matching the template parameter lists
8446 /// of two templates that might be redeclarations.
8447 ///
8448 /// \code
8449 /// template<template<int I> class TT> struct X;
8450 /// template<template<int Value> class Other> struct X;
8451 /// \endcode
8452 TPL_TemplateTemplateParmMatch,
8453
8454 /// We are matching the template parameter lists of a template
8455 /// template argument against the template parameter lists of a template
8456 /// template parameter.
8457 ///
8458 /// \code
8459 /// template<template<int Value> class Metafun> struct X;
8460 /// template<int Value> struct integer_c;
8461 /// X<integer_c> xic;
8462 /// \endcode
8463 TPL_TemplateTemplateArgumentMatch,
8464
8465 /// We are determining whether the template-parameters are equivalent
8466 /// according to C++ [temp.over.link]/6. This comparison does not consider
8467 /// constraints.
8468 ///
8469 /// \code
8470 /// template<C1 T> void f(T);
8471 /// template<C2 T> void f(T);
8472 /// \endcode
8473 TPL_TemplateParamsEquivalent,
8474 };
8475
8476 bool TemplateParameterListsAreEqual(
8477 const NamedDecl *NewInstFrom, TemplateParameterList *New,
8478 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8479 TemplateParameterListEqualKind Kind,
8480 SourceLocation TemplateArgLoc = SourceLocation());
8481
8482 bool TemplateParameterListsAreEqual(
8483 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
8484 TemplateParameterListEqualKind Kind,
8485 SourceLocation TemplateArgLoc = SourceLocation()) {
8486 return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain,
8487 Kind, TemplateArgLoc);
8488 }
8489
8490 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
8491
8492 /// Called when the parser has parsed a C++ typename
8493 /// specifier, e.g., "typename T::type".
8494 ///
8495 /// \param S The scope in which this typename type occurs.
8496 /// \param TypenameLoc the location of the 'typename' keyword
8497 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8498 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
8499 /// \param IdLoc the location of the identifier.
8500 /// \param IsImplicitTypename context where T::type refers to a type.
8501 TypeResult ActOnTypenameType(
8502 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
8503 const IdentifierInfo &II, SourceLocation IdLoc,
8504 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
8505
8506 /// Called when the parser has parsed a C++ typename
8507 /// specifier that ends in a template-id, e.g.,
8508 /// "typename MetaFun::template apply<T1, T2>".
8509 ///
8510 /// \param S The scope in which this typename type occurs.
8511 /// \param TypenameLoc the location of the 'typename' keyword
8512 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8513 /// \param TemplateLoc the location of the 'template' keyword, if any.
8514 /// \param TemplateName The template name.
8515 /// \param TemplateII The identifier used to name the template.
8516 /// \param TemplateIILoc The location of the template name.
8517 /// \param LAngleLoc The location of the opening angle bracket ('<').
8518 /// \param TemplateArgs The template arguments.
8519 /// \param RAngleLoc The location of the closing angle bracket ('>').
8520 TypeResult
8521 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8522 const CXXScopeSpec &SS,
8523 SourceLocation TemplateLoc,
8524 TemplateTy TemplateName,
8525 IdentifierInfo *TemplateII,
8526 SourceLocation TemplateIILoc,
8527 SourceLocation LAngleLoc,
8528 ASTTemplateArgsPtr TemplateArgs,
8529 SourceLocation RAngleLoc);
8530
8531 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8532 SourceLocation KeywordLoc,
8533 NestedNameSpecifierLoc QualifierLoc,
8534 const IdentifierInfo &II,
8535 SourceLocation IILoc,
8536 TypeSourceInfo **TSI,
8537 bool DeducedTSTContext);
8538
8539 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8540 SourceLocation KeywordLoc,
8541 NestedNameSpecifierLoc QualifierLoc,
8542 const IdentifierInfo &II,
8543 SourceLocation IILoc,
8544 bool DeducedTSTContext = true);
8545
8546
8547 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8548 SourceLocation Loc,
8549 DeclarationName Name);
8550 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
8551
8552 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
8553 bool RebuildTemplateParamsInCurrentInstantiation(
8554 TemplateParameterList *Params);
8555
8556 std::string
8557 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8558 const TemplateArgumentList &Args);
8559
8560 std::string
8561 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8562 const TemplateArgument *Args,
8563 unsigned NumArgs);
8564
8565 //===--------------------------------------------------------------------===//
8566 // C++ Concepts
8567 //===--------------------------------------------------------------------===//
8568 Decl *ActOnConceptDefinition(
8569 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8570 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
8571
8572 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
8573 bool &AddToScope);
8574
8575 RequiresExprBodyDecl *
8576 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8577 ArrayRef<ParmVarDecl *> LocalParameters,
8578 Scope *BodyScope);
8579 void ActOnFinishRequiresExpr();
8580 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8581 concepts::Requirement *ActOnTypeRequirement(
8582 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
8583 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
8584 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8585 SourceLocation NoexceptLoc);
8586 concepts::Requirement *
8587 ActOnCompoundRequirement(
8588 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8589 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8590 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8591 concepts::ExprRequirement *
8592 BuildExprRequirement(
8593 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8594 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8595 concepts::ExprRequirement *
8596 BuildExprRequirement(
8597 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8598 bool IsSatisfied, SourceLocation NoexceptLoc,
8599 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8600 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8601 concepts::TypeRequirement *
8602 BuildTypeRequirement(
8603 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8604 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8605 concepts::NestedRequirement *
8606 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8607 const ASTConstraintSatisfaction &Satisfaction);
8608 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8609 RequiresExprBodyDecl *Body,
8610 ArrayRef<ParmVarDecl *> LocalParameters,
8611 ArrayRef<concepts::Requirement *> Requirements,
8612 SourceLocation ClosingBraceLoc);
8613
8614 //===--------------------------------------------------------------------===//
8615 // C++ Variadic Templates (C++0x [temp.variadic])
8616 //===--------------------------------------------------------------------===//
8617
8618 /// Determine whether an unexpanded parameter pack might be permitted in this
8619 /// location. Useful for error recovery.
8620 bool isUnexpandedParameterPackPermitted();
8621
8622 /// The context in which an unexpanded parameter pack is
8623 /// being diagnosed.
8624 ///
8625 /// Note that the values of this enumeration line up with the first
8626 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
8627 enum UnexpandedParameterPackContext {
8628 /// An arbitrary expression.
8629 UPPC_Expression = 0,
8630
8631 /// The base type of a class type.
8632 UPPC_BaseType,
8633
8634 /// The type of an arbitrary declaration.
8635 UPPC_DeclarationType,
8636
8637 /// The type of a data member.
8638 UPPC_DataMemberType,
8639
8640 /// The size of a bit-field.
8641 UPPC_BitFieldWidth,
8642
8643 /// The expression in a static assertion.
8644 UPPC_StaticAssertExpression,
8645
8646 /// The fixed underlying type of an enumeration.
8647 UPPC_FixedUnderlyingType,
8648
8649 /// The enumerator value.
8650 UPPC_EnumeratorValue,
8651
8652 /// A using declaration.
8653 UPPC_UsingDeclaration,
8654
8655 /// A friend declaration.
8656 UPPC_FriendDeclaration,
8657
8658 /// A declaration qualifier.
8659 UPPC_DeclarationQualifier,
8660
8661 /// An initializer.
8662 UPPC_Initializer,
8663
8664 /// A default argument.
8665 UPPC_DefaultArgument,
8666
8667 /// The type of a non-type template parameter.
8668 UPPC_NonTypeTemplateParameterType,
8669
8670 /// The type of an exception.
8671 UPPC_ExceptionType,
8672
8673 /// Partial specialization.
8674 UPPC_PartialSpecialization,
8675
8676 /// Microsoft __if_exists.
8677 UPPC_IfExists,
8678
8679 /// Microsoft __if_not_exists.
8680 UPPC_IfNotExists,
8681
8682 /// Lambda expression.
8683 UPPC_Lambda,
8684
8685 /// Block expression.
8686 UPPC_Block,
8687
8688 /// A type constraint.
8689 UPPC_TypeConstraint,
8690
8691 // A requirement in a requires-expression.
8692 UPPC_Requirement,
8693
8694 // A requires-clause.
8695 UPPC_RequiresClause,
8696 };
8697
8698 /// Diagnose unexpanded parameter packs.
8699 ///
8700 /// \param Loc The location at which we should emit the diagnostic.
8701 ///
8702 /// \param UPPC The context in which we are diagnosing unexpanded
8703 /// parameter packs.
8704 ///
8705 /// \param Unexpanded the set of unexpanded parameter packs.
8706 ///
8707 /// \returns true if an error occurred, false otherwise.
8708 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
8709 UnexpandedParameterPackContext UPPC,
8710 ArrayRef<UnexpandedParameterPack> Unexpanded);
8711
8712 /// If the given type contains an unexpanded parameter pack,
8713 /// diagnose the error.
8714 ///
8715 /// \param Loc The source location where a diagnostc should be emitted.
8716 ///
8717 /// \param T The type that is being checked for unexpanded parameter
8718 /// packs.
8719 ///
8720 /// \returns true if an error occurred, false otherwise.
8721 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
8722 UnexpandedParameterPackContext UPPC);
8723
8724 /// If the given expression contains an unexpanded parameter
8725 /// pack, diagnose the error.
8726 ///
8727 /// \param E The expression that is being checked for unexpanded
8728 /// parameter packs.
8729 ///
8730 /// \returns true if an error occurred, false otherwise.
8731 bool DiagnoseUnexpandedParameterPack(Expr *E,
8732 UnexpandedParameterPackContext UPPC = UPPC_Expression);
8733
8734 /// If the given requirees-expression contains an unexpanded reference to one
8735 /// of its own parameter packs, diagnose the error.
8736 ///
8737 /// \param RE The requiress-expression that is being checked for unexpanded
8738 /// parameter packs.
8739 ///
8740 /// \returns true if an error occurred, false otherwise.
8741 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
8742
8743 /// If the given nested-name-specifier contains an unexpanded
8744 /// parameter pack, diagnose the error.
8745 ///
8746 /// \param SS The nested-name-specifier that is being checked for
8747 /// unexpanded parameter packs.
8748 ///
8749 /// \returns true if an error occurred, false otherwise.
8750 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
8751 UnexpandedParameterPackContext UPPC);
8752
8753 /// If the given name contains an unexpanded parameter pack,
8754 /// diagnose the error.
8755 ///
8756 /// \param NameInfo The name (with source location information) that
8757 /// is being checked for unexpanded parameter packs.
8758 ///
8759 /// \returns true if an error occurred, false otherwise.
8760 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
8761 UnexpandedParameterPackContext UPPC);
8762
8763 /// If the given template name contains an unexpanded parameter pack,
8764 /// diagnose the error.
8765 ///
8766 /// \param Loc The location of the template name.
8767 ///
8768 /// \param Template The template name that is being checked for unexpanded
8769 /// parameter packs.
8770 ///
8771 /// \returns true if an error occurred, false otherwise.
8772 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8773 TemplateName Template,
8774 UnexpandedParameterPackContext UPPC);
8775
8776 /// If the given template argument contains an unexpanded parameter
8777 /// pack, diagnose the error.
8778 ///
8779 /// \param Arg The template argument that is being checked for unexpanded
8780 /// parameter packs.
8781 ///
8782 /// \returns true if an error occurred, false otherwise.
8783 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8784 UnexpandedParameterPackContext UPPC);
8785
8786 /// Collect the set of unexpanded parameter packs within the given
8787 /// template argument.
8788 ///
8789 /// \param Arg The template argument that will be traversed to find
8790 /// unexpanded parameter packs.
8791 void collectUnexpandedParameterPacks(TemplateArgument Arg,
8792 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8793
8794 /// Collect the set of unexpanded parameter packs within the given
8795 /// template argument.
8796 ///
8797 /// \param Arg The template argument that will be traversed to find
8798 /// unexpanded parameter packs.
8799 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8800 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8801
8802 /// Collect the set of unexpanded parameter packs within the given
8803 /// type.
8804 ///
8805 /// \param T The type that will be traversed to find
8806 /// unexpanded parameter packs.
8807 void collectUnexpandedParameterPacks(QualType T,
8808 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8809
8810 /// Collect the set of unexpanded parameter packs within the given
8811 /// type.
8812 ///
8813 /// \param TL The type that will be traversed to find
8814 /// unexpanded parameter packs.
8815 void collectUnexpandedParameterPacks(TypeLoc TL,
8816 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8817
8818 /// Collect the set of unexpanded parameter packs within the given
8819 /// nested-name-specifier.
8820 ///
8821 /// \param NNS The nested-name-specifier that will be traversed to find
8822 /// unexpanded parameter packs.
8823 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8824 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8825
8826 /// Collect the set of unexpanded parameter packs within the given
8827 /// name.
8828 ///
8829 /// \param NameInfo The name that will be traversed to find
8830 /// unexpanded parameter packs.
8831 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8832 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8833
8834 /// Invoked when parsing a template argument followed by an
8835 /// ellipsis, which creates a pack expansion.
8836 ///
8837 /// \param Arg The template argument preceding the ellipsis, which
8838 /// may already be invalid.
8839 ///
8840 /// \param EllipsisLoc The location of the ellipsis.
8841 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8842 SourceLocation EllipsisLoc);
8843
8844 /// Invoked when parsing a type followed by an ellipsis, which
8845 /// creates a pack expansion.
8846 ///
8847 /// \param Type The type preceding the ellipsis, which will become
8848 /// the pattern of the pack expansion.
8849 ///
8850 /// \param EllipsisLoc The location of the ellipsis.
8851 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8852
8853 /// Construct a pack expansion type from the pattern of the pack
8854 /// expansion.
8855 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8856 SourceLocation EllipsisLoc,
8857 std::optional<unsigned> NumExpansions);
8858
8859 /// Construct a pack expansion type from the pattern of the pack
8860 /// expansion.
8861 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
8862 SourceLocation EllipsisLoc,
8863 std::optional<unsigned> NumExpansions);
8864
8865 /// Invoked when parsing an expression followed by an ellipsis, which
8866 /// creates a pack expansion.
8867 ///
8868 /// \param Pattern The expression preceding the ellipsis, which will become
8869 /// the pattern of the pack expansion.
8870 ///
8871 /// \param EllipsisLoc The location of the ellipsis.
8872 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8873
8874 /// Invoked when parsing an expression followed by an ellipsis, which
8875 /// creates a pack expansion.
8876 ///
8877 /// \param Pattern The expression preceding the ellipsis, which will become
8878 /// the pattern of the pack expansion.
8879 ///
8880 /// \param EllipsisLoc The location of the ellipsis.
8881 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8882 std::optional<unsigned> NumExpansions);
8883
8884 /// Determine whether we could expand a pack expansion with the
8885 /// given set of parameter packs into separate arguments by repeatedly
8886 /// transforming the pattern.
8887 ///
8888 /// \param EllipsisLoc The location of the ellipsis that identifies the
8889 /// pack expansion.
8890 ///
8891 /// \param PatternRange The source range that covers the entire pattern of
8892 /// the pack expansion.
8893 ///
8894 /// \param Unexpanded The set of unexpanded parameter packs within the
8895 /// pattern.
8896 ///
8897 /// \param ShouldExpand Will be set to \c true if the transformer should
8898 /// expand the corresponding pack expansions into separate arguments. When
8899 /// set, \c NumExpansions must also be set.
8900 ///
8901 /// \param RetainExpansion Whether the caller should add an unexpanded
8902 /// pack expansion after all of the expanded arguments. This is used
8903 /// when extending explicitly-specified template argument packs per
8904 /// C++0x [temp.arg.explicit]p9.
8905 ///
8906 /// \param NumExpansions The number of separate arguments that will be in
8907 /// the expanded form of the corresponding pack expansion. This is both an
8908 /// input and an output parameter, which can be set by the caller if the
8909 /// number of expansions is known a priori (e.g., due to a prior substitution)
8910 /// and will be set by the callee when the number of expansions is known.
8911 /// The callee must set this value when \c ShouldExpand is \c true; it may
8912 /// set this value in other cases.
8913 ///
8914 /// \returns true if an error occurred (e.g., because the parameter packs
8915 /// are to be instantiated with arguments of different lengths), false
8916 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8917 /// must be set.
8918 bool CheckParameterPacksForExpansion(
8919 SourceLocation EllipsisLoc, SourceRange PatternRange,
8920 ArrayRef<UnexpandedParameterPack> Unexpanded,
8921 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
8922 bool &RetainExpansion, std::optional<unsigned> &NumExpansions);
8923
8924 /// Determine the number of arguments in the given pack expansion
8925 /// type.
8926 ///
8927 /// This routine assumes that the number of arguments in the expansion is
8928 /// consistent across all of the unexpanded parameter packs in its pattern.
8929 ///
8930 /// Returns an empty Optional if the type can't be expanded.
8931 std::optional<unsigned> getNumArgumentsInExpansion(
8932 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
8933
8934 /// Determine whether the given declarator contains any unexpanded
8935 /// parameter packs.
8936 ///
8937 /// This routine is used by the parser to disambiguate function declarators
8938 /// with an ellipsis prior to the ')', e.g.,
8939 ///
8940 /// \code
8941 /// void f(T...);
8942 /// \endcode
8943 ///
8944 /// To determine whether we have an (unnamed) function parameter pack or
8945 /// a variadic function.
8946 ///
8947 /// \returns true if the declarator contains any unexpanded parameter packs,
8948 /// false otherwise.
8949 bool containsUnexpandedParameterPacks(Declarator &D);
8950
8951 /// Returns the pattern of the pack expansion for a template argument.
8952 ///
8953 /// \param OrigLoc The template argument to expand.
8954 ///
8955 /// \param Ellipsis Will be set to the location of the ellipsis.
8956 ///
8957 /// \param NumExpansions Will be set to the number of expansions that will
8958 /// be generated from this pack expansion, if known a priori.
8959 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8960 TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis,
8961 std::optional<unsigned> &NumExpansions) const;
8962
8963 /// Given a template argument that contains an unexpanded parameter pack, but
8964 /// which has already been substituted, attempt to determine the number of
8965 /// elements that will be produced once this argument is fully-expanded.
8966 ///
8967 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8968 /// avoid actually expanding the pack where possible.
8969 std::optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8970
8971 //===--------------------------------------------------------------------===//
8972 // C++ Template Argument Deduction (C++ [temp.deduct])
8973 //===--------------------------------------------------------------------===//
8974
8975 /// Adjust the type \p ArgFunctionType to match the calling convention,
8976 /// noreturn, and optionally the exception specification of \p FunctionType.
8977 /// Deduction often wants to ignore these properties when matching function
8978 /// types.
8979 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8980 bool AdjustExceptionSpec = false);
8981
8982 /// Describes the result of template argument deduction.
8983 ///
8984 /// The TemplateDeductionResult enumeration describes the result of
8985 /// template argument deduction, as returned from
8986 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8987 /// structure provides additional information about the results of
8988 /// template argument deduction, e.g., the deduced template argument
8989 /// list (if successful) or the specific template parameters or
8990 /// deduced arguments that were involved in the failure.
8991 enum TemplateDeductionResult {
8992 /// Template argument deduction was successful.
8993 TDK_Success = 0,
8994 /// The declaration was invalid; do nothing.
8995 TDK_Invalid,
8996 /// Template argument deduction exceeded the maximum template
8997 /// instantiation depth (which has already been diagnosed).
8998 TDK_InstantiationDepth,
8999 /// Template argument deduction did not deduce a value
9000 /// for every template parameter.
9001 TDK_Incomplete,
9002 /// Template argument deduction did not deduce a value for every
9003 /// expansion of an expanded template parameter pack.
9004 TDK_IncompletePack,
9005 /// Template argument deduction produced inconsistent
9006 /// deduced values for the given template parameter.
9007 TDK_Inconsistent,
9008 /// Template argument deduction failed due to inconsistent
9009 /// cv-qualifiers on a template parameter type that would
9010 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
9011 /// but were given a non-const "X".
9012 TDK_Underqualified,
9013 /// Substitution of the deduced template argument values
9014 /// resulted in an error.
9015 TDK_SubstitutionFailure,
9016 /// After substituting deduced template arguments, a dependent
9017 /// parameter type did not match the corresponding argument.
9018 TDK_DeducedMismatch,
9019 /// After substituting deduced template arguments, an element of
9020 /// a dependent parameter type did not match the corresponding element
9021 /// of the corresponding argument (when deducing from an initializer list).
9022 TDK_DeducedMismatchNested,
9023 /// A non-depnedent component of the parameter did not match the
9024 /// corresponding component of the argument.
9025 TDK_NonDeducedMismatch,
9026 /// When performing template argument deduction for a function
9027 /// template, there were too many call arguments.
9028 TDK_TooManyArguments,
9029 /// When performing template argument deduction for a function
9030 /// template, there were too few call arguments.
9031 TDK_TooFewArguments,
9032 /// The explicitly-specified template arguments were not valid
9033 /// template arguments for the given template.
9034 TDK_InvalidExplicitArguments,
9035 /// Checking non-dependent argument conversions failed.
9036 TDK_NonDependentConversionFailure,
9037 /// The deduced arguments did not satisfy the constraints associated
9038 /// with the template.
9039 TDK_ConstraintsNotSatisfied,
9040 /// Deduction failed; that's all we know.
9041 TDK_MiscellaneousDeductionFailure,
9042 /// CUDA Target attributes do not match.
9043 TDK_CUDATargetMismatch,
9044 /// Some error which was already diagnosed.
9045 TDK_AlreadyDiagnosed
9046 };
9047
9048 TemplateDeductionResult
9049 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
9050 const TemplateArgumentList &TemplateArgs,
9051 sema::TemplateDeductionInfo &Info);
9052
9053 TemplateDeductionResult
9054 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
9055 const TemplateArgumentList &TemplateArgs,
9056 sema::TemplateDeductionInfo &Info);
9057
9058 TemplateDeductionResult SubstituteExplicitTemplateArguments(
9059 FunctionTemplateDecl *FunctionTemplate,
9060 TemplateArgumentListInfo &ExplicitTemplateArgs,
9061 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
9062 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
9063 sema::TemplateDeductionInfo &Info);
9064
9065 /// brief A function argument from which we performed template argument
9066 // deduction for a call.
9067 struct OriginalCallArg {
9068 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
9069 unsigned ArgIdx, QualType OriginalArgType)
9070 : OriginalParamType(OriginalParamType),
9071 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
9072 OriginalArgType(OriginalArgType) {}
9073
9074 QualType OriginalParamType;
9075 bool DecomposedParam;
9076 unsigned ArgIdx;
9077 QualType OriginalArgType;
9078 };
9079
9080 TemplateDeductionResult FinishTemplateArgumentDeduction(
9081 FunctionTemplateDecl *FunctionTemplate,
9082 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
9083 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
9084 sema::TemplateDeductionInfo &Info,
9085 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
9086 bool PartialOverloading = false,
9087 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
9088
9089 TemplateDeductionResult DeduceTemplateArguments(
9090 FunctionTemplateDecl *FunctionTemplate,
9091 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
9092 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
9093 bool PartialOverloading,
9094 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
9095
9096 TemplateDeductionResult
9097 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
9098 TemplateArgumentListInfo *ExplicitTemplateArgs,
9099 QualType ArgFunctionType,
9100 FunctionDecl *&Specialization,
9101 sema::TemplateDeductionInfo &Info,
9102 bool IsAddressOfFunction = false);
9103
9104 TemplateDeductionResult
9105 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
9106 QualType ToType,
9107 CXXConversionDecl *&Specialization,
9108 sema::TemplateDeductionInfo &Info);
9109
9110 TemplateDeductionResult
9111 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
9112 TemplateArgumentListInfo *ExplicitTemplateArgs,
9113 FunctionDecl *&Specialization,
9114 sema::TemplateDeductionInfo &Info,
9115 bool IsAddressOfFunction = false);
9116
9117 /// Substitute Replacement for \p auto in \p TypeWithAuto
9118 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
9119 /// Substitute Replacement for auto in TypeWithAuto
9120 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
9121 QualType Replacement);
9122
9123 // Substitute auto in TypeWithAuto for a Dependent auto type
9124 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
9125
9126 // Substitute auto in TypeWithAuto for a Dependent auto type
9127 TypeSourceInfo *
9128 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
9129
9130 /// Completely replace the \c auto in \p TypeWithAuto by
9131 /// \p Replacement. This does not retain any \c auto type sugar.
9132 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
9133 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
9134 QualType Replacement);
9135
9136 TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer,
9137 QualType &Result,
9138 sema::TemplateDeductionInfo &Info,
9139 bool DependentDeduction = false,
9140 bool IgnoreConstraints = false);
9141 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
9142 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
9143 bool Diagnose = true);
9144
9145 /// Declare implicit deduction guides for a class template if we've
9146 /// not already done so.
9147 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
9148 SourceLocation Loc);
9149
9150 QualType DeduceTemplateSpecializationFromInitializer(
9151 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9152 const InitializationKind &Kind, MultiExprArg Init);
9153
9154 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
9155 QualType Type, TypeSourceInfo *TSI,
9156 SourceRange Range, bool DirectInit,
9157 Expr *Init);
9158
9159 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
9160
9161 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
9162 SourceLocation ReturnLoc, Expr *RetExpr,
9163 const AutoType *AT);
9164
9165 FunctionTemplateDecl *getMoreSpecializedTemplate(
9166 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
9167 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
9168 unsigned NumCallArguments2, bool Reversed = false);
9169 UnresolvedSetIterator
9170 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
9171 TemplateSpecCandidateSet &FailedCandidates,
9172 SourceLocation Loc,
9173 const PartialDiagnostic &NoneDiag,
9174 const PartialDiagnostic &AmbigDiag,
9175 const PartialDiagnostic &CandidateDiag,
9176 bool Complain = true, QualType TargetType = QualType());
9177
9178 ClassTemplatePartialSpecializationDecl *
9179 getMoreSpecializedPartialSpecialization(
9180 ClassTemplatePartialSpecializationDecl *PS1,
9181 ClassTemplatePartialSpecializationDecl *PS2,
9182 SourceLocation Loc);
9183
9184 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
9185 sema::TemplateDeductionInfo &Info);
9186
9187 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
9188 VarTemplatePartialSpecializationDecl *PS1,
9189 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
9190
9191 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
9192 sema::TemplateDeductionInfo &Info);
9193
9194 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
9195 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
9196
9197 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
9198 unsigned Depth, llvm::SmallBitVector &Used);
9199
9200 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
9201 bool OnlyDeduced,
9202 unsigned Depth,
9203 llvm::SmallBitVector &Used);
9204 void MarkDeducedTemplateParameters(
9205 const FunctionTemplateDecl *FunctionTemplate,
9206 llvm::SmallBitVector &Deduced) {
9207 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
9208 }
9209 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
9210 const FunctionTemplateDecl *FunctionTemplate,
9211 llvm::SmallBitVector &Deduced);
9212
9213 //===--------------------------------------------------------------------===//
9214 // C++ Template Instantiation
9215 //
9216
9217 MultiLevelTemplateArgumentList
9218 getTemplateInstantiationArgs(const NamedDecl *D, bool Final = false,
9219 const TemplateArgumentList *Innermost = nullptr,
9220 bool RelativeToPrimary = false,
9221 const FunctionDecl *Pattern = nullptr,
9222 bool ForConstraintInstantiation = false,
9223 bool SkipForSpecialization = false);
9224
9225 /// A context in which code is being synthesized (where a source location
9226 /// alone is not sufficient to identify the context). This covers template
9227 /// instantiation and various forms of implicitly-generated functions.
9228 struct CodeSynthesisContext {
9229 /// The kind of template instantiation we are performing
9230 enum SynthesisKind {
9231 /// We are instantiating a template declaration. The entity is
9232 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
9233 TemplateInstantiation,
9234
9235 /// We are instantiating a default argument for a template
9236 /// parameter. The Entity is the template parameter whose argument is
9237 /// being instantiated, the Template is the template, and the
9238 /// TemplateArgs/NumTemplateArguments provide the template arguments as
9239 /// specified.
9240 DefaultTemplateArgumentInstantiation,
9241
9242 /// We are instantiating a default argument for a function.
9243 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
9244 /// provides the template arguments as specified.
9245 DefaultFunctionArgumentInstantiation,
9246
9247 /// We are substituting explicit template arguments provided for
9248 /// a function template. The entity is a FunctionTemplateDecl.
9249 ExplicitTemplateArgumentSubstitution,
9250
9251 /// We are substituting template argument determined as part of
9252 /// template argument deduction for either a class template
9253 /// partial specialization or a function template. The
9254 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
9255 /// a TemplateDecl.
9256 DeducedTemplateArgumentSubstitution,
9257
9258 /// We are substituting prior template arguments into a new
9259 /// template parameter. The template parameter itself is either a
9260 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
9261 PriorTemplateArgumentSubstitution,
9262
9263 /// We are checking the validity of a default template argument that
9264 /// has been used when naming a template-id.
9265 DefaultTemplateArgumentChecking,
9266
9267 /// We are computing the exception specification for a defaulted special
9268 /// member function.
9269 ExceptionSpecEvaluation,
9270
9271 /// We are instantiating the exception specification for a function
9272 /// template which was deferred until it was needed.
9273 ExceptionSpecInstantiation,
9274
9275 /// We are instantiating a requirement of a requires expression.
9276 RequirementInstantiation,
9277
9278 /// We are checking the satisfaction of a nested requirement of a requires
9279 /// expression.
9280 NestedRequirementConstraintsCheck,
9281
9282 /// We are declaring an implicit special member function.
9283 DeclaringSpecialMember,
9284
9285 /// We are declaring an implicit 'operator==' for a defaulted
9286 /// 'operator<=>'.
9287 DeclaringImplicitEqualityComparison,
9288
9289 /// We are defining a synthesized function (such as a defaulted special
9290 /// member).
9291 DefiningSynthesizedFunction,
9292
9293 // We are checking the constraints associated with a constrained entity or
9294 // the constraint expression of a concept. This includes the checks that
9295 // atomic constraints have the type 'bool' and that they can be constant
9296 // evaluated.
9297 ConstraintsCheck,
9298
9299 // We are substituting template arguments into a constraint expression.
9300 ConstraintSubstitution,
9301
9302 // We are normalizing a constraint expression.
9303 ConstraintNormalization,
9304
9305 // Instantiating a Requires Expression parameter clause.
9306 RequirementParameterInstantiation,
9307
9308 // We are substituting into the parameter mapping of an atomic constraint
9309 // during normalization.
9310 ParameterMappingSubstitution,
9311
9312 /// We are rewriting a comparison operator in terms of an operator<=>.
9313 RewritingOperatorAsSpaceship,
9314
9315 /// We are initializing a structured binding.
9316 InitializingStructuredBinding,
9317
9318 /// We are marking a class as __dllexport.
9319 MarkingClassDllexported,
9320
9321 /// We are building an implied call from __builtin_dump_struct. The
9322 /// arguments are in CallArgs.
9323 BuildingBuiltinDumpStructCall,
9324
9325 /// Added for Template instantiation observation.
9326 /// Memoization means we are _not_ instantiating a template because
9327 /// it is already instantiated (but we entered a context where we
9328 /// would have had to if it was not already instantiated).
9329 Memoization
9330 } Kind;
9331
9332 /// Was the enclosing context a non-instantiation SFINAE context?
9333 bool SavedInNonInstantiationSFINAEContext;
9334
9335 /// The point of instantiation or synthesis within the source code.
9336 SourceLocation PointOfInstantiation;
9337
9338 /// The entity that is being synthesized.
9339 Decl *Entity;
9340
9341 /// The template (or partial specialization) in which we are
9342 /// performing the instantiation, for substitutions of prior template
9343 /// arguments.
9344 NamedDecl *Template;
9345
9346 union {
9347 /// The list of template arguments we are substituting, if they
9348 /// are not part of the entity.
9349 const TemplateArgument *TemplateArgs;
9350
9351 /// The list of argument expressions in a synthesized call.
9352 const Expr *const *CallArgs;
9353 };
9354
9355 // FIXME: Wrap this union around more members, or perhaps store the
9356 // kind-specific members in the RAII object owning the context.
9357 union {
9358 /// The number of template arguments in TemplateArgs.
9359 unsigned NumTemplateArgs;
9360
9361 /// The number of expressions in CallArgs.
9362 unsigned NumCallArgs;
9363
9364 /// The special member being declared or defined.
9365 CXXSpecialMember SpecialMember;
9366 };
9367
9368 ArrayRef<TemplateArgument> template_arguments() const {
9369 assert(Kind != DeclaringSpecialMember);
9370 return {TemplateArgs, NumTemplateArgs};
9371 }
9372
9373 /// The template deduction info object associated with the
9374 /// substitution or checking of explicit or deduced template arguments.
9375 sema::TemplateDeductionInfo *DeductionInfo;
9376
9377 /// The source range that covers the construct that cause
9378 /// the instantiation, e.g., the template-id that causes a class
9379 /// template instantiation.
9380 SourceRange InstantiationRange;
9381
9382 CodeSynthesisContext()
9383 : Kind(TemplateInstantiation),
9384 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
9385 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
9386 DeductionInfo(nullptr) {}
9387
9388 /// Determines whether this template is an actual instantiation
9389 /// that should be counted toward the maximum instantiation depth.
9390 bool isInstantiationRecord() const;
9391 };
9392
9393 /// List of active code synthesis contexts.
9394 ///
9395 /// This vector is treated as a stack. As synthesis of one entity requires
9396 /// synthesis of another, additional contexts are pushed onto the stack.
9397 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
9398
9399 /// Specializations whose definitions are currently being instantiated.
9400 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
9401
9402 /// Non-dependent types used in templates that have already been instantiated
9403 /// by some template instantiation.
9404 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
9405
9406 /// Extra modules inspected when performing a lookup during a template
9407 /// instantiation. Computed lazily.
9408 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
9409
9410 /// Cache of additional modules that should be used for name lookup
9411 /// within the current template instantiation. Computed lazily; use
9412 /// getLookupModules() to get a complete set.
9413 llvm::DenseSet<Module*> LookupModulesCache;
9414
9415 /// Get the set of additional modules that should be checked during
9416 /// name lookup. A module and its imports become visible when instanting a
9417 /// template defined within it.
9418 llvm::DenseSet<Module*> &getLookupModules();
9419
9420 /// Map from the most recent declaration of a namespace to the most
9421 /// recent visible declaration of that namespace.
9422 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
9423
9424 /// Whether we are in a SFINAE context that is not associated with
9425 /// template instantiation.
9426 ///
9427 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
9428 /// of a template instantiation or template argument deduction.
9429 bool InNonInstantiationSFINAEContext;
9430
9431 /// The number of \p CodeSynthesisContexts that are not template
9432 /// instantiations and, therefore, should not be counted as part of the
9433 /// instantiation depth.
9434 ///
9435 /// When the instantiation depth reaches the user-configurable limit
9436 /// \p LangOptions::InstantiationDepth we will abort instantiation.
9437 // FIXME: Should we have a similar limit for other forms of synthesis?
9438 unsigned NonInstantiationEntries;
9439
9440 /// The depth of the context stack at the point when the most recent
9441 /// error or warning was produced.
9442 ///
9443 /// This value is used to suppress printing of redundant context stacks
9444 /// when there are multiple errors or warnings in the same instantiation.
9445 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
9446 unsigned LastEmittedCodeSynthesisContextDepth = 0;
9447
9448 /// The template instantiation callbacks to trace or track
9449 /// instantiations (objects can be chained).
9450 ///
9451 /// This callbacks is used to print, trace or track template
9452 /// instantiations as they are being constructed.
9453 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
9454 TemplateInstCallbacks;
9455
9456 /// The current index into pack expansion arguments that will be
9457 /// used for substitution of parameter packs.
9458 ///
9459 /// The pack expansion index will be -1 to indicate that parameter packs
9460 /// should be instantiated as themselves. Otherwise, the index specifies
9461 /// which argument within the parameter pack will be used for substitution.
9462 int ArgumentPackSubstitutionIndex;
9463
9464 /// RAII object used to change the argument pack substitution index
9465 /// within a \c Sema object.
9466 ///
9467 /// See \c ArgumentPackSubstitutionIndex for more information.
9468 class ArgumentPackSubstitutionIndexRAII {
9469 Sema &Self;
9470 int OldSubstitutionIndex;
9471
9472 public:
9473 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
9474 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
9475 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
9476 }
9477
9478 ~ArgumentPackSubstitutionIndexRAII() {
9479 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
9480 }
9481 };
9482
9483 friend class ArgumentPackSubstitutionRAII;
9484
9485 /// For each declaration that involved template argument deduction, the
9486 /// set of diagnostics that were suppressed during that template argument
9487 /// deduction.
9488 ///
9489 /// FIXME: Serialize this structure to the AST file.
9490 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
9491 SuppressedDiagnosticsMap;
9492 SuppressedDiagnosticsMap SuppressedDiagnostics;
9493
9494 /// A stack object to be created when performing template
9495 /// instantiation.
9496 ///
9497 /// Construction of an object of type \c InstantiatingTemplate
9498 /// pushes the current instantiation onto the stack of active
9499 /// instantiations. If the size of this stack exceeds the maximum
9500 /// number of recursive template instantiations, construction
9501 /// produces an error and evaluates true.
9502 ///
9503 /// Destruction of this object will pop the named instantiation off
9504 /// the stack.
9505 struct InstantiatingTemplate {
9506 /// Note that we are instantiating a class template,
9507 /// function template, variable template, alias template,
9508 /// or a member thereof.
9509 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9510 Decl *Entity,
9511 SourceRange InstantiationRange = SourceRange());
9512
9513 struct ExceptionSpecification {};
9514 /// Note that we are instantiating an exception specification
9515 /// of a function template.
9516 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9517 FunctionDecl *Entity, ExceptionSpecification,
9518 SourceRange InstantiationRange = SourceRange());
9519
9520 /// Note that we are instantiating a default argument in a
9521 /// template-id.
9522 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9523 TemplateParameter Param, TemplateDecl *Template,
9524 ArrayRef<TemplateArgument> TemplateArgs,
9525 SourceRange InstantiationRange = SourceRange());
9526
9527 /// Note that we are substituting either explicitly-specified or
9528 /// deduced template arguments during function template argument deduction.
9529 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9530 FunctionTemplateDecl *FunctionTemplate,
9531 ArrayRef<TemplateArgument> TemplateArgs,
9532 CodeSynthesisContext::SynthesisKind Kind,
9533 sema::TemplateDeductionInfo &DeductionInfo,
9534 SourceRange InstantiationRange = SourceRange());
9535
9536 /// Note that we are instantiating as part of template
9537 /// argument deduction for a class template declaration.
9538 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9539 TemplateDecl *Template,
9540 ArrayRef<TemplateArgument> TemplateArgs,
9541 sema::TemplateDeductionInfo &DeductionInfo,
9542 SourceRange InstantiationRange = SourceRange());
9543
9544 /// Note that we are instantiating as part of template
9545 /// argument deduction for a class template partial
9546 /// specialization.
9547 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9548 ClassTemplatePartialSpecializationDecl *PartialSpec,
9549 ArrayRef<TemplateArgument> TemplateArgs,
9550 sema::TemplateDeductionInfo &DeductionInfo,
9551 SourceRange InstantiationRange = SourceRange());
9552
9553 /// Note that we are instantiating as part of template
9554 /// argument deduction for a variable template partial
9555 /// specialization.
9556 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9557 VarTemplatePartialSpecializationDecl *PartialSpec,
9558 ArrayRef<TemplateArgument> TemplateArgs,
9559 sema::TemplateDeductionInfo &DeductionInfo,
9560 SourceRange InstantiationRange = SourceRange());
9561
9562 /// Note that we are instantiating a default argument for a function
9563 /// parameter.
9564 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9565 ParmVarDecl *Param,
9566 ArrayRef<TemplateArgument> TemplateArgs,
9567 SourceRange InstantiationRange = SourceRange());
9568
9569 /// Note that we are substituting prior template arguments into a
9570 /// non-type parameter.
9571 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9572 NamedDecl *Template,
9573 NonTypeTemplateParmDecl *Param,
9574 ArrayRef<TemplateArgument> TemplateArgs,
9575 SourceRange InstantiationRange);
9576
9577 /// Note that we are substituting prior template arguments into a
9578 /// template template parameter.
9579 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9580 NamedDecl *Template,
9581 TemplateTemplateParmDecl *Param,
9582 ArrayRef<TemplateArgument> TemplateArgs,
9583 SourceRange InstantiationRange);
9584
9585 /// Note that we are checking the default template argument
9586 /// against the template parameter for a given template-id.
9587 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9588 TemplateDecl *Template,
9589 NamedDecl *Param,
9590 ArrayRef<TemplateArgument> TemplateArgs,
9591 SourceRange InstantiationRange);
9592
9593 struct ConstraintsCheck {};
9594 /// \brief Note that we are checking the constraints associated with some
9595 /// constrained entity (a concept declaration or a template with associated
9596 /// constraints).
9597 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9598 ConstraintsCheck, NamedDecl *Template,
9599 ArrayRef<TemplateArgument> TemplateArgs,
9600 SourceRange InstantiationRange);
9601
9602 struct ConstraintSubstitution {};
9603 /// \brief Note that we are checking a constraint expression associated
9604 /// with a template declaration or as part of the satisfaction check of a
9605 /// concept.
9606 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9607 ConstraintSubstitution, NamedDecl *Template,
9608 sema::TemplateDeductionInfo &DeductionInfo,
9609 SourceRange InstantiationRange);
9610
9611 struct ConstraintNormalization {};
9612 /// \brief Note that we are normalizing a constraint expression.
9613 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9614 ConstraintNormalization, NamedDecl *Template,
9615 SourceRange InstantiationRange);
9616
9617 struct ParameterMappingSubstitution {};
9618 /// \brief Note that we are subtituting into the parameter mapping of an
9619 /// atomic constraint during constraint normalization.
9620 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9621 ParameterMappingSubstitution, NamedDecl *Template,
9622 SourceRange InstantiationRange);
9623
9624 /// \brief Note that we are substituting template arguments into a part of
9625 /// a requirement of a requires expression.
9626 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9627 concepts::Requirement *Req,
9628 sema::TemplateDeductionInfo &DeductionInfo,
9629 SourceRange InstantiationRange = SourceRange());
9630
9631 /// \brief Note that we are checking the satisfaction of the constraint
9632 /// expression inside of a nested requirement.
9633 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9634 concepts::NestedRequirement *Req, ConstraintsCheck,
9635 SourceRange InstantiationRange = SourceRange());
9636
9637 /// \brief Note that we are checking a requires clause.
9638 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9639 const RequiresExpr *E,
9640 sema::TemplateDeductionInfo &DeductionInfo,
9641 SourceRange InstantiationRange);
9642 /// Note that we have finished instantiating this template.
9643 void Clear();
9644
9645 ~InstantiatingTemplate() { Clear(); }
9646
9647 /// Determines whether we have exceeded the maximum
9648 /// recursive template instantiations.
9649 bool isInvalid() const { return Invalid; }
9650
9651 /// Determine whether we are already instantiating this
9652 /// specialization in some surrounding active instantiation.
9653 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
9654
9655 private:
9656 Sema &SemaRef;
9657 bool Invalid;
9658 bool AlreadyInstantiating;
9659 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
9660 SourceRange InstantiationRange);
9661
9662 InstantiatingTemplate(
9663 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
9664 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
9665 Decl *Entity, NamedDecl *Template = nullptr,
9666 ArrayRef<TemplateArgument> TemplateArgs = std::nullopt,
9667 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
9668
9669 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
9670
9671 InstantiatingTemplate&
9672 operator=(const InstantiatingTemplate&) = delete;
9673 };
9674
9675 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
9676 void popCodeSynthesisContext();
9677
9678 /// Determine whether we are currently performing template instantiation.
9679 bool inTemplateInstantiation() const {
9680 return CodeSynthesisContexts.size() > NonInstantiationEntries;
9681 }
9682
9683 void PrintContextStack() {
9684 if (!CodeSynthesisContexts.empty() &&
9685 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
9686 PrintInstantiationStack();
9687 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
9688 }
9689 if (PragmaAttributeCurrentTargetDecl)
9690 PrintPragmaAttributeInstantiationPoint();
9691 }
9692 void PrintInstantiationStack();
9693
9694 void PrintPragmaAttributeInstantiationPoint();
9695
9696 /// Determines whether we are currently in a context where
9697 /// template argument substitution failures are not considered
9698 /// errors.
9699 ///
9700 /// \returns An empty \c Optional if we're not in a SFINAE context.
9701 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
9702 /// template-deduction context object, which can be used to capture
9703 /// diagnostics that will be suppressed.
9704 std::optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
9705
9706 /// Determines whether we are currently in a context that
9707 /// is not evaluated as per C++ [expr] p5.
9708 bool isUnevaluatedContext() const {
9709 assert(!ExprEvalContexts.empty() &&
9710 "Must be in an expression evaluation context");
9711 return ExprEvalContexts.back().isUnevaluated();
9712 }
9713
9714 bool isConstantEvaluatedContext() const {
9715 assert(!ExprEvalContexts.empty() &&
9716 "Must be in an expression evaluation context");
9717 return ExprEvalContexts.back().isConstantEvaluated();
9718 }
9719
9720 bool isImmediateFunctionContext() const {
9721 assert(!ExprEvalContexts.empty() &&
9722 "Must be in an expression evaluation context");
9723 return ExprEvalContexts.back().isImmediateFunctionContext();
9724 }
9725
9726 bool isCheckingDefaultArgumentOrInitializer() const {
9727 assert(!ExprEvalContexts.empty() &&
9728 "Must be in an expression evaluation context");
9729 const ExpressionEvaluationContextRecord &Ctx = ExprEvalContexts.back();
9730 return (Ctx.Context ==
9731 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
9732 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
9733 }
9734
9735 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
9736 InnermostDeclarationWithDelayedImmediateInvocations() const {
9737 assert(!ExprEvalContexts.empty() &&
9738 "Must be in an expression evaluation context");
9739 for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) {
9740 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
9741 Ctx.DelayedDefaultInitializationContext)
9742 return Ctx.DelayedDefaultInitializationContext;
9743 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
9744 Ctx.isUnevaluated())
9745 break;
9746 }
9747 return std::nullopt;
9748 }
9749
9750 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
9751 OutermostDeclarationWithDelayedImmediateInvocations() const {
9752 assert(!ExprEvalContexts.empty() &&
9753 "Must be in an expression evaluation context");
9754 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
9755 for (auto &Ctx : llvm::reverse(ExprEvalContexts)) {
9756 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
9757 !Ctx.DelayedDefaultInitializationContext && Res)
9758 break;
9759 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
9760 Ctx.isUnevaluated())
9761 break;
9762 Res = Ctx.DelayedDefaultInitializationContext;
9763 }
9764 return Res;
9765 }
9766
9767 /// RAII class used to determine whether SFINAE has
9768 /// trapped any errors that occur during template argument
9769 /// deduction.
9770 class SFINAETrap {
9771 Sema &SemaRef;
9772 unsigned PrevSFINAEErrors;
9773 bool PrevInNonInstantiationSFINAEContext;
9774 bool PrevAccessCheckingSFINAE;
9775 bool PrevLastDiagnosticIgnored;
9776
9777 public:
9778 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
9779 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
9780 PrevInNonInstantiationSFINAEContext(
9781 SemaRef.InNonInstantiationSFINAEContext),
9782 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
9783 PrevLastDiagnosticIgnored(
9784 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
9785 {
9786 if (!SemaRef.isSFINAEContext())
9787 SemaRef.InNonInstantiationSFINAEContext = true;
9788 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
9789 }
9790
9791 ~SFINAETrap() {
9792 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
9793 SemaRef.InNonInstantiationSFINAEContext
9794 = PrevInNonInstantiationSFINAEContext;
9795 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
9796 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
9797 PrevLastDiagnosticIgnored);
9798 }
9799
9800 /// Determine whether any SFINAE errors have been trapped.
9801 bool hasErrorOccurred() const {
9802 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
9803 }
9804 };
9805
9806 /// RAII class used to indicate that we are performing provisional
9807 /// semantic analysis to determine the validity of a construct, so
9808 /// typo-correction and diagnostics in the immediate context (not within
9809 /// implicitly-instantiated templates) should be suppressed.
9810 class TentativeAnalysisScope {
9811 Sema &SemaRef;
9812 // FIXME: Using a SFINAETrap for this is a hack.
9813 SFINAETrap Trap;
9814 bool PrevDisableTypoCorrection;
9815 public:
9816 explicit TentativeAnalysisScope(Sema &SemaRef)
9817 : SemaRef(SemaRef), Trap(SemaRef, true),
9818 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
9819 SemaRef.DisableTypoCorrection = true;
9820 }
9821 ~TentativeAnalysisScope() {
9822 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
9823 }
9824 };
9825
9826 /// The current instantiation scope used to store local
9827 /// variables.
9828 LocalInstantiationScope *CurrentInstantiationScope;
9829
9830 /// Tracks whether we are in a context where typo correction is
9831 /// disabled.
9832 bool DisableTypoCorrection;
9833
9834 /// The number of typos corrected by CorrectTypo.
9835 unsigned TyposCorrected;
9836
9837 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9838 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9839
9840 /// A cache containing identifiers for which typo correction failed and
9841 /// their locations, so that repeated attempts to correct an identifier in a
9842 /// given location are ignored if typo correction already failed for it.
9843 IdentifierSourceLocations TypoCorrectionFailures;
9844
9845 /// Worker object for performing CFG-based warnings.
9846 sema::AnalysisBasedWarnings AnalysisWarnings;
9847 threadSafety::BeforeSet *ThreadSafetyDeclCache;
9848
9849 /// An entity for which implicit template instantiation is required.
9850 ///
9851 /// The source location associated with the declaration is the first place in
9852 /// the source code where the declaration was "used". It is not necessarily
9853 /// the point of instantiation (which will be either before or after the
9854 /// namespace-scope declaration that triggered this implicit instantiation),
9855 /// However, it is the location that diagnostics should generally refer to,
9856 /// because users will need to know what code triggered the instantiation.
9857 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9858
9859 /// The queue of implicit template instantiations that are required
9860 /// but have not yet been performed.
9861 std::deque<PendingImplicitInstantiation> PendingInstantiations;
9862
9863 /// Queue of implicit template instantiations that cannot be performed
9864 /// eagerly.
9865 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9866
9867 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
9868 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
9869 SavedPendingInstantiations;
9870
9871 class GlobalEagerInstantiationScope {
9872 public:
9873 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9874 : S(S), Enabled(Enabled) {
9875 if (!Enabled) return;
9876
9877 S.SavedPendingInstantiations.emplace_back();
9878 S.SavedPendingInstantiations.back().swap(S.PendingInstantiations);
9879
9880 S.SavedVTableUses.emplace_back();
9881 S.SavedVTableUses.back().swap(S.VTableUses);
9882 }
9883
9884 void perform() {
9885 if (Enabled) {
9886 S.DefineUsedVTables();
9887 S.PerformPendingInstantiations();
9888 }
9889 }
9890
9891 ~GlobalEagerInstantiationScope() {
9892 if (!Enabled) return;
9893
9894 // Restore the set of pending vtables.
9895 assert(S.VTableUses.empty() &&
9896 "VTableUses should be empty before it is discarded.");
9897 S.VTableUses.swap(S.SavedVTableUses.back());
9898 S.SavedVTableUses.pop_back();
9899
9900 // Restore the set of pending implicit instantiations.
9901 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9902 assert(S.PendingInstantiations.empty() &&
9903 "PendingInstantiations should be empty before it is discarded.");
9904 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
9905 S.SavedPendingInstantiations.pop_back();
9906 } else {
9907 // Template instantiations in the PCH may be delayed until the TU.
9908 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
9909 S.PendingInstantiations.insert(
9910 S.PendingInstantiations.end(),
9911 S.SavedPendingInstantiations.back().begin(),
9912 S.SavedPendingInstantiations.back().end());
9913 S.SavedPendingInstantiations.pop_back();
9914 }
9915 }
9916
9917 private:
9918 Sema &S;
9919 bool Enabled;
9920 };
9921
9922 /// The queue of implicit template instantiations that are required
9923 /// and must be performed within the current local scope.
9924 ///
9925 /// This queue is only used for member functions of local classes in
9926 /// templates, which must be instantiated in the same scope as their
9927 /// enclosing function, so that they can reference function-local
9928 /// types, static variables, enumerators, etc.
9929 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
9930
9931 class LocalEagerInstantiationScope {
9932 public:
9933 LocalEagerInstantiationScope(Sema &S) : S(S) {
9934 SavedPendingLocalImplicitInstantiations.swap(
9935 S.PendingLocalImplicitInstantiations);
9936 }
9937
9938 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
9939
9940 ~LocalEagerInstantiationScope() {
9941 assert(S.PendingLocalImplicitInstantiations.empty() &&
9942 "there shouldn't be any pending local implicit instantiations");
9943 SavedPendingLocalImplicitInstantiations.swap(
9944 S.PendingLocalImplicitInstantiations);
9945 }
9946
9947 private:
9948 Sema &S;
9949 std::deque<PendingImplicitInstantiation>
9950 SavedPendingLocalImplicitInstantiations;
9951 };
9952
9953 /// A helper class for building up ExtParameterInfos.
9954 class ExtParameterInfoBuilder {
9955 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
9956 bool HasInteresting = false;
9957
9958 public:
9959 /// Set the ExtParameterInfo for the parameter at the given index,
9960 ///
9961 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
9962 assert(Infos.size() <= index);
9963 Infos.resize(index);
9964 Infos.push_back(info);
9965
9966 if (!HasInteresting)
9967 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
9968 }
9969
9970 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
9971 /// ExtParameterInfo array we've built up.
9972 const FunctionProtoType::ExtParameterInfo *
9973 getPointerOrNull(unsigned numParams) {
9974 if (!HasInteresting) return nullptr;
9975 Infos.resize(numParams);
9976 return Infos.data();
9977 }
9978 };
9979
9980 void PerformPendingInstantiations(bool LocalOnly = false);
9981
9982 TypeSourceInfo *SubstType(TypeSourceInfo *T,
9983 const MultiLevelTemplateArgumentList &TemplateArgs,
9984 SourceLocation Loc, DeclarationName Entity,
9985 bool AllowDeducedTST = false);
9986
9987 QualType SubstType(QualType T,
9988 const MultiLevelTemplateArgumentList &TemplateArgs,
9989 SourceLocation Loc, DeclarationName Entity);
9990
9991 TypeSourceInfo *SubstType(TypeLoc TL,
9992 const MultiLevelTemplateArgumentList &TemplateArgs,
9993 SourceLocation Loc, DeclarationName Entity);
9994
9995 TypeSourceInfo *SubstFunctionDeclType(
9996 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
9997 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
9998 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
9999 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
10000 const MultiLevelTemplateArgumentList &Args);
10001 bool SubstExceptionSpec(SourceLocation Loc,
10002 FunctionProtoType::ExceptionSpecInfo &ESI,
10003 SmallVectorImpl<QualType> &ExceptionStorage,
10004 const MultiLevelTemplateArgumentList &Args);
10005 ParmVarDecl *
10006 SubstParmVarDecl(ParmVarDecl *D,
10007 const MultiLevelTemplateArgumentList &TemplateArgs,
10008 int indexAdjustment, std::optional<unsigned> NumExpansions,
10009 bool ExpectParameterPack, bool EvaluateConstraints = true);
10010 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
10011 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
10012 const MultiLevelTemplateArgumentList &TemplateArgs,
10013 SmallVectorImpl<QualType> &ParamTypes,
10014 SmallVectorImpl<ParmVarDecl *> *OutParams,
10015 ExtParameterInfoBuilder &ParamInfos);
10016 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
10017 const MultiLevelTemplateArgumentList &TemplateArgs,
10018 bool ForCallExpr = false);
10019 ExprResult SubstExpr(Expr *E,
10020 const MultiLevelTemplateArgumentList &TemplateArgs);
10021
10022 // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator
10023 // to disable constraint evaluation, then restore the state.
10024 template <typename InstTy> struct ConstraintEvalRAII {
10025 InstTy &TI;
10026 bool OldValue;
10027
10028 ConstraintEvalRAII(InstTy &TI)
10029 : TI(TI), OldValue(TI.getEvaluateConstraints()) {
10030 TI.setEvaluateConstraints(false);
10031 }
10032 ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); }
10033 };
10034
10035 // Unlike the above, this evaluates constraints, which should only happen at
10036 // 'constraint checking' time.
10037 ExprResult
10038 SubstConstraintExpr(Expr *E,
10039 const MultiLevelTemplateArgumentList &TemplateArgs);
10040
10041 /// Substitute the given template arguments into a list of
10042 /// expressions, expanding pack expansions if required.
10043 ///
10044 /// \param Exprs The list of expressions to substitute into.
10045 ///
10046 /// \param IsCall Whether this is some form of call, in which case
10047 /// default arguments will be dropped.
10048 ///
10049 /// \param TemplateArgs The set of template arguments to substitute.
10050 ///
10051 /// \param Outputs Will receive all of the substituted arguments.
10052 ///
10053 /// \returns true if an error occurred, false otherwise.
10054 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
10055 const MultiLevelTemplateArgumentList &TemplateArgs,
10056 SmallVectorImpl<Expr *> &Outputs);
10057
10058 StmtResult SubstStmt(Stmt *S,
10059 const MultiLevelTemplateArgumentList &TemplateArgs);
10060
10061 TemplateParameterList *
10062 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
10063 const MultiLevelTemplateArgumentList &TemplateArgs,
10064 bool EvaluateConstraints = true);
10065
10066 bool
10067 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
10068 const MultiLevelTemplateArgumentList &TemplateArgs,
10069 TemplateArgumentListInfo &Outputs);
10070
10071 Decl *SubstDecl(Decl *D, DeclContext *Owner,
10072 const MultiLevelTemplateArgumentList &TemplateArgs);
10073
10074 /// Substitute the name and return type of a defaulted 'operator<=>' to form
10075 /// an implicit 'operator=='.
10076 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
10077 FunctionDecl *Spaceship);
10078
10079 ExprResult SubstInitializer(Expr *E,
10080 const MultiLevelTemplateArgumentList &TemplateArgs,
10081 bool CXXDirectInit);
10082
10083 bool
10084 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
10085 CXXRecordDecl *Pattern,
10086 const MultiLevelTemplateArgumentList &TemplateArgs);
10087
10088 bool
10089 InstantiateClass(SourceLocation PointOfInstantiation,
10090 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
10091 const MultiLevelTemplateArgumentList &TemplateArgs,
10092 TemplateSpecializationKind TSK,
10093 bool Complain = true);
10094
10095 bool InstantiateEnum(SourceLocation PointOfInstantiation,
10096 EnumDecl *Instantiation, EnumDecl *Pattern,
10097 const MultiLevelTemplateArgumentList &TemplateArgs,
10098 TemplateSpecializationKind TSK);
10099
10100 bool InstantiateInClassInitializer(
10101 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
10102 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
10103
10104 struct LateInstantiatedAttribute {
10105 const Attr *TmplAttr;
10106 LocalInstantiationScope *Scope;
10107 Decl *NewDecl;
10108
10109 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
10110 Decl *D)
10111 : TmplAttr(A), Scope(S), NewDecl(D)
10112 { }
10113 };
10114 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
10115
10116 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
10117 const Decl *Pattern, Decl *Inst,
10118 LateInstantiatedAttrVec *LateAttrs = nullptr,
10119 LocalInstantiationScope *OuterMostScope = nullptr);
10120 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
10121
10122 void
10123 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
10124 const Decl *Pattern, Decl *Inst,
10125 LateInstantiatedAttrVec *LateAttrs = nullptr,
10126 LocalInstantiationScope *OuterMostScope = nullptr);
10127
10128 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
10129
10130 bool usesPartialOrExplicitSpecialization(
10131 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
10132
10133 bool
10134 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
10135 ClassTemplateSpecializationDecl *ClassTemplateSpec,
10136 TemplateSpecializationKind TSK,
10137 bool Complain = true);
10138
10139 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
10140 CXXRecordDecl *Instantiation,
10141 const MultiLevelTemplateArgumentList &TemplateArgs,
10142 TemplateSpecializationKind TSK);
10143
10144 void InstantiateClassTemplateSpecializationMembers(
10145 SourceLocation PointOfInstantiation,
10146 ClassTemplateSpecializationDecl *ClassTemplateSpec,
10147 TemplateSpecializationKind TSK);
10148
10149 NestedNameSpecifierLoc
10150 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
10151 const MultiLevelTemplateArgumentList &TemplateArgs);
10152
10153 DeclarationNameInfo
10154 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
10155 const MultiLevelTemplateArgumentList &TemplateArgs);
10156 TemplateName
10157 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
10158 SourceLocation Loc,
10159 const MultiLevelTemplateArgumentList &TemplateArgs);
10160
10161 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
10162 const MultiLevelTemplateArgumentList &TemplateArgs,
10163 bool EvaluateConstraint);
10164
10165 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
10166 ParmVarDecl *Param);
10167 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
10168 FunctionDecl *Function);
10169 bool CheckInstantiatedFunctionTemplateConstraints(
10170 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
10171 ArrayRef<TemplateArgument> TemplateArgs,
10172 ConstraintSatisfaction &Satisfaction);
10173 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
10174 const TemplateArgumentList *Args,
10175 SourceLocation Loc);
10176 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
10177 FunctionDecl *Function,
10178 bool Recursive = false,
10179 bool DefinitionRequired = false,
10180 bool AtEndOfTU = false);
10181 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
10182 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
10183 const TemplateArgumentList &TemplateArgList,
10184 const TemplateArgumentListInfo &TemplateArgsInfo,
10185 SmallVectorImpl<TemplateArgument> &Converted,
10186 SourceLocation PointOfInstantiation,
10187 LateInstantiatedAttrVec *LateAttrs = nullptr,
10188 LocalInstantiationScope *StartingScope = nullptr);
10189 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
10190 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
10191 const MultiLevelTemplateArgumentList &TemplateArgs);
10192 void
10193 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
10194 const MultiLevelTemplateArgumentList &TemplateArgs,
10195 LateInstantiatedAttrVec *LateAttrs,
10196 DeclContext *Owner,
10197 LocalInstantiationScope *StartingScope,
10198 bool InstantiatingVarTemplate = false,
10199 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
10200
10201 void InstantiateVariableInitializer(
10202 VarDecl *Var, VarDecl *OldVar,
10203 const MultiLevelTemplateArgumentList &TemplateArgs);
10204 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
10205 VarDecl *Var, bool Recursive = false,
10206 bool DefinitionRequired = false,
10207 bool AtEndOfTU = false);
10208
10209 void InstantiateMemInitializers(CXXConstructorDecl *New,
10210 const CXXConstructorDecl *Tmpl,
10211 const MultiLevelTemplateArgumentList &TemplateArgs);
10212
10213 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
10214 const MultiLevelTemplateArgumentList &TemplateArgs,
10215 bool FindingInstantiatedContext = false);
10216 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
10217 const MultiLevelTemplateArgumentList &TemplateArgs);
10218
10219 // Objective-C declarations.
10220 enum ObjCContainerKind {
10221 OCK_None = -1,
10222 OCK_Interface = 0,
10223 OCK_Protocol,
10224 OCK_Category,
10225 OCK_ClassExtension,
10226 OCK_Implementation,
10227 OCK_CategoryImplementation
10228 };
10229 ObjCContainerKind getObjCContainerKind() const;
10230
10231 DeclResult actOnObjCTypeParam(Scope *S,
10232 ObjCTypeParamVariance variance,
10233 SourceLocation varianceLoc,
10234 unsigned index,
10235 IdentifierInfo *paramName,
10236 SourceLocation paramLoc,
10237 SourceLocation colonLoc,
10238 ParsedType typeBound);
10239
10240 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
10241 ArrayRef<Decl *> typeParams,
10242 SourceLocation rAngleLoc);
10243 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
10244
10245 ObjCInterfaceDecl *ActOnStartClassInterface(
10246 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
10247 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
10248 IdentifierInfo *SuperName, SourceLocation SuperLoc,
10249 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
10250 Decl *const *ProtoRefs, unsigned NumProtoRefs,
10251 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
10252 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody);
10253
10254 void ActOnSuperClassOfClassInterface(Scope *S,
10255 SourceLocation AtInterfaceLoc,
10256 ObjCInterfaceDecl *IDecl,
10257 IdentifierInfo *ClassName,
10258 SourceLocation ClassLoc,
10259 IdentifierInfo *SuperName,
10260 SourceLocation SuperLoc,
10261 ArrayRef<ParsedType> SuperTypeArgs,
10262 SourceRange SuperTypeArgsRange);
10263
10264 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
10265 SmallVectorImpl<SourceLocation> &ProtocolLocs,
10266 IdentifierInfo *SuperName,
10267 SourceLocation SuperLoc);
10268
10269 Decl *ActOnCompatibilityAlias(
10270 SourceLocation AtCompatibilityAliasLoc,
10271 IdentifierInfo *AliasName, SourceLocation AliasLocation,
10272 IdentifierInfo *ClassName, SourceLocation ClassLocation);
10273
10274 bool CheckForwardProtocolDeclarationForCircularDependency(
10275 IdentifierInfo *PName,
10276 SourceLocation &PLoc, SourceLocation PrevLoc,
10277 const ObjCList<ObjCProtocolDecl> &PList);
10278
10279 ObjCProtocolDecl *ActOnStartProtocolInterface(
10280 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
10281 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
10282 unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
10283 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList,
10284 SkipBodyInfo *SkipBody);
10285
10286 ObjCCategoryDecl *ActOnStartCategoryInterface(
10287 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
10288 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
10289 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
10290 Decl *const *ProtoRefs, unsigned NumProtoRefs,
10291 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
10292 const ParsedAttributesView &AttrList);
10293
10294 ObjCImplementationDecl *ActOnStartClassImplementation(
10295 SourceLocation AtClassImplLoc, IdentifierInfo *ClassName,
10296 SourceLocation ClassLoc, IdentifierInfo *SuperClassname,
10297 SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList);
10298
10299 ObjCCategoryImplDecl *ActOnStartCategoryImplementation(
10300 SourceLocation AtCatImplLoc, IdentifierInfo *ClassName,
10301 SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc,
10302 const ParsedAttributesView &AttrList);
10303
10304 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
10305 ArrayRef<Decl *> Decls);
10306
10307 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
10308 IdentifierInfo **IdentList,
10309 SourceLocation *IdentLocs,
10310 ArrayRef<ObjCTypeParamList *> TypeParamLists,
10311 unsigned NumElts);
10312
10313 DeclGroupPtrTy
10314 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
10315 ArrayRef<IdentifierLocPair> IdentList,
10316 const ParsedAttributesView &attrList);
10317
10318 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
10319 ArrayRef<IdentifierLocPair> ProtocolId,
10320 SmallVectorImpl<Decl *> &Protocols);
10321
10322 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
10323 SourceLocation ProtocolLoc,
10324 IdentifierInfo *TypeArgId,
10325 SourceLocation TypeArgLoc,
10326 bool SelectProtocolFirst = false);
10327
10328 /// Given a list of identifiers (and their locations), resolve the
10329 /// names to either Objective-C protocol qualifiers or type
10330 /// arguments, as appropriate.
10331 void actOnObjCTypeArgsOrProtocolQualifiers(
10332 Scope *S,
10333 ParsedType baseType,
10334 SourceLocation lAngleLoc,
10335 ArrayRef<IdentifierInfo *> identifiers,
10336 ArrayRef<SourceLocation> identifierLocs,
10337 SourceLocation rAngleLoc,
10338 SourceLocation &typeArgsLAngleLoc,
10339 SmallVectorImpl<ParsedType> &typeArgs,
10340 SourceLocation &typeArgsRAngleLoc,
10341 SourceLocation &protocolLAngleLoc,
10342 SmallVectorImpl<Decl *> &protocols,
10343 SourceLocation &protocolRAngleLoc,
10344 bool warnOnIncompleteProtocols);
10345
10346 /// Build a an Objective-C protocol-qualified 'id' type where no
10347 /// base type was specified.
10348 TypeResult actOnObjCProtocolQualifierType(
10349 SourceLocation lAngleLoc,
10350 ArrayRef<Decl *> protocols,
10351 ArrayRef<SourceLocation> protocolLocs,
10352 SourceLocation rAngleLoc);
10353
10354 /// Build a specialized and/or protocol-qualified Objective-C type.
10355 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
10356 Scope *S,
10357 SourceLocation Loc,
10358 ParsedType BaseType,
10359 SourceLocation TypeArgsLAngleLoc,
10360 ArrayRef<ParsedType> TypeArgs,
10361 SourceLocation TypeArgsRAngleLoc,
10362 SourceLocation ProtocolLAngleLoc,
10363 ArrayRef<Decl *> Protocols,
10364 ArrayRef<SourceLocation> ProtocolLocs,
10365 SourceLocation ProtocolRAngleLoc);
10366
10367 /// Build an Objective-C type parameter type.
10368 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
10369 SourceLocation ProtocolLAngleLoc,
10370 ArrayRef<ObjCProtocolDecl *> Protocols,
10371 ArrayRef<SourceLocation> ProtocolLocs,
10372 SourceLocation ProtocolRAngleLoc,
10373 bool FailOnError = false);
10374
10375 /// Build an Objective-C object pointer type.
10376 QualType BuildObjCObjectType(
10377 QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
10378 ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
10379 SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
10380 ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
10381 bool FailOnError, bool Rebuilding);
10382
10383 /// Ensure attributes are consistent with type.
10384 /// \param [in, out] Attributes The attributes to check; they will
10385 /// be modified to be consistent with \p PropertyTy.
10386 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
10387 SourceLocation Loc,
10388 unsigned &Attributes,
10389 bool propertyInPrimaryClass);
10390
10391 /// Process the specified property declaration and create decls for the
10392 /// setters and getters as needed.
10393 /// \param property The property declaration being processed
10394 void ProcessPropertyDecl(ObjCPropertyDecl *property);
10395
10396
10397 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
10398 ObjCPropertyDecl *SuperProperty,
10399 const IdentifierInfo *Name,
10400 bool OverridingProtocolProperty);
10401
10402 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
10403 ObjCInterfaceDecl *ID);
10404
10405 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
10406 ArrayRef<Decl *> allMethods = std::nullopt,
10407 ArrayRef<DeclGroupPtrTy> allTUVars = std::nullopt);
10408
10409 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
10410 SourceLocation LParenLoc,
10411 FieldDeclarator &FD, ObjCDeclSpec &ODS,
10412 Selector GetterSel, Selector SetterSel,
10413 tok::ObjCKeywordKind MethodImplKind,
10414 DeclContext *lexicalDC = nullptr);
10415
10416 Decl *ActOnPropertyImplDecl(Scope *S,
10417 SourceLocation AtLoc,
10418 SourceLocation PropertyLoc,
10419 bool ImplKind,
10420 IdentifierInfo *PropertyId,
10421 IdentifierInfo *PropertyIvar,
10422 SourceLocation PropertyIvarLoc,
10423 ObjCPropertyQueryKind QueryKind);
10424
10425 enum ObjCSpecialMethodKind {
10426 OSMK_None,
10427 OSMK_Alloc,
10428 OSMK_New,
10429 OSMK_Copy,
10430 OSMK_RetainingInit,
10431 OSMK_NonRetainingInit
10432 };
10433
10434 struct ObjCArgInfo {
10435 IdentifierInfo *Name;
10436 SourceLocation NameLoc;
10437 // The Type is null if no type was specified, and the DeclSpec is invalid
10438 // in this case.
10439 ParsedType Type;
10440 ObjCDeclSpec DeclSpec;
10441
10442 /// ArgAttrs - Attribute list for this argument.
10443 ParsedAttributesView ArgAttrs;
10444 };
10445
10446 Decl *ActOnMethodDeclaration(
10447 Scope *S,
10448 SourceLocation BeginLoc, // location of the + or -.
10449 SourceLocation EndLoc, // location of the ; or {.
10450 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
10451 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
10452 // optional arguments. The number of types/arguments is obtained
10453 // from the Sel.getNumArgs().
10454 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
10455 unsigned CNumArgs, // c-style args
10456 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
10457 bool isVariadic, bool MethodDefinition);
10458
10459 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
10460 const ObjCObjectPointerType *OPT,
10461 bool IsInstance);
10462 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
10463 bool IsInstance);
10464
10465 bool CheckARCMethodDecl(ObjCMethodDecl *method);
10466 bool inferObjCARCLifetime(ValueDecl *decl);
10467
10468 void deduceOpenCLAddressSpace(ValueDecl *decl);
10469
10470 ExprResult
10471 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
10472 Expr *BaseExpr,
10473 SourceLocation OpLoc,
10474 DeclarationName MemberName,
10475 SourceLocation MemberLoc,
10476 SourceLocation SuperLoc, QualType SuperType,
10477 bool Super);
10478
10479 ExprResult
10480 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
10481 IdentifierInfo &propertyName,
10482 SourceLocation receiverNameLoc,
10483 SourceLocation propertyNameLoc);
10484
10485 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
10486
10487 /// Describes the kind of message expression indicated by a message
10488 /// send that starts with an identifier.
10489 enum ObjCMessageKind {
10490 /// The message is sent to 'super'.
10491 ObjCSuperMessage,
10492 /// The message is an instance message.
10493 ObjCInstanceMessage,
10494 /// The message is a class message, and the identifier is a type
10495 /// name.
10496 ObjCClassMessage
10497 };
10498
10499 ObjCMessageKind getObjCMessageKind(Scope *S,
10500 IdentifierInfo *Name,
10501 SourceLocation NameLoc,
10502 bool IsSuper,
10503 bool HasTrailingDot,
10504 ParsedType &ReceiverType);
10505
10506 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
10507 Selector Sel,
10508 SourceLocation LBracLoc,
10509 ArrayRef<SourceLocation> SelectorLocs,
10510 SourceLocation RBracLoc,
10511 MultiExprArg Args);
10512
10513 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
10514 QualType ReceiverType,
10515 SourceLocation SuperLoc,
10516 Selector Sel,
10517 ObjCMethodDecl *Method,
10518 SourceLocation LBracLoc,
10519 ArrayRef<SourceLocation> SelectorLocs,
10520 SourceLocation RBracLoc,
10521 MultiExprArg Args,
10522 bool isImplicit = false);
10523
10524 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
10525 bool isSuperReceiver,
10526 SourceLocation Loc,
10527 Selector Sel,
10528 ObjCMethodDecl *Method,
10529 MultiExprArg Args);
10530
10531 ExprResult ActOnClassMessage(Scope *S,
10532 ParsedType Receiver,
10533 Selector Sel,
10534 SourceLocation LBracLoc,
10535 ArrayRef<SourceLocation> SelectorLocs,
10536 SourceLocation RBracLoc,
10537 MultiExprArg Args);
10538
10539 ExprResult BuildInstanceMessage(Expr *Receiver,
10540 QualType ReceiverType,
10541 SourceLocation SuperLoc,
10542 Selector Sel,
10543 ObjCMethodDecl *Method,
10544 SourceLocation LBracLoc,
10545 ArrayRef<SourceLocation> SelectorLocs,
10546 SourceLocation RBracLoc,
10547 MultiExprArg Args,
10548 bool isImplicit = false);
10549
10550 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
10551 QualType ReceiverType,
10552 SourceLocation Loc,
10553 Selector Sel,
10554 ObjCMethodDecl *Method,
10555 MultiExprArg Args);
10556
10557 ExprResult ActOnInstanceMessage(Scope *S,
10558 Expr *Receiver,
10559 Selector Sel,
10560 SourceLocation LBracLoc,
10561 ArrayRef<SourceLocation> SelectorLocs,
10562 SourceLocation RBracLoc,
10563 MultiExprArg Args);
10564
10565 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
10566 ObjCBridgeCastKind Kind,
10567 SourceLocation BridgeKeywordLoc,
10568 TypeSourceInfo *TSInfo,
10569 Expr *SubExpr);
10570
10571 ExprResult ActOnObjCBridgedCast(Scope *S,
10572 SourceLocation LParenLoc,
10573 ObjCBridgeCastKind Kind,
10574 SourceLocation BridgeKeywordLoc,
10575 ParsedType Type,
10576 SourceLocation RParenLoc,
10577 Expr *SubExpr);
10578
10579 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
10580
10581 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
10582
10583 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
10584 CastKind &Kind);
10585
10586 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
10587 QualType DestType, QualType SrcType,
10588 ObjCInterfaceDecl *&RelatedClass,
10589 ObjCMethodDecl *&ClassMethod,
10590 ObjCMethodDecl *&InstanceMethod,
10591 TypedefNameDecl *&TDNDecl,
10592 bool CfToNs, bool Diagnose = true);
10593
10594 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
10595 QualType DestType, QualType SrcType,
10596 Expr *&SrcExpr, bool Diagnose = true);
10597
10598 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
10599 bool Diagnose = true);
10600
10601 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
10602
10603 /// Check whether the given new method is a valid override of the
10604 /// given overridden method, and set any properties that should be inherited.
10605 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
10606 const ObjCMethodDecl *Overridden);
10607
10608 /// Describes the compatibility of a result type with its method.
10609 enum ResultTypeCompatibilityKind {
10610 RTC_Compatible,
10611 RTC_Incompatible,
10612 RTC_Unknown
10613 };
10614
10615 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
10616 ObjCMethodDecl *overridden);
10617
10618 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
10619 ObjCInterfaceDecl *CurrentClass,
10620 ResultTypeCompatibilityKind RTC);
10621
10622 enum PragmaOptionsAlignKind {
10623 POAK_Native, // #pragma options align=native
10624 POAK_Natural, // #pragma options align=natural
10625 POAK_Packed, // #pragma options align=packed
10626 POAK_Power, // #pragma options align=power
10627 POAK_Mac68k, // #pragma options align=mac68k
10628 POAK_Reset // #pragma options align=reset
10629 };
10630
10631 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
10632 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
10633 PragmaClangSectionAction Action,
10634 PragmaClangSectionKind SecKind, StringRef SecName);
10635
10636 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
10637 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
10638 SourceLocation PragmaLoc);
10639
10640 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
10641 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
10642 StringRef SlotLabel, Expr *Alignment);
10643
10644 enum class PragmaAlignPackDiagnoseKind {
10645 NonDefaultStateAtInclude,
10646 ChangedStateAtExit
10647 };
10648
10649 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
10650 SourceLocation IncludeLoc);
10651 void DiagnoseUnterminatedPragmaAlignPack();
10652
10653 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
10654 /// strict_gs_check.
10655 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
10656 PragmaMsStackAction Action,
10657 bool Value);
10658
10659 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
10660 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
10661
10662 /// ActOnPragmaMSComment - Called on well formed
10663 /// \#pragma comment(kind, "arg").
10664 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
10665 StringRef Arg);
10666
10667 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
10668 /// pointers_to_members(representation method[, general purpose
10669 /// representation]).
10670 void ActOnPragmaMSPointersToMembers(
10671 LangOptions::PragmaMSPointersToMembersKind Kind,
10672 SourceLocation PragmaLoc);
10673
10674 /// Called on well formed \#pragma vtordisp().
10675 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
10676 SourceLocation PragmaLoc,
10677 MSVtorDispMode Value);
10678
10679 enum PragmaSectionKind {
10680 PSK_DataSeg,
10681 PSK_BSSSeg,
10682 PSK_ConstSeg,
10683 PSK_CodeSeg,
10684 };
10685
10686 bool UnifySection(StringRef SectionName, int SectionFlags,
10687 NamedDecl *TheDecl);
10688 bool UnifySection(StringRef SectionName,
10689 int SectionFlags,
10690 SourceLocation PragmaSectionLocation);
10691
10692 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
10693 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
10694 PragmaMsStackAction Action,
10695 llvm::StringRef StackSlotLabel,
10696 StringLiteral *SegmentName,
10697 llvm::StringRef PragmaName);
10698
10699 /// Called on well formed \#pragma section().
10700 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
10701 int SectionFlags, StringLiteral *SegmentName);
10702
10703 /// Called on well-formed \#pragma init_seg().
10704 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
10705 StringLiteral *SegmentName);
10706
10707 /// Called on well-formed \#pragma alloc_text().
10708 void ActOnPragmaMSAllocText(
10709 SourceLocation PragmaLocation, StringRef Section,
10710 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
10711 &Functions);
10712
10713 /// Called on #pragma clang __debug dump II
10714 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
10715
10716 /// Called on #pragma clang __debug dump E
10717 void ActOnPragmaDump(Expr *E);
10718
10719 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
10720 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
10721 StringRef Value);
10722
10723 /// Are precise floating point semantics currently enabled?
10724 bool isPreciseFPEnabled() {
10725 return !CurFPFeatures.getAllowFPReassociate() &&
10726 !CurFPFeatures.getNoSignedZero() &&
10727 !CurFPFeatures.getAllowReciprocal() &&
10728 !CurFPFeatures.getAllowApproxFunc();
10729 }
10730
10731 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
10732 LangOptions::FPEvalMethodKind Value);
10733
10734 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
10735 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
10736 PragmaFloatControlKind Value);
10737
10738 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
10739 void ActOnPragmaUnused(const Token &Identifier,
10740 Scope *curScope,
10741 SourceLocation PragmaLoc);
10742
10743 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
10744 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
10745 SourceLocation PragmaLoc);
10746
10747 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
10748 SourceLocation Loc);
10749 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
10750
10751 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
10752 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
10753 SourceLocation PragmaLoc,
10754 SourceLocation WeakNameLoc);
10755
10756 /// ActOnPragmaRedefineExtname - Called on well formed
10757 /// \#pragma redefine_extname oldname newname.
10758 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
10759 IdentifierInfo* AliasName,
10760 SourceLocation PragmaLoc,
10761 SourceLocation WeakNameLoc,
10762 SourceLocation AliasNameLoc);
10763
10764 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
10765 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
10766 IdentifierInfo* AliasName,
10767 SourceLocation PragmaLoc,
10768 SourceLocation WeakNameLoc,
10769 SourceLocation AliasNameLoc);
10770
10771 /// ActOnPragmaFPContract - Called on well formed
10772 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
10773 /// \#pragma clang fp contract
10774 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
10775
10776 /// Called on well formed
10777 /// \#pragma clang fp reassociate
10778 void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
10779
10780 /// ActOnPragmaFenvAccess - Called on well formed
10781 /// \#pragma STDC FENV_ACCESS
10782 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
10783
10784 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
10785 void ActOnPragmaFPExceptions(SourceLocation Loc,
10786 LangOptions::FPExceptionModeKind);
10787
10788 /// Called to set constant rounding mode for floating point operations.
10789 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
10790
10791 /// Called to set exception behavior for floating point operations.
10792 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
10793
10794 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
10795 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
10796 void AddAlignmentAttributesForRecord(RecordDecl *RD);
10797
10798 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
10799 void AddMsStructLayoutForRecord(RecordDecl *RD);
10800
10801 /// PushNamespaceVisibilityAttr - Note that we've entered a
10802 /// namespace with a visibility attribute.
10803 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
10804 SourceLocation Loc);
10805
10806 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
10807 /// add an appropriate visibility attribute.
10808 void AddPushedVisibilityAttribute(Decl *RD);
10809
10810 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
10811 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
10812 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
10813
10814 /// FreeVisContext - Deallocate and null out VisContext.
10815 void FreeVisContext();
10816
10817 /// AddCFAuditedAttribute - Check whether we're currently within
10818 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
10819 /// the appropriate attribute.
10820 void AddCFAuditedAttribute(Decl *D);
10821
10822 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
10823 SourceLocation PragmaLoc,
10824 attr::ParsedSubjectMatchRuleSet Rules);
10825 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
10826 const IdentifierInfo *Namespace);
10827
10828 /// Called on well-formed '\#pragma clang attribute pop'.
10829 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
10830 const IdentifierInfo *Namespace);
10831
10832 /// Adds the attributes that have been specified using the
10833 /// '\#pragma clang attribute push' directives to the given declaration.
10834 void AddPragmaAttributes(Scope *S, Decl *D);
10835
10836 void DiagnoseUnterminatedPragmaAttribute();
10837
10838 /// Called on well formed \#pragma clang optimize.
10839 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
10840
10841 /// #pragma optimize("[optimization-list]", on | off).
10842 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
10843
10844 /// Call on well formed \#pragma function.
10845 void
10846 ActOnPragmaMSFunction(SourceLocation Loc,
10847 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
10848
10849 /// Get the location for the currently active "\#pragma clang optimize
10850 /// off". If this location is invalid, then the state of the pragma is "on".
10851 SourceLocation getOptimizeOffPragmaLocation() const {
10852 return OptimizeOffPragmaLocation;
10853 }
10854
10855 /// Only called on function definitions; if there is a pragma in scope
10856 /// with the effect of a range-based optnone, consider marking the function
10857 /// with attribute optnone.
10858 void AddRangeBasedOptnone(FunctionDecl *FD);
10859
10860 /// Only called on function definitions; if there is a `#pragma alloc_text`
10861 /// that decides which code section the function should be in, add
10862 /// attribute section to the function.
10863 void AddSectionMSAllocText(FunctionDecl *FD);
10864
10865 /// Adds the 'optnone' attribute to the function declaration if there
10866 /// are no conflicts; Loc represents the location causing the 'optnone'
10867 /// attribute to be added (usually because of a pragma).
10868 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
10869
10870 /// Only called on function definitions; if there is a MSVC #pragma optimize
10871 /// in scope, consider changing the function's attributes based on the
10872 /// optimization list passed to the pragma.
10873 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
10874
10875 /// Only called on function definitions; if there is a pragma in scope
10876 /// with the effect of a range-based no_builtin, consider marking the function
10877 /// with attribute no_builtin.
10878 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
10879
10880 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
10881 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10882 bool IsPackExpansion);
10883 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
10884 bool IsPackExpansion);
10885
10886 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
10887 /// declaration.
10888 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10889 Expr *OE);
10890
10891 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
10892 /// declaration.
10893 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
10894 Expr *ParamExpr);
10895
10896 /// AddAlignValueAttr - Adds an align_value attribute to a particular
10897 /// declaration.
10898 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
10899
10900 /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
10901 void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
10902 StringRef Annot, MutableArrayRef<Expr *> Args);
10903
10904 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
10905 /// (unless they are value dependent or type dependent). Returns false
10906 /// and emits a diagnostic if one or more of the arguments could not be
10907 /// folded into a constant.
10908 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
10909 MutableArrayRef<Expr *> Args);
10910
10911 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
10912 /// declaration.
10913 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
10914 Expr *MaxThreads, Expr *MinBlocks);
10915
10916 /// AddModeAttr - Adds a mode attribute to a particular declaration.
10917 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
10918 bool InInstantiation = false);
10919
10920 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
10921 ParameterABI ABI);
10922
10923 enum class RetainOwnershipKind {NS, CF, OS};
10924 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
10925 RetainOwnershipKind K, bool IsTemplateInstantiation);
10926
10927 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
10928 /// attribute to a particular declaration.
10929 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
10930 Expr *Min, Expr *Max);
10931
10932 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
10933 /// particular declaration.
10934 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
10935 Expr *Min, Expr *Max);
10936
10937 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
10938
10939 //===--------------------------------------------------------------------===//
10940 // C++ Coroutines
10941 //
10942 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
10943 StringRef Keyword);
10944 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10945 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10946 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
10947
10948 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
10949 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
10950 UnresolvedLookupExpr *Lookup);
10951 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
10952 Expr *Awaiter, bool IsImplicit = false);
10953 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
10954 UnresolvedLookupExpr *Lookup);
10955 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
10956 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
10957 bool IsImplicit = false);
10958 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
10959 bool buildCoroutineParameterMoves(SourceLocation Loc);
10960 VarDecl *buildCoroutinePromise(SourceLocation Loc);
10961 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
10962 /// Lookup 'coroutine_traits' in std namespace and std::experimental
10963 /// namespace. The namespace found is recorded in Namespace.
10964 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
10965 SourceLocation FuncLoc);
10966 /// Check that the expression co_await promise.final_suspend() shall not be
10967 /// potentially-throwing.
10968 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
10969
10970 //===--------------------------------------------------------------------===//
10971 // OpenMP directives and clauses.
10972 //
10973private:
10974 void *VarDataSharingAttributesStack;
10975
10976 struct DeclareTargetContextInfo {
10977 struct MapInfo {
10978 OMPDeclareTargetDeclAttr::MapTypeTy MT;
10979 SourceLocation Loc;
10980 };
10981 /// Explicitly listed variables and functions in a 'to' or 'link' clause.
10982 llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped;
10983
10984 /// The 'device_type' as parsed from the clause.
10985 OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
10986
10987 /// The directive kind, `begin declare target` or `declare target`.
10988 OpenMPDirectiveKind Kind;
10989
10990 /// The directive with indirect clause.
10991 std::optional<Expr *> Indirect;
10992
10993 /// The directive location.
10994 SourceLocation Loc;
10995
10996 DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc)
10997 : Kind(Kind), Loc(Loc) {}
10998 };
10999
11000 /// Number of nested '#pragma omp declare target' directives.
11001 SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting;
11002
11003 /// Initialization of data-sharing attributes stack.
11004 void InitDataSharingAttributesStack();
11005 void DestroyDataSharingAttributesStack();
11006 ExprResult
11007 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
11008 bool StrictlyPositive = true,
11009 bool SuppressExprDiags = false);
11010 /// Returns OpenMP nesting level for current directive.
11011 unsigned getOpenMPNestingLevel() const;
11012
11013 /// Adjusts the function scopes index for the target-based regions.
11014 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
11015 unsigned Level) const;
11016
11017 /// Returns the number of scopes associated with the construct on the given
11018 /// OpenMP level.
11019 int getNumberOfConstructScopes(unsigned Level) const;
11020
11021 /// Push new OpenMP function region for non-capturing function.
11022 void pushOpenMPFunctionRegion();
11023
11024 /// Pop OpenMP function region for non-capturing function.
11025 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
11026
11027 /// Analyzes and checks a loop nest for use by a loop transformation.
11028 ///
11029 /// \param Kind The loop transformation directive kind.
11030 /// \param NumLoops How many nested loops the directive is expecting.
11031 /// \param AStmt Associated statement of the transformation directive.
11032 /// \param LoopHelpers [out] The loop analysis result.
11033 /// \param Body [out] The body code nested in \p NumLoops loop.
11034 /// \param OriginalInits [out] Collection of statements and declarations that
11035 /// must have been executed/declared before entering the
11036 /// loop.
11037 ///
11038 /// \return Whether there was any error.
11039 bool checkTransformableLoopNest(
11040 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
11041 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
11042 Stmt *&Body,
11043 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
11044 &OriginalInits);
11045
11046 /// Helper to keep information about the current `omp begin/end declare
11047 /// variant` nesting.
11048 struct OMPDeclareVariantScope {
11049 /// The associated OpenMP context selector.
11050 OMPTraitInfo *TI;
11051
11052 /// The associated OpenMP context selector mangling.
11053 std::string NameSuffix;
11054
11055 OMPDeclareVariantScope(OMPTraitInfo &TI);
11056 };
11057
11058 /// Return the OMPTraitInfo for the surrounding scope, if any.
11059 OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
11060 return OMPDeclareVariantScopes.empty() ? nullptr
11061 : OMPDeclareVariantScopes.back().TI;
11062 }
11063
11064 /// The current `omp begin/end declare variant` scopes.
11065 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
11066
11067 /// The current `omp begin/end assumes` scopes.
11068 SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
11069
11070 /// All `omp assumes` we encountered so far.
11071 SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
11072
11073public:
11074 /// The declarator \p D defines a function in the scope \p S which is nested
11075 /// in an `omp begin/end declare variant` scope. In this method we create a
11076 /// declaration for \p D and rename \p D according to the OpenMP context
11077 /// selector of the surrounding scope. Return all base functions in \p Bases.
11078 void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
11079 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
11080 SmallVectorImpl<FunctionDecl *> &Bases);
11081
11082 /// Register \p D as specialization of all base functions in \p Bases in the
11083 /// current `omp begin/end declare variant` scope.
11084 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
11085 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
11086
11087 /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
11088 void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
11089
11090 /// Can we exit an OpenMP declare variant scope at the moment.
11091 bool isInOpenMPDeclareVariantScope() const {
11092 return !OMPDeclareVariantScopes.empty();
11093 }
11094
11095 /// Given the potential call expression \p Call, determine if there is a
11096 /// specialization via the OpenMP declare variant mechanism available. If
11097 /// there is, return the specialized call expression, otherwise return the
11098 /// original \p Call.
11099 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
11100 SourceLocation LParenLoc, MultiExprArg ArgExprs,
11101 SourceLocation RParenLoc, Expr *ExecConfig);
11102
11103 /// Handle a `omp begin declare variant`.
11104 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
11105
11106 /// Handle a `omp end declare variant`.
11107 void ActOnOpenMPEndDeclareVariant();
11108
11109 /// Checks if the variant/multiversion functions are compatible.
11110 bool areMultiversionVariantFunctionsCompatible(
11111 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11112 const PartialDiagnostic &NoProtoDiagID,
11113 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11114 const PartialDiagnosticAt &NoSupportDiagIDAt,
11115 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11116 bool ConstexprSupported, bool CLinkageMayDiffer);
11117
11118 /// Function tries to capture lambda's captured variables in the OpenMP region
11119 /// before the original lambda is captured.
11120 void tryCaptureOpenMPLambdas(ValueDecl *V);
11121
11122 /// Return true if the provided declaration \a VD should be captured by
11123 /// reference.
11124 /// \param Level Relative level of nested OpenMP construct for that the check
11125 /// is performed.
11126 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
11127 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
11128 unsigned OpenMPCaptureLevel) const;
11129
11130 /// Check if the specified variable is used in one of the private
11131 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
11132 /// constructs.
11133 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
11134 unsigned StopAt = 0);
11135
11136 /// The member expression(this->fd) needs to be rebuilt in the template
11137 /// instantiation to generate private copy for OpenMP when default
11138 /// clause is used. The function will return true if default
11139 /// cluse is used.
11140 bool isOpenMPRebuildMemberExpr(ValueDecl *D);
11141
11142 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
11143 ExprObjectKind OK, SourceLocation Loc);
11144
11145 /// If the current region is a loop-based region, mark the start of the loop
11146 /// construct.
11147 void startOpenMPLoop();
11148
11149 /// If the current region is a range loop-based region, mark the start of the
11150 /// loop construct.
11151 void startOpenMPCXXRangeFor();
11152
11153 /// Check if the specified variable is used in 'private' clause.
11154 /// \param Level Relative level of nested OpenMP construct for that the check
11155 /// is performed.
11156 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
11157 unsigned CapLevel) const;
11158
11159 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
11160 /// for \p FD based on DSA for the provided corresponding captured declaration
11161 /// \p D.
11162 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
11163
11164 /// Check if the specified variable is captured by 'target' directive.
11165 /// \param Level Relative level of nested OpenMP construct for that the check
11166 /// is performed.
11167 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
11168 unsigned CaptureLevel) const;
11169
11170 /// Check if the specified global variable must be captured by outer capture
11171 /// regions.
11172 /// \param Level Relative level of nested OpenMP construct for that
11173 /// the check is performed.
11174 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
11175 unsigned CaptureLevel) const;
11176
11177 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
11178 Expr *Op);
11179 /// Called on start of new data sharing attribute block.
11180 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
11181 const DeclarationNameInfo &DirName, Scope *CurScope,
11182 SourceLocation Loc);
11183 /// Start analysis of clauses.
11184 void StartOpenMPClause(OpenMPClauseKind K);
11185 /// End analysis of clauses.
11186 void EndOpenMPClause();
11187 /// Called on end of data sharing attribute block.
11188 void EndOpenMPDSABlock(Stmt *CurDirective);
11189
11190 /// Check if the current region is an OpenMP loop region and if it is,
11191 /// mark loop control variable, used in \p Init for loop initialization, as
11192 /// private by default.
11193 /// \param Init First part of the for loop.
11194 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
11195
11196 /// Called on well-formed '\#pragma omp metadirective' after parsing
11197 /// of the associated statement.
11198 StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses,
11199 Stmt *AStmt, SourceLocation StartLoc,
11200 SourceLocation EndLoc);
11201
11202 // OpenMP directives and clauses.
11203 /// Called on correct id-expression from the '#pragma omp
11204 /// threadprivate'.
11205 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
11206 const DeclarationNameInfo &Id,
11207 OpenMPDirectiveKind Kind);
11208 /// Called on well-formed '#pragma omp threadprivate'.
11209 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
11210 SourceLocation Loc,
11211 ArrayRef<Expr *> VarList);
11212 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
11213 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
11214 ArrayRef<Expr *> VarList);
11215 /// Called on well-formed '#pragma omp allocate'.
11216 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
11217 ArrayRef<Expr *> VarList,
11218 ArrayRef<OMPClause *> Clauses,
11219 DeclContext *Owner = nullptr);
11220
11221 /// Called on well-formed '#pragma omp [begin] assume[s]'.
11222 void ActOnOpenMPAssumesDirective(SourceLocation Loc,
11223 OpenMPDirectiveKind DKind,
11224 ArrayRef<std::string> Assumptions,
11225 bool SkippedClauses);
11226
11227 /// Check if there is an active global `omp begin assumes` directive.
11228 bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
11229
11230 /// Check if there is an active global `omp assumes` directive.
11231 bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
11232
11233 /// Called on well-formed '#pragma omp end assumes'.
11234 void ActOnOpenMPEndAssumesDirective();
11235
11236 /// Called on well-formed '#pragma omp requires'.
11237 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
11238 ArrayRef<OMPClause *> ClauseList);
11239 /// Check restrictions on Requires directive
11240 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
11241 ArrayRef<OMPClause *> Clauses);
11242 /// Check if the specified type is allowed to be used in 'omp declare
11243 /// reduction' construct.
11244 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11245 TypeResult ParsedType);
11246 /// Called on start of '#pragma omp declare reduction'.
11247 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
11248 Scope *S, DeclContext *DC, DeclarationName Name,
11249 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11250 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
11251 /// Initialize declare reduction construct initializer.
11252 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
11253 /// Finish current declare reduction construct initializer.
11254 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
11255 /// Initialize declare reduction construct initializer.
11256 /// \return omp_priv variable.
11257 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
11258 /// Finish current declare reduction construct initializer.
11259 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
11260 VarDecl *OmpPrivParm);
11261 /// Called at the end of '#pragma omp declare reduction'.
11262 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
11263 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
11264
11265 /// Check variable declaration in 'omp declare mapper' construct.
11266 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
11267 /// Check if the specified type is allowed to be used in 'omp declare
11268 /// mapper' construct.
11269 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
11270 TypeResult ParsedType);
11271 /// Called on start of '#pragma omp declare mapper'.
11272 DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
11273 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
11274 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
11275 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
11276 Decl *PrevDeclInScope = nullptr);
11277 /// Build the mapper variable of '#pragma omp declare mapper'.
11278 ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
11279 QualType MapperType,
11280 SourceLocation StartLoc,
11281 DeclarationName VN);
11282 void ActOnOpenMPIteratorVarDecl(VarDecl *VD);
11283 bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
11284 const ValueDecl *getOpenMPDeclareMapperVarName() const;
11285
11286 /// Called on the start of target region i.e. '#pragma omp declare target'.
11287 bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
11288
11289 /// Called at the end of target region i.e. '#pragma omp end declare target'.
11290 const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective();
11291
11292 /// Called once a target context is completed, that can be when a
11293 /// '#pragma omp end declare target' was encountered or when a
11294 /// '#pragma omp declare target' without declaration-definition-seq was
11295 /// encountered.
11296 void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
11297
11298 /// Report unterminated 'omp declare target' or 'omp begin declare target' at
11299 /// the end of a compilation unit.
11300 void DiagnoseUnterminatedOpenMPDeclareTarget();
11301
11302 /// Searches for the provided declaration name for OpenMP declare target
11303 /// directive.
11304 NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope,
11305 CXXScopeSpec &ScopeSpec,
11306 const DeclarationNameInfo &Id);
11307
11308 /// Called on correct id-expression from the '#pragma omp declare target'.
11309 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
11310 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11311 DeclareTargetContextInfo &DTCI);
11312
11313 /// Check declaration inside target region.
11314 void
11315 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
11316 SourceLocation IdLoc = SourceLocation());
11317 /// Finishes analysis of the deferred functions calls that may be declared as
11318 /// host/nohost during device/host compilation.
11319 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
11320 const FunctionDecl *Callee,
11321 SourceLocation Loc);
11322
11323 /// Return true if currently in OpenMP task with untied clause context.
11324 bool isInOpenMPTaskUntiedContext() const;
11325
11326 /// Return true inside OpenMP declare target region.
11327 bool isInOpenMPDeclareTargetContext() const {
11328 return !DeclareTargetNesting.empty();
11329 }
11330 /// Return true inside OpenMP target region.
11331 bool isInOpenMPTargetExecutionDirective() const;
11332
11333 /// Return the number of captured regions created for an OpenMP directive.
11334 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
11335
11336 /// Initialization of captured region for OpenMP region.
11337 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
11338
11339 /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to
11340 /// an OpenMP loop directive.
11341 StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt);
11342
11343 /// Process a canonical OpenMP loop nest that can either be a canonical
11344 /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an
11345 /// OpenMP loop transformation construct.
11346 StmtResult ActOnOpenMPLoopnest(Stmt *AStmt);
11347
11348 /// End of OpenMP region.
11349 ///
11350 /// \param S Statement associated with the current OpenMP region.
11351 /// \param Clauses List of clauses for the current OpenMP region.
11352 ///
11353 /// \returns Statement for finished OpenMP region.
11354 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
11355 StmtResult ActOnOpenMPExecutableDirective(
11356 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
11357 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
11358 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
11359 /// Called on well-formed '\#pragma omp parallel' after parsing
11360 /// of the associated statement.
11361 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
11362 Stmt *AStmt,
11363 SourceLocation StartLoc,
11364 SourceLocation EndLoc);
11365 using VarsWithInheritedDSAType =
11366 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
11367 /// Called on well-formed '\#pragma omp simd' after parsing
11368 /// of the associated statement.
11369 StmtResult
11370 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11371 SourceLocation StartLoc, SourceLocation EndLoc,
11372 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11373 /// Called on well-formed '#pragma omp tile' after parsing of its clauses and
11374 /// the associated statement.
11375 StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
11376 Stmt *AStmt, SourceLocation StartLoc,
11377 SourceLocation EndLoc);
11378 /// Called on well-formed '#pragma omp unroll' after parsing of its clauses
11379 /// and the associated statement.
11380 StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
11381 Stmt *AStmt, SourceLocation StartLoc,
11382 SourceLocation EndLoc);
11383 /// Called on well-formed '\#pragma omp for' after parsing
11384 /// of the associated statement.
11385 StmtResult
11386 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11387 SourceLocation StartLoc, SourceLocation EndLoc,
11388 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11389 /// Called on well-formed '\#pragma omp for simd' after parsing
11390 /// of the associated statement.
11391 StmtResult
11392 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11393 SourceLocation StartLoc, SourceLocation EndLoc,
11394 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11395 /// Called on well-formed '\#pragma omp sections' after parsing
11396 /// of the associated statement.
11397 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
11398 Stmt *AStmt, SourceLocation StartLoc,
11399 SourceLocation EndLoc);
11400 /// Called on well-formed '\#pragma omp section' after parsing of the
11401 /// associated statement.
11402 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
11403 SourceLocation EndLoc);
11404 /// Called on well-formed '\#pragma omp single' after parsing of the
11405 /// associated statement.
11406 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
11407 Stmt *AStmt, SourceLocation StartLoc,
11408 SourceLocation EndLoc);
11409 /// Called on well-formed '\#pragma omp master' after parsing of the
11410 /// associated statement.
11411 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
11412 SourceLocation EndLoc);
11413 /// Called on well-formed '\#pragma omp critical' after parsing of the
11414 /// associated statement.
11415 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
11416 ArrayRef<OMPClause *> Clauses,
11417 Stmt *AStmt, SourceLocation StartLoc,
11418 SourceLocation EndLoc);
11419 /// Called on well-formed '\#pragma omp parallel for' after parsing
11420 /// of the associated statement.
11421 StmtResult ActOnOpenMPParallelForDirective(
11422 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11423 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11424 /// Called on well-formed '\#pragma omp parallel for simd' after
11425 /// parsing of the associated statement.
11426 StmtResult ActOnOpenMPParallelForSimdDirective(
11427 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11428 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11429 /// Called on well-formed '\#pragma omp parallel master' after
11430 /// parsing of the associated statement.
11431 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
11432 Stmt *AStmt,
11433 SourceLocation StartLoc,
11434 SourceLocation EndLoc);
11435 /// Called on well-formed '\#pragma omp parallel masked' after
11436 /// parsing of the associated statement.
11437 StmtResult ActOnOpenMPParallelMaskedDirective(ArrayRef<OMPClause *> Clauses,
11438 Stmt *AStmt,
11439 SourceLocation StartLoc,
11440 SourceLocation EndLoc);
11441 /// Called on well-formed '\#pragma omp parallel sections' after
11442 /// parsing of the associated statement.
11443 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
11444 Stmt *AStmt,
11445 SourceLocation StartLoc,
11446 SourceLocation EndLoc);
11447 /// Called on well-formed '\#pragma omp task' after parsing of the
11448 /// associated statement.
11449 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
11450 Stmt *AStmt, SourceLocation StartLoc,
11451 SourceLocation EndLoc);
11452 /// Called on well-formed '\#pragma omp taskyield'.
11453 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
11454 SourceLocation EndLoc);
11455 /// Called on well-formed '\#pragma omp error'.
11456 /// Error direcitive is allowed in both declared and excutable contexts.
11457 /// Adding InExContext to identify which context is called from.
11458 StmtResult ActOnOpenMPErrorDirective(ArrayRef<OMPClause *> Clauses,
11459 SourceLocation StartLoc,
11460 SourceLocation EndLoc,
11461 bool InExContext = true);
11462 /// Called on well-formed '\#pragma omp barrier'.
11463 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
11464 SourceLocation EndLoc);
11465 /// Called on well-formed '\#pragma omp taskwait'.
11466 StmtResult ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
11467 SourceLocation StartLoc,
11468 SourceLocation EndLoc);
11469 /// Called on well-formed '\#pragma omp taskgroup'.
11470 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
11471 Stmt *AStmt, SourceLocation StartLoc,
11472 SourceLocation EndLoc);
11473 /// Called on well-formed '\#pragma omp flush'.
11474 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
11475 SourceLocation StartLoc,
11476 SourceLocation EndLoc);
11477 /// Called on well-formed '\#pragma omp depobj'.
11478 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
11479 SourceLocation StartLoc,
11480 SourceLocation EndLoc);
11481 /// Called on well-formed '\#pragma omp scan'.
11482 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
11483 SourceLocation StartLoc,
11484 SourceLocation EndLoc);
11485 /// Called on well-formed '\#pragma omp ordered' after parsing of the
11486 /// associated statement.
11487 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
11488 Stmt *AStmt, SourceLocation StartLoc,
11489 SourceLocation EndLoc);
11490 /// Called on well-formed '\#pragma omp atomic' after parsing of the
11491 /// associated statement.
11492 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
11493 Stmt *AStmt, SourceLocation StartLoc,
11494 SourceLocation EndLoc);
11495 /// Called on well-formed '\#pragma omp target' after parsing of the
11496 /// associated statement.
11497 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11498 Stmt *AStmt, SourceLocation StartLoc,
11499 SourceLocation EndLoc);
11500 /// Called on well-formed '\#pragma omp target data' after parsing of
11501 /// the associated statement.
11502 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11503 Stmt *AStmt, SourceLocation StartLoc,
11504 SourceLocation EndLoc);
11505 /// Called on well-formed '\#pragma omp target enter data' after
11506 /// parsing of the associated statement.
11507 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11508 SourceLocation StartLoc,
11509 SourceLocation EndLoc,
11510 Stmt *AStmt);
11511 /// Called on well-formed '\#pragma omp target exit data' after
11512 /// parsing of the associated statement.
11513 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11514 SourceLocation StartLoc,
11515 SourceLocation EndLoc,
11516 Stmt *AStmt);
11517 /// Called on well-formed '\#pragma omp target parallel' after
11518 /// parsing of the associated statement.
11519 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11520 Stmt *AStmt,
11521 SourceLocation StartLoc,
11522 SourceLocation EndLoc);
11523 /// Called on well-formed '\#pragma omp target parallel for' after
11524 /// parsing of the associated statement.
11525 StmtResult ActOnOpenMPTargetParallelForDirective(
11526 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11527 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11528 /// Called on well-formed '\#pragma omp teams' after parsing of the
11529 /// associated statement.
11530 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11531 Stmt *AStmt, SourceLocation StartLoc,
11532 SourceLocation EndLoc);
11533 /// Called on well-formed '\#pragma omp teams loop' after parsing of the
11534 /// associated statement.
11535 StmtResult ActOnOpenMPTeamsGenericLoopDirective(
11536 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11537 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11538 /// Called on well-formed '\#pragma omp target teams loop' after parsing of
11539 /// the associated statement.
11540 StmtResult ActOnOpenMPTargetTeamsGenericLoopDirective(
11541 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11542 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11543 /// Called on well-formed '\#pragma omp parallel loop' after parsing of the
11544 /// associated statement.
11545 StmtResult ActOnOpenMPParallelGenericLoopDirective(
11546 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11547 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11548 /// Called on well-formed '\#pragma omp target parallel loop' after parsing
11549 /// of the associated statement.
11550 StmtResult ActOnOpenMPTargetParallelGenericLoopDirective(
11551 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11552 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11553 /// Called on well-formed '\#pragma omp cancellation point'.
11554 StmtResult
11555 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11556 SourceLocation EndLoc,
11557 OpenMPDirectiveKind CancelRegion);
11558 /// Called on well-formed '\#pragma omp cancel'.
11559 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11560 SourceLocation StartLoc,
11561 SourceLocation EndLoc,
11562 OpenMPDirectiveKind CancelRegion);
11563 /// Called on well-formed '\#pragma omp taskloop' after parsing of the
11564 /// associated statement.
11565 StmtResult
11566 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11567 SourceLocation StartLoc, SourceLocation EndLoc,
11568 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11569 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
11570 /// the associated statement.
11571 StmtResult ActOnOpenMPTaskLoopSimdDirective(
11572 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11573 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11574 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
11575 /// associated statement.
11576 StmtResult ActOnOpenMPMasterTaskLoopDirective(
11577 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11578 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11579 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
11580 /// the associated statement.
11581 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
11582 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11583 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11584 /// Called on well-formed '\#pragma omp parallel master taskloop' after
11585 /// parsing of the associated statement.
11586 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
11587 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11588 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11589 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
11590 /// parsing of the associated statement.
11591 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11592 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11593 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11594 /// Called on well-formed '\#pragma omp masked taskloop' after parsing of the
11595 /// associated statement.
11596 StmtResult ActOnOpenMPMaskedTaskLoopDirective(
11597 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11598 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11599 /// Called on well-formed '\#pragma omp masked taskloop simd' after parsing of
11600 /// the associated statement.
11601 StmtResult ActOnOpenMPMaskedTaskLoopSimdDirective(
11602 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11603 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11604 /// Called on well-formed '\#pragma omp parallel masked taskloop' after
11605 /// parsing of the associated statement.
11606 StmtResult ActOnOpenMPParallelMaskedTaskLoopDirective(
11607 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11608 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11609 /// Called on well-formed '\#pragma omp parallel masked taskloop simd' after
11610 /// parsing of the associated statement.
11611 StmtResult ActOnOpenMPParallelMaskedTaskLoopSimdDirective(
11612 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11613 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11614 /// Called on well-formed '\#pragma omp distribute' after parsing
11615 /// of the associated statement.
11616 StmtResult
11617 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11618 SourceLocation StartLoc, SourceLocation EndLoc,
11619 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11620 /// Called on well-formed '\#pragma omp target update'.
11621 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11622 SourceLocation StartLoc,
11623 SourceLocation EndLoc,
11624 Stmt *AStmt);
11625 /// Called on well-formed '\#pragma omp distribute parallel for' after
11626 /// parsing of the associated statement.
11627 StmtResult ActOnOpenMPDistributeParallelForDirective(
11628 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11629 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11630 /// Called on well-formed '\#pragma omp distribute parallel for simd'
11631 /// after parsing of the associated statement.
11632 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
11633 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11634 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11635 /// Called on well-formed '\#pragma omp distribute simd' after
11636 /// parsing of the associated statement.
11637 StmtResult ActOnOpenMPDistributeSimdDirective(
11638 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11639 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11640 /// Called on well-formed '\#pragma omp target parallel for simd' after
11641 /// parsing of the associated statement.
11642 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
11643 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11644 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11645 /// Called on well-formed '\#pragma omp target simd' after parsing of
11646 /// the associated statement.
11647 StmtResult
11648 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11649 SourceLocation StartLoc, SourceLocation EndLoc,
11650 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11651 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
11652 /// the associated statement.
11653 StmtResult ActOnOpenMPTeamsDistributeDirective(
11654 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11655 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11656 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
11657 /// of the associated statement.
11658 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
11659 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11660 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11661 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
11662 /// after parsing of the associated statement.
11663 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11664 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11665 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11666 /// Called on well-formed '\#pragma omp teams distribute parallel for'
11667 /// after parsing of the associated statement.
11668 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
11669 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11670 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11671 /// Called on well-formed '\#pragma omp target teams' after parsing of the
11672 /// associated statement.
11673 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11674 Stmt *AStmt,
11675 SourceLocation StartLoc,
11676 SourceLocation EndLoc);
11677 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
11678 /// of the associated statement.
11679 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
11680 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11681 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11682 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
11683 /// after parsing of the associated statement.
11684 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11685 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11686 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11687 /// Called on well-formed '\#pragma omp target teams distribute parallel for
11688 /// simd' after parsing of the associated statement.
11689 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11690 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11691 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11692 /// Called on well-formed '\#pragma omp target teams distribute simd' after
11693 /// parsing of the associated statement.
11694 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
11695 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11696 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11697 /// Called on well-formed '\#pragma omp interop'.
11698 StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
11699 SourceLocation StartLoc,
11700 SourceLocation EndLoc);
11701 /// Called on well-formed '\#pragma omp dispatch' after parsing of the
11702 // /associated statement.
11703 StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
11704 Stmt *AStmt, SourceLocation StartLoc,
11705 SourceLocation EndLoc);
11706 /// Called on well-formed '\#pragma omp masked' after parsing of the
11707 // /associated statement.
11708 StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
11709 Stmt *AStmt, SourceLocation StartLoc,
11710 SourceLocation EndLoc);
11711
11712 /// Called on well-formed '\#pragma omp loop' after parsing of the
11713 /// associated statement.
11714 StmtResult ActOnOpenMPGenericLoopDirective(
11715 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11716 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11717
11718 /// Checks correctness of linear modifiers.
11719 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11720 SourceLocation LinLoc);
11721 /// Checks that the specified declaration matches requirements for the linear
11722 /// decls.
11723 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11724 OpenMPLinearClauseKind LinKind, QualType Type,
11725 bool IsDeclareSimd = false);
11726
11727 /// Called on well-formed '\#pragma omp declare simd' after parsing of
11728 /// the associated method/function.
11729 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
11730 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
11731 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
11732 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
11733 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
11734
11735 /// Checks '\#pragma omp declare variant' variant function and original
11736 /// functions after parsing of the associated method/function.
11737 /// \param DG Function declaration to which declare variant directive is
11738 /// applied to.
11739 /// \param VariantRef Expression that references the variant function, which
11740 /// must be used instead of the original one, specified in \p DG.
11741 /// \param TI The trait info object representing the match clause.
11742 /// \param NumAppendArgs The number of omp_interop_t arguments to account for
11743 /// in checking.
11744 /// \returns std::nullopt, if the function/variant function are not compatible
11745 /// with the pragma, pair of original function/variant ref expression
11746 /// otherwise.
11747 std::optional<std::pair<FunctionDecl *, Expr *>>
11748 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
11749 OMPTraitInfo &TI, unsigned NumAppendArgs,
11750 SourceRange SR);
11751
11752 /// Called on well-formed '\#pragma omp declare variant' after parsing of
11753 /// the associated method/function.
11754 /// \param FD Function declaration to which declare variant directive is
11755 /// applied to.
11756 /// \param VariantRef Expression that references the variant function, which
11757 /// must be used instead of the original one, specified in \p DG.
11758 /// \param TI The context traits associated with the function variant.
11759 /// \param AdjustArgsNothing The list of 'nothing' arguments.
11760 /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments.
11761 /// \param AppendArgs The list of 'append_args' arguments.
11762 /// \param AdjustArgsLoc The Location of an 'adjust_args' clause.
11763 /// \param AppendArgsLoc The Location of an 'append_args' clause.
11764 /// \param SR The SourceRange of the 'declare variant' directive.
11765 void ActOnOpenMPDeclareVariantDirective(
11766 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
11767 ArrayRef<Expr *> AdjustArgsNothing,
11768 ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
11769 ArrayRef<OMPInteropInfo> AppendArgs, SourceLocation AdjustArgsLoc,
11770 SourceLocation AppendArgsLoc, SourceRange SR);
11771
11772 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
11773 Expr *Expr,
11774 SourceLocation StartLoc,
11775 SourceLocation LParenLoc,
11776 SourceLocation EndLoc);
11777 /// Called on well-formed 'allocator' clause.
11778 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
11779 SourceLocation StartLoc,
11780 SourceLocation LParenLoc,
11781 SourceLocation EndLoc);
11782 /// Called on well-formed 'if' clause.
11783 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11784 Expr *Condition, SourceLocation StartLoc,
11785 SourceLocation LParenLoc,
11786 SourceLocation NameModifierLoc,
11787 SourceLocation ColonLoc,
11788 SourceLocation EndLoc);
11789 /// Called on well-formed 'final' clause.
11790 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
11791 SourceLocation LParenLoc,
11792 SourceLocation EndLoc);
11793 /// Called on well-formed 'num_threads' clause.
11794 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11795 SourceLocation StartLoc,
11796 SourceLocation LParenLoc,
11797 SourceLocation EndLoc);
11798 /// Called on well-formed 'align' clause.
11799 OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc,
11800 SourceLocation LParenLoc,
11801 SourceLocation EndLoc);
11802 /// Called on well-formed 'safelen' clause.
11803 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
11804 SourceLocation StartLoc,
11805 SourceLocation LParenLoc,
11806 SourceLocation EndLoc);
11807 /// Called on well-formed 'simdlen' clause.
11808 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
11809 SourceLocation LParenLoc,
11810 SourceLocation EndLoc);
11811 /// Called on well-form 'sizes' clause.
11812 OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
11813 SourceLocation StartLoc,
11814 SourceLocation LParenLoc,
11815 SourceLocation EndLoc);
11816 /// Called on well-form 'full' clauses.
11817 OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc,
11818 SourceLocation EndLoc);
11819 /// Called on well-form 'partial' clauses.
11820 OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc,
11821 SourceLocation LParenLoc,
11822 SourceLocation EndLoc);
11823 /// Called on well-formed 'collapse' clause.
11824 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
11825 SourceLocation StartLoc,
11826 SourceLocation LParenLoc,
11827 SourceLocation EndLoc);
11828 /// Called on well-formed 'ordered' clause.
11829 OMPClause *
11830 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
11831 SourceLocation LParenLoc = SourceLocation(),
11832 Expr *NumForLoops = nullptr);
11833 /// Called on well-formed 'grainsize' clause.
11834 OMPClause *ActOnOpenMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier,
11835 Expr *Size, SourceLocation StartLoc,
11836 SourceLocation LParenLoc,
11837 SourceLocation ModifierLoc,
11838 SourceLocation EndLoc);
11839 /// Called on well-formed 'num_tasks' clause.
11840 OMPClause *ActOnOpenMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier,
11841 Expr *NumTasks, SourceLocation StartLoc,
11842 SourceLocation LParenLoc,
11843 SourceLocation ModifierLoc,
11844 SourceLocation EndLoc);
11845 /// Called on well-formed 'hint' clause.
11846 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11847 SourceLocation LParenLoc,
11848 SourceLocation EndLoc);
11849 /// Called on well-formed 'detach' clause.
11850 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
11851 SourceLocation LParenLoc,
11852 SourceLocation EndLoc);
11853
11854 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
11855 unsigned Argument,
11856 SourceLocation ArgumentLoc,
11857 SourceLocation StartLoc,
11858 SourceLocation LParenLoc,
11859 SourceLocation EndLoc);
11860 /// Called on well-formed 'when' clause.
11861 OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc,
11862 SourceLocation LParenLoc,
11863 SourceLocation EndLoc);
11864 /// Called on well-formed 'default' clause.
11865 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
11866 SourceLocation KindLoc,
11867 SourceLocation StartLoc,
11868 SourceLocation LParenLoc,
11869 SourceLocation EndLoc);
11870 /// Called on well-formed 'proc_bind' clause.
11871 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
11872 SourceLocation KindLoc,
11873 SourceLocation StartLoc,
11874 SourceLocation LParenLoc,
11875 SourceLocation EndLoc);
11876 /// Called on well-formed 'order' clause.
11877 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseModifier Modifier,
11878 OpenMPOrderClauseKind Kind,
11879 SourceLocation StartLoc,
11880 SourceLocation LParenLoc,
11881 SourceLocation MLoc, SourceLocation KindLoc,
11882 SourceLocation EndLoc);
11883 /// Called on well-formed 'update' clause.
11884 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
11885 SourceLocation KindLoc,
11886 SourceLocation StartLoc,
11887 SourceLocation LParenLoc,
11888 SourceLocation EndLoc);
11889
11890 OMPClause *ActOnOpenMPSingleExprWithArgClause(
11891 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
11892 SourceLocation StartLoc, SourceLocation LParenLoc,
11893 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
11894 SourceLocation EndLoc);
11895 /// Called on well-formed 'schedule' clause.
11896 OMPClause *ActOnOpenMPScheduleClause(
11897 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
11898 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11899 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11900 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
11901
11902 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
11903 SourceLocation EndLoc);
11904 /// Called on well-formed 'nowait' clause.
11905 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11906 SourceLocation EndLoc);
11907 /// Called on well-formed 'untied' clause.
11908 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11909 SourceLocation EndLoc);
11910 /// Called on well-formed 'mergeable' clause.
11911 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11912 SourceLocation EndLoc);
11913 /// Called on well-formed 'read' clause.
11914 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
11915 SourceLocation EndLoc);
11916 /// Called on well-formed 'write' clause.
11917 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
11918 SourceLocation EndLoc);
11919 /// Called on well-formed 'update' clause.</