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/APINotes/APINotesManager.h" |
18 | #include "clang/AST/ASTFwd.h" |
19 | #include "clang/AST/ASTLambda.h" |
20 | #include "clang/AST/Attr.h" |
21 | #include "clang/AST/AttrIterator.h" |
22 | #include "clang/AST/CharUnits.h" |
23 | #include "clang/AST/DeclBase.h" |
24 | #include "clang/AST/DeclCXX.h" |
25 | #include "clang/AST/DeclTemplate.h" |
26 | #include "clang/AST/DeclarationName.h" |
27 | #include "clang/AST/Expr.h" |
28 | #include "clang/AST/ExprCXX.h" |
29 | #include "clang/AST/ExprConcepts.h" |
30 | #include "clang/AST/ExternalASTSource.h" |
31 | #include "clang/AST/NestedNameSpecifier.h" |
32 | #include "clang/AST/OperationKinds.h" |
33 | #include "clang/AST/StmtCXX.h" |
34 | #include "clang/AST/Type.h" |
35 | #include "clang/AST/TypeLoc.h" |
36 | #include "clang/Basic/AttrSubjectMatchRules.h" |
37 | #include "clang/Basic/Builtins.h" |
38 | #include "clang/Basic/CapturedStmt.h" |
39 | #include "clang/Basic/Cuda.h" |
40 | #include "clang/Basic/DiagnosticSema.h" |
41 | #include "clang/Basic/ExceptionSpecificationType.h" |
42 | #include "clang/Basic/ExpressionTraits.h" |
43 | #include "clang/Basic/LLVM.h" |
44 | #include "clang/Basic/Lambda.h" |
45 | #include "clang/Basic/LangOptions.h" |
46 | #include "clang/Basic/Module.h" |
47 | #include "clang/Basic/OpenCLOptions.h" |
48 | #include "clang/Basic/OperatorKinds.h" |
49 | #include "clang/Basic/PartialDiagnostic.h" |
50 | #include "clang/Basic/PragmaKinds.h" |
51 | #include "clang/Basic/SourceLocation.h" |
52 | #include "clang/Basic/Specifiers.h" |
53 | #include "clang/Basic/StackExhaustionHandler.h" |
54 | #include "clang/Basic/TemplateKinds.h" |
55 | #include "clang/Basic/TokenKinds.h" |
56 | #include "clang/Basic/TypeTraits.h" |
57 | #include "clang/Sema/AnalysisBasedWarnings.h" |
58 | #include "clang/Sema/Attr.h" |
59 | #include "clang/Sema/CleanupInfo.h" |
60 | #include "clang/Sema/DeclSpec.h" |
61 | #include "clang/Sema/ExternalSemaSource.h" |
62 | #include "clang/Sema/IdentifierResolver.h" |
63 | #include "clang/Sema/Ownership.h" |
64 | #include "clang/Sema/ParsedAttr.h" |
65 | #include "clang/Sema/Redeclaration.h" |
66 | #include "clang/Sema/Scope.h" |
67 | #include "clang/Sema/SemaBase.h" |
68 | #include "clang/Sema/TypoCorrection.h" |
69 | #include "clang/Sema/Weak.h" |
70 | #include "llvm/ADT/APInt.h" |
71 | #include "llvm/ADT/ArrayRef.h" |
72 | #include "llvm/ADT/BitmaskEnum.h" |
73 | #include "llvm/ADT/DenseMap.h" |
74 | #include "llvm/ADT/DenseSet.h" |
75 | #include "llvm/ADT/FloatingPointMode.h" |
76 | #include "llvm/ADT/FoldingSet.h" |
77 | #include "llvm/ADT/MapVector.h" |
78 | #include "llvm/ADT/PointerIntPair.h" |
79 | #include "llvm/ADT/PointerUnion.h" |
80 | #include "llvm/ADT/STLExtras.h" |
81 | #include "llvm/ADT/STLForwardCompat.h" |
82 | #include "llvm/ADT/STLFunctionalExtras.h" |
83 | #include "llvm/ADT/SetVector.h" |
84 | #include "llvm/ADT/SmallBitVector.h" |
85 | #include "llvm/ADT/SmallPtrSet.h" |
86 | #include "llvm/ADT/SmallSet.h" |
87 | #include "llvm/ADT/SmallVector.h" |
88 | #include "llvm/ADT/StringExtras.h" |
89 | #include "llvm/ADT/StringMap.h" |
90 | #include "llvm/ADT/TinyPtrVector.h" |
91 | #include "llvm/Support/Allocator.h" |
92 | #include "llvm/Support/Compiler.h" |
93 | #include "llvm/Support/Error.h" |
94 | #include "llvm/Support/ErrorHandling.h" |
95 | #include <cassert> |
96 | #include <climits> |
97 | #include <cstddef> |
98 | #include <cstdint> |
99 | #include <deque> |
100 | #include <functional> |
101 | #include <iterator> |
102 | #include <memory> |
103 | #include <optional> |
104 | #include <string> |
105 | #include <tuple> |
106 | #include <type_traits> |
107 | #include <utility> |
108 | #include <vector> |
109 | |
110 | namespace llvm { |
111 | struct InlineAsmIdentifierInfo; |
112 | } // namespace llvm |
113 | |
114 | namespace clang { |
115 | class ADLResult; |
116 | class APValue; |
117 | struct ASTConstraintSatisfaction; |
118 | class ASTConsumer; |
119 | class ASTContext; |
120 | class ASTDeclReader; |
121 | class ASTMutationListener; |
122 | class ASTReader; |
123 | class ASTWriter; |
124 | class CXXBasePath; |
125 | class CXXBasePaths; |
126 | class CXXFieldCollector; |
127 | class CodeCompleteConsumer; |
128 | enum class ComparisonCategoryType : unsigned char; |
129 | class ConstraintSatisfaction; |
130 | class DarwinSDKInfo; |
131 | class DeclGroupRef; |
132 | class DeducedTemplateArgument; |
133 | struct DeductionFailureInfo; |
134 | class DependentDiagnostic; |
135 | class Designation; |
136 | class IdentifierInfo; |
137 | class ImplicitConversionSequence; |
138 | typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; |
139 | class InitializationKind; |
140 | class InitializationSequence; |
141 | class InitializedEntity; |
142 | enum class LangAS : unsigned int; |
143 | class LocalInstantiationScope; |
144 | class LookupResult; |
145 | class MangleNumberingContext; |
146 | typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; |
147 | class ModuleLoader; |
148 | class MultiLevelTemplateArgumentList; |
149 | struct NormalizedConstraint; |
150 | class ObjCInterfaceDecl; |
151 | class ObjCMethodDecl; |
152 | struct OverloadCandidate; |
153 | enum class OverloadCandidateParamOrder : char; |
154 | enum OverloadCandidateRewriteKind : unsigned; |
155 | class OverloadCandidateSet; |
156 | class Preprocessor; |
157 | class SemaAMDGPU; |
158 | class SemaARM; |
159 | class SemaAVR; |
160 | class SemaBPF; |
161 | class SemaCodeCompletion; |
162 | class SemaCUDA; |
163 | class SemaHLSL; |
164 | class SemaHexagon; |
165 | class SemaLoongArch; |
166 | class SemaM68k; |
167 | class SemaMIPS; |
168 | class SemaMSP430; |
169 | class SemaNVPTX; |
170 | class SemaObjC; |
171 | class SemaOpenACC; |
172 | class SemaOpenCL; |
173 | class SemaOpenMP; |
174 | class SemaPPC; |
175 | class SemaPseudoObject; |
176 | class SemaRISCV; |
177 | class SemaSPIRV; |
178 | class SemaSYCL; |
179 | class SemaSwift; |
180 | class SemaSystemZ; |
181 | class SemaWasm; |
182 | class SemaX86; |
183 | class StandardConversionSequence; |
184 | class TemplateArgument; |
185 | class TemplateArgumentLoc; |
186 | class TemplateInstantiationCallback; |
187 | class TemplatePartialOrderingContext; |
188 | class TemplateSpecCandidateSet; |
189 | class Token; |
190 | class TypeConstraint; |
191 | class TypoCorrectionConsumer; |
192 | class UnresolvedSetImpl; |
193 | class UnresolvedSetIterator; |
194 | class VisibleDeclConsumer; |
195 | |
196 | namespace sema { |
197 | class BlockScopeInfo; |
198 | class Capture; |
199 | class CapturedRegionScopeInfo; |
200 | class CapturingScopeInfo; |
201 | class CompoundScopeInfo; |
202 | class DelayedDiagnostic; |
203 | class DelayedDiagnosticPool; |
204 | class FunctionScopeInfo; |
205 | class LambdaScopeInfo; |
206 | class SemaPPCallbacks; |
207 | class TemplateDeductionInfo; |
208 | } // namespace sema |
209 | |
210 | // AssignmentAction - This is used by all the assignment diagnostic functions |
211 | // to represent what is actually causing the operation |
212 | enum class AssignmentAction { |
213 | Assigning, |
214 | Passing, |
215 | Returning, |
216 | Converting, |
217 | Initializing, |
218 | Sending, |
219 | Casting, |
220 | Passing_CFAudited |
221 | }; |
222 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, |
223 | const AssignmentAction &AA) { |
224 | DB << llvm::to_underlying(E: AA); |
225 | return DB; |
226 | } |
227 | |
228 | namespace threadSafety { |
229 | class BeforeSet; |
230 | void threadSafetyCleanup(BeforeSet *Cache); |
231 | } // namespace threadSafety |
232 | |
233 | // FIXME: No way to easily map from TemplateTypeParmTypes to |
234 | // TemplateTypeParmDecls, so we have this horrible PointerUnion. |
235 | typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>, |
236 | SourceLocation> |
237 | UnexpandedParameterPack; |
238 | |
239 | /// Describes whether we've seen any nullability information for the given |
240 | /// file. |
241 | struct FileNullability { |
242 | /// The first pointer declarator (of any pointer kind) in the file that does |
243 | /// not have a corresponding nullability annotation. |
244 | SourceLocation PointerLoc; |
245 | |
246 | /// The end location for the first pointer declarator in the file. Used for |
247 | /// placing fix-its. |
248 | SourceLocation PointerEndLoc; |
249 | |
250 | /// Which kind of pointer declarator we saw. |
251 | uint8_t PointerKind; |
252 | |
253 | /// Whether we saw any type nullability annotations in the given file. |
254 | bool SawTypeNullability = false; |
255 | }; |
256 | |
257 | /// A mapping from file IDs to a record of whether we've seen nullability |
258 | /// information in that file. |
259 | class FileNullabilityMap { |
260 | /// A mapping from file IDs to the nullability information for each file ID. |
261 | llvm::DenseMap<FileID, FileNullability> Map; |
262 | |
263 | /// A single-element cache based on the file ID. |
264 | struct { |
265 | FileID File; |
266 | FileNullability Nullability; |
267 | } Cache; |
268 | |
269 | public: |
270 | FileNullability &operator[](FileID file) { |
271 | // Check the single-element cache. |
272 | if (file == Cache.File) |
273 | return Cache.Nullability; |
274 | |
275 | // It's not in the single-element cache; flush the cache if we have one. |
276 | if (!Cache.File.isInvalid()) { |
277 | Map[Cache.File] = Cache.Nullability; |
278 | } |
279 | |
280 | // Pull this entry into the cache. |
281 | Cache.File = file; |
282 | Cache.Nullability = Map[file]; |
283 | return Cache.Nullability; |
284 | } |
285 | }; |
286 | |
287 | /// Tracks expected type during expression parsing, for use in code completion. |
288 | /// The type is tied to a particular token, all functions that update or consume |
289 | /// the type take a start location of the token they are looking at as a |
290 | /// parameter. This avoids updating the type on hot paths in the parser. |
291 | class PreferredTypeBuilder { |
292 | public: |
293 | PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {} |
294 | |
295 | void enterCondition(Sema &S, SourceLocation Tok); |
296 | void enterReturn(Sema &S, SourceLocation Tok); |
297 | void enterVariableInit(SourceLocation Tok, Decl *D); |
298 | /// Handles e.g. BaseType{ .D = Tok... |
299 | void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, |
300 | const Designation &D); |
301 | /// Computing a type for the function argument may require running |
302 | /// overloading, so we postpone its computation until it is actually needed. |
303 | /// |
304 | /// Clients should be very careful when using this function, as it stores a |
305 | /// function_ref, clients should make sure all calls to get() with the same |
306 | /// location happen while function_ref is alive. |
307 | /// |
308 | /// The callback should also emit signature help as a side-effect, but only |
309 | /// if the completion point has been reached. |
310 | void enterFunctionArgument(SourceLocation Tok, |
311 | llvm::function_ref<QualType()> ComputeType); |
312 | |
313 | void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); |
314 | void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, |
315 | SourceLocation OpLoc); |
316 | void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); |
317 | void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); |
318 | void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); |
319 | /// Handles all type casts, including C-style cast, C++ casts, etc. |
320 | void enterTypeCast(SourceLocation Tok, QualType CastType); |
321 | |
322 | /// Get the expected type associated with this location, if any. |
323 | /// |
324 | /// If the location is a function argument, determining the expected type |
325 | /// involves considering all function overloads and the arguments so far. |
326 | /// In this case, signature help for these function overloads will be reported |
327 | /// as a side-effect (only if the completion point has been reached). |
328 | QualType get(SourceLocation Tok) const { |
329 | if (!Enabled || Tok != ExpectedLoc) |
330 | return QualType(); |
331 | if (!Type.isNull()) |
332 | return Type; |
333 | if (ComputeType) |
334 | return ComputeType(); |
335 | return QualType(); |
336 | } |
337 | |
338 | private: |
339 | bool Enabled; |
340 | /// Start position of a token for which we store expected type. |
341 | SourceLocation ExpectedLoc; |
342 | /// Expected type for a token starting at ExpectedLoc. |
343 | QualType Type; |
344 | /// A function to compute expected type at ExpectedLoc. It is only considered |
345 | /// if Type is null. |
346 | llvm::function_ref<QualType()> ComputeType; |
347 | }; |
348 | |
349 | struct SkipBodyInfo { |
350 | SkipBodyInfo() = default; |
351 | bool ShouldSkip = false; |
352 | bool CheckSameAsPrevious = false; |
353 | NamedDecl *Previous = nullptr; |
354 | NamedDecl *New = nullptr; |
355 | }; |
356 | |
357 | /// Describes the result of template argument deduction. |
358 | /// |
359 | /// The TemplateDeductionResult enumeration describes the result of |
360 | /// template argument deduction, as returned from |
361 | /// DeduceTemplateArguments(). The separate TemplateDeductionInfo |
362 | /// structure provides additional information about the results of |
363 | /// template argument deduction, e.g., the deduced template argument |
364 | /// list (if successful) or the specific template parameters or |
365 | /// deduced arguments that were involved in the failure. |
366 | enum class TemplateDeductionResult { |
367 | /// Template argument deduction was successful. |
368 | Success = 0, |
369 | /// The declaration was invalid; do nothing. |
370 | Invalid, |
371 | /// Template argument deduction exceeded the maximum template |
372 | /// instantiation depth (which has already been diagnosed). |
373 | InstantiationDepth, |
374 | /// Template argument deduction did not deduce a value |
375 | /// for every template parameter. |
376 | Incomplete, |
377 | /// Template argument deduction did not deduce a value for every |
378 | /// expansion of an expanded template parameter pack. |
379 | IncompletePack, |
380 | /// Template argument deduction produced inconsistent |
381 | /// deduced values for the given template parameter. |
382 | Inconsistent, |
383 | /// Template argument deduction failed due to inconsistent |
384 | /// cv-qualifiers on a template parameter type that would |
385 | /// otherwise be deduced, e.g., we tried to deduce T in "const T" |
386 | /// but were given a non-const "X". |
387 | Underqualified, |
388 | /// Substitution of the deduced template argument values |
389 | /// resulted in an error. |
390 | SubstitutionFailure, |
391 | /// After substituting deduced template arguments, a dependent |
392 | /// parameter type did not match the corresponding argument. |
393 | DeducedMismatch, |
394 | /// After substituting deduced template arguments, an element of |
395 | /// a dependent parameter type did not match the corresponding element |
396 | /// of the corresponding argument (when deducing from an initializer list). |
397 | DeducedMismatchNested, |
398 | /// A non-depnedent component of the parameter did not match the |
399 | /// corresponding component of the argument. |
400 | NonDeducedMismatch, |
401 | /// When performing template argument deduction for a function |
402 | /// template, there were too many call arguments. |
403 | TooManyArguments, |
404 | /// When performing template argument deduction for a function |
405 | /// template, there were too few call arguments. |
406 | TooFewArguments, |
407 | /// The explicitly-specified template arguments were not valid |
408 | /// template arguments for the given template. |
409 | InvalidExplicitArguments, |
410 | /// Checking non-dependent argument conversions failed. |
411 | NonDependentConversionFailure, |
412 | /// The deduced arguments did not satisfy the constraints associated |
413 | /// with the template. |
414 | ConstraintsNotSatisfied, |
415 | /// Deduction failed; that's all we know. |
416 | MiscellaneousDeductionFailure, |
417 | /// CUDA Target attributes do not match. |
418 | CUDATargetMismatch, |
419 | /// Some error which was already diagnosed. |
420 | AlreadyDiagnosed |
421 | }; |
422 | |
423 | /// Kinds of C++ special members. |
424 | enum class CXXSpecialMemberKind { |
425 | DefaultConstructor, |
426 | CopyConstructor, |
427 | MoveConstructor, |
428 | CopyAssignment, |
429 | MoveAssignment, |
430 | Destructor, |
431 | Invalid |
432 | }; |
433 | |
434 | /// The kind of conversion being performed. |
435 | enum class CheckedConversionKind { |
436 | /// An implicit conversion. |
437 | Implicit, |
438 | /// A C-style cast. |
439 | CStyleCast, |
440 | /// A functional-style cast. |
441 | FunctionalCast, |
442 | /// A cast other than a C-style cast. |
443 | OtherCast, |
444 | /// A conversion for an operand of a builtin overloaded operator. |
445 | ForBuiltinOverloadedOp |
446 | }; |
447 | |
448 | enum class TagUseKind { |
449 | Reference, // Reference to a tag: 'struct foo *X;' |
450 | Declaration, // Fwd decl of a tag: 'struct foo;' |
451 | Definition, // Definition of a tag: 'struct foo { int X; } Y;' |
452 | Friend // Friend declaration: 'friend struct foo;' |
453 | }; |
454 | |
455 | /// Used with attributes/effects with a boolean condition, e.g. `nonblocking`. |
456 | enum class FunctionEffectMode : uint8_t { |
457 | None, // effect is not present. |
458 | False, // effect(false). |
459 | True, // effect(true). |
460 | Dependent // effect(expr) where expr is dependent. |
461 | }; |
462 | |
463 | /// Sema - This implements semantic analysis and AST building for C. |
464 | /// \nosubgrouping |
465 | class Sema final : public SemaBase { |
466 | // Table of Contents |
467 | // ----------------- |
468 | // 1. Semantic Analysis (Sema.cpp) |
469 | // 2. API Notes (SemaAPINotes.cpp) |
470 | // 3. C++ Access Control (SemaAccess.cpp) |
471 | // 4. Attributes (SemaAttr.cpp) |
472 | // 5. Availability Attribute Handling (SemaAvailability.cpp) |
473 | // 6. Bounds Safety (SemaBoundsSafety.cpp) |
474 | // 7. Casts (SemaCast.cpp) |
475 | // 8. Extra Semantic Checking (SemaChecking.cpp) |
476 | // 9. C++ Coroutines (SemaCoroutine.cpp) |
477 | // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp) |
478 | // 11. Declarations (SemaDecl.cpp) |
479 | // 12. Declaration Attribute Handling (SemaDeclAttr.cpp) |
480 | // 13. C++ Declarations (SemaDeclCXX.cpp) |
481 | // 14. C++ Exception Specifications (SemaExceptionSpec.cpp) |
482 | // 15. Expressions (SemaExpr.cpp) |
483 | // 16. C++ Expressions (SemaExprCXX.cpp) |
484 | // 17. Member Access Expressions (SemaExprMember.cpp) |
485 | // 18. Initializers (SemaInit.cpp) |
486 | // 19. C++ Lambda Expressions (SemaLambda.cpp) |
487 | // 20. Name Lookup (SemaLookup.cpp) |
488 | // 21. Modules (SemaModule.cpp) |
489 | // 22. C++ Overloading (SemaOverload.cpp) |
490 | // 23. Statements (SemaStmt.cpp) |
491 | // 24. `inline asm` Statement (SemaStmtAsm.cpp) |
492 | // 25. Statement Attribute Handling (SemaStmtAttr.cpp) |
493 | // 26. C++ Templates (SemaTemplate.cpp) |
494 | // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp) |
495 | // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp) |
496 | // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp) |
497 | // 30. C++ Template Declaration Instantiation |
498 | // (SemaTemplateInstantiateDecl.cpp) |
499 | // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp) |
500 | // 32. Constraints and Concepts (SemaConcept.cpp) |
501 | // 33. Types (SemaType.cpp) |
502 | // 34. FixIt Helpers (SemaFixItUtils.cpp) |
503 | // 35. Function Effects (SemaFunctionEffects.cpp) |
504 | |
505 | /// \name Semantic Analysis |
506 | /// Implementations are in Sema.cpp |
507 | ///@{ |
508 | |
509 | public: |
510 | Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, |
511 | TranslationUnitKind TUKind = TU_Complete, |
512 | CodeCompleteConsumer *CompletionConsumer = nullptr); |
513 | ~Sema(); |
514 | |
515 | /// Perform initialization that occurs after the parser has been |
516 | /// initialized but before it parses anything. |
517 | void Initialize(); |
518 | |
519 | /// This virtual key function only exists to limit the emission of debug info |
520 | /// describing the Sema class. GCC and Clang only emit debug info for a class |
521 | /// with a vtable when the vtable is emitted. Sema is final and not |
522 | /// polymorphic, but the debug info size savings are so significant that it is |
523 | /// worth adding a vtable just to take advantage of this optimization. |
524 | virtual void anchor(); |
525 | |
526 | const LangOptions &getLangOpts() const { return LangOpts; } |
527 | OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } |
528 | FPOptions &getCurFPFeatures() { return CurFPFeatures; } |
529 | |
530 | DiagnosticsEngine &getDiagnostics() const { return Diags; } |
531 | SourceManager &getSourceManager() const { return SourceMgr; } |
532 | Preprocessor &getPreprocessor() const { return PP; } |
533 | ASTContext &getASTContext() const { return Context; } |
534 | ASTConsumer &getASTConsumer() const { return Consumer; } |
535 | ASTMutationListener *getASTMutationListener() const; |
536 | ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); } |
537 | |
538 | DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, |
539 | StringRef Platform); |
540 | DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(); |
541 | |
542 | /// Registers an external source. If an external source already exists, |
543 | /// creates a multiplex external source and appends to it. |
544 | /// |
545 | ///\param[in] E - A non-null external sema source. |
546 | /// |
547 | void addExternalSource(ExternalSemaSource *E); |
548 | |
549 | /// Print out statistics about the semantic analysis. |
550 | void PrintStats() const; |
551 | |
552 | /// Run some code with "sufficient" stack space. (Currently, at least 256K is |
553 | /// guaranteed). Produces a warning if we're low on stack space and allocates |
554 | /// more in that case. Use this in code that may recurse deeply (for example, |
555 | /// in template instantiation) to avoid stack overflow. |
556 | void runWithSufficientStackSpace(SourceLocation Loc, |
557 | llvm::function_ref<void()> Fn); |
558 | |
559 | /// Returns default addr space for method qualifiers. |
560 | LangAS getDefaultCXXMethodAddrSpace() const; |
561 | |
562 | /// Load weak undeclared identifiers from the external source. |
563 | void LoadExternalWeakUndeclaredIdentifiers(); |
564 | |
565 | /// Determine if VD, which must be a variable or function, is an external |
566 | /// symbol that nonetheless can't be referenced from outside this translation |
567 | /// unit because its type has no linkage and it's not extern "C". |
568 | bool isExternalWithNoLinkageType(const ValueDecl *VD) const; |
569 | |
570 | /// Obtain a sorted list of functions that are undefined but ODR-used. |
571 | void getUndefinedButUsed( |
572 | SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined); |
573 | |
574 | typedef std::pair<SourceLocation, bool> DeleteExprLoc; |
575 | typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; |
576 | /// Retrieves list of suspicious delete-expressions that will be checked at |
577 | /// the end of translation unit. |
578 | const llvm::MapVector<FieldDecl *, DeleteLocs> & |
579 | getMismatchingDeleteExpressions() const; |
580 | |
581 | /// Cause the built diagnostic to be emitted on the DiagosticsEngine. |
582 | /// This is closely coupled to the SemaDiagnosticBuilder class and |
583 | /// should not be used elsewhere. |
584 | void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB); |
585 | |
586 | void addImplicitTypedef(StringRef Name, QualType T); |
587 | |
588 | /// Whether uncompilable error has occurred. This includes error happens |
589 | /// in deferred diagnostics. |
590 | bool hasUncompilableErrorOccurred() const; |
591 | |
592 | /// Looks through the macro-expansion chain for the given |
593 | /// location, looking for a macro expansion with the given name. |
594 | /// If one is found, returns true and sets the location to that |
595 | /// expansion loc. |
596 | bool findMacroSpelling(SourceLocation &loc, StringRef name); |
597 | |
598 | /// Calls \c Lexer::getLocForEndOfToken() |
599 | SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); |
600 | |
601 | /// Retrieve the module loader associated with the preprocessor. |
602 | ModuleLoader &getModuleLoader() const; |
603 | |
604 | /// Invent a new identifier for parameters of abbreviated templates. |
605 | IdentifierInfo * |
606 | InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, |
607 | unsigned Index); |
608 | |
609 | void emitAndClearUnusedLocalTypedefWarnings(); |
610 | |
611 | // Emit all deferred diagnostics. |
612 | void emitDeferredDiags(); |
613 | |
614 | enum TUFragmentKind { |
615 | /// The global module fragment, between 'module;' and a module-declaration. |
616 | Global, |
617 | /// A normal translation unit fragment. For a non-module unit, this is the |
618 | /// entire translation unit. Otherwise, it runs from the module-declaration |
619 | /// to the private-module-fragment (if any) or the end of the TU (if not). |
620 | Normal, |
621 | /// The private module fragment, between 'module :private;' and the end of |
622 | /// the translation unit. |
623 | Private |
624 | }; |
625 | |
626 | /// This is called before the very first declaration in the translation unit |
627 | /// is parsed. Note that the ASTContext may have already injected some |
628 | /// declarations. |
629 | void ActOnStartOfTranslationUnit(); |
630 | /// ActOnEndOfTranslationUnit - This is called at the very end of the |
631 | /// translation unit when EOF is reached and all but the top-level scope is |
632 | /// popped. |
633 | void ActOnEndOfTranslationUnit(); |
634 | void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); |
635 | |
636 | /// Determines the active Scope associated with the given declaration |
637 | /// context. |
638 | /// |
639 | /// This routine maps a declaration context to the active Scope object that |
640 | /// represents that declaration context in the parser. It is typically used |
641 | /// from "scope-less" code (e.g., template instantiation, lazy creation of |
642 | /// declarations) that injects a name for name-lookup purposes and, therefore, |
643 | /// must update the Scope. |
644 | /// |
645 | /// \returns The scope corresponding to the given declaraion context, or NULL |
646 | /// if no such scope is open. |
647 | Scope *getScopeForContext(DeclContext *Ctx); |
648 | |
649 | void PushFunctionScope(); |
650 | void PushBlockScope(Scope *BlockScope, BlockDecl *Block); |
651 | sema::LambdaScopeInfo *PushLambdaScope(); |
652 | |
653 | /// This is used to inform Sema what the current TemplateParameterDepth |
654 | /// is during Parsing. Currently it is used to pass on the depth |
655 | /// when parsing generic lambda 'auto' parameters. |
656 | void RecordParsingTemplateParameterDepth(unsigned Depth); |
657 | |
658 | void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, |
659 | RecordDecl *RD, CapturedRegionKind K, |
660 | unsigned OpenMPCaptureLevel = 0); |
661 | |
662 | /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short |
663 | /// time after they've been popped. |
664 | class PoppedFunctionScopeDeleter { |
665 | Sema *Self; |
666 | |
667 | public: |
668 | explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} |
669 | void operator()(sema::FunctionScopeInfo *Scope) const; |
670 | }; |
671 | |
672 | using PoppedFunctionScopePtr = |
673 | std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; |
674 | |
675 | /// Pop a function (or block or lambda or captured region) scope from the |
676 | /// stack. |
677 | /// |
678 | /// \param WP The warning policy to use for CFG-based warnings, or null if |
679 | /// such warnings should not be produced. |
680 | /// \param D The declaration corresponding to this function scope, if |
681 | /// producing CFG-based warnings. |
682 | /// \param BlockType The type of the block expression, if D is a BlockDecl. |
683 | PoppedFunctionScopePtr |
684 | PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, |
685 | const Decl *D = nullptr, |
686 | QualType BlockType = QualType()); |
687 | |
688 | sema::FunctionScopeInfo *getEnclosingFunction() const; |
689 | |
690 | void setFunctionHasBranchIntoScope(); |
691 | void setFunctionHasBranchProtectedScope(); |
692 | void setFunctionHasIndirectGoto(); |
693 | void setFunctionHasMustTail(); |
694 | |
695 | void PushCompoundScope(bool IsStmtExpr); |
696 | void PopCompoundScope(); |
697 | |
698 | /// Determine whether any errors occurred within this function/method/ |
699 | /// block. |
700 | bool hasAnyUnrecoverableErrorsInThisFunction() const; |
701 | |
702 | /// Retrieve the current block, if any. |
703 | sema::BlockScopeInfo *getCurBlock(); |
704 | |
705 | /// Get the innermost lambda or block enclosing the current location, if any. |
706 | /// This looks through intervening non-lambda, non-block scopes such as local |
707 | /// functions. |
708 | sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const; |
709 | |
710 | /// Retrieve the current lambda scope info, if any. |
711 | /// \param IgnoreNonLambdaCapturingScope true if should find the top-most |
712 | /// lambda scope info ignoring all inner capturing scopes that are not |
713 | /// lambda scopes. |
714 | sema::LambdaScopeInfo * |
715 | getCurLambda(bool IgnoreNonLambdaCapturingScope = false); |
716 | |
717 | /// Retrieve the current generic lambda info, if any. |
718 | sema::LambdaScopeInfo *getCurGenericLambda(); |
719 | |
720 | /// Retrieve the current captured region, if any. |
721 | sema::CapturedRegionScopeInfo *getCurCapturedRegion(); |
722 | |
723 | void (SourceRange ); |
724 | |
725 | /// Retrieve the parser's current scope. |
726 | /// |
727 | /// This routine must only be used when it is certain that semantic analysis |
728 | /// and the parser are in precisely the same context, which is not the case |
729 | /// when, e.g., we are performing any kind of template instantiation. |
730 | /// Therefore, the only safe places to use this scope are in the parser |
731 | /// itself and in routines directly invoked from the parser and *never* from |
732 | /// template substitution or instantiation. |
733 | Scope *getCurScope() const { return CurScope; } |
734 | |
735 | IdentifierInfo *getSuperIdentifier() const; |
736 | |
737 | DeclContext *getCurLexicalContext() const { |
738 | return OriginalLexicalContext ? OriginalLexicalContext : CurContext; |
739 | } |
740 | |
741 | SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, |
742 | const FunctionDecl *FD = nullptr); |
743 | SemaDiagnosticBuilder targetDiag(SourceLocation Loc, |
744 | const PartialDiagnostic &PD, |
745 | const FunctionDecl *FD = nullptr) { |
746 | return targetDiag(Loc, DiagID: PD.getDiagID(), FD) << PD; |
747 | } |
748 | |
749 | /// Check if the type is allowed to be used for the current target. |
750 | void checkTypeSupport(QualType Ty, SourceLocation Loc, |
751 | ValueDecl *D = nullptr); |
752 | |
753 | // /// The kind of conversion being performed. |
754 | // enum CheckedConversionKind { |
755 | // /// An implicit conversion. |
756 | // CCK_ImplicitConversion, |
757 | // /// A C-style cast. |
758 | // CCK_CStyleCast, |
759 | // /// A functional-style cast. |
760 | // CCK_FunctionalCast, |
761 | // /// A cast other than a C-style cast. |
762 | // CCK_OtherCast, |
763 | // /// A conversion for an operand of a builtin overloaded operator. |
764 | // CCK_ForBuiltinOverloadedOp |
765 | // }; |
766 | |
767 | /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit |
768 | /// cast. If there is already an implicit cast, merge into the existing one. |
769 | /// If isLvalue, the result of the cast is an lvalue. |
770 | ExprResult ImpCastExprToType( |
771 | Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue, |
772 | const CXXCastPath *BasePath = nullptr, |
773 | CheckedConversionKind CCK = CheckedConversionKind::Implicit); |
774 | |
775 | /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding |
776 | /// to the conversion from scalar type ScalarTy to the Boolean type. |
777 | static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); |
778 | |
779 | /// If \p AllowLambda is true, treat lambda as function. |
780 | DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const; |
781 | |
782 | /// Returns a pointer to the innermost enclosing function, or nullptr if the |
783 | /// current context is not inside a function. If \p AllowLambda is true, |
784 | /// this can return the call operator of an enclosing lambda, otherwise |
785 | /// lambdas are skipped when looking for an enclosing function. |
786 | FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const; |
787 | |
788 | /// getCurMethodDecl - If inside of a method body, this returns a pointer to |
789 | /// the method decl for the method being parsed. If we're currently |
790 | /// in a 'block', this returns the containing context. |
791 | ObjCMethodDecl *getCurMethodDecl(); |
792 | |
793 | /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method |
794 | /// or C function we're in, otherwise return null. If we're currently |
795 | /// in a 'block', this returns the containing context. |
796 | NamedDecl *getCurFunctionOrMethodDecl() const; |
797 | |
798 | /// Warn if we're implicitly casting from a _Nullable pointer type to a |
799 | /// _Nonnull one. |
800 | void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, |
801 | SourceLocation Loc); |
802 | |
803 | /// Warn when implicitly casting 0 to nullptr. |
804 | void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); |
805 | |
806 | /// Warn when implicitly changing function effects. |
807 | void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType, |
808 | SourceLocation Loc); |
809 | |
810 | /// makeUnavailableInSystemHeader - There is an error in the current |
811 | /// context. If we're still in a system header, and we can plausibly |
812 | /// make the relevant declaration unavailable instead of erroring, do |
813 | /// so and return true. |
814 | bool (SourceLocation loc, |
815 | UnavailableAttr::ImplicitReason reason); |
816 | |
817 | /// Retrieve a suitable printing policy for diagnostics. |
818 | PrintingPolicy getPrintingPolicy() const { |
819 | return getPrintingPolicy(Ctx: Context, PP); |
820 | } |
821 | |
822 | /// Retrieve a suitable printing policy for diagnostics. |
823 | static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, |
824 | const Preprocessor &PP); |
825 | |
826 | /// Scope actions. |
827 | void ActOnTranslationUnitScope(Scope *S); |
828 | |
829 | /// Determine whether \param D is function like (function or function |
830 | /// template) for parsing. |
831 | bool isDeclaratorFunctionLike(Declarator &D); |
832 | |
833 | /// The maximum alignment, same as in llvm::Value. We duplicate them here |
834 | /// because that allows us not to duplicate the constants in clang code, |
835 | /// which we must to since we can't directly use the llvm constants. |
836 | /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp |
837 | /// |
838 | /// This is the greatest alignment value supported by load, store, and alloca |
839 | /// instructions, and global values. |
840 | static const unsigned MaxAlignmentExponent = 32; |
841 | static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent; |
842 | |
843 | /// Flag indicating whether or not to collect detailed statistics. |
844 | bool CollectStats; |
845 | |
846 | std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; |
847 | |
848 | /// Stack containing information about each of the nested |
849 | /// function, block, and method scopes that are currently active. |
850 | SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; |
851 | |
852 | /// The index of the first FunctionScope that corresponds to the current |
853 | /// context. |
854 | unsigned FunctionScopesStart = 0; |
855 | |
856 | /// Track the number of currently active capturing scopes. |
857 | unsigned CapturingFunctionScopes = 0; |
858 | |
859 | llvm::BumpPtrAllocator BumpAlloc; |
860 | |
861 | /// The kind of translation unit we are processing. |
862 | /// |
863 | /// When we're processing a complete translation unit, Sema will perform |
864 | /// end-of-translation-unit semantic tasks (such as creating |
865 | /// initializers for tentative definitions in C) once parsing has |
866 | /// completed. Modules and precompiled headers perform different kinds of |
867 | /// checks. |
868 | const TranslationUnitKind TUKind; |
869 | |
870 | /// Translation Unit Scope - useful to Objective-C actions that need |
871 | /// to lookup file scope declarations in the "ordinary" C decl namespace. |
872 | /// For example, user-defined classes, built-in "id" type, etc. |
873 | Scope *TUScope; |
874 | |
875 | void incrementMSManglingNumber() const { |
876 | return CurScope->incrementMSManglingNumber(); |
877 | } |
878 | |
879 | /// Try to recover by turning the given expression into a |
880 | /// call. Returns true if recovery was attempted or an error was |
881 | /// emitted; this may also leave the ExprResult invalid. |
882 | bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, |
883 | bool ForceComplain = false, |
884 | bool (*IsPlausibleResult)(QualType) = nullptr); |
885 | |
886 | /// Figure out if an expression could be turned into a call. |
887 | /// |
888 | /// Use this when trying to recover from an error where the programmer may |
889 | /// have written just the name of a function instead of actually calling it. |
890 | /// |
891 | /// \param E - The expression to examine. |
892 | /// \param ZeroArgCallReturnTy - If the expression can be turned into a call |
893 | /// with no arguments, this parameter is set to the type returned by such a |
894 | /// call; otherwise, it is set to an empty QualType. |
895 | /// \param OverloadSet - If the expression is an overloaded function |
896 | /// name, this parameter is populated with the decls of the various |
897 | /// overloads. |
898 | bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, |
899 | UnresolvedSetImpl &NonTemplateOverloads); |
900 | |
901 | typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; |
902 | typedef OpaquePtr<TemplateName> TemplateTy; |
903 | typedef OpaquePtr<QualType> TypeTy; |
904 | |
905 | OpenCLOptions OpenCLFeatures; |
906 | FPOptions CurFPFeatures; |
907 | |
908 | const LangOptions &LangOpts; |
909 | Preprocessor &PP; |
910 | ASTContext &Context; |
911 | ASTConsumer &Consumer; |
912 | DiagnosticsEngine &Diags; |
913 | SourceManager &SourceMgr; |
914 | api_notes::APINotesManager APINotes; |
915 | |
916 | /// A RAII object to enter scope of a compound statement. |
917 | class CompoundScopeRAII { |
918 | public: |
919 | CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { |
920 | S.ActOnStartOfCompoundStmt(IsStmtExpr); |
921 | } |
922 | |
923 | ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } |
924 | |
925 | private: |
926 | Sema &S; |
927 | }; |
928 | |
929 | /// An RAII helper that pops function a function scope on exit. |
930 | struct FunctionScopeRAII { |
931 | Sema &S; |
932 | bool Active; |
933 | FunctionScopeRAII(Sema &S) : S(S), Active(true) {} |
934 | ~FunctionScopeRAII() { |
935 | if (Active) |
936 | S.PopFunctionScopeInfo(); |
937 | } |
938 | void disable() { Active = false; } |
939 | }; |
940 | |
941 | sema::FunctionScopeInfo *getCurFunction() const { |
942 | return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); |
943 | } |
944 | |
945 | /// Worker object for performing CFG-based warnings. |
946 | sema::AnalysisBasedWarnings AnalysisWarnings; |
947 | threadSafety::BeforeSet *ThreadSafetyDeclCache; |
948 | |
949 | /// Callback to the parser to parse templated functions when needed. |
950 | typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); |
951 | typedef void LateTemplateParserCleanupCB(void *P); |
952 | LateTemplateParserCB *LateTemplateParser; |
953 | LateTemplateParserCleanupCB *LateTemplateParserCleanup; |
954 | void *OpaqueParser; |
955 | |
956 | void SetLateTemplateParser(LateTemplateParserCB *LTP, |
957 | LateTemplateParserCleanupCB *LTPCleanup, void *P) { |
958 | LateTemplateParser = LTP; |
959 | LateTemplateParserCleanup = LTPCleanup; |
960 | OpaqueParser = P; |
961 | } |
962 | |
963 | /// Callback to the parser to parse a type expressed as a string. |
964 | std::function<TypeResult(StringRef, StringRef, SourceLocation)> |
965 | ParseTypeFromStringCallback; |
966 | |
967 | /// VAListTagName - The declaration name corresponding to __va_list_tag. |
968 | /// This is used as part of a hack to omit that class from ADL results. |
969 | DeclarationName VAListTagName; |
970 | |
971 | /// Is the last error level diagnostic immediate. This is used to determined |
972 | /// whether the next info diagnostic should be immediate. |
973 | bool IsLastErrorImmediate = true; |
974 | |
975 | class DelayedDiagnostics; |
976 | |
977 | class DelayedDiagnosticsState { |
978 | sema::DelayedDiagnosticPool *SavedPool = nullptr; |
979 | friend class Sema::DelayedDiagnostics; |
980 | }; |
981 | typedef DelayedDiagnosticsState ParsingDeclState; |
982 | typedef DelayedDiagnosticsState ProcessingContextState; |
983 | |
984 | /// A class which encapsulates the logic for delaying diagnostics |
985 | /// during parsing and other processing. |
986 | class DelayedDiagnostics { |
987 | /// The current pool of diagnostics into which delayed |
988 | /// diagnostics should go. |
989 | sema::DelayedDiagnosticPool *CurPool = nullptr; |
990 | |
991 | public: |
992 | DelayedDiagnostics() = default; |
993 | |
994 | /// Adds a delayed diagnostic. |
995 | void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h |
996 | |
997 | /// Determines whether diagnostics should be delayed. |
998 | bool shouldDelayDiagnostics() { return CurPool != nullptr; } |
999 | |
1000 | /// Returns the current delayed-diagnostics pool. |
1001 | sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } |
1002 | |
1003 | /// Enter a new scope. Access and deprecation diagnostics will be |
1004 | /// collected in this pool. |
1005 | DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { |
1006 | DelayedDiagnosticsState state; |
1007 | state.SavedPool = CurPool; |
1008 | CurPool = &pool; |
1009 | return state; |
1010 | } |
1011 | |
1012 | /// Leave a delayed-diagnostic state that was previously pushed. |
1013 | /// Do not emit any of the diagnostics. This is performed as part |
1014 | /// of the bookkeeping of popping a pool "properly". |
1015 | void popWithoutEmitting(DelayedDiagnosticsState state) { |
1016 | CurPool = state.SavedPool; |
1017 | } |
1018 | |
1019 | /// Enter a new scope where access and deprecation diagnostics are |
1020 | /// not delayed. |
1021 | DelayedDiagnosticsState pushUndelayed() { |
1022 | DelayedDiagnosticsState state; |
1023 | state.SavedPool = CurPool; |
1024 | CurPool = nullptr; |
1025 | return state; |
1026 | } |
1027 | |
1028 | /// Undo a previous pushUndelayed(). |
1029 | void popUndelayed(DelayedDiagnosticsState state) { |
1030 | assert(CurPool == nullptr); |
1031 | CurPool = state.SavedPool; |
1032 | } |
1033 | } DelayedDiagnostics; |
1034 | |
1035 | ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { |
1036 | return DelayedDiagnostics.push(pool); |
1037 | } |
1038 | |
1039 | /// Diagnostics that are emitted only if we discover that the given function |
1040 | /// must be codegen'ed. Because handling these correctly adds overhead to |
1041 | /// compilation, this is currently only enabled for CUDA compilations. |
1042 | SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags; |
1043 | |
1044 | /// CurContext - This is the current declaration context of parsing. |
1045 | DeclContext *CurContext; |
1046 | |
1047 | SemaAMDGPU &AMDGPU() { |
1048 | assert(AMDGPUPtr); |
1049 | return *AMDGPUPtr; |
1050 | } |
1051 | |
1052 | SemaARM &ARM() { |
1053 | assert(ARMPtr); |
1054 | return *ARMPtr; |
1055 | } |
1056 | |
1057 | SemaAVR &AVR() { |
1058 | assert(AVRPtr); |
1059 | return *AVRPtr; |
1060 | } |
1061 | |
1062 | SemaBPF &BPF() { |
1063 | assert(BPFPtr); |
1064 | return *BPFPtr; |
1065 | } |
1066 | |
1067 | SemaCodeCompletion &CodeCompletion() { |
1068 | assert(CodeCompletionPtr); |
1069 | return *CodeCompletionPtr; |
1070 | } |
1071 | |
1072 | SemaCUDA &CUDA() { |
1073 | assert(CUDAPtr); |
1074 | return *CUDAPtr; |
1075 | } |
1076 | |
1077 | SemaHLSL &HLSL() { |
1078 | assert(HLSLPtr); |
1079 | return *HLSLPtr; |
1080 | } |
1081 | |
1082 | SemaHexagon &Hexagon() { |
1083 | assert(HexagonPtr); |
1084 | return *HexagonPtr; |
1085 | } |
1086 | |
1087 | SemaLoongArch &LoongArch() { |
1088 | assert(LoongArchPtr); |
1089 | return *LoongArchPtr; |
1090 | } |
1091 | |
1092 | SemaM68k &M68k() { |
1093 | assert(M68kPtr); |
1094 | return *M68kPtr; |
1095 | } |
1096 | |
1097 | SemaMIPS &MIPS() { |
1098 | assert(MIPSPtr); |
1099 | return *MIPSPtr; |
1100 | } |
1101 | |
1102 | SemaMSP430 &MSP430() { |
1103 | assert(MSP430Ptr); |
1104 | return *MSP430Ptr; |
1105 | } |
1106 | |
1107 | SemaNVPTX &NVPTX() { |
1108 | assert(NVPTXPtr); |
1109 | return *NVPTXPtr; |
1110 | } |
1111 | |
1112 | SemaObjC &ObjC() { |
1113 | assert(ObjCPtr); |
1114 | return *ObjCPtr; |
1115 | } |
1116 | |
1117 | SemaOpenACC &OpenACC() { |
1118 | assert(OpenACCPtr); |
1119 | return *OpenACCPtr; |
1120 | } |
1121 | |
1122 | SemaOpenCL &OpenCL() { |
1123 | assert(OpenCLPtr); |
1124 | return *OpenCLPtr; |
1125 | } |
1126 | |
1127 | SemaOpenMP &OpenMP() { |
1128 | assert(OpenMPPtr && "SemaOpenMP is dead" ); |
1129 | return *OpenMPPtr; |
1130 | } |
1131 | |
1132 | SemaPPC &PPC() { |
1133 | assert(PPCPtr); |
1134 | return *PPCPtr; |
1135 | } |
1136 | |
1137 | SemaPseudoObject &PseudoObject() { |
1138 | assert(PseudoObjectPtr); |
1139 | return *PseudoObjectPtr; |
1140 | } |
1141 | |
1142 | SemaRISCV &RISCV() { |
1143 | assert(RISCVPtr); |
1144 | return *RISCVPtr; |
1145 | } |
1146 | |
1147 | SemaSPIRV &SPIRV() { |
1148 | assert(SPIRVPtr); |
1149 | return *SPIRVPtr; |
1150 | } |
1151 | |
1152 | SemaSYCL &SYCL() { |
1153 | assert(SYCLPtr); |
1154 | return *SYCLPtr; |
1155 | } |
1156 | |
1157 | SemaSwift &Swift() { |
1158 | assert(SwiftPtr); |
1159 | return *SwiftPtr; |
1160 | } |
1161 | |
1162 | SemaSystemZ &SystemZ() { |
1163 | assert(SystemZPtr); |
1164 | return *SystemZPtr; |
1165 | } |
1166 | |
1167 | SemaWasm &Wasm() { |
1168 | assert(WasmPtr); |
1169 | return *WasmPtr; |
1170 | } |
1171 | |
1172 | SemaX86 &X86() { |
1173 | assert(X86Ptr); |
1174 | return *X86Ptr; |
1175 | } |
1176 | |
1177 | /// Source of additional semantic information. |
1178 | IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource; |
1179 | |
1180 | protected: |
1181 | friend class Parser; |
1182 | friend class InitializationSequence; |
1183 | friend class ASTReader; |
1184 | friend class ASTDeclReader; |
1185 | friend class ASTWriter; |
1186 | |
1187 | private: |
1188 | std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo; |
1189 | bool WarnedDarwinSDKInfoMissing = false; |
1190 | |
1191 | StackExhaustionHandler StackHandler; |
1192 | |
1193 | Sema(const Sema &) = delete; |
1194 | void operator=(const Sema &) = delete; |
1195 | |
1196 | /// The handler for the FileChanged preprocessor events. |
1197 | /// |
1198 | /// Used for diagnostics that implement custom semantic analysis for #include |
1199 | /// directives, like -Wpragma-pack. |
1200 | sema::SemaPPCallbacks *SemaPPCallbackHandler; |
1201 | |
1202 | /// The parser's current scope. |
1203 | /// |
1204 | /// The parser maintains this state here. |
1205 | Scope *CurScope; |
1206 | |
1207 | mutable IdentifierInfo *Ident_super; |
1208 | |
1209 | std::unique_ptr<SemaAMDGPU> AMDGPUPtr; |
1210 | std::unique_ptr<SemaARM> ARMPtr; |
1211 | std::unique_ptr<SemaAVR> AVRPtr; |
1212 | std::unique_ptr<SemaBPF> BPFPtr; |
1213 | std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr; |
1214 | std::unique_ptr<SemaCUDA> CUDAPtr; |
1215 | std::unique_ptr<SemaHLSL> HLSLPtr; |
1216 | std::unique_ptr<SemaHexagon> HexagonPtr; |
1217 | std::unique_ptr<SemaLoongArch> LoongArchPtr; |
1218 | std::unique_ptr<SemaM68k> M68kPtr; |
1219 | std::unique_ptr<SemaMIPS> MIPSPtr; |
1220 | std::unique_ptr<SemaMSP430> MSP430Ptr; |
1221 | std::unique_ptr<SemaNVPTX> NVPTXPtr; |
1222 | std::unique_ptr<SemaObjC> ObjCPtr; |
1223 | std::unique_ptr<SemaOpenACC> OpenACCPtr; |
1224 | std::unique_ptr<SemaOpenCL> OpenCLPtr; |
1225 | std::unique_ptr<SemaOpenMP> OpenMPPtr; |
1226 | std::unique_ptr<SemaPPC> PPCPtr; |
1227 | std::unique_ptr<SemaPseudoObject> PseudoObjectPtr; |
1228 | std::unique_ptr<SemaRISCV> RISCVPtr; |
1229 | std::unique_ptr<SemaSPIRV> SPIRVPtr; |
1230 | std::unique_ptr<SemaSYCL> SYCLPtr; |
1231 | std::unique_ptr<SemaSwift> SwiftPtr; |
1232 | std::unique_ptr<SemaSystemZ> SystemZPtr; |
1233 | std::unique_ptr<SemaWasm> WasmPtr; |
1234 | std::unique_ptr<SemaX86> X86Ptr; |
1235 | |
1236 | ///@} |
1237 | |
1238 | // |
1239 | // |
1240 | // ------------------------------------------------------------------------- |
1241 | // |
1242 | // |
1243 | |
1244 | /// \name API Notes |
1245 | /// Implementations are in SemaAPINotes.cpp |
1246 | ///@{ |
1247 | |
1248 | public: |
1249 | /// Map any API notes provided for this declaration to attributes on the |
1250 | /// declaration. |
1251 | /// |
1252 | /// Triggered by declaration-attribute processing. |
1253 | void ProcessAPINotes(Decl *D); |
1254 | |
1255 | ///@} |
1256 | |
1257 | // |
1258 | // |
1259 | // ------------------------------------------------------------------------- |
1260 | // |
1261 | // |
1262 | |
1263 | /// \name C++ Access Control |
1264 | /// Implementations are in SemaAccess.cpp |
1265 | ///@{ |
1266 | |
1267 | public: |
1268 | enum AccessResult { |
1269 | AR_accessible, |
1270 | AR_inaccessible, |
1271 | AR_dependent, |
1272 | AR_delayed |
1273 | }; |
1274 | |
1275 | /// SetMemberAccessSpecifier - Set the access specifier of a member. |
1276 | /// Returns true on error (when the previous member decl access specifier |
1277 | /// is different from the new member decl access specifier). |
1278 | bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, |
1279 | NamedDecl *PrevMemberDecl, |
1280 | AccessSpecifier LexicalAS); |
1281 | |
1282 | /// Perform access-control checking on a previously-unresolved member |
1283 | /// access which has now been resolved to a member. |
1284 | AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, |
1285 | DeclAccessPair FoundDecl); |
1286 | AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, |
1287 | DeclAccessPair FoundDecl); |
1288 | |
1289 | /// Checks access to an overloaded operator new or delete. |
1290 | AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, |
1291 | SourceRange PlacementRange, |
1292 | CXXRecordDecl *NamingClass, |
1293 | DeclAccessPair FoundDecl, |
1294 | bool Diagnose = true); |
1295 | |
1296 | /// Checks access to a constructor. |
1297 | AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, |
1298 | DeclAccessPair FoundDecl, |
1299 | const InitializedEntity &Entity, |
1300 | bool IsCopyBindingRefToTemp = false); |
1301 | |
1302 | /// Checks access to a constructor. |
1303 | AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, |
1304 | DeclAccessPair FoundDecl, |
1305 | const InitializedEntity &Entity, |
1306 | const PartialDiagnostic &PDiag); |
1307 | AccessResult CheckDestructorAccess(SourceLocation Loc, |
1308 | CXXDestructorDecl *Dtor, |
1309 | const PartialDiagnostic &PDiag, |
1310 | QualType objectType = QualType()); |
1311 | |
1312 | /// Checks access to the target of a friend declaration. |
1313 | AccessResult CheckFriendAccess(NamedDecl *D); |
1314 | |
1315 | /// Checks access to a member. |
1316 | AccessResult CheckMemberAccess(SourceLocation UseLoc, |
1317 | CXXRecordDecl *NamingClass, |
1318 | DeclAccessPair Found); |
1319 | |
1320 | /// Checks implicit access to a member in a structured binding. |
1321 | AccessResult |
1322 | CheckStructuredBindingMemberAccess(SourceLocation UseLoc, |
1323 | CXXRecordDecl *DecomposedClass, |
1324 | DeclAccessPair Field); |
1325 | AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, |
1326 | const SourceRange &, |
1327 | DeclAccessPair FoundDecl); |
1328 | |
1329 | /// Checks access to an overloaded member operator, including |
1330 | /// conversion operators. |
1331 | AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, |
1332 | Expr *ArgExpr, |
1333 | DeclAccessPair FoundDecl); |
1334 | AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, |
1335 | ArrayRef<Expr *> ArgExprs, |
1336 | DeclAccessPair FoundDecl); |
1337 | AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, |
1338 | DeclAccessPair FoundDecl); |
1339 | |
1340 | /// Checks access for a hierarchy conversion. |
1341 | /// |
1342 | /// \param ForceCheck true if this check should be performed even if access |
1343 | /// control is disabled; some things rely on this for semantics |
1344 | /// \param ForceUnprivileged true if this check should proceed as if the |
1345 | /// context had no special privileges |
1346 | AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, |
1347 | QualType Derived, const CXXBasePath &Path, |
1348 | unsigned DiagID, bool ForceCheck = false, |
1349 | bool ForceUnprivileged = false); |
1350 | |
1351 | /// Checks access to all the declarations in the given result set. |
1352 | void CheckLookupAccess(const LookupResult &R); |
1353 | |
1354 | /// Checks access to Target from the given class. The check will take access |
1355 | /// specifiers into account, but no member access expressions and such. |
1356 | /// |
1357 | /// \param Target the declaration to check if it can be accessed |
1358 | /// \param NamingClass the class in which the lookup was started. |
1359 | /// \param BaseType type of the left side of member access expression. |
1360 | /// \p BaseType and \p NamingClass are used for C++ access control. |
1361 | /// Depending on the lookup case, they should be set to the following: |
1362 | /// - lhs.target (member access without a qualifier): |
1363 | /// \p BaseType and \p NamingClass are both the type of 'lhs'. |
1364 | /// - lhs.X::target (member access with a qualifier): |
1365 | /// BaseType is the type of 'lhs', NamingClass is 'X' |
1366 | /// - X::target (qualified lookup without member access): |
1367 | /// BaseType is null, NamingClass is 'X'. |
1368 | /// - target (unqualified lookup). |
1369 | /// BaseType is null, NamingClass is the parent class of 'target'. |
1370 | /// \return true if the Target is accessible from the Class, false otherwise. |
1371 | bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, |
1372 | QualType BaseType); |
1373 | |
1374 | /// Is the given member accessible for the purposes of deciding whether to |
1375 | /// define a special member function as deleted? |
1376 | bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, |
1377 | DeclAccessPair Found, QualType ObjectType, |
1378 | SourceLocation Loc, |
1379 | const PartialDiagnostic &Diag); |
1380 | bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, |
1381 | DeclAccessPair Found, |
1382 | QualType ObjectType) { |
1383 | return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, |
1384 | SourceLocation(), PDiag()); |
1385 | } |
1386 | |
1387 | void HandleDependentAccessCheck( |
1388 | const DependentDiagnostic &DD, |
1389 | const MultiLevelTemplateArgumentList &TemplateArgs); |
1390 | void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); |
1391 | |
1392 | ///@} |
1393 | |
1394 | // |
1395 | // |
1396 | // ------------------------------------------------------------------------- |
1397 | // |
1398 | // |
1399 | |
1400 | /// \name Attributes |
1401 | /// Implementations are in SemaAttr.cpp |
1402 | ///@{ |
1403 | |
1404 | public: |
1405 | /// Controls member pointer representation format under the MS ABI. |
1406 | LangOptions::PragmaMSPointersToMembersKind |
1407 | MSPointerToMemberRepresentationMethod; |
1408 | |
1409 | bool MSStructPragmaOn; // True when \#pragma ms_struct on |
1410 | |
1411 | /// Source location for newly created implicit MSInheritanceAttrs |
1412 | SourceLocation ImplicitMSInheritanceAttrLoc; |
1413 | |
1414 | /// pragma clang section kind |
1415 | enum PragmaClangSectionKind { |
1416 | PCSK_Invalid = 0, |
1417 | PCSK_BSS = 1, |
1418 | PCSK_Data = 2, |
1419 | PCSK_Rodata = 3, |
1420 | PCSK_Text = 4, |
1421 | PCSK_Relro = 5 |
1422 | }; |
1423 | |
1424 | enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; |
1425 | |
1426 | struct PragmaClangSection { |
1427 | std::string SectionName; |
1428 | bool Valid = false; |
1429 | SourceLocation PragmaLocation; |
1430 | }; |
1431 | |
1432 | PragmaClangSection PragmaClangBSSSection; |
1433 | PragmaClangSection PragmaClangDataSection; |
1434 | PragmaClangSection PragmaClangRodataSection; |
1435 | PragmaClangSection PragmaClangRelroSection; |
1436 | PragmaClangSection PragmaClangTextSection; |
1437 | |
1438 | enum PragmaMsStackAction { |
1439 | PSK_Reset = 0x0, // #pragma () |
1440 | PSK_Set = 0x1, // #pragma (value) |
1441 | PSK_Push = 0x2, // #pragma (push[, id]) |
1442 | PSK_Pop = 0x4, // #pragma (pop[, id]) |
1443 | PSK_Show = 0x8, // #pragma (show) -- only for "pack"! |
1444 | PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) |
1445 | PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) |
1446 | }; |
1447 | |
1448 | struct PragmaPackInfo { |
1449 | PragmaMsStackAction Action; |
1450 | StringRef SlotLabel; |
1451 | Token Alignment; |
1452 | }; |
1453 | |
1454 | // #pragma pack and align. |
1455 | class AlignPackInfo { |
1456 | public: |
1457 | // `Native` represents default align mode, which may vary based on the |
1458 | // platform. |
1459 | enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; |
1460 | |
1461 | // #pragma pack info constructor |
1462 | AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) |
1463 | : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { |
1464 | assert(Num == PackNumber && "The pack number has been truncated." ); |
1465 | } |
1466 | |
1467 | // #pragma align info constructor |
1468 | AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) |
1469 | : PackAttr(false), AlignMode(M), |
1470 | PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} |
1471 | |
1472 | explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} |
1473 | |
1474 | AlignPackInfo() : AlignPackInfo(Native, false) {} |
1475 | |
1476 | // When a AlignPackInfo itself cannot be used, this returns an 32-bit |
1477 | // integer encoding for it. This should only be passed to |
1478 | // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. |
1479 | static uint32_t getRawEncoding(const AlignPackInfo &Info) { |
1480 | std::uint32_t Encoding{}; |
1481 | if (Info.IsXLStack()) |
1482 | Encoding |= IsXLMask; |
1483 | |
1484 | Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; |
1485 | |
1486 | if (Info.IsPackAttr()) |
1487 | Encoding |= PackAttrMask; |
1488 | |
1489 | Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; |
1490 | |
1491 | return Encoding; |
1492 | } |
1493 | |
1494 | static AlignPackInfo getFromRawEncoding(unsigned Encoding) { |
1495 | bool IsXL = static_cast<bool>(Encoding & IsXLMask); |
1496 | AlignPackInfo::Mode M = |
1497 | static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); |
1498 | int PackNumber = (Encoding & PackNumMask) >> 4; |
1499 | |
1500 | if (Encoding & PackAttrMask) |
1501 | return AlignPackInfo(M, PackNumber, IsXL); |
1502 | |
1503 | return AlignPackInfo(M, IsXL); |
1504 | } |
1505 | |
1506 | bool IsPackAttr() const { return PackAttr; } |
1507 | |
1508 | bool IsAlignAttr() const { return !PackAttr; } |
1509 | |
1510 | Mode getAlignMode() const { return AlignMode; } |
1511 | |
1512 | unsigned getPackNumber() const { return PackNumber; } |
1513 | |
1514 | bool IsPackSet() const { |
1515 | // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack |
1516 | // attriute on a decl. |
1517 | return PackNumber != UninitPackVal && PackNumber != 0; |
1518 | } |
1519 | |
1520 | bool IsXLStack() const { return XLStack; } |
1521 | |
1522 | bool operator==(const AlignPackInfo &Info) const { |
1523 | return std::tie(args: AlignMode, args: PackNumber, args: PackAttr, args: XLStack) == |
1524 | std::tie(args: Info.AlignMode, args: Info.PackNumber, args: Info.PackAttr, |
1525 | args: Info.XLStack); |
1526 | } |
1527 | |
1528 | bool operator!=(const AlignPackInfo &Info) const { |
1529 | return !(*this == Info); |
1530 | } |
1531 | |
1532 | private: |
1533 | /// \brief True if this is a pragma pack attribute, |
1534 | /// not a pragma align attribute. |
1535 | bool PackAttr; |
1536 | |
1537 | /// \brief The alignment mode that is in effect. |
1538 | Mode AlignMode; |
1539 | |
1540 | /// \brief The pack number of the stack. |
1541 | unsigned char PackNumber; |
1542 | |
1543 | /// \brief True if it is a XL #pragma align/pack stack. |
1544 | bool XLStack; |
1545 | |
1546 | /// \brief Uninitialized pack value. |
1547 | static constexpr unsigned char UninitPackVal = -1; |
1548 | |
1549 | // Masks to encode and decode an AlignPackInfo. |
1550 | static constexpr uint32_t IsXLMask{0x0000'0001}; |
1551 | static constexpr uint32_t AlignModeMask{0x0000'0006}; |
1552 | static constexpr uint32_t PackAttrMask{0x00000'0008}; |
1553 | static constexpr uint32_t PackNumMask{0x0000'01F0}; |
1554 | }; |
1555 | |
1556 | template <typename ValueType> struct PragmaStack { |
1557 | struct Slot { |
1558 | llvm::StringRef StackSlotLabel; |
1559 | ValueType Value; |
1560 | SourceLocation PragmaLocation; |
1561 | SourceLocation PragmaPushLocation; |
1562 | Slot(llvm::StringRef StackSlotLabel, ValueType Value, |
1563 | SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) |
1564 | : StackSlotLabel(StackSlotLabel), Value(Value), |
1565 | PragmaLocation(PragmaLocation), |
1566 | PragmaPushLocation(PragmaPushLocation) {} |
1567 | }; |
1568 | |
1569 | void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, |
1570 | llvm::StringRef StackSlotLabel, ValueType Value) { |
1571 | if (Action == PSK_Reset) { |
1572 | CurrentValue = DefaultValue; |
1573 | CurrentPragmaLocation = PragmaLocation; |
1574 | return; |
1575 | } |
1576 | if (Action & PSK_Push) |
1577 | Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, |
1578 | PragmaLocation); |
1579 | else if (Action & PSK_Pop) { |
1580 | if (!StackSlotLabel.empty()) { |
1581 | // If we've got a label, try to find it and jump there. |
1582 | auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { |
1583 | return x.StackSlotLabel == StackSlotLabel; |
1584 | }); |
1585 | // If we found the label so pop from there. |
1586 | if (I != Stack.rend()) { |
1587 | CurrentValue = I->Value; |
1588 | CurrentPragmaLocation = I->PragmaLocation; |
1589 | Stack.erase(std::prev(I.base()), Stack.end()); |
1590 | } |
1591 | } else if (!Stack.empty()) { |
1592 | // We do not have a label, just pop the last entry. |
1593 | CurrentValue = Stack.back().Value; |
1594 | CurrentPragmaLocation = Stack.back().PragmaLocation; |
1595 | Stack.pop_back(); |
1596 | } |
1597 | } |
1598 | if (Action & PSK_Set) { |
1599 | CurrentValue = Value; |
1600 | CurrentPragmaLocation = PragmaLocation; |
1601 | } |
1602 | } |
1603 | |
1604 | // MSVC seems to add artificial slots to #pragma stacks on entering a C++ |
1605 | // method body to restore the stacks on exit, so it works like this: |
1606 | // |
1607 | // struct S { |
1608 | // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) |
1609 | // void Method {} |
1610 | // #pragma <name>(pop, InternalPragmaSlot) |
1611 | // }; |
1612 | // |
1613 | // It works even with #pragma vtordisp, although MSVC doesn't support |
1614 | // #pragma vtordisp(push [, id], n) |
1615 | // syntax. |
1616 | // |
1617 | // Push / pop a named sentinel slot. |
1618 | void SentinelAction(PragmaMsStackAction Action, StringRef Label) { |
1619 | assert((Action == PSK_Push || Action == PSK_Pop) && |
1620 | "Can only push / pop #pragma stack sentinels!" ); |
1621 | Act(PragmaLocation: CurrentPragmaLocation, Action, StackSlotLabel: Label, Value: CurrentValue); |
1622 | } |
1623 | |
1624 | // Constructors. |
1625 | explicit PragmaStack(const ValueType &Default) |
1626 | : DefaultValue(Default), CurrentValue(Default) {} |
1627 | |
1628 | bool hasValue() const { return CurrentValue != DefaultValue; } |
1629 | |
1630 | SmallVector<Slot, 2> Stack; |
1631 | ValueType DefaultValue; // Value used for PSK_Reset action. |
1632 | ValueType CurrentValue; |
1633 | SourceLocation CurrentPragmaLocation; |
1634 | }; |
1635 | // FIXME: We should serialize / deserialize these if they occur in a PCH (but |
1636 | // we shouldn't do so if they're in a module). |
1637 | |
1638 | /// Whether to insert vtordisps prior to virtual bases in the Microsoft |
1639 | /// C++ ABI. Possible values are 0, 1, and 2, which mean: |
1640 | /// |
1641 | /// 0: Suppress all vtordisps |
1642 | /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial |
1643 | /// structors |
1644 | /// 2: Always insert vtordisps to support RTTI on partially constructed |
1645 | /// objects |
1646 | PragmaStack<MSVtorDispMode> VtorDispStack; |
1647 | PragmaStack<AlignPackInfo> AlignPackStack; |
1648 | // The current #pragma align/pack values and locations at each #include. |
1649 | struct AlignPackIncludeState { |
1650 | AlignPackInfo CurrentValue; |
1651 | SourceLocation CurrentPragmaLocation; |
1652 | bool HasNonDefaultValue, ShouldWarnOnInclude; |
1653 | }; |
1654 | SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; |
1655 | // Segment #pragmas. |
1656 | PragmaStack<StringLiteral *> DataSegStack; |
1657 | PragmaStack<StringLiteral *> BSSSegStack; |
1658 | PragmaStack<StringLiteral *> ConstSegStack; |
1659 | PragmaStack<StringLiteral *> CodeSegStack; |
1660 | |
1661 | // #pragma strict_gs_check. |
1662 | PragmaStack<bool> StrictGuardStackCheckStack; |
1663 | |
1664 | // This stack tracks the current state of Sema.CurFPFeatures. |
1665 | PragmaStack<FPOptionsOverride> FpPragmaStack; |
1666 | FPOptionsOverride CurFPFeatureOverrides() { |
1667 | FPOptionsOverride result; |
1668 | if (!FpPragmaStack.hasValue()) { |
1669 | result = FPOptionsOverride(); |
1670 | } else { |
1671 | result = FpPragmaStack.CurrentValue; |
1672 | } |
1673 | return result; |
1674 | } |
1675 | |
1676 | enum PragmaSectionKind { |
1677 | PSK_DataSeg, |
1678 | PSK_BSSSeg, |
1679 | PSK_ConstSeg, |
1680 | PSK_CodeSeg, |
1681 | }; |
1682 | |
1683 | // RAII object to push / pop sentinel slots for all MS #pragma stacks. |
1684 | // Actions should be performed only if we enter / exit a C++ method body. |
1685 | class PragmaStackSentinelRAII { |
1686 | public: |
1687 | PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); |
1688 | ~PragmaStackSentinelRAII(); |
1689 | |
1690 | private: |
1691 | Sema &S; |
1692 | StringRef SlotLabel; |
1693 | bool ShouldAct; |
1694 | }; |
1695 | |
1696 | /// Last section used with #pragma init_seg. |
1697 | StringLiteral *CurInitSeg; |
1698 | SourceLocation CurInitSegLoc; |
1699 | |
1700 | /// Sections used with #pragma alloc_text. |
1701 | llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap; |
1702 | |
1703 | /// VisContext - Manages the stack for \#pragma GCC visibility. |
1704 | void *VisContext; // Really a "PragmaVisStack*" |
1705 | |
1706 | /// This an attribute introduced by \#pragma clang attribute. |
1707 | struct PragmaAttributeEntry { |
1708 | SourceLocation Loc; |
1709 | ParsedAttr *Attribute; |
1710 | SmallVector<attr::SubjectMatchRule, 4> MatchRules; |
1711 | bool IsUsed; |
1712 | }; |
1713 | |
1714 | /// A push'd group of PragmaAttributeEntries. |
1715 | struct PragmaAttributeGroup { |
1716 | /// The location of the push attribute. |
1717 | SourceLocation Loc; |
1718 | /// The namespace of this push group. |
1719 | const IdentifierInfo *Namespace; |
1720 | SmallVector<PragmaAttributeEntry, 2> Entries; |
1721 | }; |
1722 | |
1723 | SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; |
1724 | |
1725 | /// The declaration that is currently receiving an attribute from the |
1726 | /// #pragma attribute stack. |
1727 | const Decl *PragmaAttributeCurrentTargetDecl; |
1728 | |
1729 | /// This represents the last location of a "#pragma clang optimize off" |
1730 | /// directive if such a directive has not been closed by an "on" yet. If |
1731 | /// optimizations are currently "on", this is set to an invalid location. |
1732 | SourceLocation OptimizeOffPragmaLocation; |
1733 | |
1734 | /// Get the location for the currently active "\#pragma clang optimize |
1735 | /// off". If this location is invalid, then the state of the pragma is "on". |
1736 | SourceLocation getOptimizeOffPragmaLocation() const { |
1737 | return OptimizeOffPragmaLocation; |
1738 | } |
1739 | |
1740 | /// The "on" or "off" argument passed by \#pragma optimize, that denotes |
1741 | /// whether the optimizations in the list passed to the pragma should be |
1742 | /// turned off or on. This boolean is true by default because command line |
1743 | /// options are honored when `#pragma optimize("", on)`. |
1744 | /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing) |
1745 | bool MSPragmaOptimizeIsOn = true; |
1746 | |
1747 | /// Set of no-builtin functions listed by \#pragma function. |
1748 | llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins; |
1749 | |
1750 | /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to |
1751 | /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. |
1752 | void AddAlignmentAttributesForRecord(RecordDecl *RD); |
1753 | |
1754 | /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. |
1755 | void AddMsStructLayoutForRecord(RecordDecl *RD); |
1756 | |
1757 | /// Add gsl::Pointer attribute to std::container::iterator |
1758 | /// \param ND The declaration that introduces the name |
1759 | /// std::container::iterator. \param UnderlyingRecord The record named by ND. |
1760 | void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); |
1761 | |
1762 | /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. |
1763 | void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); |
1764 | |
1765 | /// Add [[clang:::lifetimebound]] attr for std:: functions and methods. |
1766 | void inferLifetimeBoundAttribute(FunctionDecl *FD); |
1767 | |
1768 | /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods. |
1769 | void inferLifetimeCaptureByAttribute(FunctionDecl *FD); |
1770 | |
1771 | /// Add [[gsl::Pointer]] attributes for std:: types. |
1772 | void inferGslPointerAttribute(TypedefNameDecl *TD); |
1773 | |
1774 | LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL, |
1775 | StringRef ParamName); |
1776 | // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X' |
1777 | // can be the name of a function parameter, we need to parse the function |
1778 | // declaration and rest of the parameters before processesing 'X'. Therefore |
1779 | // do this lazily instead of processing while parsing the annotation itself. |
1780 | void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD); |
1781 | |
1782 | /// Add _Nullable attributes for std:: types. |
1783 | void inferNullableClassAttribute(CXXRecordDecl *CRD); |
1784 | |
1785 | enum PragmaOptionsAlignKind { |
1786 | POAK_Native, // #pragma options align=native |
1787 | POAK_Natural, // #pragma options align=natural |
1788 | POAK_Packed, // #pragma options align=packed |
1789 | POAK_Power, // #pragma options align=power |
1790 | POAK_Mac68k, // #pragma options align=mac68k |
1791 | POAK_Reset // #pragma options align=reset |
1792 | }; |
1793 | |
1794 | /// ActOnPragmaClangSection - Called on well formed \#pragma clang section |
1795 | void ActOnPragmaClangSection(SourceLocation PragmaLoc, |
1796 | PragmaClangSectionAction Action, |
1797 | PragmaClangSectionKind SecKind, |
1798 | StringRef SecName); |
1799 | |
1800 | /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. |
1801 | void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, |
1802 | SourceLocation PragmaLoc); |
1803 | |
1804 | /// ActOnPragmaPack - Called on well formed \#pragma pack(...). |
1805 | void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, |
1806 | StringRef SlotLabel, Expr *Alignment); |
1807 | |
1808 | /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs |
1809 | /// (unless they are value dependent or type dependent). Returns false |
1810 | /// and emits a diagnostic if one or more of the arguments could not be |
1811 | /// folded into a constant. |
1812 | bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, |
1813 | MutableArrayRef<Expr *> Args); |
1814 | |
1815 | enum class PragmaAlignPackDiagnoseKind { |
1816 | NonDefaultStateAtInclude, |
1817 | ChangedStateAtExit |
1818 | }; |
1819 | |
1820 | void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, |
1821 | SourceLocation IncludeLoc); |
1822 | void DiagnoseUnterminatedPragmaAlignPack(); |
1823 | |
1824 | /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. |
1825 | void ActOnPragmaMSStruct(PragmaMSStructKind Kind); |
1826 | |
1827 | /// ActOnPragmaMSComment - Called on well formed |
1828 | /// \#pragma comment(kind, "arg"). |
1829 | void (SourceLocation , PragmaMSCommentKind Kind, |
1830 | StringRef Arg); |
1831 | |
1832 | /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch |
1833 | void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, |
1834 | StringRef Value); |
1835 | |
1836 | /// Are precise floating point semantics currently enabled? |
1837 | bool isPreciseFPEnabled() { |
1838 | return !CurFPFeatures.getAllowFPReassociate() && |
1839 | !CurFPFeatures.getNoSignedZero() && |
1840 | !CurFPFeatures.getAllowReciprocal() && |
1841 | !CurFPFeatures.getAllowApproxFunc(); |
1842 | } |
1843 | |
1844 | void ActOnPragmaFPEvalMethod(SourceLocation Loc, |
1845 | LangOptions::FPEvalMethodKind Value); |
1846 | |
1847 | /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control |
1848 | void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, |
1849 | PragmaFloatControlKind Value); |
1850 | |
1851 | /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma |
1852 | /// pointers_to_members(representation method[, general purpose |
1853 | /// representation]). |
1854 | void ActOnPragmaMSPointersToMembers( |
1855 | LangOptions::PragmaMSPointersToMembersKind Kind, |
1856 | SourceLocation PragmaLoc); |
1857 | |
1858 | /// Called on well formed \#pragma vtordisp(). |
1859 | void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, |
1860 | SourceLocation PragmaLoc, MSVtorDispMode Value); |
1861 | |
1862 | bool UnifySection(StringRef SectionName, int SectionFlags, |
1863 | NamedDecl *TheDecl); |
1864 | bool UnifySection(StringRef SectionName, int SectionFlags, |
1865 | SourceLocation PragmaSectionLocation); |
1866 | |
1867 | /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. |
1868 | void ActOnPragmaMSSeg(SourceLocation PragmaLocation, |
1869 | PragmaMsStackAction Action, |
1870 | llvm::StringRef StackSlotLabel, |
1871 | StringLiteral *SegmentName, llvm::StringRef PragmaName); |
1872 | |
1873 | /// Called on well formed \#pragma section(). |
1874 | void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, |
1875 | StringLiteral *SegmentName); |
1876 | |
1877 | /// Called on well-formed \#pragma init_seg(). |
1878 | void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, |
1879 | StringLiteral *SegmentName); |
1880 | |
1881 | /// Called on well-formed \#pragma alloc_text(). |
1882 | void ActOnPragmaMSAllocText( |
1883 | SourceLocation PragmaLocation, StringRef Section, |
1884 | const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>> |
1885 | &Functions); |
1886 | |
1887 | /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma |
1888 | /// strict_gs_check. |
1889 | void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation, |
1890 | PragmaMsStackAction Action, |
1891 | bool Value); |
1892 | |
1893 | /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. |
1894 | void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, |
1895 | SourceLocation PragmaLoc); |
1896 | |
1897 | void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, |
1898 | SourceLocation PragmaLoc, |
1899 | attr::ParsedSubjectMatchRuleSet Rules); |
1900 | void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, |
1901 | const IdentifierInfo *Namespace); |
1902 | |
1903 | /// Called on well-formed '\#pragma clang attribute pop'. |
1904 | void ActOnPragmaAttributePop(SourceLocation PragmaLoc, |
1905 | const IdentifierInfo *Namespace); |
1906 | |
1907 | /// Adds the attributes that have been specified using the |
1908 | /// '\#pragma clang attribute push' directives to the given declaration. |
1909 | void AddPragmaAttributes(Scope *S, Decl *D); |
1910 | |
1911 | void PrintPragmaAttributeInstantiationPoint(); |
1912 | |
1913 | void DiagnoseUnterminatedPragmaAttribute(); |
1914 | |
1915 | /// Called on well formed \#pragma clang optimize. |
1916 | void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); |
1917 | |
1918 | /// #pragma optimize("[optimization-list]", on | off). |
1919 | void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn); |
1920 | |
1921 | /// Call on well formed \#pragma function. |
1922 | void |
1923 | ActOnPragmaMSFunction(SourceLocation Loc, |
1924 | const llvm::SmallVectorImpl<StringRef> &NoBuiltins); |
1925 | |
1926 | /// Only called on function definitions; if there is a pragma in scope |
1927 | /// with the effect of a range-based optnone, consider marking the function |
1928 | /// with attribute optnone. |
1929 | void AddRangeBasedOptnone(FunctionDecl *FD); |
1930 | |
1931 | /// Only called on function definitions; if there is a `#pragma alloc_text` |
1932 | /// that decides which code section the function should be in, add |
1933 | /// attribute section to the function. |
1934 | void AddSectionMSAllocText(FunctionDecl *FD); |
1935 | |
1936 | /// Adds the 'optnone' attribute to the function declaration if there |
1937 | /// are no conflicts; Loc represents the location causing the 'optnone' |
1938 | /// attribute to be added (usually because of a pragma). |
1939 | void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); |
1940 | |
1941 | /// Only called on function definitions; if there is a MSVC #pragma optimize |
1942 | /// in scope, consider changing the function's attributes based on the |
1943 | /// optimization list passed to the pragma. |
1944 | void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD); |
1945 | |
1946 | /// Only called on function definitions; if there is a pragma in scope |
1947 | /// with the effect of a range-based no_builtin, consider marking the function |
1948 | /// with attribute no_builtin. |
1949 | void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD); |
1950 | |
1951 | /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, |
1952 | /// add an appropriate visibility attribute. |
1953 | void AddPushedVisibilityAttribute(Decl *RD); |
1954 | |
1955 | /// FreeVisContext - Deallocate and null out VisContext. |
1956 | void FreeVisContext(); |
1957 | |
1958 | /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . |
1959 | void ActOnPragmaVisibility(const IdentifierInfo *VisType, |
1960 | SourceLocation PragmaLoc); |
1961 | |
1962 | /// ActOnPragmaFPContract - Called on well formed |
1963 | /// \#pragma {STDC,OPENCL} FP_CONTRACT and |
1964 | /// \#pragma clang fp contract |
1965 | void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); |
1966 | |
1967 | /// Called on well formed |
1968 | /// \#pragma clang fp reassociate |
1969 | /// or |
1970 | /// \#pragma clang fp reciprocal |
1971 | void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind, |
1972 | bool IsEnabled); |
1973 | |
1974 | /// ActOnPragmaFenvAccess - Called on well formed |
1975 | /// \#pragma STDC FENV_ACCESS |
1976 | void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); |
1977 | |
1978 | /// ActOnPragmaCXLimitedRange - Called on well formed |
1979 | /// \#pragma STDC CX_LIMITED_RANGE |
1980 | void ActOnPragmaCXLimitedRange(SourceLocation Loc, |
1981 | LangOptions::ComplexRangeKind Range); |
1982 | |
1983 | /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. |
1984 | void ActOnPragmaFPExceptions(SourceLocation Loc, |
1985 | LangOptions::FPExceptionModeKind); |
1986 | |
1987 | /// Called to set constant rounding mode for floating point operations. |
1988 | void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode); |
1989 | |
1990 | /// Called to set exception behavior for floating point operations. |
1991 | void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); |
1992 | |
1993 | /// PushNamespaceVisibilityAttr - Note that we've entered a |
1994 | /// namespace with a visibility attribute. |
1995 | void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, |
1996 | SourceLocation Loc); |
1997 | |
1998 | /// PopPragmaVisibility - Pop the top element of the visibility stack; used |
1999 | /// for '\#pragma GCC visibility' and visibility attributes on namespaces. |
2000 | void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); |
2001 | |
2002 | /// Handles semantic checking for features that are common to all attributes, |
2003 | /// such as checking whether a parameter was properly specified, or the |
2004 | /// correct number of arguments were passed, etc. Returns true if the |
2005 | /// attribute has been diagnosed. |
2006 | bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A, |
2007 | bool SkipArgCountCheck = false); |
2008 | bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A, |
2009 | bool SkipArgCountCheck = false); |
2010 | |
2011 | ///@} |
2012 | |
2013 | // |
2014 | // |
2015 | // ------------------------------------------------------------------------- |
2016 | // |
2017 | // |
2018 | |
2019 | /// \name Availability Attribute Handling |
2020 | /// Implementations are in SemaAvailability.cpp |
2021 | ///@{ |
2022 | |
2023 | public: |
2024 | /// Issue any -Wunguarded-availability warnings in \c FD |
2025 | void DiagnoseUnguardedAvailabilityViolations(Decl *FD); |
2026 | |
2027 | void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); |
2028 | |
2029 | /// Retrieve the current function, if any, that should be analyzed for |
2030 | /// potential availability violations. |
2031 | sema::FunctionScopeInfo *getCurFunctionAvailabilityContext(); |
2032 | |
2033 | void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, |
2034 | const ObjCInterfaceDecl *UnknownObjCClass, |
2035 | bool ObjCPropertyAccess, |
2036 | bool AvoidPartialAvailabilityChecks = false, |
2037 | ObjCInterfaceDecl *ClassReceiver = nullptr); |
2038 | |
2039 | ///@} |
2040 | |
2041 | // |
2042 | // |
2043 | // ------------------------------------------------------------------------- |
2044 | // |
2045 | // |
2046 | |
2047 | /// \name Bounds Safety |
2048 | /// Implementations are in SemaBoundsSafety.cpp |
2049 | ///@{ |
2050 | public: |
2051 | /// Check if applying the specified attribute variant from the "counted by" |
2052 | /// family of attributes to FieldDecl \p FD is semantically valid. If |
2053 | /// semantically invalid diagnostics will be emitted explaining the problems. |
2054 | /// |
2055 | /// \param FD The FieldDecl to apply the attribute to |
2056 | /// \param E The count expression on the attribute |
2057 | /// \param CountInBytes If true the attribute is from the "sized_by" family of |
2058 | /// attributes. If the false the attribute is from |
2059 | /// "counted_by" family of attributes. |
2060 | /// \param OrNull If true the attribute is from the "_or_null" suffixed family |
2061 | /// of attributes. If false the attribute does not have the |
2062 | /// suffix. |
2063 | /// |
2064 | /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g. |
2065 | /// \p CountInBytes and \p OrNull both being true indicates the |
2066 | /// `counted_by_or_null` attribute. |
2067 | /// |
2068 | /// \returns false iff semantically valid. |
2069 | bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, |
2070 | bool OrNull); |
2071 | |
2072 | ///@} |
2073 | |
2074 | // |
2075 | // |
2076 | // ------------------------------------------------------------------------- |
2077 | // |
2078 | // |
2079 | |
2080 | /// \name Casts |
2081 | /// Implementations are in SemaCast.cpp |
2082 | ///@{ |
2083 | |
2084 | public: |
2085 | static bool isCast(CheckedConversionKind CCK) { |
2086 | return CCK == CheckedConversionKind::CStyleCast || |
2087 | CCK == CheckedConversionKind::FunctionalCast || |
2088 | CCK == CheckedConversionKind::OtherCast; |
2089 | } |
2090 | |
2091 | /// ActOnCXXNamedCast - Parse |
2092 | /// {dynamic,static,reinterpret,const,addrspace}_cast's. |
2093 | ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, |
2094 | SourceLocation LAngleBracketLoc, Declarator &D, |
2095 | SourceLocation RAngleBracketLoc, |
2096 | SourceLocation LParenLoc, Expr *E, |
2097 | SourceLocation RParenLoc); |
2098 | |
2099 | ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, |
2100 | TypeSourceInfo *Ty, Expr *E, |
2101 | SourceRange AngleBrackets, SourceRange Parens); |
2102 | |
2103 | ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, |
2104 | ExprResult Operand, |
2105 | SourceLocation RParenLoc); |
2106 | |
2107 | ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, |
2108 | Expr *Operand, SourceLocation RParenLoc); |
2109 | |
2110 | // Checks that reinterpret casts don't have undefined behavior. |
2111 | void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, |
2112 | bool IsDereference, SourceRange Range); |
2113 | |
2114 | // Checks that the vector type should be initialized from a scalar |
2115 | // by splatting the value rather than populating a single element. |
2116 | // This is the case for AltiVecVector types as well as with |
2117 | // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified. |
2118 | bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy); |
2119 | |
2120 | // Checks if the -faltivec-src-compat=gcc option is specified. |
2121 | // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are |
2122 | // treated the same way as they are when trying to initialize |
2123 | // these vectors on gcc (an error is emitted). |
2124 | bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, |
2125 | QualType SrcTy); |
2126 | |
2127 | ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, |
2128 | SourceLocation RParenLoc, Expr *Op); |
2129 | |
2130 | ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, |
2131 | SourceLocation LParenLoc, |
2132 | Expr *CastExpr, |
2133 | SourceLocation RParenLoc); |
2134 | |
2135 | ///@} |
2136 | |
2137 | // |
2138 | // |
2139 | // ------------------------------------------------------------------------- |
2140 | // |
2141 | // |
2142 | |
2143 | /// \name Extra Semantic Checking |
2144 | /// Implementations are in SemaChecking.cpp |
2145 | ///@{ |
2146 | |
2147 | public: |
2148 | /// Used to change context to isConstantEvaluated without pushing a heavy |
2149 | /// ExpressionEvaluationContextRecord object. |
2150 | bool isConstantEvaluatedOverride = false; |
2151 | |
2152 | bool isConstantEvaluatedContext() const { |
2153 | return currentEvaluationContext().isConstantEvaluated() || |
2154 | isConstantEvaluatedOverride; |
2155 | } |
2156 | |
2157 | SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, |
2158 | unsigned ByteNo) const; |
2159 | |
2160 | enum FormatArgumentPassingKind { |
2161 | FAPK_Fixed, // values to format are fixed (no C-style variadic arguments) |
2162 | FAPK_Variadic, // values to format are passed as variadic arguments |
2163 | FAPK_VAList, // values to format are passed in a va_list |
2164 | }; |
2165 | |
2166 | // Used to grab the relevant information from a FormatAttr and a |
2167 | // FunctionDeclaration. |
2168 | struct FormatStringInfo { |
2169 | unsigned FormatIdx; |
2170 | unsigned FirstDataArg; |
2171 | FormatArgumentPassingKind ArgPassingKind; |
2172 | }; |
2173 | |
2174 | /// Given a FunctionDecl's FormatAttr, attempts to populate the |
2175 | /// FomatStringInfo parameter with the FormatAttr's correct format_idx and |
2176 | /// firstDataArg. Returns true when the format fits the function and the |
2177 | /// FormatStringInfo has been populated. |
2178 | static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, |
2179 | bool IsVariadic, FormatStringInfo *FSI); |
2180 | |
2181 | // Used by C++ template instantiation. |
2182 | ExprResult BuiltinShuffleVector(CallExpr *TheCall); |
2183 | |
2184 | /// ConvertVectorExpr - Handle __builtin_convertvector |
2185 | ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, |
2186 | SourceLocation BuiltinLoc, |
2187 | SourceLocation RParenLoc); |
2188 | |
2189 | enum FormatStringType { |
2190 | FST_Scanf, |
2191 | FST_Printf, |
2192 | FST_NSString, |
2193 | FST_Strftime, |
2194 | FST_Strfmon, |
2195 | FST_Kprintf, |
2196 | FST_FreeBSDKPrintf, |
2197 | FST_OSTrace, |
2198 | FST_OSLog, |
2199 | FST_Syslog, |
2200 | FST_Unknown |
2201 | }; |
2202 | static FormatStringType GetFormatStringType(const FormatAttr *Format); |
2203 | |
2204 | bool FormatStringHasSArg(const StringLiteral *FExpr); |
2205 | |
2206 | /// Check for comparisons of floating-point values using == and !=. Issue a |
2207 | /// warning if the comparison is not likely to do what the programmer |
2208 | /// intended. |
2209 | void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, |
2210 | BinaryOperatorKind Opcode); |
2211 | |
2212 | /// Register a magic integral constant to be used as a type tag. |
2213 | void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, |
2214 | uint64_t MagicValue, QualType Type, |
2215 | bool LayoutCompatible, bool MustBeNull); |
2216 | |
2217 | struct TypeTagData { |
2218 | TypeTagData() {} |
2219 | |
2220 | TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) |
2221 | : Type(Type), LayoutCompatible(LayoutCompatible), |
2222 | MustBeNull(MustBeNull) {} |
2223 | |
2224 | QualType Type; |
2225 | |
2226 | /// If true, \c Type should be compared with other expression's types for |
2227 | /// layout-compatibility. |
2228 | LLVM_PREFERRED_TYPE(bool) |
2229 | unsigned LayoutCompatible : 1; |
2230 | LLVM_PREFERRED_TYPE(bool) |
2231 | unsigned MustBeNull : 1; |
2232 | }; |
2233 | |
2234 | /// A pair of ArgumentKind identifier and magic value. This uniquely |
2235 | /// identifies the magic value. |
2236 | typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; |
2237 | |
2238 | /// Diagnoses the current set of gathered accesses. This typically |
2239 | /// happens at full expression level. The set is cleared after emitting the |
2240 | /// diagnostics. |
2241 | void DiagnoseMisalignedMembers(); |
2242 | |
2243 | /// This function checks if the expression is in the sef of potentially |
2244 | /// misaligned members and it is converted to some pointer type T with lower |
2245 | /// or equal alignment requirements. If so it removes it. This is used when |
2246 | /// we do not want to diagnose such misaligned access (e.g. in conversions to |
2247 | /// void*). |
2248 | void DiscardMisalignedMemberAddress(const Type *T, Expr *E); |
2249 | |
2250 | /// This function calls Action when it determines that E designates a |
2251 | /// misaligned member due to the packed attribute. This is used to emit |
2252 | /// local diagnostics like in reference binding. |
2253 | void RefersToMemberWithReducedAlignment( |
2254 | Expr *E, |
2255 | llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> |
2256 | Action); |
2257 | |
2258 | enum class AtomicArgumentOrder { API, AST }; |
2259 | ExprResult |
2260 | BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, |
2261 | SourceLocation RParenLoc, MultiExprArg Args, |
2262 | AtomicExpr::AtomicOp Op, |
2263 | AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); |
2264 | |
2265 | /// Check to see if a given expression could have '.c_str()' called on it. |
2266 | bool hasCStrMethod(const Expr *E); |
2267 | |
2268 | /// Diagnose pointers that are always non-null. |
2269 | /// \param E the expression containing the pointer |
2270 | /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is |
2271 | /// compared to a null pointer |
2272 | /// \param IsEqual True when the comparison is equal to a null pointer |
2273 | /// \param Range Extra SourceRange to highlight in the diagnostic |
2274 | void DiagnoseAlwaysNonNullPointer(Expr *E, |
2275 | Expr::NullPointerConstantKind NullType, |
2276 | bool IsEqual, SourceRange Range); |
2277 | |
2278 | /// CheckParmsForFunctionDef - Check that the parameters of the given |
2279 | /// function are appropriate for the definition of a function. This |
2280 | /// takes care of any checks that cannot be performed on the |
2281 | /// declaration itself, e.g., that the types of each of the function |
2282 | /// parameters are complete. |
2283 | bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, |
2284 | bool CheckParameterNames); |
2285 | |
2286 | /// CheckCastAlign - Implements -Wcast-align, which warns when a |
2287 | /// pointer cast increases the alignment requirements. |
2288 | void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); |
2289 | |
2290 | /// checkUnsafeAssigns - Check whether +1 expr is being assigned |
2291 | /// to weak/__unsafe_unretained type. |
2292 | bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); |
2293 | |
2294 | /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned |
2295 | /// to weak/__unsafe_unretained expression. |
2296 | void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); |
2297 | |
2298 | /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null |
2299 | /// statement as a \p Body, and it is located on the same line. |
2300 | /// |
2301 | /// This helps prevent bugs due to typos, such as: |
2302 | /// if (condition); |
2303 | /// do_stuff(); |
2304 | void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, |
2305 | unsigned DiagID); |
2306 | |
2307 | /// Warn if a for/while loop statement \p S, which is followed by |
2308 | /// \p PossibleBody, has a suspicious null statement as a body. |
2309 | void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); |
2310 | |
2311 | /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. |
2312 | void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, |
2313 | SourceLocation OpLoc); |
2314 | |
2315 | // Used for emitting the right warning by DefaultVariadicArgumentPromotion |
2316 | enum VariadicCallType { |
2317 | VariadicFunction, |
2318 | VariadicBlock, |
2319 | VariadicMethod, |
2320 | VariadicConstructor, |
2321 | VariadicDoesNotApply |
2322 | }; |
2323 | |
2324 | bool IsLayoutCompatible(QualType T1, QualType T2) const; |
2325 | bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, |
2326 | const TypeSourceInfo *Derived); |
2327 | |
2328 | /// CheckFunctionCall - Check a direct function call for various correctness |
2329 | /// and safety properties not strictly enforced by the C type system. |
2330 | bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, |
2331 | const FunctionProtoType *Proto); |
2332 | |
2333 | /// \param FPOnly restricts the arguments to floating-point types. |
2334 | std::optional<QualType> BuiltinVectorMath(CallExpr *TheCall, |
2335 | bool FPOnly = false); |
2336 | bool BuiltinVectorToScalarMath(CallExpr *TheCall); |
2337 | |
2338 | void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, |
2339 | const Expr *ThisArg, ArrayRef<const Expr *> Args); |
2340 | |
2341 | /// Handles the checks for format strings, non-POD arguments to vararg |
2342 | /// functions, NULL arguments passed to non-NULL parameters, diagnose_if |
2343 | /// attributes and AArch64 SME attributes. |
2344 | void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, |
2345 | const Expr *ThisArg, ArrayRef<const Expr *> Args, |
2346 | bool IsMemberFunction, SourceLocation Loc, SourceRange Range, |
2347 | VariadicCallType CallType); |
2348 | |
2349 | /// \brief Enforce the bounds of a TCB |
2350 | /// CheckTCBEnforcement - Enforces that every function in a named TCB only |
2351 | /// directly calls other functions in the same TCB as marked by the |
2352 | /// enforce_tcb and enforce_tcb_leaf attributes. |
2353 | void CheckTCBEnforcement(const SourceLocation CallExprLoc, |
2354 | const NamedDecl *Callee); |
2355 | |
2356 | void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc); |
2357 | |
2358 | /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr |
2359 | /// TheCall is a constant expression. |
2360 | bool BuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); |
2361 | |
2362 | /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr |
2363 | /// TheCall is a constant expression in the range [Low, High]. |
2364 | bool BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, |
2365 | bool RangeIsError = true); |
2366 | |
2367 | /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr |
2368 | /// TheCall is a constant expression is a multiple of Num.. |
2369 | bool BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, |
2370 | unsigned Multiple); |
2371 | |
2372 | /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a |
2373 | /// constant expression representing a power of 2. |
2374 | bool BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); |
2375 | |
2376 | /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is |
2377 | /// a constant expression representing an arbitrary byte value shifted left by |
2378 | /// a multiple of 8 bits. |
2379 | bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, |
2380 | unsigned ArgBits); |
2381 | |
2382 | /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of |
2383 | /// TheCall is a constant expression representing either a shifted byte value, |
2384 | /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression |
2385 | /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some |
2386 | /// Arm MVE intrinsics. |
2387 | bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, |
2388 | unsigned ArgBits); |
2389 | |
2390 | /// Checks that a call expression's argument count is at least the desired |
2391 | /// number. This is useful when doing custom type-checking on a variadic |
2392 | /// function. Returns true on error. |
2393 | bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount); |
2394 | |
2395 | /// Checks that a call expression's argument count is at most the desired |
2396 | /// number. This is useful when doing custom type-checking on a variadic |
2397 | /// function. Returns true on error. |
2398 | bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount); |
2399 | |
2400 | /// Checks that a call expression's argument count is in the desired range. |
2401 | /// This is useful when doing custom type-checking on a variadic function. |
2402 | /// Returns true on error. |
2403 | bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, |
2404 | unsigned MaxArgCount); |
2405 | |
2406 | /// Checks that a call expression's argument count is the desired number. |
2407 | /// This is useful when doing custom type-checking. Returns true on error. |
2408 | bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount); |
2409 | |
2410 | /// Returns true if the argument consists of one contiguous run of 1s with any |
2411 | /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, |
2412 | /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, |
2413 | /// since all 1s are not contiguous. |
2414 | bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum); |
2415 | |
2416 | void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, |
2417 | bool *ICContext = nullptr, |
2418 | bool IsListInit = false); |
2419 | |
2420 | bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, |
2421 | bool CheckForFloatArgs = true); |
2422 | bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall); |
2423 | |
2424 | private: |
2425 | void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, |
2426 | const ArraySubscriptExpr *ASE = nullptr, |
2427 | bool AllowOnePastEnd = true, bool IndexNegated = false); |
2428 | void CheckArrayAccess(const Expr *E); |
2429 | |
2430 | bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, |
2431 | const FunctionProtoType *Proto); |
2432 | |
2433 | /// Checks function calls when a FunctionDecl or a NamedDecl is not available, |
2434 | /// such as function pointers returned from functions. |
2435 | bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); |
2436 | |
2437 | /// CheckConstructorCall - Check a constructor call for correctness and safety |
2438 | /// properties not enforced by the C type system. |
2439 | void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, |
2440 | ArrayRef<const Expr *> Args, |
2441 | const FunctionProtoType *Proto, SourceLocation Loc); |
2442 | |
2443 | /// Warn if a pointer or reference argument passed to a function points to an |
2444 | /// object that is less aligned than the parameter. This can happen when |
2445 | /// creating a typedef with a lower alignment than the original type and then |
2446 | /// calling functions defined in terms of the original type. |
2447 | void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, |
2448 | StringRef ParamName, QualType ArgTy, QualType ParamTy); |
2449 | |
2450 | ExprResult CheckOSLogFormatStringArg(Expr *Arg); |
2451 | |
2452 | ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, |
2453 | CallExpr *TheCall); |
2454 | |
2455 | bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, |
2456 | CallExpr *TheCall); |
2457 | |
2458 | void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); |
2459 | |
2460 | /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' |
2461 | /// for validity. Emit an error and return true on failure; return false |
2462 | /// on success. |
2463 | bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); |
2464 | bool BuiltinVAStartARMMicrosoft(CallExpr *Call); |
2465 | |
2466 | /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and |
2467 | /// friends. This is declared to take (...), so we have to check everything. |
2468 | bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID); |
2469 | |
2470 | /// BuiltinSemaBuiltinFPClassification - Handle functions like |
2471 | /// __builtin_isnan and friends. This is declared to take (...), so we have |
2472 | /// to check everything. |
2473 | bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs, |
2474 | unsigned BuiltinID); |
2475 | |
2476 | /// Perform semantic analysis for a call to __builtin_complex. |
2477 | bool BuiltinComplex(CallExpr *TheCall); |
2478 | bool BuiltinOSLogFormat(CallExpr *TheCall); |
2479 | |
2480 | /// BuiltinPrefetch - Handle __builtin_prefetch. |
2481 | /// This is declared to take (const void*, ...) and can take two |
2482 | /// optional constant int args. |
2483 | bool BuiltinPrefetch(CallExpr *TheCall); |
2484 | |
2485 | /// Handle __builtin_alloca_with_align. This is declared |
2486 | /// as (size_t, size_t) where the second size_t must be a power of 2 greater |
2487 | /// than 8. |
2488 | bool BuiltinAllocaWithAlign(CallExpr *TheCall); |
2489 | |
2490 | /// BuiltinArithmeticFence - Handle __arithmetic_fence. |
2491 | bool BuiltinArithmeticFence(CallExpr *TheCall); |
2492 | |
2493 | /// BuiltinAssume - Handle __assume (MS Extension). |
2494 | /// __assume does not evaluate its arguments, and should warn if its argument |
2495 | /// has side effects. |
2496 | bool BuiltinAssume(CallExpr *TheCall); |
2497 | |
2498 | /// Handle __builtin_assume_aligned. This is declared |
2499 | /// as (const void*, size_t, ...) and can take one optional constant int arg. |
2500 | bool BuiltinAssumeAligned(CallExpr *TheCall); |
2501 | |
2502 | /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). |
2503 | /// This checks that the target supports __builtin_longjmp and |
2504 | /// that val is a constant 1. |
2505 | bool BuiltinLongjmp(CallExpr *TheCall); |
2506 | |
2507 | /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). |
2508 | /// This checks that the target supports __builtin_setjmp. |
2509 | bool BuiltinSetjmp(CallExpr *TheCall); |
2510 | |
2511 | /// We have a call to a function like __sync_fetch_and_add, which is an |
2512 | /// overloaded function based on the pointer type of its first argument. |
2513 | /// The main BuildCallExpr routines have already promoted the types of |
2514 | /// arguments because all of these calls are prototyped as void(...). |
2515 | /// |
2516 | /// This function goes through and does final semantic checking for these |
2517 | /// builtins, as well as generating any warnings. |
2518 | ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult); |
2519 | |
2520 | /// BuiltinNontemporalOverloaded - We have a call to |
2521 | /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an |
2522 | /// overloaded function based on the pointer type of its last argument. |
2523 | /// |
2524 | /// This function goes through and does final semantic checking for these |
2525 | /// builtins. |
2526 | ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult); |
2527 | ExprResult AtomicOpsOverloaded(ExprResult TheCallResult, |
2528 | AtomicExpr::AtomicOp Op); |
2529 | |
2530 | /// \param FPOnly restricts the arguments to floating-point types. |
2531 | bool BuiltinElementwiseMath(CallExpr *TheCall, bool FPOnly = false); |
2532 | bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall); |
2533 | |
2534 | bool BuiltinNonDeterministicValue(CallExpr *TheCall); |
2535 | |
2536 | enum BuiltinCountedByRefKind { |
2537 | AssignmentKind, |
2538 | InitializerKind, |
2539 | FunctionArgKind, |
2540 | ReturnArgKind, |
2541 | ArraySubscriptKind, |
2542 | BinaryExprKind, |
2543 | }; |
2544 | |
2545 | bool CheckInvalidBuiltinCountedByRef(const Expr *E, |
2546 | BuiltinCountedByRefKind K); |
2547 | bool BuiltinCountedByRef(CallExpr *TheCall); |
2548 | |
2549 | // Matrix builtin handling. |
2550 | ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult); |
2551 | ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall, |
2552 | ExprResult CallResult); |
2553 | ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall, |
2554 | ExprResult CallResult); |
2555 | |
2556 | /// CheckFormatArguments - Check calls to printf and scanf (and similar |
2557 | /// functions) for correct use of format strings. |
2558 | /// Returns true if a format string has been fully checked. |
2559 | bool CheckFormatArguments(const FormatAttr *Format, |
2560 | ArrayRef<const Expr *> Args, bool IsCXXMember, |
2561 | VariadicCallType CallType, SourceLocation Loc, |
2562 | SourceRange Range, |
2563 | llvm::SmallBitVector &CheckedVarArgs); |
2564 | bool CheckFormatArguments(ArrayRef<const Expr *> Args, |
2565 | FormatArgumentPassingKind FAPK, unsigned format_idx, |
2566 | unsigned firstDataArg, FormatStringType Type, |
2567 | VariadicCallType CallType, SourceLocation Loc, |
2568 | SourceRange range, |
2569 | llvm::SmallBitVector &CheckedVarArgs); |
2570 | |
2571 | void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl); |
2572 | |
2573 | /// Warn when using the wrong abs() function. |
2574 | void CheckAbsoluteValueFunction(const CallExpr *Call, |
2575 | const FunctionDecl *FDecl); |
2576 | |
2577 | void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); |
2578 | |
2579 | /// Check for dangerous or invalid arguments to memset(). |
2580 | /// |
2581 | /// This issues warnings on known problematic, dangerous or unspecified |
2582 | /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' |
2583 | /// function calls. |
2584 | /// |
2585 | /// \param Call The call expression to diagnose. |
2586 | void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, |
2587 | IdentifierInfo *FnName); |
2588 | |
2589 | // Warn if the user has made the 'size' argument to strlcpy or strlcat |
2590 | // be the size of the source, instead of the destination. |
2591 | void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); |
2592 | |
2593 | // Warn on anti-patterns as the 'size' argument to strncat. |
2594 | // The correct size argument should look like following: |
2595 | // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); |
2596 | void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); |
2597 | |
2598 | /// Alerts the user that they are attempting to free a non-malloc'd object. |
2599 | void CheckFreeArguments(const CallExpr *E); |
2600 | |
2601 | void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, |
2602 | SourceLocation ReturnLoc, bool isObjCMethod = false, |
2603 | const AttrVec *Attrs = nullptr, |
2604 | const FunctionDecl *FD = nullptr); |
2605 | |
2606 | /// Diagnoses "dangerous" implicit conversions within the given |
2607 | /// expression (which is a full expression). Implements -Wconversion |
2608 | /// and -Wsign-compare. |
2609 | /// |
2610 | /// \param CC the "context" location of the implicit conversion, i.e. |
2611 | /// the most location of the syntactic entity requiring the implicit |
2612 | /// conversion |
2613 | void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); |
2614 | |
2615 | /// CheckBoolLikeConversion - Check conversion of given expression to boolean. |
2616 | /// Input argument E is a logical expression. |
2617 | void CheckBoolLikeConversion(Expr *E, SourceLocation CC); |
2618 | |
2619 | /// Diagnose when expression is an integer constant expression and its |
2620 | /// evaluation results in integer overflow |
2621 | void CheckForIntOverflow(const Expr *E); |
2622 | void CheckUnsequencedOperations(const Expr *E); |
2623 | |
2624 | /// Perform semantic checks on a completed expression. This will either |
2625 | /// be a full-expression or a default argument expression. |
2626 | void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), |
2627 | bool IsConstexpr = false); |
2628 | |
2629 | void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, |
2630 | Expr *Init); |
2631 | |
2632 | /// A map from magic value to type information. |
2633 | std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> |
2634 | TypeTagForDatatypeMagicValues; |
2635 | |
2636 | /// Peform checks on a call of a function with argument_with_type_tag |
2637 | /// or pointer_with_type_tag attributes. |
2638 | void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, |
2639 | const ArrayRef<const Expr *> ExprArgs, |
2640 | SourceLocation CallSiteLoc); |
2641 | |
2642 | /// Check if we are taking the address of a packed field |
2643 | /// as this may be a problem if the pointer value is dereferenced. |
2644 | void CheckAddressOfPackedMember(Expr *rhs); |
2645 | |
2646 | /// Helper class that collects misaligned member designations and |
2647 | /// their location info for delayed diagnostics. |
2648 | struct MisalignedMember { |
2649 | Expr *E; |
2650 | RecordDecl *RD; |
2651 | ValueDecl *MD; |
2652 | CharUnits Alignment; |
2653 | |
2654 | MisalignedMember() : E(), RD(), MD() {} |
2655 | MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, |
2656 | CharUnits Alignment) |
2657 | : E(E), RD(RD), MD(MD), Alignment(Alignment) {} |
2658 | explicit MisalignedMember(Expr *E) |
2659 | : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} |
2660 | |
2661 | bool operator==(const MisalignedMember &m) { return this->E == m.E; } |
2662 | }; |
2663 | /// Small set of gathered accesses to potentially misaligned members |
2664 | /// due to the packed attribute. |
2665 | SmallVector<MisalignedMember, 4> MisalignedMembers; |
2666 | |
2667 | /// Adds an expression to the set of gathered misaligned members. |
2668 | void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, |
2669 | CharUnits Alignment); |
2670 | ///@} |
2671 | |
2672 | // |
2673 | // |
2674 | // ------------------------------------------------------------------------- |
2675 | // |
2676 | // |
2677 | |
2678 | /// \name C++ Coroutines |
2679 | /// Implementations are in SemaCoroutine.cpp |
2680 | ///@{ |
2681 | |
2682 | public: |
2683 | /// The C++ "std::coroutine_traits" template, which is defined in |
2684 | /// \<coroutine_traits> |
2685 | ClassTemplateDecl *StdCoroutineTraitsCache; |
2686 | |
2687 | bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, |
2688 | StringRef Keyword); |
2689 | ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); |
2690 | ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); |
2691 | StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); |
2692 | |
2693 | ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc); |
2694 | ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E, |
2695 | UnresolvedLookupExpr *Lookup); |
2696 | ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, |
2697 | Expr *Awaiter, bool IsImplicit = false); |
2698 | ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, |
2699 | UnresolvedLookupExpr *Lookup); |
2700 | ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); |
2701 | StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, |
2702 | bool IsImplicit = false); |
2703 | StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); |
2704 | bool buildCoroutineParameterMoves(SourceLocation Loc); |
2705 | VarDecl *buildCoroutinePromise(SourceLocation Loc); |
2706 | void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); |
2707 | |
2708 | // As a clang extension, enforces that a non-coroutine function must be marked |
2709 | // with [[clang::coro_wrapper]] if it returns a type marked with |
2710 | // [[clang::coro_return_type]]. |
2711 | // Expects that FD is not a coroutine. |
2712 | void CheckCoroutineWrapper(FunctionDecl *FD); |
2713 | /// Lookup 'coroutine_traits' in std namespace and std::experimental |
2714 | /// namespace. The namespace found is recorded in Namespace. |
2715 | ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, |
2716 | SourceLocation FuncLoc); |
2717 | /// Check that the expression co_await promise.final_suspend() shall not be |
2718 | /// potentially-throwing. |
2719 | bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); |
2720 | |
2721 | ///@} |
2722 | |
2723 | // |
2724 | // |
2725 | // ------------------------------------------------------------------------- |
2726 | // |
2727 | // |
2728 | |
2729 | /// \name C++ Scope Specifiers |
2730 | /// Implementations are in SemaCXXScopeSpec.cpp |
2731 | ///@{ |
2732 | |
2733 | public: |
2734 | // Marks SS invalid if it represents an incomplete type. |
2735 | bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); |
2736 | // Complete an enum decl, maybe without a scope spec. |
2737 | bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, |
2738 | CXXScopeSpec *SS = nullptr); |
2739 | |
2740 | /// Compute the DeclContext that is associated with the given type. |
2741 | /// |
2742 | /// \param T the type for which we are attempting to find a DeclContext. |
2743 | /// |
2744 | /// \returns the declaration context represented by the type T, |
2745 | /// or NULL if the declaration context cannot be computed (e.g., because it is |
2746 | /// dependent and not the current instantiation). |
2747 | DeclContext *computeDeclContext(QualType T); |
2748 | |
2749 | /// Compute the DeclContext that is associated with the given |
2750 | /// scope specifier. |
2751 | /// |
2752 | /// \param SS the C++ scope specifier as it appears in the source |
2753 | /// |
2754 | /// \param EnteringContext when true, we will be entering the context of |
2755 | /// this scope specifier, so we can retrieve the declaration context of a |
2756 | /// class template or class template partial specialization even if it is |
2757 | /// not the current instantiation. |
2758 | /// |
2759 | /// \returns the declaration context represented by the scope specifier @p SS, |
2760 | /// or NULL if the declaration context cannot be computed (e.g., because it is |
2761 | /// dependent and not the current instantiation). |
2762 | DeclContext *computeDeclContext(const CXXScopeSpec &SS, |
2763 | bool EnteringContext = false); |
2764 | bool isDependentScopeSpecifier(const CXXScopeSpec &SS); |
2765 | |
2766 | /// If the given nested name specifier refers to the current |
2767 | /// instantiation, return the declaration that corresponds to that |
2768 | /// current instantiation (C++0x [temp.dep.type]p1). |
2769 | /// |
2770 | /// \param NNS a dependent nested name specifier. |
2771 | CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); |
2772 | |
2773 | /// The parser has parsed a global nested-name-specifier '::'. |
2774 | /// |
2775 | /// \param CCLoc The location of the '::'. |
2776 | /// |
2777 | /// \param SS The nested-name-specifier, which will be updated in-place |
2778 | /// to reflect the parsed nested-name-specifier. |
2779 | /// |
2780 | /// \returns true if an error occurred, false otherwise. |
2781 | bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); |
2782 | |
2783 | /// The parser has parsed a '__super' nested-name-specifier. |
2784 | /// |
2785 | /// \param SuperLoc The location of the '__super' keyword. |
2786 | /// |
2787 | /// \param ColonColonLoc The location of the '::'. |
2788 | /// |
2789 | /// \param SS The nested-name-specifier, which will be updated in-place |
2790 | /// to reflect the parsed nested-name-specifier. |
2791 | /// |
2792 | /// \returns true if an error occurred, false otherwise. |
2793 | bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, |
2794 | SourceLocation ColonColonLoc, CXXScopeSpec &SS); |
2795 | |
2796 | /// Determines whether the given declaration is an valid acceptable |
2797 | /// result for name lookup of a nested-name-specifier. |
2798 | /// \param SD Declaration checked for nested-name-specifier. |
2799 | /// \param IsExtension If not null and the declaration is accepted as an |
2800 | /// extension, the pointed variable is assigned true. |
2801 | bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, |
2802 | bool *CanCorrect = nullptr); |
2803 | |
2804 | /// If the given nested-name-specifier begins with a bare identifier |
2805 | /// (e.g., Base::), perform name lookup for that identifier as a |
2806 | /// nested-name-specifier within the given scope, and return the result of |
2807 | /// that name lookup. |
2808 | NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); |
2809 | |
2810 | /// Keeps information about an identifier in a nested-name-spec. |
2811 | /// |
2812 | struct NestedNameSpecInfo { |
2813 | /// The type of the object, if we're parsing nested-name-specifier in |
2814 | /// a member access expression. |
2815 | ParsedType ObjectType; |
2816 | |
2817 | /// The identifier preceding the '::'. |
2818 | IdentifierInfo *Identifier; |
2819 | |
2820 | /// The location of the identifier. |
2821 | SourceLocation IdentifierLoc; |
2822 | |
2823 | /// The location of the '::'. |
2824 | SourceLocation CCLoc; |
2825 | |
2826 | /// Creates info object for the most typical case. |
2827 | NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, |
2828 | SourceLocation ColonColonLoc, |
2829 | ParsedType ObjectType = ParsedType()) |
2830 | : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), |
2831 | CCLoc(ColonColonLoc) {} |
2832 | |
2833 | NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, |
2834 | SourceLocation ColonColonLoc, QualType ObjectType) |
2835 | : ObjectType(ParsedType::make(P: ObjectType)), Identifier(II), |
2836 | IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {} |
2837 | }; |
2838 | |
2839 | /// Build a new nested-name-specifier for "identifier::", as described |
2840 | /// by ActOnCXXNestedNameSpecifier. |
2841 | /// |
2842 | /// \param S Scope in which the nested-name-specifier occurs. |
2843 | /// \param IdInfo Parser information about an identifier in the |
2844 | /// nested-name-spec. |
2845 | /// \param EnteringContext If true, enter the context specified by the |
2846 | /// nested-name-specifier. |
2847 | /// \param SS Optional nested name specifier preceding the identifier. |
2848 | /// \param ScopeLookupResult Provides the result of name lookup within the |
2849 | /// scope of the nested-name-specifier that was computed at template |
2850 | /// definition time. |
2851 | /// \param ErrorRecoveryLookup Specifies if the method is called to improve |
2852 | /// error recovery and what kind of recovery is performed. |
2853 | /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':' |
2854 | /// are allowed. The bool value pointed by this parameter is set to |
2855 | /// 'true' if the identifier is treated as if it was followed by ':', |
2856 | /// not '::'. |
2857 | /// \param OnlyNamespace If true, only considers namespaces in lookup. |
2858 | /// |
2859 | /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in |
2860 | /// that it contains an extra parameter \p ScopeLookupResult, which provides |
2861 | /// the result of name lookup within the scope of the nested-name-specifier |
2862 | /// that was computed at template definition time. |
2863 | /// |
2864 | /// If ErrorRecoveryLookup is true, then this call is used to improve error |
2865 | /// recovery. This means that it should not emit diagnostics, it should |
2866 | /// just return true on failure. It also means it should only return a valid |
2867 | /// scope if it *knows* that the result is correct. It should not return in a |
2868 | /// dependent context, for example. Nor will it extend \p SS with the scope |
2869 | /// specifier. |
2870 | bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, |
2871 | bool EnteringContext, CXXScopeSpec &SS, |
2872 | NamedDecl *ScopeLookupResult, |
2873 | bool ErrorRecoveryLookup, |
2874 | bool *IsCorrectedToColon = nullptr, |
2875 | bool OnlyNamespace = false); |
2876 | |
2877 | /// The parser has parsed a nested-name-specifier 'identifier::'. |
2878 | /// |
2879 | /// \param S The scope in which this nested-name-specifier occurs. |
2880 | /// |
2881 | /// \param IdInfo Parser information about an identifier in the |
2882 | /// nested-name-spec. |
2883 | /// |
2884 | /// \param EnteringContext Whether we're entering the context nominated by |
2885 | /// this nested-name-specifier. |
2886 | /// |
2887 | /// \param SS The nested-name-specifier, which is both an input |
2888 | /// parameter (the nested-name-specifier before this type) and an |
2889 | /// output parameter (containing the full nested-name-specifier, |
2890 | /// including this new type). |
2891 | /// |
2892 | /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' |
2893 | /// are allowed. The bool value pointed by this parameter is set to 'true' |
2894 | /// if the identifier is treated as if it was followed by ':', not '::'. |
2895 | /// |
2896 | /// \param OnlyNamespace If true, only considers namespaces in lookup. |
2897 | /// |
2898 | /// \returns true if an error occurred, false otherwise. |
2899 | bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, |
2900 | bool EnteringContext, CXXScopeSpec &SS, |
2901 | bool *IsCorrectedToColon = nullptr, |
2902 | bool OnlyNamespace = false); |
2903 | |
2904 | /// The parser has parsed a nested-name-specifier |
2905 | /// 'template[opt] template-name < template-args >::'. |
2906 | /// |
2907 | /// \param S The scope in which this nested-name-specifier occurs. |
2908 | /// |
2909 | /// \param SS The nested-name-specifier, which is both an input |
2910 | /// parameter (the nested-name-specifier before this type) and an |
2911 | /// output parameter (containing the full nested-name-specifier, |
2912 | /// including this new type). |
2913 | /// |
2914 | /// \param TemplateKWLoc the location of the 'template' keyword, if any. |
2915 | /// \param TemplateName the template name. |
2916 | /// \param TemplateNameLoc The location of the template name. |
2917 | /// \param LAngleLoc The location of the opening angle bracket ('<'). |
2918 | /// \param TemplateArgs The template arguments. |
2919 | /// \param RAngleLoc The location of the closing angle bracket ('>'). |
2920 | /// \param CCLoc The location of the '::'. |
2921 | /// |
2922 | /// \param EnteringContext Whether we're entering the context of the |
2923 | /// nested-name-specifier. |
2924 | /// |
2925 | /// |
2926 | /// \returns true if an error occurred, false otherwise. |
2927 | bool ActOnCXXNestedNameSpecifier( |
2928 | Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
2929 | TemplateTy TemplateName, SourceLocation TemplateNameLoc, |
2930 | SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, |
2931 | SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); |
2932 | |
2933 | bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, |
2934 | SourceLocation ColonColonLoc); |
2935 | |
2936 | bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS, |
2937 | const DeclSpec &DS, |
2938 | SourceLocation ColonColonLoc, |
2939 | QualType Type); |
2940 | |
2941 | /// IsInvalidUnlessNestedName - This method is used for error recovery |
2942 | /// purposes to determine whether the specified identifier is only valid as |
2943 | /// a nested name specifier, for example a namespace name. It is |
2944 | /// conservatively correct to always return false from this method. |
2945 | /// |
2946 | /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier. |
2947 | bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, |
2948 | NestedNameSpecInfo &IdInfo, |
2949 | bool EnteringContext); |
2950 | |
2951 | /// Given a C++ nested-name-specifier, produce an annotation value |
2952 | /// that the parser can use later to reconstruct the given |
2953 | /// nested-name-specifier. |
2954 | /// |
2955 | /// \param SS A nested-name-specifier. |
2956 | /// |
2957 | /// \returns A pointer containing all of the information in the |
2958 | /// nested-name-specifier \p SS. |
2959 | void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); |
2960 | |
2961 | /// Given an annotation pointer for a nested-name-specifier, restore |
2962 | /// the nested-name-specifier structure. |
2963 | /// |
2964 | /// \param Annotation The annotation pointer, produced by |
2965 | /// \c SaveNestedNameSpecifierAnnotation(). |
2966 | /// |
2967 | /// \param AnnotationRange The source range corresponding to the annotation. |
2968 | /// |
2969 | /// \param SS The nested-name-specifier that will be updated with the contents |
2970 | /// of the annotation pointer. |
2971 | void RestoreNestedNameSpecifierAnnotation(void *Annotation, |
2972 | SourceRange AnnotationRange, |
2973 | CXXScopeSpec &SS); |
2974 | |
2975 | bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); |
2976 | |
2977 | /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global |
2978 | /// scope or nested-name-specifier) is parsed, part of a declarator-id. |
2979 | /// After this method is called, according to [C++ 3.4.3p3], names should be |
2980 | /// looked up in the declarator-id's scope, until the declarator is parsed and |
2981 | /// ActOnCXXExitDeclaratorScope is called. |
2982 | /// The 'SS' should be a non-empty valid CXXScopeSpec. |
2983 | bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); |
2984 | |
2985 | /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously |
2986 | /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same |
2987 | /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. |
2988 | /// Used to indicate that names should revert to being looked up in the |
2989 | /// defining scope. |
2990 | void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); |
2991 | |
2992 | ///@} |
2993 | |
2994 | // |
2995 | // |
2996 | // ------------------------------------------------------------------------- |
2997 | // |
2998 | // |
2999 | |
3000 | /// \name Declarations |
3001 | /// Implementations are in SemaDecl.cpp |
3002 | ///@{ |
3003 | |
3004 | public: |
3005 | IdentifierResolver IdResolver; |
3006 | |
3007 | /// The index of the first InventedParameterInfo that refers to the current |
3008 | /// context. |
3009 | unsigned InventedParameterInfosStart = 0; |
3010 | |
3011 | /// A RAII object to temporarily push a declaration context. |
3012 | class { |
3013 | private: |
3014 | Sema &; |
3015 | DeclContext *; |
3016 | ProcessingContextState ; |
3017 | QualType ; |
3018 | unsigned ; |
3019 | unsigned ; |
3020 | |
3021 | public: |
3022 | (Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) |
3023 | : S(S), SavedContext(S.CurContext), |
3024 | SavedContextState(S.DelayedDiagnostics.pushUndelayed()), |
3025 | SavedCXXThisTypeOverride(S.CXXThisTypeOverride), |
3026 | SavedFunctionScopesStart(S.FunctionScopesStart), |
3027 | SavedInventedParameterInfosStart(S.InventedParameterInfosStart) { |
3028 | assert(ContextToPush && "pushing null context" ); |
3029 | S.CurContext = ContextToPush; |
3030 | if (NewThisContext) |
3031 | S.CXXThisTypeOverride = QualType(); |
3032 | // Any saved FunctionScopes do not refer to this context. |
3033 | S.FunctionScopesStart = S.FunctionScopes.size(); |
3034 | S.InventedParameterInfosStart = S.InventedParameterInfos.size(); |
3035 | } |
3036 | |
3037 | void () { |
3038 | if (!SavedContext) |
3039 | return; |
3040 | S.CurContext = SavedContext; |
3041 | S.DelayedDiagnostics.popUndelayed(state: SavedContextState); |
3042 | S.CXXThisTypeOverride = SavedCXXThisTypeOverride; |
3043 | S.FunctionScopesStart = SavedFunctionScopesStart; |
3044 | S.InventedParameterInfosStart = SavedInventedParameterInfosStart; |
3045 | SavedContext = nullptr; |
3046 | } |
3047 | |
3048 | () { pop(); } |
3049 | }; |
3050 | |
3051 | void DiagnoseInvalidJumps(Stmt *Body); |
3052 | |
3053 | /// The function definitions which were renamed as part of typo-correction |
3054 | /// to match their respective declarations. We want to keep track of them |
3055 | /// to ensure that we don't emit a "redefinition" error if we encounter a |
3056 | /// correctly named definition after the renamed definition. |
3057 | llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; |
3058 | |
3059 | /// A cache of the flags available in enumerations with the flag_bits |
3060 | /// attribute. |
3061 | mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache; |
3062 | |
3063 | /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before |
3064 | /// declared. Rare. May alias another identifier, declared or undeclared. |
3065 | /// |
3066 | /// For aliases, the target identifier is used as a key for eventual |
3067 | /// processing when the target is declared. For the single-identifier form, |
3068 | /// the sole identifier is used as the key. Each entry is a `SetVector` |
3069 | /// (ordered by parse order) of aliases (identified by the alias name) in case |
3070 | /// of multiple aliases to the same undeclared identifier. |
3071 | llvm::MapVector< |
3072 | IdentifierInfo *, |
3073 | llvm::SetVector< |
3074 | WeakInfo, llvm::SmallVector<WeakInfo, 1u>, |
3075 | llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>> |
3076 | WeakUndeclaredIdentifiers; |
3077 | |
3078 | /// ExtnameUndeclaredIdentifiers - Identifiers contained in |
3079 | /// \#pragma redefine_extname before declared. Used in Solaris system headers |
3080 | /// to define functions that occur in multiple standards to call the version |
3081 | /// in the currently selected standard. |
3082 | llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *> ExtnameUndeclaredIdentifiers; |
3083 | |
3084 | /// Set containing all typedefs that are likely unused. |
3085 | llvm::SmallSetVector<const TypedefNameDecl *, 4> |
3086 | UnusedLocalTypedefNameCandidates; |
3087 | |
3088 | typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, |
3089 | &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> |
3090 | UnusedFileScopedDeclsType; |
3091 | |
3092 | /// The set of file scoped decls seen so far that have not been used |
3093 | /// and must warn if not used. Only contains the first declaration. |
3094 | UnusedFileScopedDeclsType UnusedFileScopedDecls; |
3095 | |
3096 | typedef LazyVector<VarDecl *, ExternalSemaSource, |
3097 | &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> |
3098 | TentativeDefinitionsType; |
3099 | |
3100 | /// All the tentative definitions encountered in the TU. |
3101 | TentativeDefinitionsType TentativeDefinitions; |
3102 | |
3103 | /// All the external declarations encoutered and used in the TU. |
3104 | SmallVector<DeclaratorDecl *, 4> ExternalDeclarations; |
3105 | |
3106 | /// Generally null except when we temporarily switch decl contexts, |
3107 | /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext. |
3108 | DeclContext *OriginalLexicalContext; |
3109 | |
3110 | /// Is the module scope we are in a C++ Header Unit? |
3111 | bool () const { |
3112 | return ModuleScopes.empty() ? false |
3113 | : ModuleScopes.back().Module->isHeaderUnit(); |
3114 | } |
3115 | |
3116 | /// Get the module owning an entity. |
3117 | Module *getOwningModule(const Decl *Entity) { |
3118 | return Entity->getOwningModule(); |
3119 | } |
3120 | |
3121 | DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); |
3122 | |
3123 | /// If the identifier refers to a type name within this scope, |
3124 | /// return the declaration of that type. |
3125 | /// |
3126 | /// This routine performs ordinary name lookup of the identifier II |
3127 | /// within the given scope, with optional C++ scope specifier SS, to |
3128 | /// determine whether the name refers to a type. If so, returns an |
3129 | /// opaque pointer (actually a QualType) corresponding to that |
3130 | /// type. Otherwise, returns NULL. |
3131 | ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, |
3132 | Scope *S, CXXScopeSpec *SS = nullptr, |
3133 | bool isClassName = false, bool HasTrailingDot = false, |
3134 | ParsedType ObjectType = nullptr, |
3135 | bool IsCtorOrDtorName = false, |
3136 | bool WantNontrivialTypeSourceInfo = false, |
3137 | bool IsClassTemplateDeductionContext = true, |
3138 | ImplicitTypenameContext AllowImplicitTypename = |
3139 | ImplicitTypenameContext::No, |
3140 | IdentifierInfo **CorrectedII = nullptr); |
3141 | |
3142 | /// isTagName() - This method is called *for error recovery purposes only* |
3143 | /// to determine if the specified name is a valid tag name ("struct foo"). If |
3144 | /// so, this returns the TST for the tag corresponding to it (TST_enum, |
3145 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to |
3146 | /// diagnose cases in C where the user forgot to specify the tag. |
3147 | TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); |
3148 | |
3149 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, |
3150 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes |
3151 | /// then downgrade the missing typename error to a warning. |
3152 | /// This is needed for MSVC compatibility; Example: |
3153 | /// @code |
3154 | /// template<class T> class A { |
3155 | /// public: |
3156 | /// typedef int TYPE; |
3157 | /// }; |
3158 | /// template<class T> class B : public A<T> { |
3159 | /// public: |
3160 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. |
3161 | /// }; |
3162 | /// @endcode |
3163 | bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); |
3164 | void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, |
3165 | Scope *S, CXXScopeSpec *SS, |
3166 | ParsedType &SuggestedType, |
3167 | bool IsTemplateName = false); |
3168 | |
3169 | /// Attempt to behave like MSVC in situations where lookup of an unqualified |
3170 | /// type name has failed in a dependent context. In these situations, we |
3171 | /// automatically form a DependentTypeName that will retry lookup in a related |
3172 | /// scope during instantiation. |
3173 | ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, |
3174 | SourceLocation NameLoc, |
3175 | bool IsTemplateTypeArg); |
3176 | |
3177 | /// Describes the result of the name lookup and resolution performed |
3178 | /// by \c ClassifyName(). |
3179 | enum NameClassificationKind { |
3180 | /// This name is not a type or template in this context, but might be |
3181 | /// something else. |
3182 | NC_Unknown, |
3183 | /// Classification failed; an error has been produced. |
3184 | NC_Error, |
3185 | /// The name has been typo-corrected to a keyword. |
3186 | NC_Keyword, |
3187 | /// The name was classified as a type. |
3188 | NC_Type, |
3189 | /// The name was classified as a specific non-type, non-template |
3190 | /// declaration. ActOnNameClassifiedAsNonType should be called to |
3191 | /// convert the declaration to an expression. |
3192 | NC_NonType, |
3193 | /// The name was classified as an ADL-only function name. |
3194 | /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the |
3195 | /// result to an expression. |
3196 | NC_UndeclaredNonType, |
3197 | /// The name denotes a member of a dependent type that could not be |
3198 | /// resolved. ActOnNameClassifiedAsDependentNonType should be called to |
3199 | /// convert the result to an expression. |
3200 | NC_DependentNonType, |
3201 | /// The name was classified as an overload set, and an expression |
3202 | /// representing that overload set has been formed. |
3203 | /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable |
3204 | /// expression referencing the overload set. |
3205 | NC_OverloadSet, |
3206 | /// The name was classified as a template whose specializations are types. |
3207 | NC_TypeTemplate, |
3208 | /// The name was classified as a variable template name. |
3209 | NC_VarTemplate, |
3210 | /// The name was classified as a function template name. |
3211 | NC_FunctionTemplate, |
3212 | /// The name was classified as an ADL-only function template name. |
3213 | NC_UndeclaredTemplate, |
3214 | /// The name was classified as a concept name. |
3215 | NC_Concept, |
3216 | }; |
3217 | |
3218 | class NameClassification { |
3219 | NameClassificationKind Kind; |
3220 | union { |
3221 | ExprResult Expr; |
3222 | NamedDecl *NonTypeDecl; |
3223 | TemplateName Template; |
3224 | ParsedType Type; |
3225 | }; |
3226 | |
3227 | explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} |
3228 | |
3229 | public: |
3230 | NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} |
3231 | |
3232 | NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} |
3233 | |
3234 | static NameClassification Error() { return NameClassification(NC_Error); } |
3235 | |
3236 | static NameClassification Unknown() { |
3237 | return NameClassification(NC_Unknown); |
3238 | } |
3239 | |
3240 | static NameClassification OverloadSet(ExprResult E) { |
3241 | NameClassification Result(NC_OverloadSet); |
3242 | Result.Expr = E; |
3243 | return Result; |
3244 | } |
3245 | |
3246 | static NameClassification NonType(NamedDecl *D) { |
3247 | NameClassification Result(NC_NonType); |
3248 | Result.NonTypeDecl = D; |
3249 | return Result; |
3250 | } |
3251 | |
3252 | static NameClassification UndeclaredNonType() { |
3253 | return NameClassification(NC_UndeclaredNonType); |
3254 | } |
3255 | |
3256 | static NameClassification DependentNonType() { |
3257 | return NameClassification(NC_DependentNonType); |
3258 | } |
3259 | |
3260 | static NameClassification TypeTemplate(TemplateName Name) { |
3261 | NameClassification Result(NC_TypeTemplate); |
3262 | Result.Template = Name; |
3263 | return Result; |
3264 | } |
3265 | |
3266 | static NameClassification VarTemplate(TemplateName Name) { |
3267 | NameClassification Result(NC_VarTemplate); |
3268 | Result.Template = Name; |
3269 | return Result; |
3270 | } |
3271 | |
3272 | static NameClassification FunctionTemplate(TemplateName Name) { |
3273 | NameClassification Result(NC_FunctionTemplate); |
3274 | Result.Template = Name; |
3275 | return Result; |
3276 | } |
3277 | |
3278 | static NameClassification Concept(TemplateName Name) { |
3279 | NameClassification Result(NC_Concept); |
3280 | Result.Template = Name; |
3281 | return Result; |
3282 | } |
3283 | |
3284 | static NameClassification UndeclaredTemplate(TemplateName Name) { |
3285 | NameClassification Result(NC_UndeclaredTemplate); |
3286 | Result.Template = Name; |
3287 | return Result; |
3288 | } |
3289 | |
3290 | NameClassificationKind getKind() const { return Kind; } |
3291 | |
3292 | ExprResult getExpression() const { |
3293 | assert(Kind == NC_OverloadSet); |
3294 | return Expr; |
3295 | } |
3296 | |
3297 | ParsedType getType() const { |
3298 | assert(Kind == NC_Type); |
3299 | return Type; |
3300 | } |
3301 | |
3302 | NamedDecl *getNonTypeDecl() const { |
3303 | assert(Kind == NC_NonType); |
3304 | return NonTypeDecl; |
3305 | } |
3306 | |
3307 | TemplateName getTemplateName() const { |
3308 | assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || |
3309 | Kind == NC_VarTemplate || Kind == NC_Concept || |
3310 | Kind == NC_UndeclaredTemplate); |
3311 | return Template; |
3312 | } |
3313 | |
3314 | TemplateNameKind getTemplateNameKind() const { |
3315 | switch (Kind) { |
3316 | case NC_TypeTemplate: |
3317 | return TNK_Type_template; |
3318 | case NC_FunctionTemplate: |
3319 | return TNK_Function_template; |
3320 | case NC_VarTemplate: |
3321 | return TNK_Var_template; |
3322 | case NC_Concept: |
3323 | return TNK_Concept_template; |
3324 | case NC_UndeclaredTemplate: |
3325 | return TNK_Undeclared_template; |
3326 | default: |
3327 | llvm_unreachable("unsupported name classification." ); |
3328 | } |
3329 | } |
3330 | }; |
3331 | |
3332 | /// Perform name lookup on the given name, classifying it based on |
3333 | /// the results of name lookup and the following token. |
3334 | /// |
3335 | /// This routine is used by the parser to resolve identifiers and help direct |
3336 | /// parsing. When the identifier cannot be found, this routine will attempt |
3337 | /// to correct the typo and classify based on the resulting name. |
3338 | /// |
3339 | /// \param S The scope in which we're performing name lookup. |
3340 | /// |
3341 | /// \param SS The nested-name-specifier that precedes the name. |
3342 | /// |
3343 | /// \param Name The identifier. If typo correction finds an alternative name, |
3344 | /// this pointer parameter will be updated accordingly. |
3345 | /// |
3346 | /// \param NameLoc The location of the identifier. |
3347 | /// |
3348 | /// \param NextToken The token following the identifier. Used to help |
3349 | /// disambiguate the name. |
3350 | /// |
3351 | /// \param CCC The correction callback, if typo correction is desired. |
3352 | NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, |
3353 | IdentifierInfo *&Name, SourceLocation NameLoc, |
3354 | const Token &NextToken, |
3355 | CorrectionCandidateCallback *CCC = nullptr); |
3356 | |
3357 | /// Act on the result of classifying a name as an undeclared (ADL-only) |
3358 | /// non-type declaration. |
3359 | ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, |
3360 | SourceLocation NameLoc); |
3361 | /// Act on the result of classifying a name as an undeclared member of a |
3362 | /// dependent base class. |
3363 | ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, |
3364 | IdentifierInfo *Name, |
3365 | SourceLocation NameLoc, |
3366 | bool IsAddressOfOperand); |
3367 | /// Act on the result of classifying a name as a specific non-type |
3368 | /// declaration. |
3369 | ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, |
3370 | NamedDecl *Found, |
3371 | SourceLocation NameLoc, |
3372 | const Token &NextToken); |
3373 | /// Act on the result of classifying a name as an overload set. |
3374 | ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); |
3375 | |
3376 | /// Describes the detailed kind of a template name. Used in diagnostics. |
3377 | enum class TemplateNameKindForDiagnostics { |
3378 | ClassTemplate, |
3379 | FunctionTemplate, |
3380 | VarTemplate, |
3381 | AliasTemplate, |
3382 | TemplateTemplateParam, |
3383 | Concept, |
3384 | DependentTemplate |
3385 | }; |
3386 | TemplateNameKindForDiagnostics |
3387 | getTemplateNameKindForDiagnostics(TemplateName Name); |
3388 | |
3389 | /// Determine whether it's plausible that E was intended to be a |
3390 | /// template-name. |
3391 | bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { |
3392 | if (!getLangOpts().CPlusPlus || E.isInvalid()) |
3393 | return false; |
3394 | Dependent = false; |
3395 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E.get())) |
3396 | return !DRE->hasExplicitTemplateArgs(); |
3397 | if (auto *ME = dyn_cast<MemberExpr>(Val: E.get())) |
3398 | return !ME->hasExplicitTemplateArgs(); |
3399 | Dependent = true; |
3400 | if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(Val: E.get())) |
3401 | return !DSDRE->hasExplicitTemplateArgs(); |
3402 | if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(Val: E.get())) |
3403 | return !DSME->hasExplicitTemplateArgs(); |
3404 | // Any additional cases recognized here should also be handled by |
3405 | // diagnoseExprIntendedAsTemplateName. |
3406 | return false; |
3407 | } |
3408 | |
3409 | void warnOnReservedIdentifier(const NamedDecl *D); |
3410 | |
3411 | Decl *ActOnDeclarator(Scope *S, Declarator &D); |
3412 | |
3413 | NamedDecl *HandleDeclarator(Scope *S, Declarator &D, |
3414 | MultiTemplateParamsArg TemplateParameterLists); |
3415 | |
3416 | /// Attempt to fold a variable-sized type to a constant-sized type, returning |
3417 | /// true if we were successful. |
3418 | bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, |
3419 | SourceLocation Loc, |
3420 | unsigned FailedFoldDiagID); |
3421 | |
3422 | /// Register the given locally-scoped extern "C" declaration so |
3423 | /// that it can be found later for redeclarations. We include any extern "C" |
3424 | /// declaration that is not visible in the translation unit here, not just |
3425 | /// function-scope declarations. |
3426 | void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); |
3427 | |
3428 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: |
3429 | /// If T is the name of a class, then each of the following shall have a |
3430 | /// name different from T: |
3431 | /// - every static data member of class T; |
3432 | /// - every member function of class T |
3433 | /// - every member of class T that is itself a type; |
3434 | /// \returns true if the declaration name violates these rules. |
3435 | bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); |
3436 | |
3437 | /// Diagnose a declaration whose declarator-id has the given |
3438 | /// nested-name-specifier. |
3439 | /// |
3440 | /// \param SS The nested-name-specifier of the declarator-id. |
3441 | /// |
3442 | /// \param DC The declaration context to which the nested-name-specifier |
3443 | /// resolves. |
3444 | /// |
3445 | /// \param Name The name of the entity being declared. |
3446 | /// |
3447 | /// \param Loc The location of the name of the entity being declared. |
3448 | /// |
3449 | /// \param IsMemberSpecialization Whether we are declaring a member |
3450 | /// specialization. |
3451 | /// |
3452 | /// \param TemplateId The template-id, if any. |
3453 | /// |
3454 | /// \returns true if we cannot safely recover from this error, false |
3455 | /// otherwise. |
3456 | bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, |
3457 | DeclarationName Name, SourceLocation Loc, |
3458 | TemplateIdAnnotation *TemplateId, |
3459 | bool IsMemberSpecialization); |
3460 | |
3461 | bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range); |
3462 | |
3463 | bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key); |
3464 | |
3465 | /// Diagnose function specifiers on a declaration of an identifier that |
3466 | /// does not identify a function. |
3467 | void DiagnoseFunctionSpecifiers(const DeclSpec &DS); |
3468 | |
3469 | /// Return the declaration shadowed by the given typedef \p D, or null |
3470 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. |
3471 | NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, |
3472 | const LookupResult &R); |
3473 | |
3474 | /// Return the declaration shadowed by the given variable \p D, or null |
3475 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. |
3476 | NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); |
3477 | |
3478 | /// Return the declaration shadowed by the given variable \p D, or null |
3479 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. |
3480 | NamedDecl *getShadowedDeclaration(const BindingDecl *D, |
3481 | const LookupResult &R); |
3482 | /// Diagnose variable or built-in function shadowing. Implements |
3483 | /// -Wshadow. |
3484 | /// |
3485 | /// This method is called whenever a VarDecl is added to a "useful" |
3486 | /// scope. |
3487 | /// |
3488 | /// \param ShadowedDecl the declaration that is shadowed by the given variable |
3489 | /// \param R the lookup of the name |
3490 | void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, |
3491 | const LookupResult &R); |
3492 | |
3493 | /// Check -Wshadow without the advantage of a previous lookup. |
3494 | void CheckShadow(Scope *S, VarDecl *D); |
3495 | |
3496 | /// Warn if 'E', which is an expression that is about to be modified, refers |
3497 | /// to a shadowing declaration. |
3498 | void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); |
3499 | |
3500 | /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD |
3501 | /// when these variables are captured by the lambda. |
3502 | void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); |
3503 | |
3504 | void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); |
3505 | void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, |
3506 | TypedefNameDecl *NewTD); |
3507 | void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); |
3508 | NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, |
3509 | TypeSourceInfo *TInfo, |
3510 | LookupResult &Previous); |
3511 | |
3512 | /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which |
3513 | /// declares a typedef-name, either using the 'typedef' type specifier or via |
3514 | /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. |
3515 | NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, |
3516 | LookupResult &Previous, bool &Redeclaration); |
3517 | NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, |
3518 | TypeSourceInfo *TInfo, |
3519 | LookupResult &Previous, |
3520 | MultiTemplateParamsArg TemplateParamLists, |
3521 | bool &AddToScope, |
3522 | ArrayRef<BindingDecl *> Bindings = {}); |
3523 | |
3524 | /// Perform semantic checking on a newly-created variable |
3525 | /// declaration. |
3526 | /// |
3527 | /// This routine performs all of the type-checking required for a |
3528 | /// variable declaration once it has been built. It is used both to |
3529 | /// check variables after they have been parsed and their declarators |
3530 | /// have been translated into a declaration, and to check variables |
3531 | /// that have been instantiated from a template. |
3532 | /// |
3533 | /// Sets NewVD->isInvalidDecl() if an error was encountered. |
3534 | /// |
3535 | /// Returns true if the variable declaration is a redeclaration. |
3536 | bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); |
3537 | void CheckVariableDeclarationType(VarDecl *NewVD); |
3538 | void CheckCompleteVariableDeclaration(VarDecl *VD); |
3539 | |
3540 | NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, |
3541 | TypeSourceInfo *TInfo, |
3542 | LookupResult &Previous, |
3543 | MultiTemplateParamsArg TemplateParamLists, |
3544 | bool &AddToScope); |
3545 | |
3546 | /// AddOverriddenMethods - See if a method overrides any in the base classes, |
3547 | /// and if so, check that it's a valid override and remember it. |
3548 | bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); |
3549 | |
3550 | /// Perform semantic checking of a new function declaration. |
3551 | /// |
3552 | /// Performs semantic analysis of the new function declaration |
3553 | /// NewFD. This routine performs all semantic checking that does not |
3554 | /// require the actual declarator involved in the declaration, and is |
3555 | /// used both for the declaration of functions as they are parsed |
3556 | /// (called via ActOnDeclarator) and for the declaration of functions |
3557 | /// that have been instantiated via C++ template instantiation (called |
3558 | /// via InstantiateDecl). |
3559 | /// |
3560 | /// \param IsMemberSpecialization whether this new function declaration is |
3561 | /// a member specialization (that replaces any definition provided by the |
3562 | /// previous declaration). |
3563 | /// |
3564 | /// This sets NewFD->isInvalidDecl() to true if there was an error. |
3565 | /// |
3566 | /// \returns true if the function declaration is a redeclaration. |
3567 | bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, |
3568 | LookupResult &Previous, |
3569 | bool IsMemberSpecialization, bool DeclIsDefn); |
3570 | |
3571 | /// Checks if the new declaration declared in dependent context must be |
3572 | /// put in the same redeclaration chain as the specified declaration. |
3573 | /// |
3574 | /// \param D Declaration that is checked. |
3575 | /// \param PrevDecl Previous declaration found with proper lookup method for |
3576 | /// the same declaration name. |
3577 | /// \returns True if D must be added to the redeclaration chain which PrevDecl |
3578 | /// belongs to. |
3579 | bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); |
3580 | |
3581 | /// Determines if we can perform a correct type check for \p D as a |
3582 | /// redeclaration of \p PrevDecl. If not, we can generally still perform a |
3583 | /// best-effort check. |
3584 | /// |
3585 | /// \param NewD The new declaration. |
3586 | /// \param OldD The old declaration. |
3587 | /// \param NewT The portion of the type of the new declaration to check. |
3588 | /// \param OldT The portion of the type of the old declaration to check. |
3589 | bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, |
3590 | QualType NewT, QualType OldT); |
3591 | void CheckMain(FunctionDecl *FD, const DeclSpec &D); |
3592 | void CheckMSVCRTEntryPoint(FunctionDecl *FD); |
3593 | |
3594 | /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a |
3595 | /// containing class. Otherwise it will return implicit SectionAttr if the |
3596 | /// function is a definition and there is an active value on CodeSegStack |
3597 | /// (from the current #pragma code-seg value). |
3598 | /// |
3599 | /// \param FD Function being declared. |
3600 | /// \param IsDefinition Whether it is a definition or just a declaration. |
3601 | /// \returns A CodeSegAttr or SectionAttr to apply to the function or |
3602 | /// nullptr if no attribute should be added. |
3603 | Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, |
3604 | bool IsDefinition); |
3605 | |
3606 | /// Common checks for a parameter-declaration that should apply to both |
3607 | /// function parameters and non-type template parameters. |
3608 | void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); |
3609 | |
3610 | /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() |
3611 | /// to introduce parameters into function prototype scope. |
3612 | Decl *ActOnParamDeclarator(Scope *S, Declarator &D, |
3613 | SourceLocation ExplicitThisLoc = {}); |
3614 | |
3615 | /// Synthesizes a variable for a parameter arising from a |
3616 | /// typedef. |
3617 | ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, |
3618 | QualType T); |
3619 | ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, |
3620 | SourceLocation NameLoc, |
3621 | const IdentifierInfo *Name, QualType T, |
3622 | TypeSourceInfo *TSInfo, StorageClass SC); |
3623 | |
3624 | // Contexts where using non-trivial C union types can be disallowed. This is |
3625 | // passed to err_non_trivial_c_union_in_invalid_context. |
3626 | enum NonTrivialCUnionContext { |
3627 | // Function parameter. |
3628 | NTCUC_FunctionParam, |
3629 | // Function return. |
3630 | NTCUC_FunctionReturn, |
3631 | // Default-initialized object. |
3632 | NTCUC_DefaultInitializedObject, |
3633 | // Variable with automatic storage duration. |
3634 | NTCUC_AutoVar, |
3635 | // Initializer expression that might copy from another object. |
3636 | NTCUC_CopyInit, |
3637 | // Assignment. |
3638 | NTCUC_Assignment, |
3639 | // Compound literal. |
3640 | NTCUC_CompoundLiteral, |
3641 | // Block capture. |
3642 | NTCUC_BlockCapture, |
3643 | // lvalue-to-rvalue conversion of volatile type. |
3644 | NTCUC_LValueToRValueVolatile, |
3645 | }; |
3646 | |
3647 | /// Emit diagnostics if the initializer or any of its explicit or |
3648 | /// implicitly-generated subexpressions require copying or |
3649 | /// default-initializing a type that is or contains a C union type that is |
3650 | /// non-trivial to copy or default-initialize. |
3651 | void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); |
3652 | |
3653 | // These flags are passed to checkNonTrivialCUnion. |
3654 | enum NonTrivialCUnionKind { |
3655 | NTCUK_Init = 0x1, |
3656 | NTCUK_Destruct = 0x2, |
3657 | NTCUK_Copy = 0x4, |
3658 | }; |
3659 | |
3660 | /// Emit diagnostics if a non-trivial C union type or a struct that contains |
3661 | /// a non-trivial C union is used in an invalid context. |
3662 | void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, |
3663 | NonTrivialCUnionContext UseContext, |
3664 | unsigned NonTrivialKind); |
3665 | |
3666 | /// Certain globally-unique variables might be accidentally duplicated if |
3667 | /// built into multiple shared libraries with hidden visibility. This can |
3668 | /// cause problems if the variable is mutable, its initialization is |
3669 | /// effectful, or its address is taken. |
3670 | bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl); |
3671 | void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl); |
3672 | |
3673 | /// AddInitializerToDecl - Adds the initializer Init to the |
3674 | /// declaration dcl. If DirectInit is true, this is C++ direct |
3675 | /// initialization rather than copy initialization. |
3676 | void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); |
3677 | void ActOnUninitializedDecl(Decl *dcl); |
3678 | |
3679 | /// ActOnInitializerError - Given that there was an error parsing an |
3680 | /// initializer for the given declaration, try to at least re-establish |
3681 | /// invariants such as whether a variable's type is either dependent or |
3682 | /// complete. |
3683 | void ActOnInitializerError(Decl *Dcl); |
3684 | |
3685 | void ActOnCXXForRangeDecl(Decl *D); |
3686 | StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, |
3687 | IdentifierInfo *Ident, |
3688 | ParsedAttributes &Attrs); |
3689 | |
3690 | /// Check if VD needs to be dllexport/dllimport due to being in a |
3691 | /// dllexport/import function. |
3692 | void CheckStaticLocalForDllExport(VarDecl *VD); |
3693 | void CheckThreadLocalForLargeAlignment(VarDecl *VD); |
3694 | |
3695 | /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform |
3696 | /// any semantic actions necessary after any initializer has been attached. |
3697 | void FinalizeDeclaration(Decl *D); |
3698 | DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, |
3699 | ArrayRef<Decl *> Group); |
3700 | |
3701 | /// BuildDeclaratorGroup - convert a list of declarations into a declaration |
3702 | /// group, performing any necessary semantic checking. |
3703 | DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); |
3704 | |
3705 | /// Should be called on all declarations that might have attached |
3706 | /// documentation comments. |
3707 | void ActOnDocumentableDecl(Decl *D); |
3708 | void ActOnDocumentableDecls(ArrayRef<Decl *> Group); |
3709 | |
3710 | enum class FnBodyKind { |
3711 | /// C++26 [dcl.fct.def.general]p1 |
3712 | /// function-body: |
3713 | /// ctor-initializer[opt] compound-statement |
3714 | /// function-try-block |
3715 | Other, |
3716 | /// = default ; |
3717 | Default, |
3718 | /// deleted-function-body |
3719 | /// |
3720 | /// deleted-function-body: |
3721 | /// = delete ; |
3722 | /// = delete ( unevaluated-string ) ; |
3723 | Delete |
3724 | }; |
3725 | |
3726 | void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, |
3727 | SourceLocation LocAfterDecls); |
3728 | void CheckForFunctionRedefinition( |
3729 | FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, |
3730 | SkipBodyInfo *SkipBody = nullptr); |
3731 | Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, |
3732 | MultiTemplateParamsArg TemplateParamLists, |
3733 | SkipBodyInfo *SkipBody = nullptr, |
3734 | FnBodyKind BodyKind = FnBodyKind::Other); |
3735 | Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, |
3736 | SkipBodyInfo *SkipBody = nullptr, |
3737 | FnBodyKind BodyKind = FnBodyKind::Other); |
3738 | void applyFunctionAttributesBeforeParsingBody(Decl *FD); |
3739 | |
3740 | /// Determine whether we can delay parsing the body of a function or |
3741 | /// function template until it is used, assuming we don't care about emitting |
3742 | /// code for that function. |
3743 | /// |
3744 | /// This will be \c false if we may need the body of the function in the |
3745 | /// middle of parsing an expression (where it's impractical to switch to |
3746 | /// parsing a different function), for instance, if it's constexpr in C++11 |
3747 | /// or has an 'auto' return type in C++14. These cases are essentially bugs. |
3748 | bool canDelayFunctionBody(const Declarator &D); |
3749 | |
3750 | /// Determine whether we can skip parsing the body of a function |
3751 | /// definition, assuming we don't care about analyzing its body or emitting |
3752 | /// code for that function. |
3753 | /// |
3754 | /// This will be \c false only if we may need the body of the function in |
3755 | /// order to parse the rest of the program (for instance, if it is |
3756 | /// \c constexpr in C++11 or has an 'auto' return type in C++14). |
3757 | bool canSkipFunctionBody(Decl *D); |
3758 | |
3759 | /// Given the set of return statements within a function body, |
3760 | /// compute the variables that are subject to the named return value |
3761 | /// optimization. |
3762 | /// |
3763 | /// Each of the variables that is subject to the named return value |
3764 | /// optimization will be marked as NRVO variables in the AST, and any |
3765 | /// return statement that has a marked NRVO variable as its NRVO candidate can |
3766 | /// use the named return value optimization. |
3767 | /// |
3768 | /// This function applies a very simplistic algorithm for NRVO: if every |
3769 | /// return statement in the scope of a variable has the same NRVO candidate, |
3770 | /// that candidate is an NRVO variable. |
3771 | void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); |
3772 | Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); |
3773 | Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); |
3774 | Decl *ActOnSkippedFunctionBody(Decl *Decl); |
3775 | void ActOnFinishInlineFunctionDef(FunctionDecl *D); |
3776 | |
3777 | /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an |
3778 | /// attribute for which parsing is delayed. |
3779 | void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); |
3780 | |
3781 | /// Diagnose any unused parameters in the given sequence of |
3782 | /// ParmVarDecl pointers. |
3783 | void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); |
3784 | |
3785 | /// Diagnose whether the size of parameters or return value of a |
3786 | /// function or obj-c method definition is pass-by-value and larger than a |
3787 | /// specified threshold. |
3788 | void |
3789 | DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, |
3790 | QualType ReturnTy, NamedDecl *D); |
3791 | |
3792 | Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, |
3793 | SourceLocation RParenLoc); |
3794 | |
3795 | TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S); |
3796 | void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement); |
3797 | |
3798 | void ActOnPopScope(SourceLocation Loc, Scope *S); |
3799 | |
3800 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with |
3801 | /// no declarator (e.g. "struct foo;") is parsed. |
3802 | Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, |
3803 | const ParsedAttributesView &DeclAttrs, |
3804 | RecordDecl *&AnonRecord); |
3805 | |
3806 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with |
3807 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template |
3808 | /// parameters to cope with template friend declarations. |
3809 | Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, |
3810 | const ParsedAttributesView &DeclAttrs, |
3811 | MultiTemplateParamsArg TemplateParams, |
3812 | bool IsExplicitInstantiation, |
3813 | RecordDecl *&AnonRecord, |
3814 | SourceLocation EllipsisLoc = {}); |
3815 | |
3816 | /// BuildAnonymousStructOrUnion - Handle the declaration of an |
3817 | /// anonymous structure or union. Anonymous unions are a C++ feature |
3818 | /// (C++ [class.union]) and a C11 feature; anonymous structures |
3819 | /// are a C11 feature and GNU C++ extension. |
3820 | Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, |
3821 | RecordDecl *Record, |
3822 | const PrintingPolicy &Policy); |
3823 | |
3824 | /// Called once it is known whether |
3825 | /// a tag declaration is an anonymous union or struct. |
3826 | void ActOnDefinedDeclarationSpecifier(Decl *D); |
3827 | |
3828 | /// Emit diagnostic warnings for placeholder members. |
3829 | /// We can only do that after the class is fully constructed, |
3830 | /// as anonymous union/structs can insert placeholders |
3831 | /// in their parent scope (which might be a Record). |
3832 | void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record); |
3833 | |
3834 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an |
3835 | /// Microsoft C anonymous structure. |
3836 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx |
3837 | /// Example: |
3838 | /// |
3839 | /// struct A { int a; }; |
3840 | /// struct B { struct A; int b; }; |
3841 | /// |
3842 | /// void foo() { |
3843 | /// B var; |
3844 | /// var.a = 3; |
3845 | /// } |
3846 | Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, |
3847 | RecordDecl *Record); |
3848 | |
3849 | /// Common ways to introduce type names without a tag for use in diagnostics. |
3850 | /// Keep in sync with err_tag_reference_non_tag. |
3851 | enum NonTagKind { |
3852 | NTK_NonStruct, |
3853 | NTK_NonClass, |
3854 | NTK_NonUnion, |
3855 | NTK_NonEnum, |
3856 | NTK_Typedef, |
3857 | NTK_TypeAlias, |
3858 | NTK_Template, |
3859 | NTK_TypeAliasTemplate, |
3860 | NTK_TemplateTemplateArgument, |
3861 | }; |
3862 | |
3863 | /// Given a non-tag type declaration, returns an enum useful for indicating |
3864 | /// what kind of non-tag type this is. |
3865 | NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); |
3866 | |
3867 | /// Determine whether a tag with a given kind is acceptable |
3868 | /// as a redeclaration of the given tag declaration. |
3869 | /// |
3870 | /// \returns true if the new tag kind is acceptable, false otherwise. |
3871 | bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, |
3872 | bool isDefinition, SourceLocation NewTagLoc, |
3873 | const IdentifierInfo *Name); |
3874 | |
3875 | enum OffsetOfKind { |
3876 | // Not parsing a type within __builtin_offsetof. |
3877 | OOK_Outside, |
3878 | // Parsing a type within __builtin_offsetof. |
3879 | OOK_Builtin, |
3880 | // Parsing a type within macro "offsetof", defined in __buitin_offsetof |
3881 | // To improve our diagnostic message. |
3882 | OOK_Macro, |
3883 | }; |
3884 | |
3885 | /// This is invoked when we see 'struct foo' or 'struct {'. In the |
3886 | /// former case, Name will be non-null. In the later case, Name will be null. |
3887 | /// TagSpec indicates what kind of tag this is. TUK indicates whether this is |
3888 | /// a reference/declaration/definition of a tag. |
3889 | /// |
3890 | /// \param IsTypeSpecifier \c true if this is a type-specifier (or |
3891 | /// trailing-type-specifier) other than one in an alias-declaration. |
3892 | /// |
3893 | /// \param SkipBody If non-null, will be set to indicate if the caller should |
3894 | /// skip the definition of this tag and treat it as if it were a declaration. |
3895 | DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, |
3896 | SourceLocation KWLoc, CXXScopeSpec &SS, |
3897 | IdentifierInfo *Name, SourceLocation NameLoc, |
3898 | const ParsedAttributesView &Attr, AccessSpecifier AS, |
3899 | SourceLocation ModulePrivateLoc, |
3900 | MultiTemplateParamsArg TemplateParameterLists, |
3901 | bool &OwnedDecl, bool &IsDependent, |
3902 | SourceLocation ScopedEnumKWLoc, |
3903 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, |
3904 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, |
3905 | OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr); |
3906 | |
3907 | /// ActOnField - Each field of a C struct/union is passed into this in order |
3908 | /// to create a FieldDecl object for it. |
3909 | Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, |
3910 | Declarator &D, Expr *BitfieldWidth); |
3911 | |
3912 | /// HandleField - Analyze a field of a C struct or a C++ data member. |
3913 | FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, |
3914 | Declarator &D, Expr *BitfieldWidth, |
3915 | InClassInitStyle InitStyle, AccessSpecifier AS); |
3916 | |
3917 | /// Build a new FieldDecl and check its well-formedness. |
3918 | /// |
3919 | /// This routine builds a new FieldDecl given the fields name, type, |
3920 | /// record, etc. \p PrevDecl should refer to any previous declaration |
3921 | /// with the same name and in the same scope as the field to be |
3922 | /// created. |
3923 | /// |
3924 | /// \returns a new FieldDecl. |
3925 | /// |
3926 | /// \todo The Declarator argument is a hack. It will be removed once |
3927 | FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, |
3928 | TypeSourceInfo *TInfo, RecordDecl *Record, |
3929 | SourceLocation Loc, bool Mutable, |
3930 | Expr *BitfieldWidth, InClassInitStyle InitStyle, |
3931 | SourceLocation TSSL, AccessSpecifier AS, |
3932 | NamedDecl *PrevDecl, Declarator *D = nullptr); |
3933 | |
3934 | bool CheckNontrivialField(FieldDecl *FD); |
3935 | |
3936 | /// ActOnLastBitfield - This routine handles synthesized bitfields rules for |
3937 | /// class and class extensions. For every class \@interface and class |
3938 | /// extension \@interface, if the last ivar is a bitfield of any type, |
3939 | /// then add an implicit `char :0` ivar to the end of that interface. |
3940 | void ActOnLastBitfield(SourceLocation DeclStart, |
3941 | SmallVectorImpl<Decl *> &AllIvarDecls); |
3942 | |
3943 | // This is used for both record definitions and ObjC interface declarations. |
3944 | void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, |
3945 | ArrayRef<Decl *> Fields, SourceLocation LBrac, |
3946 | SourceLocation RBrac, const ParsedAttributesView &AttrList); |
3947 | |
3948 | /// ActOnTagStartDefinition - Invoked when we have entered the |
3949 | /// scope of a tag's definition (e.g., for an enumeration, class, |
3950 | /// struct, or union). |
3951 | void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); |
3952 | |
3953 | /// Perform ODR-like check for C/ObjC when merging tag types from modules. |
3954 | /// Differently from C++, actually parse the body and reject / error out |
3955 | /// in case of a structural mismatch. |
3956 | bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody); |
3957 | |
3958 | typedef void *SkippedDefinitionContext; |
3959 | |
3960 | /// Invoked when we enter a tag definition that we're skipping. |
3961 | SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); |
3962 | |
3963 | /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a |
3964 | /// C++ record definition's base-specifiers clause and are starting its |
3965 | /// member declarations. |
3966 | void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, |
3967 | SourceLocation FinalLoc, |
3968 | bool IsFinalSpelledSealed, |
3969 | bool IsAbstract, |
3970 | SourceLocation LBraceLoc); |
3971 | |
3972 | /// ActOnTagFinishDefinition - Invoked once we have finished parsing |
3973 | /// the definition of a tag (enumeration, class, struct, or union). |
3974 | void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, |
3975 | SourceRange BraceRange); |
3976 | |
3977 | void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); |
3978 | |
3979 | /// ActOnTagDefinitionError - Invoked when there was an unrecoverable |
3980 | /// error parsing the definition of a tag. |
3981 | void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); |
3982 | |
3983 | EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, |
3984 | EnumConstantDecl *LastEnumConst, |
3985 | SourceLocation IdLoc, IdentifierInfo *Id, |
3986 | Expr *val); |
3987 | |
3988 | /// Check that this is a valid underlying type for an enum declaration. |
3989 | bool CheckEnumUnderlyingType(TypeSourceInfo *TI); |
3990 | |
3991 | /// Check whether this is a valid redeclaration of a previous enumeration. |
3992 | /// \return true if the redeclaration was invalid. |
3993 | bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, |
3994 | QualType EnumUnderlyingTy, bool IsFixed, |
3995 | const EnumDecl *Prev); |
3996 | |
3997 | /// Determine whether the body of an anonymous enumeration should be skipped. |
3998 | /// \param II The name of the first enumerator. |
3999 | SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, |
4000 | SourceLocation IILoc); |
4001 | |
4002 | Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, |
4003 | SourceLocation IdLoc, IdentifierInfo *Id, |
4004 | const ParsedAttributesView &Attrs, |
4005 | SourceLocation EqualLoc, Expr *Val); |
4006 | void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, |
4007 | Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, |
4008 | const ParsedAttributesView &Attr); |
4009 | |
4010 | /// Set the current declaration context until it gets popped. |
4011 | void PushDeclContext(Scope *S, DeclContext *DC); |
4012 | void PopDeclContext(); |
4013 | |
4014 | /// EnterDeclaratorContext - Used when we must lookup names in the context |
4015 | /// of a declarator's nested name specifier. |
4016 | void EnterDeclaratorContext(Scope *S, DeclContext *DC); |
4017 | void ExitDeclaratorContext(Scope *S); |
4018 | |
4019 | /// Enter a template parameter scope, after it's been associated with a |
4020 | /// particular DeclContext. Causes lookup within the scope to chain through |
4021 | /// enclosing contexts in the correct order. |
4022 | void EnterTemplatedContext(Scope *S, DeclContext *DC); |
4023 | |
4024 | /// Push the parameters of D, which must be a function, into scope. |
4025 | void ActOnReenterFunctionContext(Scope *S, Decl *D); |
4026 | void ActOnExitFunctionContext(); |
4027 | |
4028 | /// Add this decl to the scope shadowed decl chains. |
4029 | void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); |
4030 | |
4031 | /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true |
4032 | /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns |
4033 | /// true if 'D' belongs to the given declaration context. |
4034 | /// |
4035 | /// \param AllowInlineNamespace If \c true, allow the declaration to be in the |
4036 | /// enclosing namespace set of the context, rather than contained |
4037 | /// directly within it. |
4038 | bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, |
4039 | bool AllowInlineNamespace = false) const; |
4040 | |
4041 | /// Finds the scope corresponding to the given decl context, if it |
4042 | /// happens to be an enclosing scope. Otherwise return NULL. |
4043 | static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); |
4044 | |
4045 | /// Subroutines of ActOnDeclarator(). |
4046 | TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, |
4047 | TypeSourceInfo *TInfo); |
4048 | bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New); |
4049 | |
4050 | /// Describes the kind of merge to perform for availability |
4051 | /// attributes (including "deprecated", "unavailable", and "availability"). |
4052 | enum AvailabilityMergeKind { |
4053 | /// Don't merge availability attributes at all. |
4054 | AMK_None, |
4055 | /// Merge availability attributes for a redeclaration, which requires |
4056 | /// an exact match. |
4057 | AMK_Redeclaration, |
4058 | /// Merge availability attributes for an override, which requires |
4059 | /// an exact match or a weakening of constraints. |
4060 | AMK_Override, |
4061 | /// Merge availability attributes for an implementation of |
4062 | /// a protocol requirement. |
4063 | AMK_ProtocolImplementation, |
4064 | /// Merge availability attributes for an implementation of |
4065 | /// an optional protocol requirement. |
4066 | AMK_OptionalProtocolImplementation |
4067 | }; |
4068 | |
4069 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. |
4070 | void mergeDeclAttributes(NamedDecl *New, Decl *Old, |
4071 | AvailabilityMergeKind AMK = AMK_Redeclaration); |
4072 | |
4073 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the |
4074 | /// same name and scope as a previous declaration 'Old'. Figure out |
4075 | /// how to resolve this situation, merging decls or emitting |
4076 | /// diagnostics as appropriate. If there was an error, set New to be invalid. |
4077 | void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, |
4078 | LookupResult &OldDecls); |
4079 | |
4080 | /// MergeFunctionDecl - We just parsed a function 'New' from |
4081 | /// declarator D which has the same name and scope as a previous |
4082 | /// declaration 'Old'. Figure out how to resolve this situation, |
4083 | /// merging decls or emitting diagnostics as appropriate. |
4084 | /// |
4085 | /// In C++, New and Old must be declarations that are not |
4086 | /// overloaded. Use IsOverload to determine whether New and Old are |
4087 | /// overloaded, and to select the Old declaration that New should be |
4088 | /// merged with. |
4089 | /// |
4090 | /// Returns true if there was an error, false otherwise. |
4091 | bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, |
4092 | bool MergeTypeWithOld, bool NewDeclIsDefn); |
4093 | |
4094 | /// Completes the merge of two function declarations that are |
4095 | /// known to be compatible. |
4096 | /// |
4097 | /// This routine handles the merging of attributes and other |
4098 | /// properties of function declarations from the old declaration to |
4099 | /// the new declaration, once we know that New is in fact a |
4100 | /// redeclaration of Old. |
4101 | /// |
4102 | /// \returns false |
4103 | bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, |
4104 | Scope *S, bool MergeTypeWithOld); |
4105 | void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); |
4106 | |
4107 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name |
4108 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this |
4109 | /// situation, merging decls or emitting diagnostics as appropriate. |
4110 | /// |
4111 | /// Tentative definition rules (C99 6.9.2p2) are checked by |
4112 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative |
4113 | /// definitions here, since the initializer hasn't been attached. |
4114 | void MergeVarDecl(VarDecl *New, LookupResult &Previous); |
4115 | |
4116 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and |
4117 | /// scope as a previous declaration 'Old'. Figure out how to merge their |
4118 | /// types, emitting diagnostics as appropriate. |
4119 | /// |
4120 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call |
4121 | /// back to here in AddInitializerToDecl. We can't check them before the |
4122 | /// initializer is attached. |
4123 | void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); |
4124 | |
4125 | /// We've just determined that \p Old and \p New both appear to be definitions |
4126 | /// of the same variable. Either diagnose or fix the problem. |
4127 | bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); |
4128 | void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); |
4129 | |
4130 | /// Filters out lookup results that don't fall within the given scope |
4131 | /// as determined by isDeclInScope. |
4132 | void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, |
4133 | bool ConsiderLinkage, bool AllowInlineNamespace); |
4134 | |
4135 | /// We've determined that \p New is a redeclaration of \p Old. Check that they |
4136 | /// have compatible owning modules. |
4137 | bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); |
4138 | |
4139 | /// [module.interface]p6: |
4140 | /// A redeclaration of an entity X is implicitly exported if X was introduced |
4141 | /// by an exported declaration; otherwise it shall not be exported. |
4142 | bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old); |
4143 | |
4144 | /// A wrapper function for checking the semantic restrictions of |
4145 | /// a redeclaration within a module. |
4146 | bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old); |
4147 | |
4148 | /// Check the redefinition in C++20 Modules. |
4149 | /// |
4150 | /// [basic.def.odr]p14: |
4151 | /// For any definable item D with definitions in multiple translation units, |
4152 | /// - if D is a non-inline non-templated function or variable, or |
4153 | /// - if the definitions in different translation units do not satisfy the |
4154 | /// following requirements, |
4155 | /// the program is ill-formed; a diagnostic is required only if the |
4156 | /// definable item is attached to a named module and a prior definition is |
4157 | /// reachable at the point where a later definition occurs. |
4158 | /// - Each such definition shall not be attached to a named module |
4159 | /// ([module.unit]). |
4160 | /// - Each such definition shall consist of the same sequence of tokens, ... |
4161 | /// ... |
4162 | /// |
4163 | /// Return true if the redefinition is not allowed. Return false otherwise. |
4164 | bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const; |
4165 | |
4166 | bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; |
4167 | |
4168 | /// If it's a file scoped decl that must warn if not used, keep track |
4169 | /// of it. |
4170 | void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); |
4171 | |
4172 | typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)> |
4173 | DiagReceiverTy; |
4174 | |
4175 | void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); |
4176 | void DiagnoseUnusedNestedTypedefs(const RecordDecl *D, |
4177 | DiagReceiverTy DiagReceiver); |
4178 | void DiagnoseUnusedDecl(const NamedDecl *ND); |
4179 | |
4180 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used |
4181 | /// unless they are marked attr(unused). |
4182 | void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver); |
4183 | |
4184 | /// If VD is set but not otherwise used, diagnose, for a parameter or a |
4185 | /// variable. |
4186 | void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver); |
4187 | |
4188 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting |
4189 | /// from S, where a non-field would be declared. This routine copes |
4190 | /// with the difference between C and C++ scoping rules in structs and |
4191 | /// unions. For example, the following code is well-formed in C but |
4192 | /// ill-formed in C++: |
4193 | /// @code |
4194 | /// struct S6 { |
4195 | /// enum { BAR } e; |
4196 | /// }; |
4197 | /// |
4198 | /// void test_S6() { |
4199 | /// struct S6 a; |
4200 | /// a.e = BAR; |
4201 | /// } |
4202 | /// @endcode |
4203 | /// For the declaration of BAR, this routine will return a different |
4204 | /// scope. The scope S will be the scope of the unnamed enumeration |
4205 | /// within S6. In C++, this routine will return the scope associated |
4206 | /// with S6, because the enumeration's scope is a transparent |
4207 | /// context but structures can contain non-field names. In C, this |
4208 | /// routine will return the translation unit scope, since the |
4209 | /// enumeration's scope is a transparent context and structures cannot |
4210 | /// contain non-field names. |
4211 | Scope *getNonFieldDeclScope(Scope *S); |
4212 | |
4213 | FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, |
4214 | SourceLocation Loc); |
4215 | |
4216 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at |
4217 | /// file scope. lazily create a decl for it. ForRedeclaration is true |
4218 | /// if we're creating this built-in in anticipation of redeclaring the |
4219 | /// built-in. |
4220 | NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, |
4221 | bool ForRedeclaration, SourceLocation Loc); |
4222 | |
4223 | /// Get the outermost AttributedType node that sets a calling convention. |
4224 | /// Valid types should not have multiple attributes with different CCs. |
4225 | const AttributedType *getCallingConvAttributedType(QualType T) const; |
4226 | |
4227 | /// GetNameForDeclarator - Determine the full declaration name for the |
4228 | /// given Declarator. |
4229 | DeclarationNameInfo GetNameForDeclarator(Declarator &D); |
4230 | |
4231 | /// Retrieves the declaration name from a parsed unqualified-id. |
4232 | DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); |
4233 | |
4234 | /// ParsingInitForAutoVars - a set of declarations with auto types for which |
4235 | /// we are currently parsing the initializer. |
4236 | llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars; |
4237 | |
4238 | /// Look for a locally scoped extern "C" declaration by the given name. |
4239 | NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); |
4240 | |
4241 | void deduceOpenCLAddressSpace(ValueDecl *decl); |
4242 | |
4243 | /// Adjust the \c DeclContext for a function or variable that might be a |
4244 | /// function-local external declaration. |
4245 | static bool adjustContextForLocalExternDecl(DeclContext *&DC); |
4246 | |
4247 | void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); |
4248 | |
4249 | /// Checks if the variant/multiversion functions are compatible. |
4250 | bool areMultiversionVariantFunctionsCompatible( |
4251 | const FunctionDecl *OldFD, const FunctionDecl *NewFD, |
4252 | const PartialDiagnostic &NoProtoDiagID, |
4253 | const PartialDiagnosticAt &NoteCausedDiagIDAt, |
4254 | const PartialDiagnosticAt &NoSupportDiagIDAt, |
4255 | const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, |
4256 | bool ConstexprSupported, bool CLinkageMayDiffer); |
4257 | |
4258 | /// type checking declaration initializers (C99 6.7.8) |
4259 | bool CheckForConstantInitializer( |
4260 | Expr *Init, unsigned DiagID = diag::err_init_element_not_constant); |
4261 | |
4262 | QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, |
4263 | QualType Type, TypeSourceInfo *TSI, |
4264 | SourceRange Range, bool DirectInit, |
4265 | Expr *Init); |
4266 | |
4267 | bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, |
4268 | Expr *Init); |
4269 | |
4270 | sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator); |
4271 | |
4272 | // Heuristically tells if the function is `get_return_object` member of a |
4273 | // coroutine promise_type by matching the function name. |
4274 | static bool CanBeGetReturnObject(const FunctionDecl *FD); |
4275 | static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD); |
4276 | |
4277 | /// ImplicitlyDefineFunction - An undeclared identifier was used in a function |
4278 | /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). |
4279 | NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, |
4280 | Scope *S); |
4281 | |
4282 | /// If this function is a C++ replaceable global allocation function |
4283 | /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), |
4284 | /// adds any function attributes that we know a priori based on the standard. |
4285 | /// |
4286 | /// We need to check for duplicate attributes both here and where user-written |
4287 | /// attributes are applied to declarations. |
4288 | void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( |
4289 | FunctionDecl *FD); |
4290 | |
4291 | /// Adds any function attributes that we know a priori based on |
4292 | /// the declaration of this function. |
4293 | /// |
4294 | /// These attributes can apply both to implicitly-declared builtins |
4295 | /// (like __builtin___printf_chk) or to library-declared functions |
4296 | /// like NSLog or printf. |
4297 | /// |
4298 | /// We need to check for duplicate attributes both here and where user-written |
4299 | /// attributes are applied to declarations. |
4300 | void AddKnownFunctionAttributes(FunctionDecl *FD); |
4301 | |
4302 | /// VerifyBitField - verifies that a bit field expression is an ICE and has |
4303 | /// the correct width, and that the field type is valid. |
4304 | /// Returns false on success. |
4305 | ExprResult VerifyBitField(SourceLocation FieldLoc, |
4306 | const IdentifierInfo *FieldName, QualType FieldTy, |
4307 | bool IsMsStruct, Expr *BitWidth); |
4308 | |
4309 | /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag |
4310 | /// enum. If AllowMask is true, then we also allow the complement of a valid |
4311 | /// value, to be used as a mask. |
4312 | bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, |
4313 | bool AllowMask) const; |
4314 | |
4315 | /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. |
4316 | void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, |
4317 | SourceLocation WeakNameLoc); |
4318 | |
4319 | /// ActOnPragmaRedefineExtname - Called on well formed |
4320 | /// \#pragma redefine_extname oldname newname. |
4321 | void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, |
4322 | IdentifierInfo *AliasName, |
4323 | SourceLocation PragmaLoc, |
4324 | SourceLocation WeakNameLoc, |
4325 | SourceLocation AliasNameLoc); |
4326 | |
4327 | /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. |
4328 | void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, |
4329 | SourceLocation PragmaLoc, |
4330 | SourceLocation WeakNameLoc, |
4331 | SourceLocation AliasNameLoc); |
4332 | |
4333 | /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. |
4334 | enum class FunctionEmissionStatus { |
4335 | Emitted, |
4336 | CUDADiscarded, // Discarded due to CUDA/HIP hostness |
4337 | OMPDiscarded, // Discarded due to OpenMP hostness |
4338 | TemplateDiscarded, // Discarded due to uninstantiated templates |
4339 | Unknown, |
4340 | }; |
4341 | FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, |
4342 | bool Final = false); |
4343 | |
4344 | // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. |
4345 | bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); |
4346 | |
4347 | private: |
4348 | /// Function or variable declarations to be checked for whether the deferred |
4349 | /// diagnostics should be emitted. |
4350 | llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags; |
4351 | |
4352 | /// Map of current shadowing declarations to shadowed declarations. Warn if |
4353 | /// it looks like the user is trying to modify the shadowing declaration. |
4354 | llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; |
4355 | |
4356 | // We need this to handle |
4357 | // |
4358 | // typedef struct { |
4359 | // void *foo() { return 0; } |
4360 | // } A; |
4361 | // |
4362 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' |
4363 | // for example. If 'A', foo will have external linkage. If we have '*A', |
4364 | // foo will have no linkage. Since we can't know until we get to the end |
4365 | // of the typedef, this function finds out if D might have non-external |
4366 | // linkage. Callers should verify at the end of the TU if it D has external |
4367 | // linkage or not. |
4368 | static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); |
4369 | |
4370 | ///@} |
4371 | |
4372 | // |
4373 | // |
4374 | // ------------------------------------------------------------------------- |
4375 | // |
4376 | // |
4377 | |
4378 | /// \name Declaration Attribute Handling |
4379 | /// Implementations are in SemaDeclAttr.cpp |
4380 | ///@{ |
4381 | |
4382 | public: |
4383 | /// Describes the kind of priority given to an availability attribute. |
4384 | /// |
4385 | /// The sum of priorities deteremines the final priority of the attribute. |
4386 | /// The final priority determines how the attribute will be merged. |
4387 | /// An attribute with a lower priority will always remove higher priority |
4388 | /// attributes for the specified platform when it is being applied. An |
4389 | /// attribute with a higher priority will not be applied if the declaration |
4390 | /// already has an availability attribute with a lower priority for the |
4391 | /// specified platform. The final prirority values are not expected to match |
4392 | /// the values in this enumeration, but instead should be treated as a plain |
4393 | /// integer value. This enumeration just names the priority weights that are |
4394 | /// used to calculate that final vaue. |
4395 | enum AvailabilityPriority : int { |
4396 | /// The availability attribute was specified explicitly next to the |
4397 | /// declaration. |
4398 | AP_Explicit = 0, |
4399 | |
4400 | /// The availability attribute was applied using '#pragma clang attribute'. |
4401 | AP_PragmaClangAttribute = 1, |
4402 | |
4403 | /// The availability attribute for a specific platform was inferred from |
4404 | /// an availability attribute for another platform. |
4405 | AP_InferredFromOtherPlatform = 2 |
4406 | }; |
4407 | |
4408 | /// Describes the reason a calling convention specification was ignored, used |
4409 | /// for diagnostics. |
4410 | enum class CallingConventionIgnoredReason { |
4411 | ForThisTarget = 0, |
4412 | VariadicFunction, |
4413 | ConstructorDestructor, |
4414 | BuiltinFunction |
4415 | }; |
4416 | |
4417 | /// A helper function to provide Attribute Location for the Attr types |
4418 | /// AND the ParsedAttr. |
4419 | template <typename AttrInfo> |
4420 | static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation> |
4421 | getAttrLoc(const AttrInfo &AL) { |
4422 | return AL.getLocation(); |
4423 | } |
4424 | SourceLocation getAttrLoc(const ParsedAttr &AL); |
4425 | |
4426 | /// If Expr is a valid integer constant, get the value of the integer |
4427 | /// expression and return success or failure. May output an error. |
4428 | /// |
4429 | /// Negative argument is implicitly converted to unsigned, unless |
4430 | /// \p StrictlyUnsigned is true. |
4431 | template <typename AttrInfo> |
4432 | bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val, |
4433 | unsigned Idx = UINT_MAX, |
4434 | bool StrictlyUnsigned = false) { |
4435 | std::optional<llvm::APSInt> I = llvm::APSInt(32); |
4436 | if (Expr->isTypeDependent() || |
4437 | !(I = Expr->getIntegerConstantExpr(Ctx: Context))) { |
4438 | if (Idx != UINT_MAX) |
4439 | Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) |
4440 | << &AI << Idx << AANT_ArgumentIntegerConstant |
4441 | << Expr->getSourceRange(); |
4442 | else |
4443 | Diag(getAttrLoc(AI), diag::err_attribute_argument_type) |
4444 | << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange(); |
4445 | return false; |
4446 | } |
4447 | |
4448 | if (!I->isIntN(N: 32)) { |
4449 | Diag(Expr->getExprLoc(), diag::err_ice_too_large) |
4450 | << toString(*I, 10, false) << 32 << /* Unsigned */ 1; |
4451 | return false; |
4452 | } |
4453 | |
4454 | if (StrictlyUnsigned && I->isSigned() && I->isNegative()) { |
4455 | Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer) |
4456 | << &AI << /*non-negative*/ 1; |
4457 | return false; |
4458 | } |
4459 | |
4460 | Val = (uint32_t)I->getZExtValue(); |
4461 | return true; |
4462 | } |
4463 | |
4464 | /// WeakTopLevelDecl - Translation-unit scoped declarations generated by |
4465 | /// \#pragma weak during processing of other Decls. |
4466 | /// I couldn't figure out a clean way to generate these in-line, so |
4467 | /// we store them here and handle separately -- which is a hack. |
4468 | /// It would be best to refactor this. |
4469 | SmallVector<Decl *, 2> WeakTopLevelDecl; |
4470 | |
4471 | /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls |
4472 | SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } |
4473 | |
4474 | typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, |
4475 | &ExternalSemaSource::ReadExtVectorDecls, 2, 2> |
4476 | ExtVectorDeclsType; |
4477 | |
4478 | /// ExtVectorDecls - This is a list all the extended vector types. This allows |
4479 | /// us to associate a raw vector type with one of the ext_vector type names. |
4480 | /// This is only necessary for issuing pretty diagnostics. |
4481 | ExtVectorDeclsType ExtVectorDecls; |
4482 | |
4483 | /// Check if the argument \p E is a ASCII string literal. If not emit an error |
4484 | /// and return false, otherwise set \p Str to the value of the string literal |
4485 | /// and return true. |
4486 | bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, |
4487 | const Expr *E, StringRef &Str, |
4488 | SourceLocation *ArgLocation = nullptr); |
4489 | |
4490 | /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal. |
4491 | /// If not emit an error and return false. If the argument is an identifier it |
4492 | /// will emit an error with a fixit hint and treat it as if it was a string |
4493 | /// literal. |
4494 | bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, |
4495 | StringRef &Str, |
4496 | SourceLocation *ArgLocation = nullptr); |
4497 | |
4498 | /// Determine if type T is a valid subject for a nonnull and similar |
4499 | /// attributes. Dependent types are considered valid so they can be checked |
4500 | /// during instantiation time. By default, we look through references (the |
4501 | /// behavior used by nonnull), but if the second parameter is true, then we |
4502 | /// treat a reference type as valid. |
4503 | bool isValidPointerAttrType(QualType T, bool RefOkay = false); |
4504 | |
4505 | /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular |
4506 | /// declaration. |
4507 | void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, |
4508 | Expr *OE); |
4509 | |
4510 | /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular |
4511 | /// declaration. |
4512 | void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, |
4513 | Expr *ParamExpr); |
4514 | |
4515 | bool CheckAttrTarget(const ParsedAttr &CurrAttr); |
4516 | bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); |
4517 | |
4518 | AvailabilityAttr *mergeAvailabilityAttr( |
4519 | NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, |
4520 | bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, |
4521 | VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, |
4522 | bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, |
4523 | int Priority, IdentifierInfo *IIEnvironment); |
4524 | |
4525 | TypeVisibilityAttr * |
4526 | mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, |
4527 | TypeVisibilityAttr::VisibilityType Vis); |
4528 | VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, |
4529 | VisibilityAttr::VisibilityType Vis); |
4530 | SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, |
4531 | StringRef Name); |
4532 | |
4533 | /// Used to implement to perform semantic checking on |
4534 | /// attribute((section("foo"))) specifiers. |
4535 | /// |
4536 | /// In this case, "foo" is passed in to be checked. If the section |
4537 | /// specifier is invalid, return an Error that indicates the problem. |
4538 | /// |
4539 | /// This is a simple quality of implementation feature to catch errors |
4540 | /// and give good diagnostics in cases when the assembler or code generator |
4541 | /// would otherwise reject the section specifier. |
4542 | llvm::Error isValidSectionSpecifier(StringRef Str); |
4543 | bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); |
4544 | CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, |
4545 | StringRef Name); |
4546 | |
4547 | // Check for things we'd like to warn about. Multiversioning issues are |
4548 | // handled later in the process, once we know how many exist. |
4549 | bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); |
4550 | |
4551 | /// Check Target Version attrs |
4552 | bool checkTargetVersionAttr(SourceLocation Loc, Decl *D, StringRef Str); |
4553 | bool checkTargetClonesAttrString( |
4554 | SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal, |
4555 | Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault, |
4556 | SmallVectorImpl<SmallString<64>> &StringsBuffer); |
4557 | |
4558 | ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, |
4559 | StringRef NewUserDiagnostic); |
4560 | FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, |
4561 | IdentifierInfo *Format, int FormatIdx, |
4562 | int FirstArg); |
4563 | |
4564 | /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. |
4565 | void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, |
4566 | bool IsPackExpansion); |
4567 | void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, |
4568 | bool IsPackExpansion); |
4569 | |
4570 | /// AddAlignValueAttr - Adds an align_value attribute to a particular |
4571 | /// declaration. |
4572 | void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); |
4573 | |
4574 | /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments. |
4575 | Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, |
4576 | MutableArrayRef<Expr *> Args); |
4577 | Attr *CreateAnnotationAttr(const ParsedAttr &AL); |
4578 | |
4579 | bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, |
4580 | bool BestCase, |
4581 | MSInheritanceModel SemanticSpelling); |
4582 | |
4583 | void CheckAlignasUnderalignment(Decl *D); |
4584 | |
4585 | /// AddModeAttr - Adds a mode attribute to a particular declaration. |
4586 | void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, |
4587 | bool InInstantiation = false); |
4588 | AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, |
4589 | const AttributeCommonInfo &CI, |
4590 | const IdentifierInfo *Ident); |
4591 | MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); |
4592 | OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, |
4593 | const AttributeCommonInfo &CI); |
4594 | InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); |
4595 | InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, |
4596 | const InternalLinkageAttr &AL); |
4597 | |
4598 | /// Check validaty of calling convention attribute \p attr. If \p FD |
4599 | /// is not null pointer, use \p FD to determine the CUDA/HIP host/device |
4600 | /// target. Otherwise, it is specified by \p CFT. |
4601 | bool CheckCallingConvAttr( |
4602 | const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr, |
4603 | CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget); |
4604 | |
4605 | /// Checks a regparm attribute, returning true if it is ill-formed and |
4606 | /// otherwise setting numParams to the appropriate value. |
4607 | bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); |
4608 | |
4609 | /// Create an CUDALaunchBoundsAttr attribute. |
4610 | CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, |
4611 | Expr *MaxThreads, |
4612 | Expr *MinBlocks, |
4613 | Expr *MaxBlocks); |
4614 | |
4615 | /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular |
4616 | /// declaration. |
4617 | void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, |
4618 | Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks); |
4619 | |
4620 | enum class RetainOwnershipKind { NS, CF, OS }; |
4621 | |
4622 | UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, |
4623 | StringRef UuidAsWritten, MSGuidDecl *GuidDecl); |
4624 | |
4625 | BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL); |
4626 | |
4627 | DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); |
4628 | DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); |
4629 | MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, |
4630 | const AttributeCommonInfo &CI, |
4631 | bool BestCase, |
4632 | MSInheritanceModel Model); |
4633 | |
4634 | EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); |
4635 | EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, |
4636 | const EnforceTCBLeafAttr &AL); |
4637 | |
4638 | /// Helper for delayed processing TransparentUnion or |
4639 | /// BPFPreserveAccessIndexAttr attribute. |
4640 | void ProcessDeclAttributeDelayed(Decl *D, |
4641 | const ParsedAttributesView &AttrList); |
4642 | |
4643 | // Options for ProcessDeclAttributeList(). |
4644 | struct ProcessDeclAttributeOptions { |
4645 | ProcessDeclAttributeOptions() |
4646 | : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {} |
4647 | |
4648 | ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) { |
4649 | ProcessDeclAttributeOptions Result = *this; |
4650 | Result.IncludeCXX11Attributes = Val; |
4651 | return Result; |
4652 | } |
4653 | |
4654 | ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) { |
4655 | ProcessDeclAttributeOptions Result = *this; |
4656 | Result.IgnoreTypeAttributes = Val; |
4657 | return Result; |
4658 | } |
4659 | |
4660 | // Should C++11 attributes be processed? |
4661 | bool IncludeCXX11Attributes; |
4662 | |
4663 | // Should any type attributes encountered be ignored? |
4664 | // If this option is false, a diagnostic will be emitted for any type |
4665 | // attributes of a kind that does not "slide" from the declaration to |
4666 | // the decl-specifier-seq. |
4667 | bool IgnoreTypeAttributes; |
4668 | }; |
4669 | |
4670 | /// ProcessDeclAttributeList - Apply all the decl attributes in the specified |
4671 | /// attribute list to the specified decl, ignoring any type attributes. |
4672 | void ProcessDeclAttributeList(Scope *S, Decl *D, |
4673 | const ParsedAttributesView &AttrList, |
4674 | const ProcessDeclAttributeOptions &Options = |
4675 | ProcessDeclAttributeOptions()); |
4676 | |
4677 | /// Annotation attributes are the only attributes allowed after an access |
4678 | /// specifier. |
4679 | bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, |
4680 | const ParsedAttributesView &AttrList); |
4681 | |
4682 | /// checkUnusedDeclAttributes - Given a declarator which is not being |
4683 | /// used to build a declaration, complain about any decl attributes |
4684 | /// which might be lying around on it. |
4685 | void checkUnusedDeclAttributes(Declarator &D); |
4686 | |
4687 | /// DeclClonePragmaWeak - clone existing decl (maybe definition), |
4688 | /// \#pragma weak needs a non-definition decl and source may not have one. |
4689 | NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II, |
4690 | SourceLocation Loc); |
4691 | |
4692 | /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak |
4693 | /// applied to it, possibly with an alias. |
4694 | void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W); |
4695 | |
4696 | void ProcessPragmaWeak(Scope *S, Decl *D); |
4697 | // Decl attributes - this routine is the top level dispatcher. |
4698 | void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); |
4699 | |
4700 | void PopParsingDeclaration(ParsingDeclState state, Decl *decl); |
4701 | |
4702 | /// Given a set of delayed diagnostics, re-emit them as if they had |
4703 | /// been delayed in the current context instead of in the given pool. |
4704 | /// Essentially, this just moves them to the current pool. |
4705 | void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); |
4706 | |
4707 | /// Check if IdxExpr is a valid parameter index for a function or |
4708 | /// instance method D. May output an error. |
4709 | /// |
4710 | /// \returns true if IdxExpr is a valid index. |
4711 | template <typename AttrInfo> |
4712 | bool checkFunctionOrMethodParameterIndex(const Decl *D, const AttrInfo &AI, |
4713 | unsigned AttrArgNum, |
4714 | const Expr *IdxExpr, ParamIdx &Idx, |
4715 | bool CanIndexImplicitThis = false) { |
4716 | assert(isFunctionOrMethodOrBlockForAttrSubject(D)); |
4717 | |
4718 | // In C++ the implicit 'this' function parameter also counts. |
4719 | // Parameters are counted from one. |
4720 | bool HP = hasFunctionProto(D); |
4721 | bool HasImplicitThisParam = isInstanceMethod(D); |
4722 | bool IV = HP && isFunctionOrMethodVariadic(D); |
4723 | unsigned NumParams = |
4724 | (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; |
4725 | |
4726 | std::optional<llvm::APSInt> IdxInt; |
4727 | if (IdxExpr->isTypeDependent() || |
4728 | !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: Context))) { |
4729 | Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) |
4730 | << &AI << AttrArgNum << AANT_ArgumentIntegerConstant |
4731 | << IdxExpr->getSourceRange(); |
4732 | return false; |
4733 | } |
4734 | |
4735 | unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX); |
4736 | if (IdxSource < 1 || (!IV && IdxSource > NumParams)) { |
4737 | Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds) |
4738 | << &AI << AttrArgNum << IdxExpr->getSourceRange(); |
4739 | return false; |
4740 | } |
4741 | if (HasImplicitThisParam && !CanIndexImplicitThis) { |
4742 | if (IdxSource == 1) { |
4743 | Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument) |
4744 | << &AI << IdxExpr->getSourceRange(); |
4745 | return false; |
4746 | } |
4747 | } |
4748 | |
4749 | Idx = ParamIdx(IdxSource, D); |
4750 | return true; |
4751 | } |
4752 | |
4753 | ///@} |
4754 | |
4755 | // |
4756 | // |
4757 | // ------------------------------------------------------------------------- |
4758 | // |
4759 | // |
4760 | |
4761 | /// \name C++ Declarations |
4762 | /// Implementations are in SemaDeclCXX.cpp |
4763 | ///@{ |
4764 | |
4765 | public: |
4766 | void CheckDelegatingCtorCycles(); |
4767 | |
4768 | /// Called before parsing a function declarator belonging to a function |
4769 | /// declaration. |
4770 | void ActOnStartFunctionDeclarationDeclarator(Declarator &D, |
4771 | unsigned TemplateParameterDepth); |
4772 | |
4773 | /// Called after parsing a function declarator belonging to a function |
4774 | /// declaration. |
4775 | void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); |
4776 | |
4777 | // Act on C++ namespaces |
4778 | Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, |
4779 | SourceLocation NamespaceLoc, |
4780 | SourceLocation IdentLoc, IdentifierInfo *Ident, |
4781 | SourceLocation LBrace, |
4782 | const ParsedAttributesView &AttrList, |
4783 | UsingDirectiveDecl *&UsingDecl, bool IsNested); |
4784 | |
4785 | /// ActOnFinishNamespaceDef - This callback is called after a namespace is |
4786 | /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. |
4787 | void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); |
4788 | |
4789 | NamespaceDecl *getStdNamespace() const; |
4790 | |
4791 | /// Retrieve the special "std" namespace, which may require us to |
4792 | /// implicitly define the namespace. |
4793 | NamespaceDecl *getOrCreateStdNamespace(); |
4794 | |
4795 | CXXRecordDecl *getStdBadAlloc() const; |
4796 | EnumDecl *getStdAlignValT() const; |
4797 | |
4798 | ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, |
4799 | const IdentifierInfo *MemberOrBase); |
4800 | |
4801 | enum class ComparisonCategoryUsage { |
4802 | /// The '<=>' operator was used in an expression and a builtin operator |
4803 | /// was selected. |
4804 | OperatorInExpression, |
4805 | /// A defaulted 'operator<=>' needed the comparison category. This |
4806 | /// typically only applies to 'std::strong_ordering', due to the implicit |
4807 | /// fallback return value. |
4808 | DefaultedOperator, |
4809 | }; |
4810 | |
4811 | /// Lookup the specified comparison category types in the standard |
4812 | /// library, an check the VarDecls possibly returned by the operator<=> |
4813 | /// builtins for that type. |
4814 | /// |
4815 | /// \return The type of the comparison category type corresponding to the |
4816 | /// specified Kind, or a null type if an error occurs |
4817 | QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, |
4818 | SourceLocation Loc, |
4819 | ComparisonCategoryUsage Usage); |
4820 | |
4821 | /// Tests whether Ty is an instance of std::initializer_list and, if |
4822 | /// it is and Element is not NULL, assigns the element type to Element. |
4823 | bool isStdInitializerList(QualType Ty, QualType *Element); |
4824 | |
4825 | /// Looks for the std::initializer_list template and instantiates it |
4826 | /// with Element, or emits an error if it's not found. |
4827 | /// |
4828 | /// \returns The instantiated template, or null on error. |
4829 | QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); |
4830 | |
4831 | /// Determine whether Ctor is an initializer-list constructor, as |
4832 | /// defined in [dcl.init.list]p2. |
4833 | bool isInitListConstructor(const FunctionDecl *Ctor); |
4834 | |
4835 | Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, |
4836 | SourceLocation NamespcLoc, CXXScopeSpec &SS, |
4837 | SourceLocation IdentLoc, |
4838 | IdentifierInfo *NamespcName, |
4839 | const ParsedAttributesView &AttrList); |
4840 | |
4841 | void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); |
4842 | |
4843 | Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, |
4844 | SourceLocation AliasLoc, IdentifierInfo *Alias, |
4845 | CXXScopeSpec &SS, SourceLocation IdentLoc, |
4846 | IdentifierInfo *Ident); |
4847 | |
4848 | /// Remove decls we can't actually see from a lookup being used to declare |
4849 | /// shadow using decls. |
4850 | /// |
4851 | /// \param S - The scope of the potential shadow decl |
4852 | /// \param Previous - The lookup of a potential shadow decl's name. |
4853 | void FilterUsingLookup(Scope *S, LookupResult &lookup); |
4854 | |
4855 | /// Hides a using shadow declaration. This is required by the current |
4856 | /// using-decl implementation when a resolvable using declaration in a |
4857 | /// class is followed by a declaration which would hide or override |
4858 | /// one or more of the using decl's targets; for example: |
4859 | /// |
4860 | /// struct Base { void foo(int); }; |
4861 | /// struct Derived : Base { |
4862 | /// using Base::foo; |
4863 | /// void foo(int); |
4864 | /// }; |
4865 | /// |
4866 | /// The governing language is C++03 [namespace.udecl]p12: |
4867 | /// |
4868 | /// When a using-declaration brings names from a base class into a |
4869 | /// derived class scope, member functions in the derived class |
4870 | /// override and/or hide member functions with the same name and |
4871 | /// parameter types in a base class (rather than conflicting). |
4872 | /// |
4873 | /// There are two ways to implement this: |
4874 | /// (1) optimistically create shadow decls when they're not hidden |
4875 | /// by existing declarations, or |
4876 | /// (2) don't create any shadow decls (or at least don't make them |
4877 | /// visible) until we've fully parsed/instantiated the class. |
4878 | /// The problem with (1) is that we might have to retroactively remove |
4879 | /// a shadow decl, which requires several O(n) operations because the |
4880 | /// decl structures are (very reasonably) not designed for removal. |
4881 | /// (2) avoids this but is very fiddly and phase-dependent. |
4882 | void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); |
4883 | |
4884 | /// Determines whether to create a using shadow decl for a particular |
4885 | /// decl, given the set of decls existing prior to this using lookup. |
4886 | bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, |
4887 | const LookupResult &PreviousDecls, |
4888 | UsingShadowDecl *&PrevShadow); |
4889 | |
4890 | /// Builds a shadow declaration corresponding to a 'using' declaration. |
4891 | UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, |
4892 | NamedDecl *Target, |
4893 | UsingShadowDecl *PrevDecl); |
4894 | |
4895 | /// Checks that the given using declaration is not an invalid |
4896 | /// redeclaration. Note that this is checking only for the using decl |
4897 | /// itself, not for any ill-formedness among the UsingShadowDecls. |
4898 | bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, |
4899 | bool HasTypenameKeyword, |
4900 | const CXXScopeSpec &SS, |
4901 | SourceLocation NameLoc, |
4902 | const LookupResult &Previous); |
4903 | |
4904 | /// Checks that the given nested-name qualifier used in a using decl |
4905 | /// in the current context is appropriately related to the current |
4906 | /// scope. If an error is found, diagnoses it and returns true. |
4907 | /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's |
4908 | /// the result of that lookup. UD is likewise nullptr, except when we have an |
4909 | /// already-populated UsingDecl whose shadow decls contain the same |
4910 | /// information (i.e. we're instantiating a UsingDecl with non-dependent |
4911 | /// scope). |
4912 | bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, |
4913 | const CXXScopeSpec &SS, |
4914 | const DeclarationNameInfo &NameInfo, |
4915 | SourceLocation NameLoc, |
4916 | const LookupResult *R = nullptr, |
4917 | const UsingDecl *UD = nullptr); |
4918 | |
4919 | /// Builds a using declaration. |
4920 | /// |
4921 | /// \param IsInstantiation - Whether this call arises from an |
4922 | /// instantiation of an unresolved using declaration. We treat |
4923 | /// the lookup differently for these declarations. |
4924 | NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, |
4925 | SourceLocation UsingLoc, |
4926 | bool HasTypenameKeyword, |
4927 | SourceLocation TypenameLoc, CXXScopeSpec &SS, |
4928 | DeclarationNameInfo NameInfo, |
4929 | SourceLocation EllipsisLoc, |
4930 | const ParsedAttributesView &AttrList, |
4931 | bool IsInstantiation, bool IsUsingIfExists); |
4932 | NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, |
4933 | SourceLocation UsingLoc, |
4934 | SourceLocation EnumLoc, |
4935 | SourceLocation NameLoc, |
4936 | TypeSourceInfo *EnumType, EnumDecl *ED); |
4937 | NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, |
4938 | ArrayRef<NamedDecl *> Expansions); |
4939 | |
4940 | /// Additional checks for a using declaration referring to a constructor name. |
4941 | bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); |
4942 | |
4943 | /// Given a derived-class using shadow declaration for a constructor and the |
4944 | /// correspnding base class constructor, find or create the implicit |
4945 | /// synthesized derived class constructor to use for this initialization. |
4946 | CXXConstructorDecl * |
4947 | findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, |
4948 | ConstructorUsingShadowDecl *DerivedShadow); |
4949 | |
4950 | Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, |
4951 | SourceLocation UsingLoc, |
4952 | SourceLocation TypenameLoc, CXXScopeSpec &SS, |
4953 | UnqualifiedId &Name, SourceLocation EllipsisLoc, |
4954 | const ParsedAttributesView &AttrList); |
4955 | Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, |
4956 | SourceLocation UsingLoc, |
4957 | SourceLocation EnumLoc, SourceRange TyLoc, |
4958 | const IdentifierInfo &II, ParsedType Ty, |
4959 | CXXScopeSpec *SS = nullptr); |
4960 | Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, |
4961 | MultiTemplateParamsArg TemplateParams, |
4962 | SourceLocation UsingLoc, UnqualifiedId &Name, |
4963 | const ParsedAttributesView &AttrList, |
4964 | TypeResult Type, Decl *DeclFromDeclSpec); |
4965 | |
4966 | /// BuildCXXConstructExpr - Creates a complete call to a constructor, |
4967 | /// including handling of its default argument expressions. |
4968 | /// |
4969 | /// \param ConstructKind - a CXXConstructExpr::ConstructionKind |
4970 | ExprResult BuildCXXConstructExpr( |
4971 | SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, |
4972 | CXXConstructorDecl *Constructor, MultiExprArg Exprs, |
4973 | bool HadMultipleCandidates, bool IsListInitialization, |
4974 | bool IsStdInitListInitialization, bool RequiresZeroInit, |
4975 | CXXConstructionKind ConstructKind, SourceRange ParenRange); |
4976 | |
4977 | /// Build a CXXConstructExpr whose constructor has already been resolved if |
4978 | /// it denotes an inherited constructor. |
4979 | ExprResult BuildCXXConstructExpr( |
4980 | SourceLocation ConstructLoc, QualType DeclInitType, |
4981 | CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, |
4982 | bool HadMultipleCandidates, bool IsListInitialization, |
4983 | bool IsStdInitListInitialization, bool RequiresZeroInit, |
4984 | CXXConstructionKind ConstructKind, SourceRange ParenRange); |
4985 | |
4986 | // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if |
4987 | // the constructor can be elidable? |
4988 | ExprResult BuildCXXConstructExpr( |
4989 | SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, |
4990 | CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, |
4991 | bool HadMultipleCandidates, bool IsListInitialization, |
4992 | bool IsStdInitListInitialization, bool RequiresZeroInit, |
4993 | CXXConstructionKind ConstructKind, SourceRange ParenRange); |
4994 | |
4995 | ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, |
4996 | SourceLocation InitLoc); |
4997 | |
4998 | /// FinalizeVarWithDestructor - Prepare for calling destructor on the |
4999 | /// constructed variable. |
5000 | void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); |
5001 | |
5002 | /// Helper class that collects exception specifications for |
5003 | /// implicitly-declared special member functions. |
5004 | class ImplicitExceptionSpecification { |
5005 | // Pointer to allow copying |
5006 | Sema *Self; |
5007 | // We order exception specifications thus: |
5008 | // noexcept is the most restrictive, but is only used in C++11. |
5009 | // throw() comes next. |
5010 | // Then a throw(collected exceptions) |
5011 | // Finally no specification, which is expressed as noexcept(false). |
5012 | // throw(...) is used instead if any called function uses it. |
5013 | ExceptionSpecificationType ComputedEST; |
5014 | llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; |
5015 | SmallVector<QualType, 4> Exceptions; |
5016 | |
5017 | void ClearExceptions() { |
5018 | ExceptionsSeen.clear(); |
5019 | Exceptions.clear(); |
5020 | } |
5021 | |
5022 | public: |
5023 | explicit ImplicitExceptionSpecification(Sema &Self) |
5024 | : Self(&Self), ComputedEST(EST_BasicNoexcept) { |
5025 | if (!Self.getLangOpts().CPlusPlus11) |
5026 | ComputedEST = EST_DynamicNone; |
5027 | } |
5028 | |
5029 | /// Get the computed exception specification type. |
5030 | ExceptionSpecificationType getExceptionSpecType() const { |
5031 | assert(!isComputedNoexcept(ComputedEST) && |
5032 | "noexcept(expr) should not be a possible result" ); |
5033 | return ComputedEST; |
5034 | } |
5035 | |
5036 | /// The number of exceptions in the exception specification. |
5037 | unsigned size() const { return Exceptions.size(); } |
5038 | |
5039 | /// The set of exceptions in the exception specification. |
5040 | const QualType *data() const { return Exceptions.data(); } |
5041 | |
5042 | /// Integrate another called method into the collected data. |
5043 | void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); |
5044 | |
5045 | /// Integrate an invoked expression into the collected data. |
5046 | void CalledExpr(Expr *E) { CalledStmt(E); } |
5047 | |
5048 | /// Integrate an invoked statement into the collected data. |
5049 | void CalledStmt(Stmt *S); |
5050 | |
5051 | /// Overwrite an EPI's exception specification with this |
5052 | /// computed exception specification. |
5053 | FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { |
5054 | FunctionProtoType::ExceptionSpecInfo ESI; |
5055 | ESI.Type = getExceptionSpecType(); |
5056 | if (ESI.Type == EST_Dynamic) { |
5057 | ESI.Exceptions = Exceptions; |
5058 | } else if (ESI.Type == EST_None) { |
5059 | /// C++11 [except.spec]p14: |
5060 | /// The exception-specification is noexcept(false) if the set of |
5061 | /// potential exceptions of the special member function contains "any" |
5062 | ESI.Type = EST_NoexceptFalse; |
5063 | ESI.NoexceptExpr = |
5064 | Self->ActOnCXXBoolLiteral(OpLoc: SourceLocation(), Kind: tok::kw_false).get(); |
5065 | } |
5066 | return ESI; |
5067 | } |
5068 | }; |
5069 | |
5070 | /// Evaluate the implicit exception specification for a defaulted |
5071 | /// special member function. |
5072 | void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); |
5073 | |
5074 | /// Check the given exception-specification and update the |
5075 | /// exception specification information with the results. |
5076 | void checkExceptionSpecification(bool IsTopLevel, |
5077 | ExceptionSpecificationType EST, |
5078 | ArrayRef<ParsedType> DynamicExceptions, |
5079 | ArrayRef<SourceRange> DynamicExceptionRanges, |
5080 | Expr *NoexceptExpr, |
5081 | SmallVectorImpl<QualType> &Exceptions, |
5082 | FunctionProtoType::ExceptionSpecInfo &ESI); |
5083 | |
5084 | /// Add an exception-specification to the given member or friend function |
5085 | /// (or function template). The exception-specification was parsed |
5086 | /// after the function itself was declared. |
5087 | void actOnDelayedExceptionSpecification( |
5088 | Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, |
5089 | ArrayRef<ParsedType> DynamicExceptions, |
5090 | ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); |
5091 | |
5092 | class InheritedConstructorInfo; |
5093 | |
5094 | /// Determine if a special member function should have a deleted |
5095 | /// definition when it is defaulted. |
5096 | bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, |
5097 | InheritedConstructorInfo *ICI = nullptr, |
5098 | bool Diagnose = false); |
5099 | |
5100 | /// Produce notes explaining why a defaulted function was defined as deleted. |
5101 | void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); |
5102 | |
5103 | /// Declare the implicit default constructor for the given class. |
5104 | /// |
5105 | /// \param ClassDecl The class declaration into which the implicit |
5106 | /// default constructor will be added. |
5107 | /// |
5108 | /// \returns The implicitly-declared default constructor. |
5109 | CXXConstructorDecl * |
5110 | DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl); |
5111 | |
5112 | /// DefineImplicitDefaultConstructor - Checks for feasibility of |
5113 | /// defining this constructor as the default constructor. |
5114 | void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, |
5115 | CXXConstructorDecl *Constructor); |
5116 | |
5117 | /// Declare the implicit destructor for the given class. |
5118 | /// |
5119 | /// \param ClassDecl The class declaration into which the implicit |
5120 | /// destructor will be added. |
5121 | /// |
5122 | /// \returns The implicitly-declared destructor. |
5123 | CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); |
5124 | |
5125 | /// DefineImplicitDestructor - Checks for feasibility of |
5126 | /// defining this destructor as the default destructor. |
5127 | void DefineImplicitDestructor(SourceLocation CurrentLocation, |
5128 | CXXDestructorDecl *Destructor); |
5129 | |
5130 | /// Build an exception spec for destructors that don't have one. |
5131 | /// |
5132 | /// C++11 says that user-defined destructors with no exception spec get one |
5133 | /// that looks as if the destructor was implicitly declared. |
5134 | void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); |
5135 | |
5136 | /// Define the specified inheriting constructor. |
5137 | void DefineInheritingConstructor(SourceLocation UseLoc, |
5138 | CXXConstructorDecl *Constructor); |
5139 | |
5140 | /// Declare the implicit copy constructor for the given class. |
5141 | /// |
5142 | /// \param ClassDecl The class declaration into which the implicit |
5143 | /// copy constructor will be added. |
5144 | /// |
5145 | /// \returns The implicitly-declared copy constructor. |
5146 | CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); |
5147 | |
5148 | /// DefineImplicitCopyConstructor - Checks for feasibility of |
5149 | /// defining this constructor as the copy constructor. |
5150 | void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, |
5151 | CXXConstructorDecl *Constructor); |
5152 | |
5153 | /// Declare the implicit move constructor for the given class. |
5154 | /// |
5155 | /// \param ClassDecl The Class declaration into which the implicit |
5156 | /// move constructor will be added. |
5157 | /// |
5158 | /// \returns The implicitly-declared move constructor, or NULL if it wasn't |
5159 | /// declared. |
5160 | CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); |
5161 | |
5162 | /// DefineImplicitMoveConstructor - Checks for feasibility of |
5163 | /// defining this constructor as the move constructor. |
5164 | void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, |
5165 | CXXConstructorDecl *Constructor); |
5166 | |
5167 | /// Declare the implicit copy assignment operator for the given class. |
5168 | /// |
5169 | /// \param ClassDecl The class declaration into which the implicit |
5170 | /// copy assignment operator will be added. |
5171 | /// |
5172 | /// \returns The implicitly-declared copy assignment operator. |
5173 | CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); |
5174 | |
5175 | /// Defines an implicitly-declared copy assignment operator. |
5176 | void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, |
5177 | CXXMethodDecl *MethodDecl); |
5178 | |
5179 | /// Declare the implicit move assignment operator for the given class. |
5180 | /// |
5181 | /// \param ClassDecl The Class declaration into which the implicit |
5182 | /// move assignment operator will be added. |
5183 | /// |
5184 | /// \returns The implicitly-declared move assignment operator, or NULL if it |
5185 | /// wasn't declared. |
5186 | CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); |
5187 | |
5188 | /// Defines an implicitly-declared move assignment operator. |
5189 | void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, |
5190 | CXXMethodDecl *MethodDecl); |
5191 | |
5192 | /// Check a completed declaration of an implicit special member. |
5193 | void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); |
5194 | |
5195 | /// Determine whether the given function is an implicitly-deleted |
5196 | /// special member function. |
5197 | bool isImplicitlyDeleted(FunctionDecl *FD); |
5198 | |
5199 | /// Check whether 'this' shows up in the type of a static member |
5200 | /// function after the (naturally empty) cv-qualifier-seq would be. |
5201 | /// |
5202 | /// \returns true if an error occurred. |
5203 | bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); |
5204 | |
5205 | /// Whether this' shows up in the exception specification of a static |
5206 | /// member function. |
5207 | bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); |
5208 | |
5209 | /// Check whether 'this' shows up in the attributes of the given |
5210 | /// static member function. |
5211 | /// |
5212 | /// \returns true if an error occurred. |
5213 | bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); |
5214 | |
5215 | bool CheckImmediateEscalatingFunctionDefinition( |
5216 | FunctionDecl *FD, const sema::FunctionScopeInfo *FSI); |
5217 | |
5218 | void DiagnoseImmediateEscalatingReason(FunctionDecl *FD); |
5219 | |
5220 | /// Given a constructor and the set of arguments provided for the |
5221 | /// constructor, convert the arguments and add any required default arguments |
5222 | /// to form a proper call to this constructor. |
5223 | /// |
5224 | /// \returns true if an error occurred, false otherwise. |
5225 | bool CompleteConstructorCall(CXXConstructorDecl *Constructor, |
5226 | QualType DeclInitType, MultiExprArg ArgsPtr, |
5227 | SourceLocation Loc, |
5228 | SmallVectorImpl<Expr *> &ConvertedArgs, |
5229 | bool AllowExplicit = false, |
5230 | bool IsListInitialization = false); |
5231 | |
5232 | /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an |
5233 | /// initializer for the declaration 'Dcl'. |
5234 | /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a |
5235 | /// static data member of class X, names should be looked up in the scope of |
5236 | /// class X. |
5237 | void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); |
5238 | |
5239 | /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an |
5240 | /// initializer for the declaration 'Dcl'. |
5241 | void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); |
5242 | |
5243 | /// Define the "body" of the conversion from a lambda object to a |
5244 | /// function pointer. |
5245 | /// |
5246 | /// This routine doesn't actually define a sensible body; rather, it fills |
5247 | /// in the initialization expression needed to copy the lambda object into |
5248 | /// the block, and IR generation actually generates the real body of the |
5249 | /// block pointer conversion. |
5250 | void |
5251 | DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, |
5252 | CXXConversionDecl *Conv); |
5253 | |
5254 | /// Define the "body" of the conversion from a lambda object to a |
5255 | /// block pointer. |
5256 | /// |
5257 | /// This routine doesn't actually define a sensible body; rather, it fills |
5258 | /// in the initialization expression needed to copy the lambda object into |
5259 | /// the block, and IR generation actually generates the real body of the |
5260 | /// block pointer conversion. |
5261 | void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, |
5262 | CXXConversionDecl *Conv); |
5263 | |
5264 | /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ |
5265 | /// linkage specification, including the language and (if present) |
5266 | /// the '{'. ExternLoc is the location of the 'extern', Lang is the |
5267 | /// language string literal. LBraceLoc, if valid, provides the location of |
5268 | /// the '{' brace. Otherwise, this linkage specification does not |
5269 | /// have any braces. |
5270 | Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, |
5271 | Expr *LangStr, SourceLocation LBraceLoc); |
5272 | |
5273 | /// ActOnFinishLinkageSpecification - Complete the definition of |
5274 | /// the C++ linkage specification LinkageSpec. If RBraceLoc is |
5275 | /// valid, it's the position of the closing '}' brace in a linkage |
5276 | /// specification that uses braces. |
5277 | Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, |
5278 | SourceLocation RBraceLoc); |
5279 | |
5280 | //===--------------------------------------------------------------------===// |
5281 | // C++ Classes |
5282 | // |
5283 | |
5284 | /// Get the class that is directly named by the current context. This is the |
5285 | /// class for which an unqualified-id in this scope could name a constructor |
5286 | /// or destructor. |
5287 | /// |
5288 | /// If the scope specifier denotes a class, this will be that class. |
5289 | /// If the scope specifier is empty, this will be the class whose |
5290 | /// member-specification we are currently within. Otherwise, there |
5291 | /// is no such class. |
5292 | CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); |
5293 | |
5294 | /// isCurrentClassName - Determine whether the identifier II is the |
5295 | /// name of the class type currently being defined. In the case of |
5296 | /// nested classes, this will only return true if II is the name of |
5297 | /// the innermost class. |
5298 | bool isCurrentClassName(const IdentifierInfo &II, Scope *S, |
5299 | const CXXScopeSpec *SS = nullptr); |
5300 | |
5301 | /// Determine whether the identifier II is a typo for the name of |
5302 | /// the class type currently being defined. If so, update it to the identifier |
5303 | /// that should have been used. |
5304 | bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); |
5305 | |
5306 | /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. |
5307 | bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, |
5308 | SourceLocation ColonLoc, |
5309 | const ParsedAttributesView &Attrs); |
5310 | |
5311 | /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member |
5312 | /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the |
5313 | /// bitfield width if there is one, 'InitExpr' specifies the initializer if |
5314 | /// one has been parsed, and 'InitStyle' is set if an in-class initializer is |
5315 | /// present (but parsing it has been deferred). |
5316 | NamedDecl * |
5317 | ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, |
5318 | MultiTemplateParamsArg TemplateParameterLists, |
5319 | Expr *BitfieldWidth, const VirtSpecifiers &VS, |
5320 | InClassInitStyle InitStyle); |
5321 | |
5322 | /// Enter a new C++ default initializer scope. After calling this, the |
5323 | /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if |
5324 | /// parsing or instantiating the initializer failed. |
5325 | void ActOnStartCXXInClassMemberInitializer(); |
5326 | |
5327 | /// This is invoked after parsing an in-class initializer for a |
5328 | /// non-static C++ class member, and after instantiating an in-class |
5329 | /// initializer in a class template. Such actions are deferred until the class |
5330 | /// is complete. |
5331 | void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, |
5332 | SourceLocation EqualLoc, |
5333 | ExprResult Init); |
5334 | |
5335 | /// Handle a C++ member initializer using parentheses syntax. |
5336 | MemInitResult |
5337 | ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, |
5338 | IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, |
5339 | const DeclSpec &DS, SourceLocation IdLoc, |
5340 | SourceLocation LParenLoc, ArrayRef<Expr *> Args, |
5341 | SourceLocation RParenLoc, SourceLocation EllipsisLoc); |
5342 | |
5343 | /// Handle a C++ member initializer using braced-init-list syntax. |
5344 | MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, |
5345 | CXXScopeSpec &SS, |
5346 | IdentifierInfo *MemberOrBase, |
5347 | ParsedType TemplateTypeTy, |
5348 | const DeclSpec &DS, SourceLocation IdLoc, |
5349 | Expr *InitList, SourceLocation EllipsisLoc); |
5350 | |
5351 | /// Handle a C++ member initializer. |
5352 | MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, |
5353 | CXXScopeSpec &SS, |
5354 | IdentifierInfo *MemberOrBase, |
5355 | ParsedType TemplateTypeTy, |
5356 | const DeclSpec &DS, SourceLocation IdLoc, |
5357 | Expr *Init, SourceLocation EllipsisLoc); |
5358 | |
5359 | MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, |
5360 | SourceLocation IdLoc); |
5361 | |
5362 | MemInitResult BuildBaseInitializer(QualType BaseType, |
5363 | TypeSourceInfo *BaseTInfo, Expr *Init, |
5364 | CXXRecordDecl *ClassDecl, |
5365 | SourceLocation EllipsisLoc); |
5366 | |
5367 | MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, |
5368 | CXXRecordDecl *ClassDecl); |
5369 | |
5370 | bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, |
5371 | CXXCtorInitializer *Initializer); |
5372 | |
5373 | bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, |
5374 | ArrayRef<CXXCtorInitializer *> Initializers = {}); |
5375 | |
5376 | /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, |
5377 | /// mark all the non-trivial destructors of its members and bases as |
5378 | /// referenced. |
5379 | void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, |
5380 | CXXRecordDecl *Record); |
5381 | |
5382 | /// Mark destructors of virtual bases of this class referenced. In the Itanium |
5383 | /// C++ ABI, this is done when emitting a destructor for any non-abstract |
5384 | /// class. In the Microsoft C++ ABI, this is done any time a class's |
5385 | /// destructor is referenced. |
5386 | void MarkVirtualBaseDestructorsReferenced( |
5387 | SourceLocation Location, CXXRecordDecl *ClassDecl, |
5388 | llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); |
5389 | |
5390 | /// Do semantic checks to allow the complete destructor variant to be emitted |
5391 | /// when the destructor is defined in another translation unit. In the Itanium |
5392 | /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they |
5393 | /// can be emitted in separate TUs. To emit the complete variant, run a subset |
5394 | /// of the checks performed when emitting a regular destructor. |
5395 | void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, |
5396 | CXXDestructorDecl *Dtor); |
5397 | |
5398 | /// The list of classes whose vtables have been used within |
5399 | /// this translation unit, and the source locations at which the |
5400 | /// first use occurred. |
5401 | typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse; |
5402 | |
5403 | /// The list of vtables that are required but have not yet been |
5404 | /// materialized. |
5405 | SmallVector<VTableUse, 16> VTableUses; |
5406 | |
5407 | /// The set of classes whose vtables have been used within |
5408 | /// this translation unit, and a bit that will be true if the vtable is |
5409 | /// required to be emitted (otherwise, it should be emitted only if needed |
5410 | /// by code generation). |
5411 | llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; |
5412 | |
5413 | /// Load any externally-stored vtable uses. |
5414 | void LoadExternalVTableUses(); |
5415 | |
5416 | /// Note that the vtable for the given class was used at the |
5417 | /// given location. |
5418 | void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, |
5419 | bool DefinitionRequired = false); |
5420 | |
5421 | /// Mark the exception specifications of all virtual member functions |
5422 | /// in the given class as needed. |
5423 | void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, |
5424 | const CXXRecordDecl *RD); |
5425 | |
5426 | /// MarkVirtualMembersReferenced - Will mark all members of the given |
5427 | /// CXXRecordDecl referenced. |
5428 | void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, |
5429 | bool ConstexprOnly = false); |
5430 | |
5431 | /// Define all of the vtables that have been used in this |
5432 | /// translation unit and reference any virtual members used by those |
5433 | /// vtables. |
5434 | /// |
5435 | /// \returns true if any work was done, false otherwise. |
5436 | bool DefineUsedVTables(); |
5437 | |
5438 | /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared |
5439 | /// special functions, such as the default constructor, copy |
5440 | /// constructor, or destructor, to the given C++ class (C++ |
5441 | /// [special]p1). This routine can only be executed just before the |
5442 | /// definition of the class is complete. |
5443 | void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); |
5444 | |
5445 | /// ActOnMemInitializers - Handle the member initializers for a constructor. |
5446 | void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, |
5447 | ArrayRef<CXXCtorInitializer *> MemInits, |
5448 | bool AnyErrors); |
5449 | |
5450 | /// Check class-level dllimport/dllexport attribute. The caller must |
5451 | /// ensure that referenceDLLExportedClassMethods is called some point later |
5452 | /// when all outer classes of Class are complete. |
5453 | void checkClassLevelDLLAttribute(CXXRecordDecl *Class); |
5454 | void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); |
5455 | |
5456 | void referenceDLLExportedClassMethods(); |
5457 | |
5458 | /// Perform propagation of DLL attributes from a derived class to a |
5459 | /// templated base class for MS compatibility. |
5460 | void propagateDLLAttrToBaseClassTemplate( |
5461 | CXXRecordDecl *Class, Attr *ClassAttr, |
5462 | ClassTemplateSpecializationDecl *BaseTemplateSpec, |
5463 | SourceLocation BaseLoc); |
5464 | |
5465 | /// Perform semantic checks on a class definition that has been |
5466 | /// completing, introducing implicitly-declared members, checking for |
5467 | /// abstract types, etc. |
5468 | /// |
5469 | /// \param S The scope in which the class was parsed. Null if we didn't just |
5470 | /// parse a class definition. |
5471 | /// \param Record The completed class. |
5472 | void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); |
5473 | |
5474 | /// Check that the C++ class annoated with "trivial_abi" satisfies all the |
5475 | /// conditions that are needed for the attribute to have an effect. |
5476 | void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); |
5477 | |
5478 | /// Check that VTable Pointer authentication is only being set on the first |
5479 | /// first instantiation of the vtable |
5480 | void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD); |
5481 | |
5482 | void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, |
5483 | Decl *TagDecl, SourceLocation LBrac, |
5484 | SourceLocation RBrac, |
5485 | const ParsedAttributesView &AttrList); |
5486 | |
5487 | /// Perform any semantic analysis which needs to be delayed until all |
5488 | /// pending class member declarations have been parsed. |
5489 | void ActOnFinishCXXMemberDecls(); |
5490 | void ActOnFinishCXXNonNestedClass(); |
5491 | |
5492 | /// This is used to implement the constant expression evaluation part of the |
5493 | /// attribute enable_if extension. There is nothing in standard C++ which |
5494 | /// would require reentering parameters. |
5495 | void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); |
5496 | unsigned ActOnReenterTemplateScope(Decl *Template, |
5497 | llvm::function_ref<Scope *()> EnterScope); |
5498 | void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); |
5499 | |
5500 | /// ActOnStartDelayedCXXMethodDeclaration - We have completed |
5501 | /// parsing a top-level (non-nested) C++ class, and we are now |
5502 | /// parsing those parts of the given Method declaration that could |
5503 | /// not be parsed earlier (C++ [class.mem]p2), such as default |
5504 | /// arguments. This action should enter the scope of the given |
5505 | /// Method declaration as if we had just parsed the qualified method |
5506 | /// name. However, it should not bring the parameters into scope; |
5507 | /// that will be performed by ActOnDelayedCXXMethodParameter. |
5508 | void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); |
5509 | void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); |
5510 | void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); |
5511 | |
5512 | /// ActOnFinishDelayedCXXMethodDeclaration - We have finished |
5513 | /// processing the delayed method declaration for Method. The method |
5514 | /// declaration is now considered finished. There may be a separate |
5515 | /// ActOnStartOfFunctionDef action later (not necessarily |
5516 | /// immediately!) for this method, if it was also defined inside the |
5517 | /// class body. |
5518 | void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); |
5519 | void ActOnFinishDelayedMemberInitializers(Decl *Record); |
5520 | |
5521 | bool EvaluateStaticAssertMessageAsString(Expr *Message, std::string &Result, |
5522 | ASTContext &Ctx, |
5523 | bool ErrorOnInvalidMessage); |
5524 | Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, |
5525 | Expr *AssertExpr, Expr *AssertMessageExpr, |
5526 | SourceLocation RParenLoc); |
5527 | Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, |
5528 | Expr *AssertExpr, Expr *AssertMessageExpr, |
5529 | SourceLocation RParenLoc, bool Failed); |
5530 | |
5531 | /// Try to print more useful information about a failed static_assert |
5532 | /// with expression \E |
5533 | void DiagnoseStaticAssertDetails(const Expr *E); |
5534 | |
5535 | /// Handle a friend type declaration. This works in tandem with |
5536 | /// ActOnTag. |
5537 | /// |
5538 | /// Notes on friend class templates: |
5539 | /// |
5540 | /// We generally treat friend class declarations as if they were |
5541 | /// declaring a class. So, for example, the elaborated type specifier |
5542 | /// in a friend declaration is required to obey the restrictions of a |
5543 | /// class-head (i.e. no typedefs in the scope chain), template |
5544 | /// parameters are required to match up with simple template-ids, &c. |
5545 | /// However, unlike when declaring a template specialization, it's |
5546 | /// okay to refer to a template specialization without an empty |
5547 | /// template parameter declaration, e.g. |
5548 | /// friend class A<T>::B<unsigned>; |
5549 | /// We permit this as a special case; if there are any template |
5550 | /// parameters present at all, require proper matching, i.e. |
5551 | /// template <> template \<class T> friend class A<int>::B; |
5552 | Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, |
5553 | MultiTemplateParamsArg TemplateParams, |
5554 | SourceLocation EllipsisLoc); |
5555 | NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, |
5556 | MultiTemplateParamsArg TemplateParams); |
5557 | |
5558 | /// CheckConstructorDeclarator - Called by ActOnDeclarator to check |
5559 | /// the well-formedness of the constructor declarator @p D with type @p |
5560 | /// R. If there are any errors in the declarator, this routine will |
5561 | /// emit diagnostics and set the invalid bit to true. In any case, the type |
5562 | /// will be updated to reflect a well-formed type for the constructor and |
5563 | /// returned. |
5564 | QualType CheckConstructorDeclarator(Declarator &D, QualType R, |
5565 | StorageClass &SC); |
5566 | |
5567 | /// CheckConstructor - Checks a fully-formed constructor for |
5568 | /// well-formedness, issuing any diagnostics required. Returns true if |
5569 | /// the constructor declarator is invalid. |
5570 | void CheckConstructor(CXXConstructorDecl *Constructor); |
5571 | |
5572 | /// CheckDestructorDeclarator - Called by ActOnDeclarator to check |
5573 | /// the well-formednes of the destructor declarator @p D with type @p |
5574 | /// R. If there are any errors in the declarator, this routine will |
5575 | /// emit diagnostics and set the declarator to invalid. Even if this happens, |
5576 | /// will be updated to reflect a well-formed type for the destructor and |
5577 | /// returned. |
5578 | QualType CheckDestructorDeclarator(Declarator &D, QualType R, |
5579 | StorageClass &SC); |
5580 | |
5581 | /// CheckDestructor - Checks a fully-formed destructor definition for |
5582 | /// well-formedness, issuing any diagnostics required. Returns true |
5583 | /// on error. |
5584 | bool CheckDestructor(CXXDestructorDecl *Destructor); |
5585 | |
5586 | /// CheckConversionDeclarator - Called by ActOnDeclarator to check the |
5587 | /// well-formednes of the conversion function declarator @p D with |
5588 | /// type @p R. If there are any errors in the declarator, this routine |
5589 | /// will emit diagnostics and return true. Otherwise, it will return |
5590 | /// false. Either way, the type @p R will be updated to reflect a |
5591 | /// well-formed type for the conversion operator. |
5592 | void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC); |
5593 | |
5594 | /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete |
5595 | /// the declaration of the given C++ conversion function. This routine |
5596 | /// is responsible for recording the conversion function in the C++ |
5597 | /// class, if possible. |
5598 | Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); |
5599 | |
5600 | /// Check the validity of a declarator that we parsed for a deduction-guide. |
5601 | /// These aren't actually declarators in the grammar, so we need to check that |
5602 | /// the user didn't specify any pieces that are not part of the |
5603 | /// deduction-guide grammar. Return true on invalid deduction-guide. |
5604 | bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, |
5605 | StorageClass &SC); |
5606 | |
5607 | void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); |
5608 | |
5609 | bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, |
5610 | CXXSpecialMemberKind CSM, |
5611 | SourceLocation DefaultLoc); |
5612 | void CheckDelayedMemberExceptionSpecs(); |
5613 | |
5614 | /// Kinds of defaulted comparison operator functions. |
5615 | enum class DefaultedComparisonKind : unsigned char { |
5616 | /// This is not a defaultable comparison operator. |
5617 | None, |
5618 | /// This is an operator== that should be implemented as a series of |
5619 | /// subobject comparisons. |
5620 | Equal, |
5621 | /// This is an operator<=> that should be implemented as a series of |
5622 | /// subobject comparisons. |
5623 | ThreeWay, |
5624 | /// This is an operator!= that should be implemented as a rewrite in terms |
5625 | /// of a == comparison. |
5626 | NotEqual, |
5627 | /// This is an <, <=, >, or >= that should be implemented as a rewrite in |
5628 | /// terms of a <=> comparison. |
5629 | Relational, |
5630 | }; |
5631 | |
5632 | bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, |
5633 | DefaultedComparisonKind DCK); |
5634 | void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, |
5635 | FunctionDecl *Spaceship); |
5636 | void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, |
5637 | DefaultedComparisonKind DCK); |
5638 | |
5639 | void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, |
5640 | QualType R, bool IsLambda, |
5641 | DeclContext *DC = nullptr); |
5642 | void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D, |
5643 | DeclarationName Name, QualType R); |
5644 | void CheckExplicitObjectLambda(Declarator &D); |
5645 | |
5646 | //===--------------------------------------------------------------------===// |
5647 | // C++ Derived Classes |
5648 | // |
5649 | |
5650 | /// Check the validity of a C++ base class specifier. |
5651 | /// |
5652 | /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics |
5653 | /// and returns NULL otherwise. |
5654 | CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, |
5655 | SourceRange SpecifierRange, bool Virtual, |
5656 | AccessSpecifier Access, |
5657 | TypeSourceInfo *TInfo, |
5658 | SourceLocation EllipsisLoc); |
5659 | |
5660 | /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is |
5661 | /// one entry in the base class list of a class specifier, for |
5662 | /// example: |
5663 | /// class foo : public bar, virtual private baz { |
5664 | /// 'public bar' and 'virtual private baz' are each base-specifiers. |
5665 | BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, |
5666 | const ParsedAttributesView &Attrs, bool Virtual, |
5667 | AccessSpecifier Access, ParsedType basetype, |
5668 | SourceLocation BaseLoc, |
5669 | SourceLocation EllipsisLoc); |
5670 | |
5671 | /// Performs the actual work of attaching the given base class |
5672 | /// specifiers to a C++ class. |
5673 | bool AttachBaseSpecifiers(CXXRecordDecl *Class, |
5674 | MutableArrayRef<CXXBaseSpecifier *> Bases); |
5675 | |
5676 | /// ActOnBaseSpecifiers - Attach the given base specifiers to the |
5677 | /// class, after checking whether there are any duplicate base |
5678 | /// classes. |
5679 | void ActOnBaseSpecifiers(Decl *ClassDecl, |
5680 | MutableArrayRef<CXXBaseSpecifier *> Bases); |
5681 | |
5682 | /// Determine whether the type \p Derived is a C++ class that is |
5683 | /// derived from the type \p Base. |
5684 | bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); |
5685 | |
5686 | /// Determine whether the type \p Derived is a C++ class that is |
5687 | /// derived from the type \p Base. |
5688 | bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, |
5689 | CXXBasePaths &Paths); |
5690 | |
5691 | // FIXME: I don't like this name. |
5692 | void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); |
5693 | |
5694 | bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, |
5695 | SourceLocation Loc, SourceRange Range, |
5696 | CXXCastPath *BasePath = nullptr, |
5697 | bool IgnoreAccess = false); |
5698 | |
5699 | /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base |
5700 | /// conversion (where Derived and Base are class types) is |
5701 | /// well-formed, meaning that the conversion is unambiguous (and |
5702 | /// that all of the base classes are accessible). Returns true |
5703 | /// and emits a diagnostic if the code is ill-formed, returns false |
5704 | /// otherwise. Loc is the location where this routine should point to |
5705 | /// if there is an error, and Range is the source range to highlight |
5706 | /// if there is an error. |
5707 | /// |
5708 | /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the |
5709 | /// diagnostic for the respective type of error will be suppressed, but the |
5710 | /// check for ill-formed code will still be performed. |
5711 | bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, |
5712 | unsigned InaccessibleBaseID, |
5713 | unsigned AmbiguousBaseConvID, |
5714 | SourceLocation Loc, SourceRange Range, |
5715 | DeclarationName Name, CXXCastPath *BasePath, |
5716 | bool IgnoreAccess = false); |
5717 | |
5718 | /// Builds a string representing ambiguous paths from a |
5719 | /// specific derived class to different subobjects of the same base |
5720 | /// class. |
5721 | /// |
5722 | /// This function builds a string that can be used in error messages |
5723 | /// to show the different paths that one can take through the |
5724 | /// inheritance hierarchy to go from the derived class to different |
5725 | /// subobjects of a base class. The result looks something like this: |
5726 | /// @code |
5727 | /// struct D -> struct B -> struct A |
5728 | /// struct D -> struct C -> struct A |
5729 | /// @endcode |
5730 | std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); |
5731 | |
5732 | bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, |
5733 | const CXXMethodDecl *Old); |
5734 | |
5735 | /// CheckOverridingFunctionReturnType - Checks whether the return types are |
5736 | /// covariant, according to C++ [class.virtual]p5. |
5737 | bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, |
5738 | const CXXMethodDecl *Old); |
5739 | |
5740 | // Check that the overriding method has no explicit object parameter. |
5741 | bool CheckExplicitObjectOverride(CXXMethodDecl *New, |
5742 | const CXXMethodDecl *Old); |
5743 | |
5744 | /// Mark the given method pure. |
5745 | /// |
5746 | /// \param Method the method to be marked pure. |
5747 | /// |
5748 | /// \param InitRange the source range that covers the "0" initializer. |
5749 | bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); |
5750 | |
5751 | /// CheckOverrideControl - Check C++11 override control semantics. |
5752 | void CheckOverrideControl(NamedDecl *D); |
5753 | |
5754 | /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was |
5755 | /// not used in the declaration of an overriding method. |
5756 | void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); |
5757 | |
5758 | /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member |
5759 | /// function overrides a virtual member function marked 'final', according to |
5760 | /// C++11 [class.virtual]p4. |
5761 | bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, |
5762 | const CXXMethodDecl *Old); |
5763 | |
5764 | enum AbstractDiagSelID { |
5765 | AbstractNone = -1, |
5766 | AbstractReturnType, |
5767 | AbstractParamType, |
5768 | AbstractVariableType, |
5769 | AbstractFieldType, |
5770 | AbstractIvarType, |
5771 | AbstractSynthesizedIvarType, |
5772 | AbstractArrayType |
5773 | }; |
5774 | |
5775 | struct TypeDiagnoser; |
5776 | |
5777 | bool isAbstractType(SourceLocation Loc, QualType T); |
5778 | bool RequireNonAbstractType(SourceLocation Loc, QualType T, |
5779 | TypeDiagnoser &Diagnoser); |
5780 | template <typename... Ts> |
5781 | bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, |
5782 | const Ts &...Args) { |
5783 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
5784 | return RequireNonAbstractType(Loc, T, Diagnoser); |
5785 | } |
5786 | |
5787 | void DiagnoseAbstractType(const CXXRecordDecl *RD); |
5788 | |
5789 | //===--------------------------------------------------------------------===// |
5790 | // C++ Overloaded Operators [C++ 13.5] |
5791 | // |
5792 | |
5793 | /// CheckOverloadedOperatorDeclaration - Check whether the declaration |
5794 | /// of this overloaded operator is well-formed. If so, returns false; |
5795 | /// otherwise, emits appropriate diagnostics and returns true. |
5796 | bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); |
5797 | |
5798 | /// CheckLiteralOperatorDeclaration - Check whether the declaration |
5799 | /// of this literal operator function is well-formed. If so, returns |
5800 | /// false; otherwise, emits appropriate diagnostics and returns true. |
5801 | bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); |
5802 | |
5803 | /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression |
5804 | /// found in an explicit(bool) specifier. |
5805 | ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); |
5806 | |
5807 | /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. |
5808 | /// Returns true if the explicit specifier is now resolved. |
5809 | bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); |
5810 | |
5811 | /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a |
5812 | /// C++ if/switch/while/for statement. |
5813 | /// e.g: "if (int x = f()) {...}" |
5814 | DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); |
5815 | |
5816 | // Emitting members of dllexported classes is delayed until the class |
5817 | // (including field initializers) is fully parsed. |
5818 | SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses; |
5819 | SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions; |
5820 | |
5821 | /// Merge the exception specifications of two variable declarations. |
5822 | /// |
5823 | /// This is called when there's a redeclaration of a VarDecl. The function |
5824 | /// checks if the redeclaration might have an exception specification and |
5825 | /// validates compatibility and merges the specs if necessary. |
5826 | void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); |
5827 | |
5828 | /// MergeCXXFunctionDecl - Merge two declarations of the same C++ |
5829 | /// function, once we already know that they have the same |
5830 | /// type. Subroutine of MergeFunctionDecl. Returns true if there was an |
5831 | /// error, false otherwise. |
5832 | bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); |
5833 | |
5834 | /// Helpers for dealing with blocks and functions. |
5835 | void CheckCXXDefaultArguments(FunctionDecl *FD); |
5836 | |
5837 | /// CheckExtraCXXDefaultArguments - Check for any extra default |
5838 | /// arguments in the declarator, which is not a function declaration |
5839 | /// or definition and therefore is not permitted to have default |
5840 | /// arguments. This routine should be invoked for every declarator |
5841 | /// that is not a function declaration or definition. |
5842 | void (Declarator &D); |
5843 | |
5844 | CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD) { |
5845 | return getDefaultedFunctionKind(MD).asSpecialMember(); |
5846 | } |
5847 | |
5848 | /// Perform semantic analysis for the variable declaration that |
5849 | /// occurs within a C++ catch clause, returning the newly-created |
5850 | /// variable. |
5851 | VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, |
5852 | SourceLocation StartLoc, |
5853 | SourceLocation IdLoc, |
5854 | const IdentifierInfo *Id); |
5855 | |
5856 | /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch |
5857 | /// handler. |
5858 | Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); |
5859 | |
5860 | void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); |
5861 | |
5862 | /// Handle a friend tag declaration where the scope specifier was |
5863 | /// templated. |
5864 | DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, |
5865 | unsigned TagSpec, SourceLocation TagLoc, |
5866 | CXXScopeSpec &SS, IdentifierInfo *Name, |
5867 | SourceLocation NameLoc, |
5868 | SourceLocation EllipsisLoc, |
5869 | const ParsedAttributesView &Attr, |
5870 | MultiTemplateParamsArg TempParamLists); |
5871 | |
5872 | MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, |
5873 | SourceLocation DeclStart, Declarator &D, |
5874 | Expr *BitfieldWidth, |
5875 | InClassInitStyle InitStyle, |
5876 | AccessSpecifier AS, |
5877 | const ParsedAttr &MSPropertyAttr); |
5878 | |
5879 | /// Diagnose why the specified class does not have a trivial special member of |
5880 | /// the given kind. |
5881 | void DiagnoseNontrivial(const CXXRecordDecl *Record, |
5882 | CXXSpecialMemberKind CSM); |
5883 | |
5884 | enum TrivialABIHandling { |
5885 | /// The triviality of a method unaffected by "trivial_abi". |
5886 | TAH_IgnoreTrivialABI, |
5887 | |
5888 | /// The triviality of a method affected by "trivial_abi". |
5889 | TAH_ConsiderTrivialABI |
5890 | }; |
5891 | |
5892 | /// Determine whether a defaulted or deleted special member function is |
5893 | /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, |
5894 | /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. |
5895 | bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, |
5896 | TrivialABIHandling TAH = TAH_IgnoreTrivialABI, |
5897 | bool Diagnose = false); |
5898 | |
5899 | /// For a defaulted function, the kind of defaulted function that it is. |
5900 | class DefaultedFunctionKind { |
5901 | LLVM_PREFERRED_TYPE(CXXSpecialMemberKind) |
5902 | unsigned SpecialMember : 8; |
5903 | unsigned Comparison : 8; |
5904 | |
5905 | public: |
5906 | DefaultedFunctionKind() |
5907 | : SpecialMember(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid)), |
5908 | Comparison(llvm::to_underlying(E: DefaultedComparisonKind::None)) {} |
5909 | DefaultedFunctionKind(CXXSpecialMemberKind CSM) |
5910 | : SpecialMember(llvm::to_underlying(E: CSM)), |
5911 | Comparison(llvm::to_underlying(E: DefaultedComparisonKind::None)) {} |
5912 | DefaultedFunctionKind(DefaultedComparisonKind Comp) |
5913 | : SpecialMember(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid)), |
5914 | Comparison(llvm::to_underlying(E: Comp)) {} |
5915 | |
5916 | bool isSpecialMember() const { |
5917 | return static_cast<CXXSpecialMemberKind>(SpecialMember) != |
5918 | CXXSpecialMemberKind::Invalid; |
5919 | } |
5920 | bool isComparison() const { |
5921 | return static_cast<DefaultedComparisonKind>(Comparison) != |
5922 | DefaultedComparisonKind::None; |
5923 | } |
5924 | |
5925 | explicit operator bool() const { |
5926 | return isSpecialMember() || isComparison(); |
5927 | } |
5928 | |
5929 | CXXSpecialMemberKind asSpecialMember() const { |
5930 | return static_cast<CXXSpecialMemberKind>(SpecialMember); |
5931 | } |
5932 | DefaultedComparisonKind asComparison() const { |
5933 | return static_cast<DefaultedComparisonKind>(Comparison); |
5934 | } |
5935 | |
5936 | /// Get the index of this function kind for use in diagnostics. |
5937 | unsigned getDiagnosticIndex() const { |
5938 | static_assert(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid) > |
5939 | llvm::to_underlying(E: CXXSpecialMemberKind::Destructor), |
5940 | "invalid should have highest index" ); |
5941 | static_assert((unsigned)DefaultedComparisonKind::None == 0, |
5942 | "none should be equal to zero" ); |
5943 | return SpecialMember + Comparison; |
5944 | } |
5945 | }; |
5946 | |
5947 | /// Determine the kind of defaulting that would be done for a given function. |
5948 | /// |
5949 | /// If the function is both a default constructor and a copy / move |
5950 | /// constructor (due to having a default argument for the first parameter), |
5951 | /// this picks CXXSpecialMemberKind::DefaultConstructor. |
5952 | /// |
5953 | /// FIXME: Check that case is properly handled by all callers. |
5954 | DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); |
5955 | |
5956 | /// Handle a C++11 empty-declaration and attribute-declaration. |
5957 | Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, |
5958 | SourceLocation SemiLoc); |
5959 | |
5960 | enum class CheckConstexprKind { |
5961 | /// Diagnose issues that are non-constant or that are extensions. |
5962 | Diagnose, |
5963 | /// Identify whether this function satisfies the formal rules for constexpr |
5964 | /// functions in the current lanugage mode (with no extensions). |
5965 | CheckValid |
5966 | }; |
5967 | |
5968 | // Check whether a function declaration satisfies the requirements of a |
5969 | // constexpr function definition or a constexpr constructor definition. If so, |
5970 | // return true. If not, produce appropriate diagnostics (unless asked not to |
5971 | // by Kind) and return false. |
5972 | // |
5973 | // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. |
5974 | bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, |
5975 | CheckConstexprKind Kind); |
5976 | |
5977 | /// Diagnose methods which overload virtual methods in a base class |
5978 | /// without overriding any. |
5979 | void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); |
5980 | |
5981 | /// Check if a method overloads virtual methods in a base class without |
5982 | /// overriding any. |
5983 | void |
5984 | FindHiddenVirtualMethods(CXXMethodDecl *MD, |
5985 | SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods); |
5986 | void |
5987 | NoteHiddenVirtualMethods(CXXMethodDecl *MD, |
5988 | SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods); |
5989 | |
5990 | /// ActOnParamDefaultArgument - Check whether the default argument |
5991 | /// provided for a function parameter is well-formed. If so, attach it |
5992 | /// to the parameter declaration. |
5993 | void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, |
5994 | Expr *defarg); |
5995 | |
5996 | /// ActOnParamUnparsedDefaultArgument - We've seen a default |
5997 | /// argument for a function parameter, but we can't parse it yet |
5998 | /// because we're inside a class definition. Note that this default |
5999 | /// argument will be parsed later. |
6000 | void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, |
6001 | SourceLocation ArgLoc); |
6002 | |
6003 | /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of |
6004 | /// the default argument for the parameter param failed. |
6005 | void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, |
6006 | Expr *DefaultArg); |
6007 | ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, |
6008 | SourceLocation EqualLoc); |
6009 | void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, |
6010 | SourceLocation EqualLoc); |
6011 | |
6012 | void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); |
6013 | void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, |
6014 | StringLiteral *Message = nullptr); |
6015 | void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); |
6016 | |
6017 | void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, |
6018 | StringLiteral *DeletedMessage = nullptr); |
6019 | void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); |
6020 | ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); |
6021 | ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); |
6022 | |
6023 | NamedDecl * |
6024 | ActOnDecompositionDeclarator(Scope *S, Declarator &D, |
6025 | MultiTemplateParamsArg TemplateParamLists); |
6026 | void DiagPlaceholderVariableDefinition(SourceLocation Loc); |
6027 | bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, |
6028 | RecordDecl *ClassDecl, |
6029 | const IdentifierInfo *Name); |
6030 | |
6031 | unsigned GetDecompositionElementCount(QualType DecompType); |
6032 | void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); |
6033 | |
6034 | /// Stack containing information needed when in C++2a an 'auto' is encountered |
6035 | /// in a function declaration parameter type specifier in order to invent a |
6036 | /// corresponding template parameter in the enclosing abbreviated function |
6037 | /// template. This information is also present in LambdaScopeInfo, stored in |
6038 | /// the FunctionScopes stack. |
6039 | SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; |
6040 | |
6041 | /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. |
6042 | std::unique_ptr<CXXFieldCollector> FieldCollector; |
6043 | |
6044 | typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType; |
6045 | /// Set containing all declared private fields that are not used. |
6046 | NamedDeclSetType UnusedPrivateFields; |
6047 | |
6048 | typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy; |
6049 | |
6050 | /// PureVirtualClassDiagSet - a set of class declarations which we have |
6051 | /// emitted a list of pure virtual functions. Used to prevent emitting the |
6052 | /// same list more than once. |
6053 | std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; |
6054 | |
6055 | typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, |
6056 | &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> |
6057 | DelegatingCtorDeclsType; |
6058 | |
6059 | /// All the delegating constructors seen so far in the file, used for |
6060 | /// cycle detection at the end of the TU. |
6061 | DelegatingCtorDeclsType DelegatingCtorDecls; |
6062 | |
6063 | /// The C++ "std" namespace, where the standard library resides. |
6064 | LazyDeclPtr StdNamespace; |
6065 | |
6066 | /// The C++ "std::initializer_list" template, which is defined in |
6067 | /// \<initializer_list>. |
6068 | ClassTemplateDecl *StdInitializerList; |
6069 | |
6070 | // Contains the locations of the beginning of unparsed default |
6071 | // argument locations. |
6072 | llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; |
6073 | |
6074 | /// UndefinedInternals - all the used, undefined objects which require a |
6075 | /// definition in this translation unit. |
6076 | llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; |
6077 | |
6078 | typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind> |
6079 | SpecialMemberDecl; |
6080 | |
6081 | /// The C++ special members which we are currently in the process of |
6082 | /// declaring. If this process recursively triggers the declaration of the |
6083 | /// same special member, we should act as if it is not yet declared. |
6084 | llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; |
6085 | |
6086 | void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); |
6087 | |
6088 | void ActOnDefaultCtorInitializers(Decl *CDtorDecl); |
6089 | |
6090 | typedef ProcessingContextState ParsingClassState; |
6091 | ParsingClassState PushParsingClass() { |
6092 | ParsingClassDepth++; |
6093 | return DelayedDiagnostics.pushUndelayed(); |
6094 | } |
6095 | void PopParsingClass(ParsingClassState state) { |
6096 | ParsingClassDepth--; |
6097 | DelayedDiagnostics.popUndelayed(state); |
6098 | } |
6099 | |
6100 | ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, |
6101 | CXXScopeSpec &SS, |
6102 | ParsedType TemplateTypeTy, |
6103 | IdentifierInfo *MemberOrBase); |
6104 | |
6105 | private: |
6106 | void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, |
6107 | QualType ResultTy, |
6108 | ArrayRef<QualType> Args); |
6109 | |
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 | /// Check if there is a field shadowing. |
6116 | void CheckShadowInheritedFields(const SourceLocation &Loc, |
6117 | DeclarationName FieldName, |
6118 | const CXXRecordDecl *RD, |
6119 | bool DeclIsField = true); |
6120 | |
6121 | ///@} |
6122 | |
6123 | // |
6124 | // |
6125 | // ------------------------------------------------------------------------- |
6126 | // |
6127 | // |
6128 | |
6129 | /// \name C++ Exception Specifications |
6130 | /// Implementations are in SemaExceptionSpec.cpp |
6131 | ///@{ |
6132 | |
6133 | public: |
6134 | /// All the overriding functions seen during a class definition |
6135 | /// that had their exception spec checks delayed, plus the overridden |
6136 | /// function. |
6137 | SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2> |
6138 | DelayedOverridingExceptionSpecChecks; |
6139 | |
6140 | /// All the function redeclarations seen during a class definition that had |
6141 | /// their exception spec checks delayed, plus the prior declaration they |
6142 | /// should be checked against. Except during error recovery, the new decl |
6143 | /// should always be a friend declaration, as that's the only valid way to |
6144 | /// redeclare a special member before its class is complete. |
6145 | SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2> |
6146 | DelayedEquivalentExceptionSpecChecks; |
6147 | |
6148 | /// Determine if we're in a case where we need to (incorrectly) eagerly |
6149 | /// parse an exception specification to work around a libstdc++ bug. |
6150 | bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); |
6151 | |
6152 | /// Check the given noexcept-specifier, convert its expression, and compute |
6153 | /// the appropriate ExceptionSpecificationType. |
6154 | ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr, |
6155 | ExceptionSpecificationType &EST); |
6156 | |
6157 | CanThrowResult canThrow(const Stmt *E); |
6158 | /// Determine whether the callee of a particular function call can throw. |
6159 | /// E, D and Loc are all optional. |
6160 | static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, |
6161 | SourceLocation Loc = SourceLocation()); |
6162 | const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, |
6163 | const FunctionProtoType *FPT); |
6164 | void UpdateExceptionSpec(FunctionDecl *FD, |
6165 | const FunctionProtoType::ExceptionSpecInfo &ESI); |
6166 | |
6167 | /// CheckSpecifiedExceptionType - Check if the given type is valid in an |
6168 | /// exception specification. Incomplete types, or pointers to incomplete types |
6169 | /// other than void are not allowed. |
6170 | /// |
6171 | /// \param[in,out] T The exception type. This will be decayed to a pointer |
6172 | /// type |
6173 | /// when the input is an array or a function type. |
6174 | bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); |
6175 | |
6176 | /// CheckDistantExceptionSpec - Check if the given type is a pointer or |
6177 | /// pointer to member to a function with an exception specification. This |
6178 | /// means that it is invalid to add another level of indirection. |
6179 | bool CheckDistantExceptionSpec(QualType T); |
6180 | bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); |
6181 | |
6182 | /// CheckEquivalentExceptionSpec - Check if the two types have equivalent |
6183 | /// exception specifications. Exception specifications are equivalent if |
6184 | /// they allow exactly the same set of exception types. It does not matter how |
6185 | /// that is achieved. See C++ [except.spec]p2. |
6186 | bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old, |
6187 | SourceLocation OldLoc, |
6188 | const FunctionProtoType *New, |
6189 | SourceLocation NewLoc); |
6190 | bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID, |
6191 | const PartialDiagnostic &NoteID, |
6192 | const FunctionProtoType *Old, |
6193 | SourceLocation OldLoc, |
6194 | const FunctionProtoType *New, |
6195 | SourceLocation NewLoc); |
6196 | bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); |
6197 | |
6198 | /// CheckExceptionSpecSubset - Check whether the second function type's |
6199 | /// exception specification is a subset (or equivalent) of the first function |
6200 | /// type. This is used by override and pointer assignment checks. |
6201 | bool CheckExceptionSpecSubset( |
6202 | const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, |
6203 | const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, |
6204 | const FunctionProtoType *Superset, bool SkipSupersetFirstParameter, |
6205 | SourceLocation SuperLoc, const FunctionProtoType *Subset, |
6206 | bool SkipSubsetFirstParameter, SourceLocation SubLoc); |
6207 | |
6208 | /// CheckParamExceptionSpec - Check if the parameter and return types of the |
6209 | /// two functions have equivalent exception specs. This is part of the |
6210 | /// assignment and override compatibility check. We do not check the |
6211 | /// parameters of parameter function pointers recursively, as no sane |
6212 | /// programmer would even be able to write such a function type. |
6213 | bool CheckParamExceptionSpec( |
6214 | const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, |
6215 | const FunctionProtoType *Target, bool SkipTargetFirstParameter, |
6216 | SourceLocation TargetLoc, const FunctionProtoType *Source, |
6217 | bool SkipSourceFirstParameter, SourceLocation SourceLoc); |
6218 | |
6219 | bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); |
6220 | |
6221 | /// CheckOverridingFunctionExceptionSpec - Checks whether the exception |
6222 | /// spec is a subset of base spec. |
6223 | bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, |
6224 | const CXXMethodDecl *Old); |
6225 | |
6226 | ///@} |
6227 | |
6228 | // |
6229 | // |
6230 | // ------------------------------------------------------------------------- |
6231 | // |
6232 | // |
6233 | |
6234 | /// \name Expressions |
6235 | /// Implementations are in SemaExpr.cpp |
6236 | ///@{ |
6237 | |
6238 | public: |
6239 | /// Describes how the expressions currently being parsed are |
6240 | /// evaluated at run-time, if at all. |
6241 | enum class ExpressionEvaluationContext { |
6242 | /// The current expression and its subexpressions occur within an |
6243 | /// unevaluated operand (C++11 [expr]p7), such as the subexpression of |
6244 | /// \c sizeof, where the type of the expression may be significant but |
6245 | /// no code will be generated to evaluate the value of the expression at |
6246 | /// run time. |
6247 | Unevaluated, |
6248 | |
6249 | /// The current expression occurs within a braced-init-list within |
6250 | /// an unevaluated operand. This is mostly like a regular unevaluated |
6251 | /// context, except that we still instantiate constexpr functions that are |
6252 | /// referenced here so that we can perform narrowing checks correctly. |
6253 | UnevaluatedList, |
6254 | |
6255 | /// The current expression occurs within a discarded statement. |
6256 | /// This behaves largely similarly to an unevaluated operand in preventing |
6257 | /// definitions from being required, but not in other ways. |
6258 | DiscardedStatement, |
6259 | |
6260 | /// The current expression occurs within an unevaluated |
6261 | /// operand that unconditionally permits abstract references to |
6262 | /// fields, such as a SIZE operator in MS-style inline assembly. |
6263 | UnevaluatedAbstract, |
6264 | |
6265 | /// The current context is "potentially evaluated" in C++11 terms, |
6266 | /// but the expression is evaluated at compile-time (like the values of |
6267 | /// cases in a switch statement). |
6268 | ConstantEvaluated, |
6269 | |
6270 | /// In addition of being constant evaluated, the current expression |
6271 | /// occurs in an immediate function context - either a consteval function |
6272 | /// or a consteval if statement. |
6273 | ImmediateFunctionContext, |
6274 | |
6275 | /// The current expression is potentially evaluated at run time, |
6276 | /// which means that code may be generated to evaluate the value of the |
6277 | /// expression at run time. |
6278 | PotentiallyEvaluated, |
6279 | |
6280 | /// The current expression is potentially evaluated, but any |
6281 | /// declarations referenced inside that expression are only used if |
6282 | /// in fact the current expression is used. |
6283 | /// |
6284 | /// This value is used when parsing default function arguments, for which |
6285 | /// we would like to provide diagnostics (e.g., passing non-POD arguments |
6286 | /// through varargs) but do not want to mark declarations as "referenced" |
6287 | /// until the default argument is used. |
6288 | PotentiallyEvaluatedIfUsed |
6289 | }; |
6290 | |
6291 | /// Store a set of either DeclRefExprs or MemberExprs that contain a reference |
6292 | /// to a variable (constant) that may or may not be odr-used in this Expr, and |
6293 | /// we won't know until all lvalue-to-rvalue and discarded value conversions |
6294 | /// have been applied to all subexpressions of the enclosing full expression. |
6295 | /// This is cleared at the end of each full expression. |
6296 | using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>; |
6297 | MaybeODRUseExprSet MaybeODRUseExprs; |
6298 | |
6299 | using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; |
6300 | |
6301 | /// Data structure used to record current or nested |
6302 | /// expression evaluation contexts. |
6303 | struct ExpressionEvaluationContextRecord { |
6304 | /// The expression evaluation context. |
6305 | ExpressionEvaluationContext Context; |
6306 | |
6307 | /// Whether the enclosing context needed a cleanup. |
6308 | CleanupInfo ParentCleanup; |
6309 | |
6310 | /// The number of active cleanup objects when we entered |
6311 | /// this expression evaluation context. |
6312 | unsigned NumCleanupObjects; |
6313 | |
6314 | /// The number of typos encountered during this expression evaluation |
6315 | /// context (i.e. the number of TypoExprs created). |
6316 | unsigned NumTypos; |
6317 | |
6318 | MaybeODRUseExprSet SavedMaybeODRUseExprs; |
6319 | |
6320 | /// The lambdas that are present within this context, if it |
6321 | /// is indeed an unevaluated context. |
6322 | SmallVector<LambdaExpr *, 2> Lambdas; |
6323 | |
6324 | /// The declaration that provides context for lambda expressions |
6325 | /// and block literals if the normal declaration context does not |
6326 | /// suffice, e.g., in a default function argument. |
6327 | Decl *ManglingContextDecl; |
6328 | |
6329 | /// If we are processing a decltype type, a set of call expressions |
6330 | /// for which we have deferred checking the completeness of the return type. |
6331 | SmallVector<CallExpr *, 8> DelayedDecltypeCalls; |
6332 | |
6333 | /// If we are processing a decltype type, a set of temporary binding |
6334 | /// expressions for which we have deferred checking the destructor. |
6335 | SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; |
6336 | |
6337 | llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; |
6338 | |
6339 | /// Expressions appearing as the LHS of a volatile assignment in this |
6340 | /// context. We produce a warning for these when popping the context if |
6341 | /// they are not discarded-value expressions nor unevaluated operands. |
6342 | SmallVector<Expr *, 2> VolatileAssignmentLHSs; |
6343 | |
6344 | /// Set of candidates for starting an immediate invocation. |
6345 | llvm::SmallVector<ImmediateInvocationCandidate, 4> |
6346 | ImmediateInvocationCandidates; |
6347 | |
6348 | /// Set of DeclRefExprs referencing a consteval function when used in a |
6349 | /// context not already known to be immediately invoked. |
6350 | llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; |
6351 | |
6352 | /// P2718R0 - Lifetime extension in range-based for loops. |
6353 | /// MaterializeTemporaryExprs in for-range-init expressions which need to |
6354 | /// extend lifetime. Add MaterializeTemporaryExpr* if the value of |
6355 | /// InLifetimeExtendingContext is true. |
6356 | SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps; |
6357 | |
6358 | /// \brief Describes whether we are in an expression constext which we have |
6359 | /// to handle differently. |
6360 | enum ExpressionKind { |
6361 | EK_Decltype, |
6362 | EK_TemplateArgument, |
6363 | EK_AttrArgument, |
6364 | EK_Other |
6365 | } ExprContext; |
6366 | |
6367 | // A context can be nested in both a discarded statement context and |
6368 | // an immediate function context, so they need to be tracked independently. |
6369 | bool InDiscardedStatement; |
6370 | bool InImmediateFunctionContext; |
6371 | bool InImmediateEscalatingFunctionContext; |
6372 | |
6373 | bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false; |
6374 | |
6375 | // We are in a constant context, but we also allow |
6376 | // non constant expressions, for example for array bounds (which may be |
6377 | // VLAs). |
6378 | bool InConditionallyConstantEvaluateContext = false; |
6379 | |
6380 | /// Whether we are currently in a context in which all temporaries must be |
6381 | /// lifetime-extended, even if they're not bound to a reference (for |
6382 | /// example, in a for-range initializer). |
6383 | bool InLifetimeExtendingContext = false; |
6384 | |
6385 | /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr. |
6386 | bool RebuildDefaultArgOrDefaultInit = false; |
6387 | |
6388 | // When evaluating immediate functions in the initializer of a default |
6389 | // argument or default member initializer, this is the declaration whose |
6390 | // default initializer is being evaluated and the location of the call |
6391 | // or constructor definition. |
6392 | struct InitializationContext { |
6393 | InitializationContext(SourceLocation Loc, ValueDecl *Decl, |
6394 | DeclContext *Context) |
6395 | : Loc(Loc), Decl(Decl), Context(Context) { |
6396 | assert(Decl && Context && "invalid initialization context" ); |
6397 | } |
6398 | |
6399 | SourceLocation Loc; |
6400 | ValueDecl *Decl = nullptr; |
6401 | DeclContext *Context = nullptr; |
6402 | }; |
6403 | std::optional<InitializationContext> DelayedDefaultInitializationContext; |
6404 | |
6405 | ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, |
6406 | unsigned NumCleanupObjects, |
6407 | CleanupInfo ParentCleanup, |
6408 | Decl *ManglingContextDecl, |
6409 | ExpressionKind ExprContext) |
6410 | : Context(Context), ParentCleanup(ParentCleanup), |
6411 | NumCleanupObjects(NumCleanupObjects), NumTypos(0), |
6412 | ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext), |
6413 | InDiscardedStatement(false), InImmediateFunctionContext(false), |
6414 | InImmediateEscalatingFunctionContext(false) {} |
6415 | |
6416 | bool isUnevaluated() const { |
6417 | return Context == ExpressionEvaluationContext::Unevaluated || |
6418 | Context == ExpressionEvaluationContext::UnevaluatedAbstract || |
6419 | Context == ExpressionEvaluationContext::UnevaluatedList; |
6420 | } |
6421 | |
6422 | bool isPotentiallyEvaluated() const { |
6423 | return Context == ExpressionEvaluationContext::PotentiallyEvaluated || |
6424 | Context == |
6425 | ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed || |
6426 | Context == ExpressionEvaluationContext::ConstantEvaluated; |
6427 | } |
6428 | |
6429 | bool isConstantEvaluated() const { |
6430 | return Context == ExpressionEvaluationContext::ConstantEvaluated || |
6431 | Context == ExpressionEvaluationContext::ImmediateFunctionContext; |
6432 | } |
6433 | |
6434 | bool isImmediateFunctionContext() const { |
6435 | return Context == ExpressionEvaluationContext::ImmediateFunctionContext || |
6436 | (Context == ExpressionEvaluationContext::DiscardedStatement && |
6437 | InImmediateFunctionContext) || |
6438 | // C++23 [expr.const]p14: |
6439 | // An expression or conversion is in an immediate function |
6440 | // context if it is potentially evaluated and either: |
6441 | // * its innermost enclosing non-block scope is a function |
6442 | // parameter scope of an immediate function, or |
6443 | // * its enclosing statement is enclosed by the compound- |
6444 | // statement of a consteval if statement. |
6445 | (Context == ExpressionEvaluationContext::PotentiallyEvaluated && |
6446 | InImmediateFunctionContext); |
6447 | } |
6448 | |
6449 | bool isDiscardedStatementContext() const { |
6450 | return Context == ExpressionEvaluationContext::DiscardedStatement || |
6451 | (Context == |
6452 | ExpressionEvaluationContext::ImmediateFunctionContext && |
6453 | InDiscardedStatement); |
6454 | } |
6455 | }; |
6456 | |
6457 | const ExpressionEvaluationContextRecord ¤tEvaluationContext() const { |
6458 | assert(!ExprEvalContexts.empty() && |
6459 | "Must be in an expression evaluation context" ); |
6460 | return ExprEvalContexts.back(); |
6461 | }; |
6462 | |
6463 | ExpressionEvaluationContextRecord ¤tEvaluationContext() { |
6464 | assert(!ExprEvalContexts.empty() && |
6465 | "Must be in an expression evaluation context" ); |
6466 | return ExprEvalContexts.back(); |
6467 | }; |
6468 | |
6469 | ExpressionEvaluationContextRecord &parentEvaluationContext() { |
6470 | assert(ExprEvalContexts.size() >= 2 && |
6471 | "Must be in an expression evaluation context" ); |
6472 | return ExprEvalContexts[ExprEvalContexts.size() - 2]; |
6473 | }; |
6474 | |
6475 | const ExpressionEvaluationContextRecord &parentEvaluationContext() const { |
6476 | return const_cast<Sema *>(this)->parentEvaluationContext(); |
6477 | }; |
6478 | |
6479 | bool isAttrContext() const { |
6480 | return ExprEvalContexts.back().ExprContext == |
6481 | ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument; |
6482 | } |
6483 | |
6484 | /// Increment when we find a reference; decrement when we find an ignored |
6485 | /// assignment. Ultimately the value is 0 if every reference is an ignored |
6486 | /// assignment. |
6487 | llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments; |
6488 | |
6489 | /// Used to control the generation of ExprWithCleanups. |
6490 | CleanupInfo Cleanup; |
6491 | |
6492 | /// ExprCleanupObjects - This is the stack of objects requiring |
6493 | /// cleanup that are created by the current full expression. |
6494 | SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; |
6495 | |
6496 | /// Determine whether the use of this declaration is valid, without |
6497 | /// emitting diagnostics. |
6498 | bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); |
6499 | // A version of DiagnoseUseOfDecl that should be used if overload resolution |
6500 | // has been used to find this declaration, which means we don't have to bother |
6501 | // checking the trailing requires clause. |
6502 | bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) { |
6503 | return DiagnoseUseOfDecl( |
6504 | D, Locs: Loc, /*UnknownObjCClass=*/UnknownObjCClass: nullptr, /*ObjCPropertyAccess=*/ObjCPropertyAccess: false, |
6505 | /*AvoidPartialAvailabilityChecks=*/AvoidPartialAvailabilityChecks: false, /*ClassReceiver=*/ClassReciever: nullptr, |
6506 | /*SkipTrailingRequiresClause=*/SkipTrailingRequiresClause: true); |
6507 | } |
6508 | |
6509 | /// Determine whether the use of this declaration is valid, and |
6510 | /// emit any corresponding diagnostics. |
6511 | /// |
6512 | /// This routine diagnoses various problems with referencing |
6513 | /// declarations that can occur when using a declaration. For example, |
6514 | /// it might warn if a deprecated or unavailable declaration is being |
6515 | /// used, or produce an error (and return true) if a C++0x deleted |
6516 | /// function is being used. |
6517 | /// |
6518 | /// \returns true if there was an error (this declaration cannot be |
6519 | /// referenced), false otherwise. |
6520 | bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, |
6521 | const ObjCInterfaceDecl *UnknownObjCClass = nullptr, |
6522 | bool ObjCPropertyAccess = false, |
6523 | bool AvoidPartialAvailabilityChecks = false, |
6524 | ObjCInterfaceDecl *ClassReciever = nullptr, |
6525 | bool SkipTrailingRequiresClause = false); |
6526 | |
6527 | /// Emit a note explaining that this function is deleted. |
6528 | void NoteDeletedFunction(FunctionDecl *FD); |
6529 | |
6530 | /// DiagnoseSentinelCalls - This routine checks whether a call or |
6531 | /// message-send is to a declaration with the sentinel attribute, and |
6532 | /// if so, it checks that the requirements of the sentinel are |
6533 | /// satisfied. |
6534 | void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, |
6535 | ArrayRef<Expr *> Args); |
6536 | |
6537 | void PushExpressionEvaluationContext( |
6538 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, |
6539 | ExpressionEvaluationContextRecord::ExpressionKind Type = |
6540 | ExpressionEvaluationContextRecord::EK_Other); |
6541 | enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; |
6542 | void PushExpressionEvaluationContext( |
6543 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, |
6544 | ExpressionEvaluationContextRecord::ExpressionKind Type = |
6545 | ExpressionEvaluationContextRecord::EK_Other); |
6546 | void PopExpressionEvaluationContext(); |
6547 | |
6548 | void DiscardCleanupsInEvaluationContext(); |
6549 | |
6550 | ExprResult TransformToPotentiallyEvaluated(Expr *E); |
6551 | TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo); |
6552 | ExprResult HandleExprEvaluationContextForTypeof(Expr *E); |
6553 | |
6554 | /// Check whether E, which is either a discarded-value expression or an |
6555 | /// unevaluated operand, is a simple-assignment to a volatlie-qualified |
6556 | /// lvalue, and if so, remove it from the list of volatile-qualified |
6557 | /// assignments that we are going to warn are deprecated. |
6558 | void CheckUnusedVolatileAssignment(Expr *E); |
6559 | |
6560 | ExprResult ActOnConstantExpression(ExprResult Res); |
6561 | |
6562 | // Functions for marking a declaration referenced. These functions also |
6563 | // contain the relevant logic for marking if a reference to a function or |
6564 | // variable is an odr-use (in the C++11 sense). There are separate variants |
6565 | // for expressions referring to a decl; these exist because odr-use marking |
6566 | // needs to be delayed for some constant variables when we build one of the |
6567 | // named expressions. |
6568 | // |
6569 | // MightBeOdrUse indicates whether the use could possibly be an odr-use, and |
6570 | // should usually be true. This only needs to be set to false if the lack of |
6571 | // odr-use cannot be determined from the current context (for instance, |
6572 | // because the name denotes a virtual function and was written without an |
6573 | // explicit nested-name-specifier). |
6574 | void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); |
6575 | |
6576 | /// Mark a function referenced, and check whether it is odr-used |
6577 | /// (C++ [basic.def.odr]p2, C99 6.9p3) |
6578 | void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, |
6579 | bool MightBeOdrUse = true); |
6580 | |
6581 | /// Mark a variable referenced, and check whether it is odr-used |
6582 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be |
6583 | /// used directly for normal expressions referring to VarDecl. |
6584 | void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); |
6585 | |
6586 | /// Perform reference-marking and odr-use handling for a DeclRefExpr. |
6587 | /// |
6588 | /// Note, this may change the dependence of the DeclRefExpr, and so needs to |
6589 | /// be handled with care if the DeclRefExpr is not newly-created. |
6590 | void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); |
6591 | |
6592 | /// Perform reference-marking and odr-use handling for a MemberExpr. |
6593 | void MarkMemberReferenced(MemberExpr *E); |
6594 | |
6595 | /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. |
6596 | void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); |
6597 | void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, |
6598 | unsigned CapturingScopeIndex); |
6599 | |
6600 | ExprResult CheckLValueToRValueConversionOperand(Expr *E); |
6601 | void CleanupVarDeclMarking(); |
6602 | |
6603 | enum TryCaptureKind { |
6604 | TryCapture_Implicit, |
6605 | TryCapture_ExplicitByVal, |
6606 | TryCapture_ExplicitByRef |
6607 | }; |
6608 | |
6609 | /// Try to capture the given variable. |
6610 | /// |
6611 | /// \param Var The variable to capture. |
6612 | /// |
6613 | /// \param Loc The location at which the capture occurs. |
6614 | /// |
6615 | /// \param Kind The kind of capture, which may be implicit (for either a |
6616 | /// block or a lambda), or explicit by-value or by-reference (for a lambda). |
6617 | /// |
6618 | /// \param EllipsisLoc The location of the ellipsis, if one is provided in |
6619 | /// an explicit lambda capture. |
6620 | /// |
6621 | /// \param BuildAndDiagnose Whether we are actually supposed to add the |
6622 | /// captures or diagnose errors. If false, this routine merely check whether |
6623 | /// the capture can occur without performing the capture itself or complaining |
6624 | /// if the variable cannot be captured. |
6625 | /// |
6626 | /// \param CaptureType Will be set to the type of the field used to capture |
6627 | /// this variable in the innermost block or lambda. Only valid when the |
6628 | /// variable can be captured. |
6629 | /// |
6630 | /// \param DeclRefType Will be set to the type of a reference to the capture |
6631 | /// from within the current scope. Only valid when the variable can be |
6632 | /// captured. |
6633 | /// |
6634 | /// \param FunctionScopeIndexToStopAt If non-null, it points to the index |
6635 | /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. |
6636 | /// This is useful when enclosing lambdas must speculatively capture |
6637 | /// variables that may or may not be used in certain specializations of |
6638 | /// a nested generic lambda. |
6639 | /// |
6640 | /// \returns true if an error occurred (i.e., the variable cannot be |
6641 | /// captured) and false if the capture succeeded. |
6642 | bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, |
6643 | TryCaptureKind Kind, SourceLocation EllipsisLoc, |
6644 | bool BuildAndDiagnose, QualType &CaptureType, |
6645 | QualType &DeclRefType, |
6646 | const unsigned *const FunctionScopeIndexToStopAt); |
6647 | |
6648 | /// Try to capture the given variable. |
6649 | bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, |
6650 | TryCaptureKind Kind = TryCapture_Implicit, |
6651 | SourceLocation EllipsisLoc = SourceLocation()); |
6652 | |
6653 | /// Checks if the variable must be captured. |
6654 | bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc); |
6655 | |
6656 | /// Given a variable, determine the type that a reference to that |
6657 | /// variable will have in the given scope. |
6658 | QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc); |
6659 | |
6660 | /// Mark all of the declarations referenced within a particular AST node as |
6661 | /// referenced. Used when template instantiation instantiates a non-dependent |
6662 | /// type -- entities referenced by the type are now referenced. |
6663 | void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); |
6664 | |
6665 | /// Mark any declarations that appear within this expression or any |
6666 | /// potentially-evaluated subexpressions as "referenced". |
6667 | /// |
6668 | /// \param SkipLocalVariables If true, don't mark local variables as |
6669 | /// 'referenced'. |
6670 | /// \param StopAt Subexpressions that we shouldn't recurse into. |
6671 | void MarkDeclarationsReferencedInExpr(Expr *E, |
6672 | bool SkipLocalVariables = false, |
6673 | ArrayRef<const Expr *> StopAt = {}); |
6674 | |
6675 | /// Try to convert an expression \p E to type \p Ty. Returns the result of the |
6676 | /// conversion. |
6677 | ExprResult tryConvertExprToType(Expr *E, QualType Ty); |
6678 | |
6679 | /// Conditionally issue a diagnostic based on the statements's reachability |
6680 | /// analysis. |
6681 | /// |
6682 | /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until |
6683 | /// the function body is parsed, and then do a basic reachability analysis to |
6684 | /// determine if the statement is reachable. If it is unreachable, the |
6685 | /// diagnostic will not be emitted. |
6686 | bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, |
6687 | const PartialDiagnostic &PD); |
6688 | |
6689 | /// Conditionally issue a diagnostic based on the current |
6690 | /// evaluation context. |
6691 | /// |
6692 | /// \param Statement If Statement is non-null, delay reporting the |
6693 | /// diagnostic until the function body is parsed, and then do a basic |
6694 | /// reachability analysis to determine if the statement is reachable. |
6695 | /// If it is unreachable, the diagnostic will not be emitted. |
6696 | bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, |
6697 | const PartialDiagnostic &PD); |
6698 | /// Similar, but diagnostic is only produced if all the specified statements |
6699 | /// are reachable. |
6700 | bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, |
6701 | const PartialDiagnostic &PD); |
6702 | |
6703 | // Primary Expressions. |
6704 | SourceRange getExprRange(Expr *E) const; |
6705 | |
6706 | ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, |
6707 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, |
6708 | bool HasTrailingLParen, bool IsAddressOfOperand, |
6709 | CorrectionCandidateCallback *CCC = nullptr, |
6710 | bool IsInlineAsmIdentifier = false, |
6711 | Token *KeywordReplacement = nullptr); |
6712 | |
6713 | /// Decomposes the given name into a DeclarationNameInfo, its location, and |
6714 | /// possibly a list of template arguments. |
6715 | /// |
6716 | /// If this produces template arguments, it is permitted to call |
6717 | /// DecomposeTemplateName. |
6718 | /// |
6719 | /// This actually loses a lot of source location information for |
6720 | /// non-standard name kinds; we should consider preserving that in |
6721 | /// some way. |
6722 | void DecomposeUnqualifiedId(const UnqualifiedId &Id, |
6723 | TemplateArgumentListInfo &Buffer, |
6724 | DeclarationNameInfo &NameInfo, |
6725 | const TemplateArgumentListInfo *&TemplateArgs); |
6726 | |
6727 | /// Diagnose a lookup that found results in an enclosing class during error |
6728 | /// recovery. This usually indicates that the results were found in a |
6729 | /// dependent base class that could not be searched as part of a template |
6730 | /// definition. Always issues a diagnostic (though this may be only a warning |
6731 | /// in MS compatibility mode). |
6732 | /// |
6733 | /// Return \c true if the error is unrecoverable, or \c false if the caller |
6734 | /// should attempt to recover using these lookup results. |
6735 | bool DiagnoseDependentMemberLookup(const LookupResult &R); |
6736 | |
6737 | /// Diagnose an empty lookup. |
6738 | /// |
6739 | /// \return false if new lookup candidates were found |
6740 | bool |
6741 | DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, |
6742 | CorrectionCandidateCallback &CCC, |
6743 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, |
6744 | ArrayRef<Expr *> Args = {}, |
6745 | DeclContext *LookupCtx = nullptr, |
6746 | TypoExpr **Out = nullptr); |
6747 | |
6748 | /// If \p D cannot be odr-used in the current expression evaluation context, |
6749 | /// return a reason explaining why. Otherwise, return NOUR_None. |
6750 | NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); |
6751 | |
6752 | DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
6753 | SourceLocation Loc, |
6754 | const CXXScopeSpec *SS = nullptr); |
6755 | DeclRefExpr * |
6756 | BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
6757 | const DeclarationNameInfo &NameInfo, |
6758 | const CXXScopeSpec *SS = nullptr, |
6759 | NamedDecl *FoundD = nullptr, |
6760 | SourceLocation TemplateKWLoc = SourceLocation(), |
6761 | const TemplateArgumentListInfo *TemplateArgs = nullptr); |
6762 | |
6763 | /// BuildDeclRefExpr - Build an expression that references a |
6764 | /// declaration that does not require a closure capture. |
6765 | DeclRefExpr * |
6766 | BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
6767 | const DeclarationNameInfo &NameInfo, |
6768 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, |
6769 | SourceLocation TemplateKWLoc = SourceLocation(), |
6770 | const TemplateArgumentListInfo *TemplateArgs = nullptr); |
6771 | |
6772 | bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, |
6773 | bool HasTrailingLParen); |
6774 | |
6775 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified |
6776 | /// declaration name, generally during template instantiation. |
6777 | /// There's a large number of things which don't need to be done along |
6778 | /// this path. |
6779 | ExprResult BuildQualifiedDeclarationNameExpr( |
6780 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, |
6781 | bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr); |
6782 | |
6783 | ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, |
6784 | bool NeedsADL, |
6785 | bool AcceptInvalidDecl = false); |
6786 | |
6787 | /// Complete semantic analysis for a reference to the given declaration. |
6788 | ExprResult BuildDeclarationNameExpr( |
6789 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, |
6790 | NamedDecl *FoundD = nullptr, |
6791 | const TemplateArgumentListInfo *TemplateArgs = nullptr, |
6792 | bool AcceptInvalidDecl = false); |
6793 | |
6794 | // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens, |
6795 | // where Tokens representing function local predefined macros (such as |
6796 | // __FUNCTION__) are replaced (expanded) with string-literal Tokens. |
6797 | std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks); |
6798 | |
6799 | ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK); |
6800 | ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); |
6801 | ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val); |
6802 | |
6803 | bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero); |
6804 | |
6805 | ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); |
6806 | ExprResult ActOnCharacterConstant(const Token &Tok, |
6807 | Scope *UDLScope = nullptr); |
6808 | ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); |
6809 | ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, |
6810 | MultiExprArg Val); |
6811 | |
6812 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string |
6813 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle |
6814 | /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come |
6815 | /// from multiple tokens. However, the common case is that StringToks points |
6816 | /// to one string. |
6817 | ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, |
6818 | Scope *UDLScope = nullptr); |
6819 | |
6820 | ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks); |
6821 | |
6822 | /// ControllingExprOrType is either an opaque pointer coming out of a |
6823 | /// ParsedType or an Expr *. FIXME: it'd be better to split this interface |
6824 | /// into two so we don't take a void *, but that's awkward because one of |
6825 | /// the operands is either a ParsedType or an Expr *, which doesn't lend |
6826 | /// itself to generic code very well. |
6827 | ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, |
6828 | SourceLocation DefaultLoc, |
6829 | SourceLocation RParenLoc, |
6830 | bool PredicateIsExpr, |
6831 | void *ControllingExprOrType, |
6832 | ArrayRef<ParsedType> ArgTypes, |
6833 | ArrayRef<Expr *> ArgExprs); |
6834 | /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME: |
6835 | /// it'd be better to split this interface into two so we don't take a |
6836 | /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that |
6837 | /// isn't a trivial change. |
6838 | ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, |
6839 | SourceLocation DefaultLoc, |
6840 | SourceLocation RParenLoc, |
6841 | bool PredicateIsExpr, |
6842 | void *ControllingExprOrType, |
6843 | ArrayRef<TypeSourceInfo *> Types, |
6844 | ArrayRef<Expr *> Exprs); |
6845 | |
6846 | // Binary/Unary Operators. 'Tok' is the token for the operator. |
6847 | ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, |
6848 | Expr *InputExpr, bool IsAfterAmp = false); |
6849 | ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, |
6850 | Expr *Input, bool IsAfterAmp = false); |
6851 | |
6852 | /// Unary Operators. 'Tok' is the token for the operator. |
6853 | ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, |
6854 | Expr *Input, bool IsAfterAmp = false); |
6855 | |
6856 | /// Determine whether the given expression is a qualified member |
6857 | /// access expression, of a form that could be turned into a pointer to member |
6858 | /// with the address-of operator. |
6859 | bool isQualifiedMemberAccess(Expr *E); |
6860 | bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, |
6861 | const Expr *Op, |
6862 | const CXXMethodDecl *MD); |
6863 | |
6864 | /// CheckAddressOfOperand - The operand of & must be either a function |
6865 | /// designator or an lvalue designating an object. If it is an lvalue, the |
6866 | /// object cannot be declared with storage class register or be a bit field. |
6867 | /// Note: The usual conversions are *not* applied to the operand of the & |
6868 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. |
6869 | /// In C++, the operand might be an overloaded function name, in which case |
6870 | /// we allow the '&' but retain the overloaded-function type. |
6871 | QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); |
6872 | |
6873 | /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c |
6874 | /// _Alignas(type-name) . |
6875 | /// [dcl.align] An alignment-specifier of the form |
6876 | /// alignas(type-id) has the same effect as alignas(alignof(type-id)). |
6877 | /// |
6878 | /// [N1570 6.7.5] _Alignas(type-name) is equivalent to |
6879 | /// _Alignas(_Alignof(type-name)). |
6880 | bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, |
6881 | SourceLocation OpLoc, SourceRange R); |
6882 | bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, |
6883 | SourceLocation OpLoc, SourceRange R); |
6884 | |
6885 | /// Build a sizeof or alignof expression given a type operand. |
6886 | ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, |
6887 | SourceLocation OpLoc, |
6888 | UnaryExprOrTypeTrait ExprKind, |
6889 | SourceRange R); |
6890 | |
6891 | /// Build a sizeof or alignof expression given an expression |
6892 | /// operand. |
6893 | ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, |
6894 | UnaryExprOrTypeTrait ExprKind); |
6895 | |
6896 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c |
6897 | /// expr and the same for @c alignof and @c __alignof |
6898 | /// Note that the ArgRange is invalid if isType is false. |
6899 | ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, |
6900 | UnaryExprOrTypeTrait ExprKind, |
6901 | bool IsType, void *TyOrEx, |
6902 | SourceRange ArgRange); |
6903 | |
6904 | /// Check for operands with placeholder types and complain if found. |
6905 | /// Returns ExprError() if there was an error and no recovery was possible. |
6906 | ExprResult CheckPlaceholderExpr(Expr *E); |
6907 | bool CheckVecStepExpr(Expr *E); |
6908 | |
6909 | /// Check the constraints on expression operands to unary type expression |
6910 | /// and type traits. |
6911 | /// |
6912 | /// Completes any types necessary and validates the constraints on the operand |
6913 | /// expression. The logic mostly mirrors the type-based overload, but may |
6914 | /// modify the expression as it completes the type for that expression through |
6915 | /// template instantiation, etc. |
6916 | bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); |
6917 | |
6918 | /// Check the constraints on operands to unary expression and type |
6919 | /// traits. |
6920 | /// |
6921 | /// This will complete any types necessary, and validate the various |
6922 | /// constraints on those operands. |
6923 | /// |
6924 | /// The UsualUnaryConversions() function is *not* called by this routine. |
6925 | /// C99 6.3.2.1p[2-4] all state: |
6926 | /// Except when it is the operand of the sizeof operator ... |
6927 | /// |
6928 | /// C++ [expr.sizeof]p4 |
6929 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer |
6930 | /// standard conversions are not applied to the operand of sizeof. |
6931 | /// |
6932 | /// This policy is followed for all of the unary trait expressions. |
6933 | bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, |
6934 | SourceRange ExprRange, |
6935 | UnaryExprOrTypeTrait ExprKind, |
6936 | StringRef KWName); |
6937 | |
6938 | ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, |
6939 | tok::TokenKind Kind, Expr *Input); |
6940 | |
6941 | ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, |
6942 | MultiExprArg ArgExprs, |
6943 | SourceLocation RLoc); |
6944 | ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, |
6945 | Expr *Idx, SourceLocation RLoc); |
6946 | |
6947 | ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, |
6948 | Expr *ColumnIdx, |
6949 | SourceLocation RBLoc); |
6950 | |
6951 | /// ConvertArgumentsForCall - Converts the arguments specified in |
6952 | /// Args/NumArgs to the parameter types of the function FDecl with |
6953 | /// function prototype Proto. Call is the call expression itself, and |
6954 | /// Fn is the function expression. For a C++ member function, this |
6955 | /// routine does not attempt to convert the object argument. Returns |
6956 | /// true if the call is ill-formed. |
6957 | bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, |
6958 | const FunctionProtoType *Proto, |
6959 | ArrayRef<Expr *> Args, SourceLocation RParenLoc, |
6960 | bool ExecConfig = false); |
6961 | |
6962 | /// CheckStaticArrayArgument - If the given argument corresponds to a static |
6963 | /// array parameter, check that it is non-null, and that if it is formed by |
6964 | /// array-to-pointer decay, the underlying array is sufficiently large. |
6965 | /// |
6966 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of |
6967 | /// the array type derivation, then for each call to the function, the value |
6968 | /// of the corresponding actual argument shall provide access to the first |
6969 | /// element of an array with at least as many elements as specified by the |
6970 | /// size expression. |
6971 | void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, |
6972 | const Expr *ArgExpr); |
6973 | |
6974 | /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. |
6975 | /// This provides the location of the left/right parens and a list of comma |
6976 | /// locations. |
6977 | ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, |
6978 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
6979 | Expr *ExecConfig = nullptr); |
6980 | |
6981 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. |
6982 | /// This provides the location of the left/right parens and a list of comma |
6983 | /// locations. |
6984 | ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, |
6985 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
6986 | Expr *ExecConfig = nullptr, |
6987 | bool IsExecConfig = false, |
6988 | bool AllowRecovery = false); |
6989 | |
6990 | /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id |
6991 | // with the specified CallArgs |
6992 | Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, |
6993 | MultiExprArg CallArgs); |
6994 | |
6995 | using ADLCallKind = CallExpr::ADLCallKind; |
6996 | |
6997 | /// BuildResolvedCallExpr - Build a call to a resolved expression, |
6998 | /// i.e. an expression not of \p OverloadTy. The expression should |
6999 | /// unary-convert to an expression of function-pointer or |
7000 | /// block-pointer type. |
7001 | /// |
7002 | /// \param NDecl the declaration being called, if available |
7003 | ExprResult |
7004 | BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, |
7005 | ArrayRef<Expr *> Arg, SourceLocation RParenLoc, |
7006 | Expr *Config = nullptr, bool IsExecConfig = false, |
7007 | ADLCallKind UsesADL = ADLCallKind::NotADL); |
7008 | |
7009 | ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, |
7010 | ParsedType &Ty, SourceLocation RParenLoc, |
7011 | Expr *CastExpr); |
7012 | |
7013 | /// Prepares for a scalar cast, performing all the necessary stages |
7014 | /// except the final cast and returning the kind required. |
7015 | CastKind PrepareScalarCast(ExprResult &src, QualType destType); |
7016 | |
7017 | /// Build an altivec or OpenCL literal. |
7018 | ExprResult BuildVectorLiteral(SourceLocation LParenLoc, |
7019 | SourceLocation RParenLoc, Expr *E, |
7020 | TypeSourceInfo *TInfo); |
7021 | |
7022 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn |
7023 | /// the ParenListExpr into a sequence of comma binary operators. |
7024 | ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); |
7025 | |
7026 | ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, |
7027 | SourceLocation RParenLoc, Expr *InitExpr); |
7028 | |
7029 | ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, |
7030 | TypeSourceInfo *TInfo, |
7031 | SourceLocation RParenLoc, |
7032 | Expr *LiteralExpr); |
7033 | |
7034 | ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, |
7035 | SourceLocation RBraceLoc); |
7036 | |
7037 | ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, |
7038 | SourceLocation RBraceLoc); |
7039 | |
7040 | /// Binary Operators. 'Tok' is the token for the operator. |
7041 | ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, |
7042 | Expr *LHSExpr, Expr *RHSExpr); |
7043 | ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, |
7044 | Expr *LHSExpr, Expr *RHSExpr); |
7045 | |
7046 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with |
7047 | /// operator @p Opc at location @c TokLoc. This routine only supports |
7048 | /// built-in operations; ActOnBinOp handles overloaded operators. |
7049 | ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, |
7050 | Expr *LHSExpr, Expr *RHSExpr); |
7051 | void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, |
7052 | UnresolvedSetImpl &Functions); |
7053 | |
7054 | /// Look for instances where it is likely the comma operator is confused with |
7055 | /// another operator. There is an explicit list of acceptable expressions for |
7056 | /// the left hand side of the comma operator, otherwise emit a warning. |
7057 | void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); |
7058 | |
7059 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null |
7060 | /// in the case of a the GNU conditional expr extension. |
7061 | ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, |
7062 | SourceLocation ColonLoc, Expr *CondExpr, |
7063 | Expr *LHSExpr, Expr *RHSExpr); |
7064 | |
7065 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". |
7066 | ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, |
7067 | LabelDecl *TheDecl); |
7068 | |
7069 | void ActOnStartStmtExpr(); |
7070 | ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, |
7071 | SourceLocation RPLoc); |
7072 | ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, |
7073 | SourceLocation RPLoc, unsigned TemplateDepth); |
7074 | // Handle the final expression in a statement expression. |
7075 | ExprResult ActOnStmtExprResult(ExprResult E); |
7076 | void ActOnStmtExprError(); |
7077 | |
7078 | // __builtin_offsetof(type, identifier(.identifier|[expr])*) |
7079 | struct OffsetOfComponent { |
7080 | SourceLocation LocStart, LocEnd; |
7081 | bool isBrackets; // true if [expr], false if .ident |
7082 | union { |
7083 | IdentifierInfo *IdentInfo; |
7084 | Expr *E; |
7085 | } U; |
7086 | }; |
7087 | |
7088 | /// __builtin_offsetof(type, a.b[123][456].c) |
7089 | ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, |
7090 | TypeSourceInfo *TInfo, |
7091 | ArrayRef<OffsetOfComponent> Components, |
7092 | SourceLocation RParenLoc); |
7093 | ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, |
7094 | SourceLocation TypeLoc, |
7095 | ParsedType ParsedArgTy, |
7096 | ArrayRef<OffsetOfComponent> Components, |
7097 | SourceLocation RParenLoc); |
7098 | |
7099 | // __builtin_choose_expr(constExpr, expr1, expr2) |
7100 | ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, |
7101 | Expr *LHSExpr, Expr *RHSExpr, |
7102 | SourceLocation RPLoc); |
7103 | |
7104 | // __builtin_va_arg(expr, type) |
7105 | ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, |
7106 | SourceLocation RPLoc); |
7107 | ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, |
7108 | TypeSourceInfo *TInfo, SourceLocation RPLoc); |
7109 | |
7110 | // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(), |
7111 | // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location() |
7112 | ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, |
7113 | SourceLocation BuiltinLoc, |
7114 | SourceLocation RPLoc); |
7115 | |
7116 | // #embed |
7117 | ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, |
7118 | StringLiteral *BinaryData); |
7119 | |
7120 | // Build a potentially resolved SourceLocExpr. |
7121 | ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, |
7122 | SourceLocation BuiltinLoc, SourceLocation RPLoc, |
7123 | DeclContext *ParentContext); |
7124 | |
7125 | // __null |
7126 | ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); |
7127 | |
7128 | bool CheckCaseExpression(Expr *E); |
7129 | |
7130 | //===------------------------- "Block" Extension ------------------------===// |
7131 | |
7132 | /// ActOnBlockStart - This callback is invoked when a block literal is |
7133 | /// started. |
7134 | void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); |
7135 | |
7136 | /// ActOnBlockArguments - This callback allows processing of block arguments. |
7137 | /// If there are no arguments, this is still invoked. |
7138 | void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, |
7139 | Scope *CurScope); |
7140 | |
7141 | /// ActOnBlockError - If there is an error parsing a block, this callback |
7142 | /// is invoked to pop the information about the block from the action impl. |
7143 | void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); |
7144 | |
7145 | /// ActOnBlockStmtExpr - This is called when the body of a block statement |
7146 | /// literal was successfully completed. ^(int x){...} |
7147 | ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, |
7148 | Scope *CurScope); |
7149 | |
7150 | //===---------------------------- Clang Extensions ----------------------===// |
7151 | |
7152 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the |
7153 | /// provided arguments. |
7154 | /// |
7155 | /// __builtin_convertvector( value, dst type ) |
7156 | /// |
7157 | ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, |
7158 | SourceLocation BuiltinLoc, |
7159 | SourceLocation RParenLoc); |
7160 | |
7161 | //===---------------------------- OpenCL Features -----------------------===// |
7162 | |
7163 | /// Parse a __builtin_astype expression. |
7164 | /// |
7165 | /// __builtin_astype( value, dst type ) |
7166 | /// |
7167 | ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, |
7168 | SourceLocation BuiltinLoc, |
7169 | SourceLocation RParenLoc); |
7170 | |
7171 | /// Create a new AsTypeExpr node (bitcast) from the arguments. |
7172 | ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, |
7173 | SourceLocation BuiltinLoc, |
7174 | SourceLocation RParenLoc); |
7175 | |
7176 | /// Attempts to produce a RecoveryExpr after some AST node cannot be created. |
7177 | ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, |
7178 | ArrayRef<Expr *> SubExprs, |
7179 | QualType T = QualType()); |
7180 | |
7181 | /// Cast a base object to a member's actual type. |
7182 | /// |
7183 | /// There are two relevant checks: |
7184 | /// |
7185 | /// C++ [class.access.base]p7: |
7186 | /// |
7187 | /// If a class member access operator [...] is used to access a non-static |
7188 | /// data member or non-static member function, the reference is ill-formed |
7189 | /// if the left operand [...] cannot be implicitly converted to a pointer to |
7190 | /// the naming class of the right operand. |
7191 | /// |
7192 | /// C++ [expr.ref]p7: |
7193 | /// |
7194 | /// If E2 is a non-static data member or a non-static member function, the |
7195 | /// program is ill-formed if the class of which E2 is directly a member is |
7196 | /// an ambiguous base (11.8) of the naming class (11.9.3) of E2. |
7197 | /// |
7198 | /// Note that the latter check does not consider access; the access of the |
7199 | /// "real" base class is checked as appropriate when checking the access of |
7200 | /// the member name. |
7201 | ExprResult PerformObjectMemberConversion(Expr *From, |
7202 | NestedNameSpecifier *Qualifier, |
7203 | NamedDecl *FoundDecl, |
7204 | NamedDecl *Member); |
7205 | |
7206 | /// CheckCallReturnType - Checks that a call expression's return type is |
7207 | /// complete. Returns true on failure. The location passed in is the location |
7208 | /// that best represents the call. |
7209 | bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, |
7210 | CallExpr *CE, FunctionDecl *FD); |
7211 | |
7212 | /// Emit a warning for all pending noderef expressions that we recorded. |
7213 | void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); |
7214 | |
7215 | ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); |
7216 | |
7217 | /// Instantiate or parse a C++ default argument expression as necessary. |
7218 | /// Return true on error. |
7219 | bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, |
7220 | ParmVarDecl *Param, Expr *Init = nullptr, |
7221 | bool SkipImmediateInvocations = true); |
7222 | |
7223 | /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating |
7224 | /// the default expr if needed. |
7225 | ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, |
7226 | ParmVarDecl *Param, Expr *Init = nullptr); |
7227 | |
7228 | /// Wrap the expression in a ConstantExpr if it is a potential immediate |
7229 | /// invocation. |
7230 | ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); |
7231 | |
7232 | void MarkExpressionAsImmediateEscalating(Expr *E); |
7233 | |
7234 | // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible. |
7235 | bool IsInvalidSMECallConversion(QualType FromType, QualType ToType); |
7236 | |
7237 | /// Abstract base class used for diagnosing integer constant |
7238 | /// expression violations. |
7239 | class VerifyICEDiagnoser { |
7240 | public: |
7241 | bool Suppress; |
7242 | |
7243 | VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {} |
7244 | |
7245 | virtual SemaDiagnosticBuilder |
7246 | diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); |
7247 | virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, |
7248 | SourceLocation Loc) = 0; |
7249 | virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); |
7250 | virtual ~VerifyICEDiagnoser() {} |
7251 | }; |
7252 | |
7253 | enum AllowFoldKind { |
7254 | NoFold, |
7255 | AllowFold, |
7256 | }; |
7257 | |
7258 | /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, |
7259 | /// and reports the appropriate diagnostics. Returns false on success. |
7260 | /// Can optionally return the value of the expression. |
7261 | ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, |
7262 | VerifyICEDiagnoser &Diagnoser, |
7263 | AllowFoldKind CanFold = NoFold); |
7264 | ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, |
7265 | unsigned DiagID, |
7266 | AllowFoldKind CanFold = NoFold); |
7267 | ExprResult VerifyIntegerConstantExpression(Expr *E, |
7268 | llvm::APSInt *Result = nullptr, |
7269 | AllowFoldKind CanFold = NoFold); |
7270 | ExprResult VerifyIntegerConstantExpression(Expr *E, |
7271 | AllowFoldKind CanFold = NoFold) { |
7272 | return VerifyIntegerConstantExpression(E, Result: nullptr, CanFold); |
7273 | } |
7274 | |
7275 | /// DiagnoseAssignmentAsCondition - Given that an expression is |
7276 | /// being used as a boolean condition, warn if it's an assignment. |
7277 | void DiagnoseAssignmentAsCondition(Expr *E); |
7278 | |
7279 | /// Redundant parentheses over an equality comparison can indicate |
7280 | /// that the user intended an assignment used as condition. |
7281 | void (ParenExpr *ParenE); |
7282 | |
7283 | class FullExprArg { |
7284 | public: |
7285 | FullExprArg() : E(nullptr) {} |
7286 | FullExprArg(Sema &actions) : E(nullptr) {} |
7287 | |
7288 | ExprResult release() { return E; } |
7289 | |
7290 | Expr *get() const { return E; } |
7291 | |
7292 | Expr *operator->() { return E; } |
7293 | |
7294 | private: |
7295 | // FIXME: No need to make the entire Sema class a friend when it's just |
7296 | // Sema::MakeFullExpr that needs access to the constructor below. |
7297 | friend class Sema; |
7298 | |
7299 | explicit FullExprArg(Expr *expr) : E(expr) {} |
7300 | |
7301 | Expr *E; |
7302 | }; |
7303 | |
7304 | FullExprArg MakeFullExpr(Expr *Arg) { |
7305 | return MakeFullExpr(Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation()); |
7306 | } |
7307 | FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { |
7308 | return FullExprArg( |
7309 | ActOnFinishFullExpr(Expr: Arg, CC, /*DiscardedValue*/ DiscardedValue: false).get()); |
7310 | } |
7311 | FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { |
7312 | ExprResult FE = |
7313 | ActOnFinishFullExpr(Expr: Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation(), |
7314 | /*DiscardedValue*/ DiscardedValue: true); |
7315 | return FullExprArg(FE.get()); |
7316 | } |
7317 | |
7318 | class ConditionResult { |
7319 | Decl *ConditionVar; |
7320 | FullExprArg Condition; |
7321 | bool Invalid; |
7322 | std::optional<bool> KnownValue; |
7323 | |
7324 | friend class Sema; |
7325 | ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, |
7326 | bool IsConstexpr) |
7327 | : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) { |
7328 | if (IsConstexpr && Condition.get()) { |
7329 | if (std::optional<llvm::APSInt> Val = |
7330 | Condition.get()->getIntegerConstantExpr(Ctx: S.Context)) { |
7331 | KnownValue = !!(*Val); |
7332 | } |
7333 | } |
7334 | } |
7335 | explicit ConditionResult(bool Invalid) |
7336 | : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), |
7337 | KnownValue(std::nullopt) {} |
7338 | |
7339 | public: |
7340 | ConditionResult() : ConditionResult(false) {} |
7341 | bool isInvalid() const { return Invalid; } |
7342 | std::pair<VarDecl *, Expr *> get() const { |
7343 | return std::make_pair(x: cast_or_null<VarDecl>(Val: ConditionVar), |
7344 | y: Condition.get()); |
7345 | } |
7346 | std::optional<bool> getKnownValue() const { return KnownValue; } |
7347 | }; |
7348 | static ConditionResult ConditionError() { return ConditionResult(true); } |
7349 | |
7350 | /// CheckBooleanCondition - Diagnose problems involving the use of |
7351 | /// the given expression as a boolean condition (e.g. in an if |
7352 | /// statement). Also performs the standard function and array |
7353 | /// decays, possibly changing the input variable. |
7354 | /// |
7355 | /// \param Loc - A location associated with the condition, e.g. the |
7356 | /// 'if' keyword. |
7357 | /// \return true iff there were any errors |
7358 | ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, |
7359 | bool IsConstexpr = false); |
7360 | |
7361 | enum class ConditionKind { |
7362 | Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. |
7363 | ConstexprIf, ///< A constant boolean condition from 'if constexpr'. |
7364 | Switch ///< An integral condition for a 'switch' statement. |
7365 | }; |
7366 | |
7367 | ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, |
7368 | ConditionKind CK, bool MissingOK = false); |
7369 | |
7370 | QualType CheckConditionalOperands( // C99 6.5.15 |
7371 | ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, |
7372 | ExprObjectKind &OK, SourceLocation QuestionLoc); |
7373 | |
7374 | /// Emit a specialized diagnostic when one expression is a null pointer |
7375 | /// constant and the other is not a pointer. Returns true if a diagnostic is |
7376 | /// emitted. |
7377 | bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, |
7378 | SourceLocation QuestionLoc); |
7379 | |
7380 | /// type checking for vector binary operators. |
7381 | QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, |
7382 | SourceLocation Loc, bool IsCompAssign, |
7383 | bool AllowBothBool, bool AllowBoolConversion, |
7384 | bool AllowBoolOperation, bool ReportInvalid); |
7385 | |
7386 | /// Return a signed ext_vector_type that is of identical size and number of |
7387 | /// elements. For floating point vectors, return an integer type of identical |
7388 | /// size and number of elements. In the non ext_vector_type case, search from |
7389 | /// the largest type to the smallest type to avoid cases where long long == |
7390 | /// long, where long gets picked over long long. |
7391 | QualType GetSignedVectorType(QualType V); |
7392 | QualType GetSignedSizelessVectorType(QualType V); |
7393 | |
7394 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that |
7395 | /// operates on extended vector types. Instead of producing an IntTy result, |
7396 | /// like a scalar comparison, a vector comparison produces a vector of integer |
7397 | /// types. |
7398 | QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, |
7399 | SourceLocation Loc, |
7400 | BinaryOperatorKind Opc); |
7401 | QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, |
7402 | SourceLocation Loc, |
7403 | BinaryOperatorKind Opc); |
7404 | QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
7405 | SourceLocation Loc, |
7406 | BinaryOperatorKind Opc); |
7407 | |
7408 | /// Context in which we're performing a usual arithmetic conversion. |
7409 | enum ArithConvKind { |
7410 | /// An arithmetic operation. |
7411 | ACK_Arithmetic, |
7412 | /// A bitwise operation. |
7413 | ACK_BitwiseOp, |
7414 | /// A comparison. |
7415 | ACK_Comparison, |
7416 | /// A conditional (?:) operator. |
7417 | ACK_Conditional, |
7418 | /// A compound assignment expression. |
7419 | ACK_CompAssign, |
7420 | }; |
7421 | |
7422 | // type checking for sizeless vector binary operators. |
7423 | QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, |
7424 | SourceLocation Loc, bool IsCompAssign, |
7425 | ArithConvKind OperationKind); |
7426 | |
7427 | /// Type checking for matrix binary operators. |
7428 | QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, |
7429 | SourceLocation Loc, |
7430 | bool IsCompAssign); |
7431 | QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, |
7432 | SourceLocation Loc, bool IsCompAssign); |
7433 | |
7434 | /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from |
7435 | /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE |
7436 | /// VLST) allowed? |
7437 | /// |
7438 | /// This will also return false if the two given types do not make sense from |
7439 | /// the perspective of SVE bitcasts. |
7440 | bool isValidSveBitcast(QualType srcType, QualType destType); |
7441 | |
7442 | /// Are the two types matrix types and do they have the same dimensions i.e. |
7443 | /// do they have the same number of rows and the same number of columns? |
7444 | bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy); |
7445 | |
7446 | bool areVectorTypesSameSize(QualType srcType, QualType destType); |
7447 | |
7448 | /// Are the two types lax-compatible vector types? That is, given |
7449 | /// that one of them is a vector, do they have equal storage sizes, |
7450 | /// where the storage size is the number of elements times the element |
7451 | /// size? |
7452 | /// |
7453 | /// This will also return false if either of the types is neither a |
7454 | /// vector nor a real type. |
7455 | bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); |
7456 | |
7457 | /// Is this a legal conversion between two types, one of which is |
7458 | /// known to be a vector type? |
7459 | bool isLaxVectorConversion(QualType srcType, QualType destType); |
7460 | |
7461 | // This returns true if at least one of the types is an altivec vector. |
7462 | bool anyAltivecTypes(QualType srcType, QualType destType); |
7463 | |
7464 | // type checking C++ declaration initializers (C++ [dcl.init]). |
7465 | |
7466 | /// Check a cast of an unknown-any type. We intentionally only |
7467 | /// trigger this for C-style casts. |
7468 | ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, |
7469 | Expr *CastExpr, CastKind &CastKind, |
7470 | ExprValueKind &VK, CXXCastPath &Path); |
7471 | |
7472 | /// Force an expression with unknown-type to an expression of the |
7473 | /// given type. |
7474 | ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); |
7475 | |
7476 | /// Type-check an expression that's being passed to an |
7477 | /// __unknown_anytype parameter. |
7478 | ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, |
7479 | QualType ¶mType); |
7480 | |
7481 | // CheckMatrixCast - Check type constraints for matrix casts. |
7482 | // We allow casting between matrixes of the same dimensions i.e. when they |
7483 | // have the same number of rows and column. Returns true if the cast is |
7484 | // invalid. |
7485 | bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, |
7486 | CastKind &Kind); |
7487 | |
7488 | // CheckVectorCast - check type constraints for vectors. |
7489 | // Since vectors are an extension, there are no C standard reference for this. |
7490 | // We allow casting between vectors and integer datatypes of the same size. |
7491 | // returns true if the cast is invalid |
7492 | bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, |
7493 | CastKind &Kind); |
7494 | |
7495 | /// Prepare `SplattedExpr` for a vector splat operation, adding |
7496 | /// implicit casts if necessary. |
7497 | ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); |
7498 | |
7499 | // CheckExtVectorCast - check type constraints for extended vectors. |
7500 | // Since vectors are an extension, there are no C standard reference for this. |
7501 | // We allow casting between vectors and integer datatypes of the same size, |
7502 | // or vectors and the element type of that vector. |
7503 | // returns the cast expr |
7504 | ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, |
7505 | CastKind &Kind); |
7506 | |
7507 | QualType PreferredConditionType(ConditionKind K) const { |
7508 | return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy; |
7509 | } |
7510 | |
7511 | // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts |
7512 | // functions and arrays to their respective pointers (C99 6.3.2.1), and |
7513 | // promotes floating-piont types according to the language semantics. |
7514 | ExprResult UsualUnaryConversions(Expr *E); |
7515 | |
7516 | // UsualUnaryFPConversions - promotes floating-point types according to the |
7517 | // current language semantics. |
7518 | ExprResult UsualUnaryFPConversions(Expr *E); |
7519 | |
7520 | /// CallExprUnaryConversions - a special case of an unary conversion |
7521 | /// performed on a function designator of a call expression. |
7522 | ExprResult CallExprUnaryConversions(Expr *E); |
7523 | |
7524 | // DefaultFunctionArrayConversion - converts functions and arrays |
7525 | // to their respective pointers (C99 6.3.2.1). |
7526 | ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); |
7527 | |
7528 | // DefaultFunctionArrayLvalueConversion - converts functions and |
7529 | // arrays to their respective pointers and performs the |
7530 | // lvalue-to-rvalue conversion. |
7531 | ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, |
7532 | bool Diagnose = true); |
7533 | |
7534 | // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on |
7535 | // the operand. This function is a no-op if the operand has a function type |
7536 | // or an array type. |
7537 | ExprResult DefaultLvalueConversion(Expr *E); |
7538 | |
7539 | // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that |
7540 | // do not have a prototype. Integer promotions are performed on each |
7541 | // argument, and arguments that have type float are promoted to double. |
7542 | ExprResult DefaultArgumentPromotion(Expr *E); |
7543 | |
7544 | VariadicCallType getVariadicCallType(FunctionDecl *FDecl, |
7545 | const FunctionProtoType *Proto, |
7546 | Expr *Fn); |
7547 | |
7548 | // Used for determining in which context a type is allowed to be passed to a |
7549 | // vararg function. |
7550 | enum VarArgKind { |
7551 | VAK_Valid, |
7552 | VAK_ValidInCXX11, |
7553 | VAK_Undefined, |
7554 | VAK_MSVCUndefined, |
7555 | VAK_Invalid |
7556 | }; |
7557 | |
7558 | /// Determine the degree of POD-ness for an expression. |
7559 | /// Incomplete types are considered POD, since this check can be performed |
7560 | /// when we're in an unevaluated context. |
7561 | VarArgKind isValidVarArgType(const QualType &Ty); |
7562 | |
7563 | /// Check to see if the given expression is a valid argument to a variadic |
7564 | /// function, issuing a diagnostic if not. |
7565 | void checkVariadicArgument(const Expr *E, VariadicCallType CT); |
7566 | |
7567 | /// GatherArgumentsForCall - Collector argument expressions for various |
7568 | /// form of call prototypes. |
7569 | bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, |
7570 | const FunctionProtoType *Proto, |
7571 | unsigned FirstParam, ArrayRef<Expr *> Args, |
7572 | SmallVectorImpl<Expr *> &AllArgs, |
7573 | VariadicCallType CallType = VariadicDoesNotApply, |
7574 | bool AllowExplicit = false, |
7575 | bool IsListInitialization = false); |
7576 | |
7577 | // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but |
7578 | // will create a runtime trap if the resulting type is not a POD type. |
7579 | ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, |
7580 | FunctionDecl *FDecl); |
7581 | |
7582 | // Check that the usual arithmetic conversions can be performed on this pair |
7583 | // of expressions that might be of enumeration type. |
7584 | void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc, |
7585 | Sema::ArithConvKind ACK); |
7586 | |
7587 | // UsualArithmeticConversions - performs the UsualUnaryConversions on it's |
7588 | // operands and then handles various conversions that are common to binary |
7589 | // operators (C99 6.3.1.8). If both operands aren't arithmetic, this |
7590 | // routine returns the first non-arithmetic type found. The client is |
7591 | // responsible for emitting appropriate error diagnostics. |
7592 | QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, |
7593 | SourceLocation Loc, ArithConvKind ACK); |
7594 | |
7595 | /// AssignConvertType - All of the 'assignment' semantic checks return this |
7596 | /// enum to indicate whether the assignment was allowed. These checks are |
7597 | /// done for simple assignments, as well as initialization, return from |
7598 | /// function, argument passing, etc. The query is phrased in terms of a |
7599 | /// source and destination type. |
7600 | enum AssignConvertType { |
7601 | /// Compatible - the types are compatible according to the standard. |
7602 | Compatible, |
7603 | |
7604 | /// PointerToInt - The assignment converts a pointer to an int, which we |
7605 | /// accept as an extension. |
7606 | PointerToInt, |
7607 | |
7608 | /// IntToPointer - The assignment converts an int to a pointer, which we |
7609 | /// accept as an extension. |
7610 | IntToPointer, |
7611 | |
7612 | /// FunctionVoidPointer - The assignment is between a function pointer and |
7613 | /// void*, which the standard doesn't allow, but we accept as an extension. |
7614 | FunctionVoidPointer, |
7615 | |
7616 | /// IncompatiblePointer - The assignment is between two pointers types that |
7617 | /// are not compatible, but we accept them as an extension. |
7618 | IncompatiblePointer, |
7619 | |
7620 | /// IncompatibleFunctionPointer - The assignment is between two function |
7621 | /// pointers types that are not compatible, but we accept them as an |
7622 | /// extension. |
7623 | IncompatibleFunctionPointer, |
7624 | |
7625 | /// IncompatibleFunctionPointerStrict - The assignment is between two |
7626 | /// function pointer types that are not identical, but are compatible, |
7627 | /// unless compiled with -fsanitize=cfi, in which case the type mismatch |
7628 | /// may trip an indirect call runtime check. |
7629 | IncompatibleFunctionPointerStrict, |
7630 | |
7631 | /// IncompatiblePointerSign - The assignment is between two pointers types |
7632 | /// which point to integers which have a different sign, but are otherwise |
7633 | /// identical. This is a subset of the above, but broken out because it's by |
7634 | /// far the most common case of incompatible pointers. |
7635 | IncompatiblePointerSign, |
7636 | |
7637 | /// CompatiblePointerDiscardsQualifiers - The assignment discards |
7638 | /// c/v/r qualifiers, which we accept as an extension. |
7639 | CompatiblePointerDiscardsQualifiers, |
7640 | |
7641 | /// IncompatiblePointerDiscardsQualifiers - The assignment |
7642 | /// discards qualifiers that we don't permit to be discarded, |
7643 | /// like address spaces. |
7644 | IncompatiblePointerDiscardsQualifiers, |
7645 | |
7646 | /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment |
7647 | /// changes address spaces in nested pointer types which is not allowed. |
7648 | /// For instance, converting __private int ** to __generic int ** is |
7649 | /// illegal even though __private could be converted to __generic. |
7650 | IncompatibleNestedPointerAddressSpaceMismatch, |
7651 | |
7652 | /// IncompatibleNestedPointerQualifiers - The assignment is between two |
7653 | /// nested pointer types, and the qualifiers other than the first two |
7654 | /// levels differ e.g. char ** -> const char **, but we accept them as an |
7655 | /// extension. |
7656 | IncompatibleNestedPointerQualifiers, |
7657 | |
7658 | /// IncompatibleVectors - The assignment is between two vector types that |
7659 | /// have the same size, which we accept as an extension. |
7660 | IncompatibleVectors, |
7661 | |
7662 | /// IntToBlockPointer - The assignment converts an int to a block |
7663 | /// pointer. We disallow this. |
7664 | IntToBlockPointer, |
7665 | |
7666 | /// IncompatibleBlockPointer - The assignment is between two block |
7667 | /// pointers types that are not compatible. |
7668 | IncompatibleBlockPointer, |
7669 | |
7670 | /// IncompatibleObjCQualifiedId - The assignment is between a qualified |
7671 | /// id type and something else (that is incompatible with it). For example, |
7672 | /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. |
7673 | IncompatibleObjCQualifiedId, |
7674 | |
7675 | /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an |
7676 | /// object with __weak qualifier. |
7677 | IncompatibleObjCWeakRef, |
7678 | |
7679 | /// Incompatible - We reject this conversion outright, it is invalid to |
7680 | /// represent it in the AST. |
7681 | Incompatible |
7682 | }; |
7683 | |
7684 | /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the |
7685 | /// assignment conversion type specified by ConvTy. This returns true if the |
7686 | /// conversion was invalid or false if the conversion was accepted. |
7687 | bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, |
7688 | QualType DstType, QualType SrcType, |
7689 | Expr *SrcExpr, AssignmentAction Action, |
7690 | bool *Complained = nullptr); |
7691 | |
7692 | /// CheckAssignmentConstraints - Perform type checking for assignment, |
7693 | /// argument passing, variable initialization, and function return values. |
7694 | /// C99 6.5.16. |
7695 | AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, |
7696 | QualType LHSType, |
7697 | QualType RHSType); |
7698 | |
7699 | /// Check assignment constraints and optionally prepare for a conversion of |
7700 | /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS |
7701 | /// is true. |
7702 | AssignConvertType CheckAssignmentConstraints(QualType LHSType, |
7703 | ExprResult &RHS, CastKind &Kind, |
7704 | bool ConvertRHS = true); |
7705 | |
7706 | /// Check assignment constraints for an assignment of RHS to LHSType. |
7707 | /// |
7708 | /// \param LHSType The destination type for the assignment. |
7709 | /// \param RHS The source expression for the assignment. |
7710 | /// \param Diagnose If \c true, diagnostics may be produced when checking |
7711 | /// for assignability. If a diagnostic is produced, \p RHS will be |
7712 | /// set to ExprError(). Note that this function may still return |
7713 | /// without producing a diagnostic, even for an invalid assignment. |
7714 | /// \param DiagnoseCFAudited If \c true, the target is a function parameter |
7715 | /// in an audited Core Foundation API and does not need to be checked |
7716 | /// for ARC retain issues. |
7717 | /// \param ConvertRHS If \c true, \p RHS will be updated to model the |
7718 | /// conversions necessary to perform the assignment. If \c false, |
7719 | /// \p Diagnose must also be \c false. |
7720 | AssignConvertType CheckSingleAssignmentConstraints( |
7721 | QualType LHSType, ExprResult &RHS, bool Diagnose = true, |
7722 | bool DiagnoseCFAudited = false, bool ConvertRHS = true); |
7723 | |
7724 | // If the lhs type is a transparent union, check whether we |
7725 | // can initialize the transparent union with the given expression. |
7726 | AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, |
7727 | ExprResult &RHS); |
7728 | |
7729 | /// the following "Check" methods will return a valid/converted QualType |
7730 | /// or a null QualType (indicating an error diagnostic was issued). |
7731 | |
7732 | /// type checking binary operators (subroutines of CreateBuiltinBinOp). |
7733 | QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, |
7734 | ExprResult &RHS); |
7735 | |
7736 | /// Diagnose cases where a scalar was implicitly converted to a vector and |
7737 | /// diagnose the underlying types. Otherwise, diagnose the error |
7738 | /// as invalid vector logical operands for non-C++ cases. |
7739 | QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, |
7740 | ExprResult &RHS); |
7741 | |
7742 | QualType CheckMultiplyDivideOperands( // C99 6.5.5 |
7743 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, |
7744 | bool IsDivide); |
7745 | QualType CheckRemainderOperands( // C99 6.5.5 |
7746 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
7747 | bool IsCompAssign = false); |
7748 | QualType CheckAdditionOperands( // C99 6.5.6 |
7749 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
7750 | BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr); |
7751 | QualType CheckSubtractionOperands( // C99 6.5.6 |
7752 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
7753 | QualType *CompLHSTy = nullptr); |
7754 | QualType CheckShiftOperands( // C99 6.5.7 |
7755 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
7756 | BinaryOperatorKind Opc, bool IsCompAssign = false); |
7757 | void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); |
7758 | QualType CheckCompareOperands( // C99 6.5.8/9 |
7759 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
7760 | BinaryOperatorKind Opc); |
7761 | QualType CheckBitwiseOperands( // C99 6.5.[10...12] |
7762 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
7763 | BinaryOperatorKind Opc); |
7764 | QualType CheckLogicalOperands( // C99 6.5.[13,14] |
7765 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
7766 | BinaryOperatorKind Opc); |
7767 | // CheckAssignmentOperands is used for both simple and compound assignment. |
7768 | // For simple assignment, pass both expressions and a null converted type. |
7769 | // For compound assignment, pass both expressions and the converted type. |
7770 | QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] |
7771 | Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, |
7772 | BinaryOperatorKind Opc); |
7773 | |
7774 | /// To be used for checking whether the arguments being passed to |
7775 | /// function exceeds the number of parameters expected for it. |
7776 | static bool TooManyArguments(size_t NumParams, size_t NumArgs, |
7777 | bool PartialOverloading = false) { |
7778 | // We check whether we're just after a comma in code-completion. |
7779 | if (NumArgs > 0 && PartialOverloading) |
7780 | return NumArgs + 1 > NumParams; // If so, we view as an extra argument. |
7781 | return NumArgs > NumParams; |
7782 | } |
7783 | |
7784 | /// Whether the AST is currently being rebuilt to correct immediate |
7785 | /// invocations. Immediate invocation candidates and references to consteval |
7786 | /// functions aren't tracked when this is set. |
7787 | bool RebuildingImmediateInvocation = false; |
7788 | |
7789 | bool isAlwaysConstantEvaluatedContext() const { |
7790 | const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext(); |
7791 | return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) && |
7792 | !Ctx.InConditionallyConstantEvaluateContext; |
7793 | } |
7794 | |
7795 | /// Determines whether we are currently in a context that |
7796 | /// is not evaluated as per C++ [expr] p5. |
7797 | bool isUnevaluatedContext() const { |
7798 | return currentEvaluationContext().isUnevaluated(); |
7799 | } |
7800 | |
7801 | bool isImmediateFunctionContext() const { |
7802 | return currentEvaluationContext().isImmediateFunctionContext(); |
7803 | } |
7804 | |
7805 | bool isInLifetimeExtendingContext() const { |
7806 | return currentEvaluationContext().InLifetimeExtendingContext; |
7807 | } |
7808 | |
7809 | bool needsRebuildOfDefaultArgOrInit() const { |
7810 | return currentEvaluationContext().RebuildDefaultArgOrDefaultInit; |
7811 | } |
7812 | |
7813 | bool isCheckingDefaultArgumentOrInitializer() const { |
7814 | const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext(); |
7815 | return (Ctx.Context == |
7816 | ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) || |
7817 | Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer; |
7818 | } |
7819 | |
7820 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> |
7821 | InnermostDeclarationWithDelayedImmediateInvocations() const { |
7822 | assert(!ExprEvalContexts.empty() && |
7823 | "Must be in an expression evaluation context" ); |
7824 | for (const auto &Ctx : llvm::reverse(C: ExprEvalContexts)) { |
7825 | if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated && |
7826 | Ctx.DelayedDefaultInitializationContext) |
7827 | return Ctx.DelayedDefaultInitializationContext; |
7828 | if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() || |
7829 | Ctx.isUnevaluated()) |
7830 | break; |
7831 | } |
7832 | return std::nullopt; |
7833 | } |
7834 | |
7835 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> |
7836 | OutermostDeclarationWithDelayedImmediateInvocations() const { |
7837 | assert(!ExprEvalContexts.empty() && |
7838 | "Must be in an expression evaluation context" ); |
7839 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res; |
7840 | for (auto &Ctx : llvm::reverse(C: ExprEvalContexts)) { |
7841 | if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated && |
7842 | !Ctx.DelayedDefaultInitializationContext && Res) |
7843 | break; |
7844 | if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() || |
7845 | Ctx.isUnevaluated()) |
7846 | break; |
7847 | Res = Ctx.DelayedDefaultInitializationContext; |
7848 | } |
7849 | return Res; |
7850 | } |
7851 | |
7852 | DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { |
7853 | return getDefaultedFunctionKind(FD).asComparison(); |
7854 | } |
7855 | |
7856 | /// Returns a field in a CXXRecordDecl that has the same name as the decl \p |
7857 | /// SelfAssigned when inside a CXXMethodDecl. |
7858 | const FieldDecl * |
7859 | getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned); |
7860 | |
7861 | void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); |
7862 | |
7863 | template <typename... Ts> |
7864 | bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, |
7865 | const Ts &...Args) { |
7866 | SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
7867 | return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); |
7868 | } |
7869 | |
7870 | template <typename... Ts> |
7871 | bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, |
7872 | const Ts &...Args) { |
7873 | SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
7874 | return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); |
7875 | } |
7876 | |
7877 | /// Abstract class used to diagnose incomplete types. |
7878 | struct TypeDiagnoser { |
7879 | TypeDiagnoser() {} |
7880 | |
7881 | virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; |
7882 | virtual ~TypeDiagnoser() {} |
7883 | }; |
7884 | |
7885 | template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { |
7886 | protected: |
7887 | unsigned DiagID; |
7888 | std::tuple<const Ts &...> Args; |
7889 | |
7890 | template <std::size_t... Is> |
7891 | void emit(const SemaDiagnosticBuilder &DB, |
7892 | std::index_sequence<Is...>) const { |
7893 | // Apply all tuple elements to the builder in order. |
7894 | bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; |
7895 | (void)Dummy; |
7896 | } |
7897 | |
7898 | public: |
7899 | BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) |
7900 | : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { |
7901 | assert(DiagID != 0 && "no diagnostic for type diagnoser" ); |
7902 | } |
7903 | |
7904 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
7905 | const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); |
7906 | emit(DB, std::index_sequence_for<Ts...>()); |
7907 | DB << T; |
7908 | } |
7909 | }; |
7910 | |
7911 | /// A derivative of BoundTypeDiagnoser for which the diagnostic's type |
7912 | /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. |
7913 | /// For example, a diagnostic with no other parameters would generally have |
7914 | /// the form "...%select{incomplete|sizeless}0 type %1...". |
7915 | template <typename... Ts> |
7916 | class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { |
7917 | public: |
7918 | SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args) |
7919 | : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} |
7920 | |
7921 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
7922 | const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); |
7923 | this->emit(DB, std::index_sequence_for<Ts...>()); |
7924 | DB << T->isSizelessType() << T; |
7925 | } |
7926 | }; |
7927 | |
7928 | /// Check an argument list for placeholders that we won't try to |
7929 | /// handle later. |
7930 | bool CheckArgsForPlaceholders(MultiExprArg args); |
7931 | |
7932 | /// The C++ "std::source_location::__impl" struct, defined in |
7933 | /// \<source_location>. |
7934 | RecordDecl *StdSourceLocationImplDecl; |
7935 | |
7936 | /// A stack of expression evaluation contexts. |
7937 | SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; |
7938 | |
7939 | // Set of failed immediate invocations to avoid double diagnosing. |
7940 | llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations; |
7941 | |
7942 | /// List of SourceLocations where 'self' is implicitly retained inside a |
7943 | /// block. |
7944 | llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> |
7945 | ImplicitlyRetainedSelfLocs; |
7946 | |
7947 | /// Do an explicit extend of the given block pointer if we're in ARC. |
7948 | void maybeExtendBlockObject(ExprResult &E); |
7949 | |
7950 | std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied; |
7951 | SourceLocation LocationOfExcessPrecisionNotSatisfied; |
7952 | void DiagnosePrecisionLossInComplexDivision(); |
7953 | |
7954 | private: |
7955 | static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); |
7956 | |
7957 | /// Methods for marking which expressions involve dereferencing a pointer |
7958 | /// marked with the 'noderef' attribute. Expressions are checked bottom up as |
7959 | /// they are parsed, meaning that a noderef pointer may not be accessed. For |
7960 | /// example, in `&*p` where `p` is a noderef pointer, we will first parse the |
7961 | /// `*p`, but need to check that `address of` is called on it. This requires |
7962 | /// keeping a container of all pending expressions and checking if the address |
7963 | /// of them are eventually taken. |
7964 | void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); |
7965 | void CheckAddressOfNoDeref(const Expr *E); |
7966 | |
7967 | ///@} |
7968 | |
7969 | // |
7970 | // |
7971 | // ------------------------------------------------------------------------- |
7972 | // |
7973 | // |
7974 | |
7975 | /// \name C++ Expressions |
7976 | /// Implementations are in SemaExprCXX.cpp |
7977 | ///@{ |
7978 | |
7979 | public: |
7980 | /// The C++ "std::bad_alloc" class, which is defined by the C++ |
7981 | /// standard library. |
7982 | LazyDeclPtr StdBadAlloc; |
7983 | |
7984 | /// The C++ "std::align_val_t" enum class, which is defined by the C++ |
7985 | /// standard library. |
7986 | LazyDeclPtr StdAlignValT; |
7987 | |
7988 | /// The C++ "type_info" declaration, which is defined in \<typeinfo>. |
7989 | RecordDecl *CXXTypeInfoDecl; |
7990 | |
7991 | /// A flag to remember whether the implicit forms of operator new and delete |
7992 | /// have been declared. |
7993 | bool GlobalNewDeleteDeclared; |
7994 | |
7995 | /// Delete-expressions to be analyzed at the end of translation unit |
7996 | /// |
7997 | /// This list contains class members, and locations of delete-expressions |
7998 | /// that could not be proven as to whether they mismatch with new-expression |
7999 | /// used in initializer of the field. |
8000 | llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; |
8001 | |
8002 | /// Handle the result of the special case name lookup for inheriting |
8003 | /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as |
8004 | /// constructor names in member using declarations, even if 'X' is not the |
8005 | /// name of the corresponding type. |
8006 | ParsedType getInheritingConstructorName(CXXScopeSpec &SS, |
8007 | SourceLocation NameLoc, |
8008 | const IdentifierInfo &Name); |
8009 | |
8010 | ParsedType getConstructorName(const IdentifierInfo &II, |
8011 | SourceLocation NameLoc, Scope *S, |
8012 | CXXScopeSpec &SS, bool EnteringContext); |
8013 | ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, |
8014 | Scope *S, CXXScopeSpec &SS, |
8015 | ParsedType ObjectType, bool EnteringContext); |
8016 | |
8017 | ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, |
8018 | ParsedType ObjectType); |
8019 | |
8020 | /// Build a C++ typeid expression with a type operand. |
8021 | ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, |
8022 | TypeSourceInfo *Operand, SourceLocation RParenLoc); |
8023 | |
8024 | /// Build a C++ typeid expression with an expression operand. |
8025 | ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, |
8026 | Expr *Operand, SourceLocation RParenLoc); |
8027 | |
8028 | /// ActOnCXXTypeid - Parse typeid( something ). |
8029 | ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, |
8030 | bool isType, void *TyOrExpr, |
8031 | SourceLocation RParenLoc); |
8032 | |
8033 | /// Build a Microsoft __uuidof expression with a type operand. |
8034 | ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, |
8035 | TypeSourceInfo *Operand, SourceLocation RParenLoc); |
8036 | |
8037 | /// Build a Microsoft __uuidof expression with an expression operand. |
8038 | ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, |
8039 | Expr *Operand, SourceLocation RParenLoc); |
8040 | |
8041 | /// ActOnCXXUuidof - Parse __uuidof( something ). |
8042 | ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, |
8043 | bool isType, void *TyOrExpr, |
8044 | SourceLocation RParenLoc); |
8045 | |
8046 | //// ActOnCXXThis - Parse 'this' pointer. |
8047 | ExprResult ActOnCXXThis(SourceLocation Loc); |
8048 | |
8049 | /// Check whether the type of 'this' is valid in the current context. |
8050 | bool CheckCXXThisType(SourceLocation Loc, QualType Type); |
8051 | |
8052 | /// Build a CXXThisExpr and mark it referenced in the current context. |
8053 | Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); |
8054 | void MarkThisReferenced(CXXThisExpr *This); |
8055 | |
8056 | /// Try to retrieve the type of the 'this' pointer. |
8057 | /// |
8058 | /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. |
8059 | QualType getCurrentThisType(); |
8060 | |
8061 | /// When non-NULL, the C++ 'this' expression is allowed despite the |
8062 | /// current context not being a non-static member function. In such cases, |
8063 | /// this provides the type used for 'this'. |
8064 | QualType CXXThisTypeOverride; |
8065 | |
8066 | /// RAII object used to temporarily allow the C++ 'this' expression |
8067 | /// to be used, with the given qualifiers on the current class type. |
8068 | class CXXThisScopeRAII { |
8069 | Sema &S; |
8070 | QualType OldCXXThisTypeOverride; |
8071 | bool Enabled; |
8072 | |
8073 | public: |
8074 | /// Introduce a new scope where 'this' may be allowed (when enabled), |
8075 | /// using the given declaration (which is either a class template or a |
8076 | /// class) along with the given qualifiers. |
8077 | /// along with the qualifiers placed on '*this'. |
8078 | CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, |
8079 | bool Enabled = true); |
8080 | |
8081 | ~CXXThisScopeRAII(); |
8082 | }; |
8083 | |
8084 | /// Make sure the value of 'this' is actually available in the current |
8085 | /// context, if it is a potentially evaluated context. |
8086 | /// |
8087 | /// \param Loc The location at which the capture of 'this' occurs. |
8088 | /// |
8089 | /// \param Explicit Whether 'this' is explicitly captured in a lambda |
8090 | /// capture list. |
8091 | /// |
8092 | /// \param FunctionScopeIndexToStopAt If non-null, it points to the index |
8093 | /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. |
8094 | /// This is useful when enclosing lambdas must speculatively capture |
8095 | /// 'this' that may or may not be used in certain specializations of |
8096 | /// a nested generic lambda (depending on whether the name resolves to |
8097 | /// a non-static member function or a static function). |
8098 | /// \return returns 'true' if failed, 'false' if success. |
8099 | bool CheckCXXThisCapture( |
8100 | SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, |
8101 | const unsigned *const FunctionScopeIndexToStopAt = nullptr, |
8102 | bool ByCopy = false); |
8103 | |
8104 | /// Determine whether the given type is the type of *this that is used |
8105 | /// outside of the body of a member function for a type that is currently |
8106 | /// being defined. |
8107 | bool isThisOutsideMemberFunctionBody(QualType BaseType); |
8108 | |
8109 | /// ActOnCXXBoolLiteral - Parse {true,false} literals. |
8110 | ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); |
8111 | |
8112 | /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. |
8113 | ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); |
8114 | |
8115 | //// ActOnCXXThrow - Parse throw expressions. |
8116 | ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); |
8117 | ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, |
8118 | bool IsThrownVarInScope); |
8119 | |
8120 | /// CheckCXXThrowOperand - Validate the operand of a throw. |
8121 | bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); |
8122 | |
8123 | /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. |
8124 | /// Can be interpreted either as function-style casting ("int(x)") |
8125 | /// or class type construction ("ClassType(x,y,z)") |
8126 | /// or creation of a value-initialized type ("int()"). |
8127 | ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, |
8128 | SourceLocation LParenOrBraceLoc, |
8129 | MultiExprArg Exprs, |
8130 | SourceLocation RParenOrBraceLoc, |
8131 | bool ListInitialization); |
8132 | |
8133 | ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, |
8134 | SourceLocation LParenLoc, |
8135 | MultiExprArg Exprs, |
8136 | SourceLocation RParenLoc, |
8137 | bool ListInitialization); |
8138 | |
8139 | /// Parsed a C++ 'new' expression (C++ 5.3.4). |
8140 | /// |
8141 | /// E.g.: |
8142 | /// @code new (memory) int[size][4] @endcode |
8143 | /// or |
8144 | /// @code ::new Foo(23, "hello") @endcode |
8145 | /// |
8146 | /// \param StartLoc The first location of the expression. |
8147 | /// \param UseGlobal True if 'new' was prefixed with '::'. |
8148 | /// \param PlacementLParen Opening paren of the placement arguments. |
8149 | /// \param PlacementArgs Placement new arguments. |
8150 | /// \param PlacementRParen Closing paren of the placement arguments. |
8151 | /// \param TypeIdParens If the type is in parens, the source range. |
8152 | /// \param D The type to be allocated, as well as array dimensions. |
8153 | /// \param Initializer The initializing expression or initializer-list, or |
8154 | /// null if there is none. |
8155 | ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, |
8156 | SourceLocation PlacementLParen, |
8157 | MultiExprArg PlacementArgs, |
8158 | SourceLocation PlacementRParen, |
8159 | SourceRange TypeIdParens, Declarator &D, |
8160 | Expr *Initializer); |
8161 | ExprResult |
8162 | BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, |
8163 | MultiExprArg PlacementArgs, SourceLocation PlacementRParen, |
8164 | SourceRange TypeIdParens, QualType AllocType, |
8165 | TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize, |
8166 | SourceRange DirectInitRange, Expr *Initializer); |
8167 | |
8168 | /// Determine whether \p FD is an aligned allocation or deallocation |
8169 | /// function that is unavailable. |
8170 | bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; |
8171 | |
8172 | /// Produce diagnostics if \p FD is an aligned allocation or deallocation |
8173 | /// function that is unavailable. |
8174 | void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, |
8175 | SourceLocation Loc); |
8176 | |
8177 | /// Checks that a type is suitable as the allocated type |
8178 | /// in a new-expression. |
8179 | bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, |
8180 | SourceRange R); |
8181 | |
8182 | /// The scope in which to find allocation functions. |
8183 | enum AllocationFunctionScope { |
8184 | /// Only look for allocation functions in the global scope. |
8185 | AFS_Global, |
8186 | /// Only look for allocation functions in the scope of the |
8187 | /// allocated class. |
8188 | AFS_Class, |
8189 | /// Look for allocation functions in both the global scope |
8190 | /// and in the scope of the allocated class. |
8191 | AFS_Both |
8192 | }; |
8193 | |
8194 | /// Finds the overloads of operator new and delete that are appropriate |
8195 | /// for the allocation. |
8196 | bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, |
8197 | AllocationFunctionScope NewScope, |
8198 | AllocationFunctionScope DeleteScope, |
8199 | QualType AllocType, bool IsArray, |
8200 | bool &PassAlignment, MultiExprArg PlaceArgs, |
8201 | FunctionDecl *&OperatorNew, |
8202 | FunctionDecl *&OperatorDelete, |
8203 | bool Diagnose = true); |
8204 | |
8205 | /// DeclareGlobalNewDelete - Declare the global forms of operator new and |
8206 | /// delete. These are: |
8207 | /// @code |
8208 | /// // C++03: |
8209 | /// void* operator new(std::size_t) throw(std::bad_alloc); |
8210 | /// void* operator new[](std::size_t) throw(std::bad_alloc); |
8211 | /// void operator delete(void *) throw(); |
8212 | /// void operator delete[](void *) throw(); |
8213 | /// // C++11: |
8214 | /// void* operator new(std::size_t); |
8215 | /// void* operator new[](std::size_t); |
8216 | /// void operator delete(void *) noexcept; |
8217 | /// void operator delete[](void *) noexcept; |
8218 | /// // C++1y: |
8219 | /// void* operator new(std::size_t); |
8220 | /// void* operator new[](std::size_t); |
8221 | /// void operator delete(void *) noexcept; |
8222 | /// void operator delete[](void *) noexcept; |
8223 | /// void operator delete(void *, std::size_t) noexcept; |
8224 | /// void operator delete[](void *, std::size_t) noexcept; |
8225 | /// @endcode |
8226 | /// Note that the placement and nothrow forms of new are *not* implicitly |
8227 | /// declared. Their use requires including \<new\>. |
8228 | void DeclareGlobalNewDelete(); |
8229 | void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, |
8230 | ArrayRef<QualType> Params); |
8231 | |
8232 | bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, |
8233 | DeclarationName Name, FunctionDecl *&Operator, |
8234 | bool Diagnose = true, bool WantSize = false, |
8235 | bool WantAligned = false); |
8236 | FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, |
8237 | bool CanProvideSize, |
8238 | bool Overaligned, |
8239 | DeclarationName Name); |
8240 | FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, |
8241 | CXXRecordDecl *RD); |
8242 | |
8243 | /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: |
8244 | /// @code ::delete ptr; @endcode |
8245 | /// or |
8246 | /// @code delete [] ptr; @endcode |
8247 | ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, |
8248 | bool ArrayForm, Expr *Operand); |
8249 | void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, |
8250 | bool IsDelete, bool CallCanBeVirtual, |
8251 | bool WarnOnNonAbstractTypes, |
8252 | SourceLocation DtorLoc); |
8253 | |
8254 | ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, |
8255 | Expr *Operand, SourceLocation RParen); |
8256 | ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, |
8257 | SourceLocation RParen); |
8258 | |
8259 | ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, |
8260 | SourceLocation OpLoc, |
8261 | tok::TokenKind OpKind, |
8262 | ParsedType &ObjectType, |
8263 | bool &MayBePseudoDestructor); |
8264 | |
8265 | ExprResult BuildPseudoDestructorExpr( |
8266 | Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, |
8267 | const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, |
8268 | SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); |
8269 | |
8270 | ExprResult ActOnPseudoDestructorExpr( |
8271 | Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, |
8272 | CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, |
8273 | SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); |
8274 | |
8275 | ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
8276 | SourceLocation OpLoc, |
8277 | tok::TokenKind OpKind, |
8278 | SourceLocation TildeLoc, |
8279 | const DeclSpec &DS); |
8280 | |
8281 | /// MaybeCreateExprWithCleanups - If the current full-expression |
8282 | /// requires any cleanups, surround it with a ExprWithCleanups node. |
8283 | /// Otherwise, just returns the passed-in expression. |
8284 | Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); |
8285 | Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); |
8286 | ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); |
8287 | |
8288 | ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { |
8289 | return ActOnFinishFullExpr( |
8290 | Expr, CC: Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); |
8291 | } |
8292 | ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, |
8293 | bool DiscardedValue, bool IsConstexpr = false, |
8294 | bool IsTemplateArgument = false); |
8295 | StmtResult ActOnFinishFullStmt(Stmt *Stmt); |
8296 | |
8297 | /// Process the expression contained within a decltype. For such expressions, |
8298 | /// certain semantic checks on temporaries are delayed until this point, and |
8299 | /// are omitted for the 'topmost' call in the decltype expression. If the |
8300 | /// topmost call bound a temporary, strip that temporary off the expression. |
8301 | ExprResult ActOnDecltypeExpression(Expr *E); |
8302 | |
8303 | bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, |
8304 | bool IsUDSuffix); |
8305 | |
8306 | bool isUsualDeallocationFunction(const CXXMethodDecl *FD); |
8307 | |
8308 | ConditionResult ActOnConditionVariable(Decl *ConditionVar, |
8309 | SourceLocation StmtLoc, |
8310 | ConditionKind CK); |
8311 | |
8312 | /// Check the use of the given variable as a C++ condition in an if, |
8313 | /// while, do-while, or switch statement. |
8314 | ExprResult CheckConditionVariable(VarDecl *ConditionVar, |
8315 | SourceLocation StmtLoc, ConditionKind CK); |
8316 | |
8317 | /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. |
8318 | ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); |
8319 | |
8320 | /// Helper function to determine whether this is the (deprecated) C++ |
8321 | /// conversion from a string literal to a pointer to non-const char or |
8322 | /// non-const wchar_t (for narrow and wide string literals, |
8323 | /// respectively). |
8324 | bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); |
8325 | |
8326 | /// PerformImplicitConversion - Perform an implicit conversion of the |
8327 | /// expression From to the type ToType using the pre-computed implicit |
8328 | /// conversion sequence ICS. Returns the converted |
8329 | /// expression. Action is the kind of conversion we're performing, |
8330 | /// used in the error message. |
8331 | ExprResult PerformImplicitConversion( |
8332 | Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, |
8333 | AssignmentAction Action, |
8334 | CheckedConversionKind CCK = CheckedConversionKind::Implicit); |
8335 | |
8336 | /// PerformImplicitConversion - Perform an implicit conversion of the |
8337 | /// expression From to the type ToType by following the standard |
8338 | /// conversion sequence SCS. Returns the converted |
8339 | /// expression. Flavor is the context in which we're performing this |
8340 | /// conversion, for use in error messages. |
8341 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, |
8342 | const StandardConversionSequence &SCS, |
8343 | AssignmentAction Action, |
8344 | CheckedConversionKind CCK); |
8345 | |
8346 | bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N); |
8347 | |
8348 | /// Parsed one of the type trait support pseudo-functions. |
8349 | ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, |
8350 | ArrayRef<ParsedType> Args, |
8351 | SourceLocation RParenLoc); |
8352 | ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, |
8353 | ArrayRef<TypeSourceInfo *> Args, |
8354 | SourceLocation RParenLoc); |
8355 | |
8356 | /// ActOnArrayTypeTrait - Parsed one of the binary type trait support |
8357 | /// pseudo-functions. |
8358 | ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, |
8359 | ParsedType LhsTy, Expr *DimExpr, |
8360 | SourceLocation RParen); |
8361 | |
8362 | ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, |
8363 | TypeSourceInfo *TSInfo, Expr *DimExpr, |
8364 | SourceLocation RParen); |
8365 | |
8366 | /// ActOnExpressionTrait - Parsed one of the unary type trait support |
8367 | /// pseudo-functions. |
8368 | ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, |
8369 | Expr *Queried, SourceLocation RParen); |
8370 | |
8371 | ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, |
8372 | Expr *Queried, SourceLocation RParen); |
8373 | |
8374 | QualType CheckPointerToMemberOperands( // C++ 5.5 |
8375 | ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, |
8376 | bool isIndirect); |
8377 | QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, |
8378 | ExprResult &RHS, |
8379 | SourceLocation QuestionLoc); |
8380 | |
8381 | QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond, |
8382 | ExprResult &LHS, ExprResult &RHS, |
8383 | SourceLocation QuestionLoc); |
8384 | |
8385 | /// Check the operands of ?: under C++ semantics. |
8386 | /// |
8387 | /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y |
8388 | /// extension. In this case, LHS == Cond. (But they're not aliases.) |
8389 | /// |
8390 | /// This function also implements GCC's vector extension and the |
8391 | /// OpenCL/ext_vector_type extension for conditionals. The vector extensions |
8392 | /// permit the use of a?b:c where the type of a is that of a integer vector |
8393 | /// with the same number of elements and size as the vectors of b and c. If |
8394 | /// one of either b or c is a scalar it is implicitly converted to match the |
8395 | /// type of the vector. Otherwise the expression is ill-formed. If both b and |
8396 | /// c are scalars, then b and c are checked and converted to the type of a if |
8397 | /// possible. |
8398 | /// |
8399 | /// The expressions are evaluated differently for GCC's and OpenCL's |
8400 | /// extensions. For the GCC extension, the ?: operator is evaluated as |
8401 | /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). |
8402 | /// For the OpenCL extensions, the ?: operator is evaluated as |
8403 | /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. , |
8404 | /// most-significant-bit-set(a[n]) ? b[n] : c[n]). |
8405 | QualType CXXCheckConditionalOperands( // C++ 5.16 |
8406 | ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, |
8407 | ExprObjectKind &OK, SourceLocation questionLoc); |
8408 | |
8409 | /// Find a merged pointer type and convert the two expressions to it. |
8410 | /// |
8411 | /// This finds the composite pointer type for \p E1 and \p E2 according to |
8412 | /// C++2a [expr.type]p3. It converts both expressions to this type and returns |
8413 | /// it. It does not emit diagnostics (FIXME: that's not true if \p |
8414 | /// ConvertArgs is \c true). |
8415 | /// |
8416 | /// \param Loc The location of the operator requiring these two expressions to |
8417 | /// be converted to the composite pointer type. |
8418 | /// |
8419 | /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target |
8420 | /// type. |
8421 | QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, |
8422 | bool ConvertArgs = true); |
8423 | QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, |
8424 | ExprResult &E2, bool ConvertArgs = true) { |
8425 | Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); |
8426 | QualType Composite = |
8427 | FindCompositePointerType(Loc, E1&: E1Tmp, E2&: E2Tmp, ConvertArgs); |
8428 | E1 = E1Tmp; |
8429 | E2 = E2Tmp; |
8430 | return Composite; |
8431 | } |
8432 | |
8433 | /// MaybeBindToTemporary - If the passed in expression has a record type with |
8434 | /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise |
8435 | /// it simply returns the passed in expression. |
8436 | ExprResult MaybeBindToTemporary(Expr *E); |
8437 | |
8438 | /// IgnoredValueConversions - Given that an expression's result is |
8439 | /// syntactically ignored, perform any conversions that are |
8440 | /// required. |
8441 | ExprResult IgnoredValueConversions(Expr *E); |
8442 | |
8443 | ExprResult CheckUnevaluatedOperand(Expr *E); |
8444 | |
8445 | /// Process any TypoExprs in the given Expr and its children, |
8446 | /// generating diagnostics as appropriate and returning a new Expr if there |
8447 | /// were typos that were all successfully corrected and ExprError if one or |
8448 | /// more typos could not be corrected. |
8449 | /// |
8450 | /// \param E The Expr to check for TypoExprs. |
8451 | /// |
8452 | /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its |
8453 | /// initializer. |
8454 | /// |
8455 | /// \param RecoverUncorrectedTypos If true, when typo correction fails, it |
8456 | /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. |
8457 | /// |
8458 | /// \param Filter A function applied to a newly rebuilt Expr to determine if |
8459 | /// it is an acceptable/usable result from a single combination of typo |
8460 | /// corrections. As long as the filter returns ExprError, different |
8461 | /// combinations of corrections will be tried until all are exhausted. |
8462 | ExprResult CorrectDelayedTyposInExpr( |
8463 | Expr *E, VarDecl *InitDecl = nullptr, |
8464 | bool RecoverUncorrectedTypos = false, |
8465 | llvm::function_ref<ExprResult(Expr *)> Filter = |
8466 | [](Expr *E) -> ExprResult { return E; }); |
8467 | |
8468 | ExprResult CorrectDelayedTyposInExpr( |
8469 | ExprResult ER, VarDecl *InitDecl = nullptr, |
8470 | bool RecoverUncorrectedTypos = false, |
8471 | llvm::function_ref<ExprResult(Expr *)> Filter = |
8472 | [](Expr *E) -> ExprResult { return E; }) { |
8473 | return ER.isInvalid() |
8474 | ? ER |
8475 | : CorrectDelayedTyposInExpr(E: ER.get(), InitDecl, |
8476 | RecoverUncorrectedTypos, Filter); |
8477 | } |
8478 | |
8479 | /// Describes the result of an "if-exists" condition check. |
8480 | enum IfExistsResult { |
8481 | /// The symbol exists. |
8482 | IER_Exists, |
8483 | |
8484 | /// The symbol does not exist. |
8485 | IER_DoesNotExist, |
8486 | |
8487 | /// The name is a dependent name, so the results will differ |
8488 | /// from one instantiation to the next. |
8489 | IER_Dependent, |
8490 | |
8491 | /// An error occurred. |
8492 | IER_Error |
8493 | }; |
8494 | |
8495 | IfExistsResult |
8496 | CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, |
8497 | const DeclarationNameInfo &TargetNameInfo); |
8498 | |
8499 | IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, |
8500 | SourceLocation KeywordLoc, |
8501 | bool IsIfExists, CXXScopeSpec &SS, |
8502 | UnqualifiedId &Name); |
8503 | |
8504 | RequiresExprBodyDecl * |
8505 | ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, |
8506 | ArrayRef<ParmVarDecl *> LocalParameters, |
8507 | Scope *BodyScope); |
8508 | void ActOnFinishRequiresExpr(); |
8509 | concepts::Requirement *ActOnSimpleRequirement(Expr *E); |
8510 | concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc, |
8511 | CXXScopeSpec &SS, |
8512 | SourceLocation NameLoc, |
8513 | const IdentifierInfo *TypeName, |
8514 | TemplateIdAnnotation *TemplateId); |
8515 | concepts::Requirement *ActOnCompoundRequirement(Expr *E, |
8516 | SourceLocation NoexceptLoc); |
8517 | concepts::Requirement *ActOnCompoundRequirement( |
8518 | Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, |
8519 | TemplateIdAnnotation *TypeConstraint, unsigned Depth); |
8520 | concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); |
8521 | concepts::ExprRequirement *BuildExprRequirement( |
8522 | Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, |
8523 | concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); |
8524 | concepts::ExprRequirement *BuildExprRequirement( |
8525 | concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, |
8526 | bool IsSatisfied, SourceLocation NoexceptLoc, |
8527 | concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); |
8528 | concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); |
8529 | concepts::TypeRequirement *BuildTypeRequirement( |
8530 | concepts::Requirement::SubstitutionDiagnostic *SubstDiag); |
8531 | concepts::NestedRequirement *BuildNestedRequirement(Expr *E); |
8532 | concepts::NestedRequirement * |
8533 | BuildNestedRequirement(StringRef InvalidConstraintEntity, |
8534 | const ASTConstraintSatisfaction &Satisfaction); |
8535 | ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, |
8536 | RequiresExprBodyDecl *Body, |
8537 | SourceLocation LParenLoc, |
8538 | ArrayRef<ParmVarDecl *> LocalParameters, |
8539 | SourceLocation RParenLoc, |
8540 | ArrayRef<concepts::Requirement *> Requirements, |
8541 | SourceLocation ClosingBraceLoc); |
8542 | |
8543 | private: |
8544 | ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, |
8545 | bool IsDelete); |
8546 | |
8547 | void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); |
8548 | void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, |
8549 | bool DeleteWasArrayForm); |
8550 | |
8551 | ///@} |
8552 | |
8553 | // |
8554 | // |
8555 | // ------------------------------------------------------------------------- |
8556 | // |
8557 | // |
8558 | |
8559 | /// \name Member Access Expressions |
8560 | /// Implementations are in SemaExprMember.cpp |
8561 | ///@{ |
8562 | |
8563 | public: |
8564 | /// Check whether an expression might be an implicit class member access. |
8565 | bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, |
8566 | bool IsAddressOfOperand); |
8567 | |
8568 | /// Builds an expression which might be an implicit member expression. |
8569 | ExprResult BuildPossibleImplicitMemberExpr( |
8570 | const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, |
8571 | const TemplateArgumentListInfo *TemplateArgs, const Scope *S); |
8572 | |
8573 | /// Builds an implicit member access expression. The current context |
8574 | /// is known to be an instance method, and the given unqualified lookup |
8575 | /// set is known to contain only instance members, at least one of which |
8576 | /// is from an appropriate type. |
8577 | ExprResult |
8578 | BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
8579 | LookupResult &R, |
8580 | const TemplateArgumentListInfo *TemplateArgs, |
8581 | bool IsDefiniteInstance, const Scope *S); |
8582 | |
8583 | ExprResult ActOnDependentMemberExpr( |
8584 | Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, |
8585 | const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
8586 | NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, |
8587 | const TemplateArgumentListInfo *TemplateArgs); |
8588 | |
8589 | /// The main callback when the parser finds something like |
8590 | /// expression . [nested-name-specifier] identifier |
8591 | /// expression -> [nested-name-specifier] identifier |
8592 | /// where 'identifier' encompasses a fairly broad spectrum of |
8593 | /// possibilities, including destructor and operator references. |
8594 | /// |
8595 | /// \param OpKind either tok::arrow or tok::period |
8596 | /// \param ObjCImpDecl the current Objective-C \@implementation |
8597 | /// decl; this is an ugly hack around the fact that Objective-C |
8598 | /// \@implementations aren't properly put in the context chain |
8599 | ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, |
8600 | tok::TokenKind OpKind, CXXScopeSpec &SS, |
8601 | SourceLocation TemplateKWLoc, |
8602 | UnqualifiedId &Member, Decl *ObjCImpDecl); |
8603 | |
8604 | MemberExpr * |
8605 | BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, |
8606 | NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, |
8607 | ValueDecl *Member, DeclAccessPair FoundDecl, |
8608 | bool HadMultipleCandidates, |
8609 | const DeclarationNameInfo &MemberNameInfo, QualType Ty, |
8610 | ExprValueKind VK, ExprObjectKind OK, |
8611 | const TemplateArgumentListInfo *TemplateArgs = nullptr); |
8612 | |
8613 | // Check whether the declarations we found through a nested-name |
8614 | // specifier in a member expression are actually members of the base |
8615 | // type. The restriction here is: |
8616 | // |
8617 | // C++ [expr.ref]p2: |
8618 | // ... In these cases, the id-expression shall name a |
8619 | // member of the class or of one of its base classes. |
8620 | // |
8621 | // So it's perfectly legitimate for the nested-name specifier to name |
8622 | // an unrelated class, and for us to find an overload set including |
8623 | // decls from classes which are not superclasses, as long as the decl |
8624 | // we actually pick through overload resolution is from a superclass. |
8625 | bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, |
8626 | const CXXScopeSpec &SS, |
8627 | const LookupResult &R); |
8628 | |
8629 | // This struct is for use by ActOnMemberAccess to allow |
8630 | // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after |
8631 | // changing the access operator from a '.' to a '->' (to see if that is the |
8632 | // change needed to fix an error about an unknown member, e.g. when the class |
8633 | // defines a custom operator->). |
8634 | struct { |
8635 | Scope *; |
8636 | UnqualifiedId &; |
8637 | Decl *; |
8638 | }; |
8639 | |
8640 | ExprResult BuildMemberReferenceExpr( |
8641 | Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, |
8642 | CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
8643 | NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, |
8644 | const TemplateArgumentListInfo *TemplateArgs, const Scope *S, |
8645 | ActOnMemberAccessExtraArgs * = nullptr); |
8646 | |
8647 | ExprResult |
8648 | BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, |
8649 | bool IsArrow, const CXXScopeSpec &SS, |
8650 | SourceLocation TemplateKWLoc, |
8651 | NamedDecl *FirstQualifierInScope, LookupResult &R, |
8652 | const TemplateArgumentListInfo *TemplateArgs, |
8653 | const Scope *S, bool SuppressQualifierCheck = false, |
8654 | ActOnMemberAccessExtraArgs * = nullptr); |
8655 | |
8656 | ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, |
8657 | SourceLocation OpLoc, |
8658 | const CXXScopeSpec &SS, FieldDecl *Field, |
8659 | DeclAccessPair FoundDecl, |
8660 | const DeclarationNameInfo &MemberNameInfo); |
8661 | |
8662 | /// Perform conversions on the LHS of a member access expression. |
8663 | ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); |
8664 | |
8665 | ExprResult BuildAnonymousStructUnionMemberReference( |
8666 | const CXXScopeSpec &SS, SourceLocation nameLoc, |
8667 | IndirectFieldDecl *indirectField, |
8668 | DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none), |
8669 | Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); |
8670 | |
8671 | private: |
8672 | void CheckMemberAccessOfNoDeref(const MemberExpr *E); |
8673 | |
8674 | ///@} |
8675 | |
8676 | // |
8677 | // |
8678 | // ------------------------------------------------------------------------- |
8679 | // |
8680 | // |
8681 | |
8682 | /// \name Initializers |
8683 | /// Implementations are in SemaInit.cpp |
8684 | ///@{ |
8685 | |
8686 | public: |
8687 | /// Stack of types that correspond to the parameter entities that are |
8688 | /// currently being copy-initialized. Can be empty. |
8689 | llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; |
8690 | |
8691 | llvm::DenseMap<unsigned, CXXDeductionGuideDecl *> |
8692 | AggregateDeductionCandidates; |
8693 | |
8694 | bool IsStringInit(Expr *Init, const ArrayType *AT); |
8695 | |
8696 | /// Determine whether we can perform aggregate initialization for the purposes |
8697 | /// of overload resolution. |
8698 | bool CanPerformAggregateInitializationForOverloadResolution( |
8699 | const InitializedEntity &Entity, InitListExpr *From); |
8700 | |
8701 | ExprResult ActOnDesignatedInitializer(Designation &Desig, |
8702 | SourceLocation EqualOrColonLoc, |
8703 | bool GNUSyntax, ExprResult Init); |
8704 | |
8705 | /// Check that the lifetime of the initializer (and its subobjects) is |
8706 | /// sufficient for initializing the entity, and perform lifetime extension |
8707 | /// (when permitted) if not. |
8708 | void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); |
8709 | |
8710 | MaterializeTemporaryExpr * |
8711 | CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, |
8712 | bool BoundToLvalueReference); |
8713 | |
8714 | /// If \p E is a prvalue denoting an unmaterialized temporary, materialize |
8715 | /// it as an xvalue. In C++98, the result will still be a prvalue, because |
8716 | /// we don't have xvalues there. |
8717 | ExprResult TemporaryMaterializationConversion(Expr *E); |
8718 | |
8719 | ExprResult PerformQualificationConversion( |
8720 | Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue, |
8721 | CheckedConversionKind CCK = CheckedConversionKind::Implicit); |
8722 | |
8723 | bool CanPerformCopyInitialization(const InitializedEntity &Entity, |
8724 | ExprResult Init); |
8725 | ExprResult PerformCopyInitialization(const InitializedEntity &Entity, |
8726 | SourceLocation EqualLoc, ExprResult Init, |
8727 | bool TopLevelOfInitList = false, |
8728 | bool AllowExplicit = false); |
8729 | |
8730 | QualType DeduceTemplateSpecializationFromInitializer( |
8731 | TypeSourceInfo *TInfo, const InitializedEntity &Entity, |
8732 | const InitializationKind &Kind, MultiExprArg Init); |
8733 | |
8734 | ///@} |
8735 | |
8736 | // |
8737 | // |
8738 | // ------------------------------------------------------------------------- |
8739 | // |
8740 | // |
8741 | |
8742 | /// \name C++ Lambda Expressions |
8743 | /// Implementations are in SemaLambda.cpp |
8744 | ///@{ |
8745 | |
8746 | public: |
8747 | /// Create a new lambda closure type. |
8748 | CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, |
8749 | TypeSourceInfo *Info, |
8750 | unsigned LambdaDependencyKind, |
8751 | LambdaCaptureDefault CaptureDefault); |
8752 | |
8753 | /// Number lambda for linkage purposes if necessary. |
8754 | void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, |
8755 | std::optional<CXXRecordDecl::LambdaNumbering> |
8756 | NumberingOverride = std::nullopt); |
8757 | |
8758 | /// Endow the lambda scope info with the relevant properties. |
8759 | void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, |
8760 | SourceRange IntroducerRange, |
8761 | LambdaCaptureDefault CaptureDefault, |
8762 | SourceLocation CaptureDefaultLoc, bool ExplicitParams, |
8763 | bool Mutable); |
8764 | |
8765 | CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange, |
8766 | CXXRecordDecl *Class); |
8767 | |
8768 | void AddTemplateParametersToLambdaCallOperator( |
8769 | CXXMethodDecl *CallOperator, CXXRecordDecl *Class, |
8770 | TemplateParameterList *TemplateParams); |
8771 | |
8772 | void CompleteLambdaCallOperator( |
8773 | CXXMethodDecl *Method, SourceLocation LambdaLoc, |
8774 | SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, |
8775 | TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, |
8776 | StorageClass SC, ArrayRef<ParmVarDecl *> Params, |
8777 | bool HasExplicitResultType); |
8778 | |
8779 | /// Returns true if the explicit object parameter was invalid. |
8780 | bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, |
8781 | SourceLocation CallLoc); |
8782 | |
8783 | /// Perform initialization analysis of the init-capture and perform |
8784 | /// any implicit conversions such as an lvalue-to-rvalue conversion if |
8785 | /// not being used to initialize a reference. |
8786 | ParsedType actOnLambdaInitCaptureInitialization( |
8787 | SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, |
8788 | IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { |
8789 | return ParsedType::make(P: buildLambdaInitCaptureInitialization( |
8790 | Loc, ByRef, EllipsisLoc, NumExpansions: std::nullopt, Id, |
8791 | DirectInit: InitKind != LambdaCaptureInitKind::CopyInit, Init)); |
8792 | } |
8793 | QualType buildLambdaInitCaptureInitialization( |
8794 | SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, |
8795 | std::optional<unsigned> NumExpansions, IdentifierInfo *Id, |
8796 | bool DirectInit, Expr *&Init); |
8797 | |
8798 | /// Create a dummy variable within the declcontext of the lambda's |
8799 | /// call operator, for name lookup purposes for a lambda init capture. |
8800 | /// |
8801 | /// CodeGen handles emission of lambda captures, ignoring these dummy |
8802 | /// variables appropriately. |
8803 | VarDecl *createLambdaInitCaptureVarDecl( |
8804 | SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, |
8805 | IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx); |
8806 | |
8807 | /// Add an init-capture to a lambda scope. |
8808 | void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef); |
8809 | |
8810 | /// Note that we have finished the explicit captures for the |
8811 | /// given lambda. |
8812 | void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); |
8813 | |
8814 | /// Deduce a block or lambda's return type based on the return |
8815 | /// statements present in the body. |
8816 | void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); |
8817 | |
8818 | /// Once the Lambdas capture are known, we can start to create the closure, |
8819 | /// call operator method, and keep track of the captures. |
8820 | /// We do the capture lookup here, but they are not actually captured until |
8821 | /// after we know what the qualifiers of the call operator are. |
8822 | void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, |
8823 | Scope *CurContext); |
8824 | |
8825 | /// This is called after parsing the explicit template parameter list |
8826 | /// on a lambda (if it exists) in C++2a. |
8827 | void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro, |
8828 | SourceLocation LAngleLoc, |
8829 | ArrayRef<NamedDecl *> TParams, |
8830 | SourceLocation RAngleLoc, |
8831 | ExprResult RequiresClause); |
8832 | |
8833 | void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, |
8834 | SourceLocation MutableLoc); |
8835 | |
8836 | void ActOnLambdaClosureParameters( |
8837 | Scope *LambdaScope, |
8838 | MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo); |
8839 | |
8840 | /// ActOnStartOfLambdaDefinition - This is called just before we start |
8841 | /// parsing the body of a lambda; it analyzes the explicit captures and |
8842 | /// arguments, and sets up various data-structures for the body of the |
8843 | /// lambda. |
8844 | void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, |
8845 | Declarator &ParamInfo, const DeclSpec &DS); |
8846 | |
8847 | /// ActOnLambdaError - If there is an error parsing a lambda, this callback |
8848 | /// is invoked to pop the information about the lambda. |
8849 | void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, |
8850 | bool IsInstantiation = false); |
8851 | |
8852 | /// ActOnLambdaExpr - This is called when the body of a lambda expression |
8853 | /// was successfully completed. |
8854 | ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body); |
8855 | |
8856 | /// Does copying/destroying the captured variable have side effects? |
8857 | bool CaptureHasSideEffects(const sema::Capture &From); |
8858 | |
8859 | /// Diagnose if an explicit lambda capture is unused. Returns true if a |
8860 | /// diagnostic is emitted. |
8861 | bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, |
8862 | const sema::Capture &From); |
8863 | |
8864 | /// Build a FieldDecl suitable to hold the given capture. |
8865 | FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); |
8866 | |
8867 | /// Initialize the given capture with a suitable expression. |
8868 | ExprResult BuildCaptureInit(const sema::Capture &Capture, |
8869 | SourceLocation ImplicitCaptureLoc, |
8870 | bool IsOpenMPMapping = false); |
8871 | |
8872 | /// Complete a lambda-expression having processed and attached the |
8873 | /// lambda body. |
8874 | ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, |
8875 | sema::LambdaScopeInfo *LSI); |
8876 | |
8877 | /// Get the return type to use for a lambda's conversion function(s) to |
8878 | /// function pointer type, given the type of the call operator. |
8879 | QualType |
8880 | getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, |
8881 | CallingConv CC); |
8882 | |
8883 | ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, |
8884 | SourceLocation ConvLocation, |
8885 | CXXConversionDecl *Conv, Expr *Src); |
8886 | |
8887 | class LambdaScopeForCallOperatorInstantiationRAII |
8888 | : private FunctionScopeRAII { |
8889 | public: |
8890 | LambdaScopeForCallOperatorInstantiationRAII( |
8891 | Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, |
8892 | LocalInstantiationScope &Scope, |
8893 | bool ShouldAddDeclsFromParentScope = true); |
8894 | }; |
8895 | |
8896 | /// Compute the mangling number context for a lambda expression or |
8897 | /// block literal. Also return the extra mangling decl if any. |
8898 | /// |
8899 | /// \param DC - The DeclContext containing the lambda expression or |
8900 | /// block literal. |
8901 | std::tuple<MangleNumberingContext *, Decl *> |
8902 | getCurrentMangleNumberContext(const DeclContext *DC); |
8903 | |
8904 | ///@} |
8905 | |
8906 | // |
8907 | // |
8908 | // ------------------------------------------------------------------------- |
8909 | // |
8910 | // |
8911 | |
8912 | /// \name Name Lookup |
8913 | /// |
8914 | /// These routines provide name lookup that is used during semantic |
8915 | /// analysis to resolve the various kinds of names (identifiers, |
8916 | /// overloaded operator names, constructor names, etc.) into zero or |
8917 | /// more declarations within a particular scope. The major entry |
8918 | /// points are LookupName, which performs unqualified name lookup, |
8919 | /// and LookupQualifiedName, which performs qualified name lookup. |
8920 | /// |
8921 | /// All name lookup is performed based on some specific criteria, |
8922 | /// which specify what names will be visible to name lookup and how |
8923 | /// far name lookup should work. These criteria are important both |
8924 | /// for capturing language semantics (certain lookups will ignore |
8925 | /// certain names, for example) and for performance, since name |
8926 | /// lookup is often a bottleneck in the compilation of C++. Name |
8927 | /// lookup criteria is specified via the LookupCriteria enumeration. |
8928 | /// |
8929 | /// The results of name lookup can vary based on the kind of name |
8930 | /// lookup performed, the current language, and the translation |
8931 | /// unit. In C, for example, name lookup will either return nothing |
8932 | /// (no entity found) or a single declaration. In C++, name lookup |
8933 | /// can additionally refer to a set of overloaded functions or |
8934 | /// result in an ambiguity. All of the possible results of name |
8935 | /// lookup are captured by the LookupResult class, which provides |
8936 | /// the ability to distinguish among them. |
8937 | /// |
8938 | /// Implementations are in SemaLookup.cpp |
8939 | ///@{ |
8940 | |
8941 | public: |
8942 | /// Tracks whether we are in a context where typo correction is |
8943 | /// disabled. |
8944 | bool DisableTypoCorrection; |
8945 | |
8946 | /// The number of typos corrected by CorrectTypo. |
8947 | unsigned TyposCorrected; |
8948 | |
8949 | typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; |
8950 | typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; |
8951 | |
8952 | /// A cache containing identifiers for which typo correction failed and |
8953 | /// their locations, so that repeated attempts to correct an identifier in a |
8954 | /// given location are ignored if typo correction already failed for it. |
8955 | IdentifierSourceLocations TypoCorrectionFailures; |
8956 | |
8957 | /// SpecialMemberOverloadResult - The overloading result for a special member |
8958 | /// function. |
8959 | /// |
8960 | /// This is basically a wrapper around PointerIntPair. The lowest bits of the |
8961 | /// integer are used to determine whether overload resolution succeeded. |
8962 | class SpecialMemberOverloadResult { |
8963 | public: |
8964 | enum Kind { NoMemberOrDeleted, Ambiguous, Success }; |
8965 | |
8966 | private: |
8967 | llvm::PointerIntPair<CXXMethodDecl *, 2> Pair; |
8968 | |
8969 | public: |
8970 | SpecialMemberOverloadResult() {} |
8971 | SpecialMemberOverloadResult(CXXMethodDecl *MD) |
8972 | : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} |
8973 | |
8974 | CXXMethodDecl *getMethod() const { return Pair.getPointer(); } |
8975 | void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } |
8976 | |
8977 | Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } |
8978 | void setKind(Kind K) { Pair.setInt(K); } |
8979 | }; |
8980 | |
8981 | class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, |
8982 | public SpecialMemberOverloadResult { |
8983 | public: |
8984 | SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) |
8985 | : FastFoldingSetNode(ID) {} |
8986 | }; |
8987 | |
8988 | /// A cache of special member function overload resolution results |
8989 | /// for C++ records. |
8990 | llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; |
8991 | |
8992 | /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by |
8993 | /// `TransformTypos` in order to keep track of any TypoExprs that are created |
8994 | /// recursively during typo correction and wipe them away if the correction |
8995 | /// fails. |
8996 | llvm::SmallVector<TypoExpr *, 2> TypoExprs; |
8997 | |
8998 | enum class AcceptableKind { Visible, Reachable }; |
8999 | |
9000 | // Members have to be NamespaceDecl* or TranslationUnitDecl*. |
9001 | // TODO: make this is a typesafe union. |
9002 | typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; |
9003 | typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; |
9004 | |
9005 | /// Describes the kind of name lookup to perform. |
9006 | enum LookupNameKind { |
9007 | /// Ordinary name lookup, which finds ordinary names (functions, |
9008 | /// variables, typedefs, etc.) in C and most kinds of names |
9009 | /// (functions, variables, members, types, etc.) in C++. |
9010 | LookupOrdinaryName = 0, |
9011 | /// Tag name lookup, which finds the names of enums, classes, |
9012 | /// structs, and unions. |
9013 | LookupTagName, |
9014 | /// Label name lookup. |
9015 | LookupLabel, |
9016 | /// Member name lookup, which finds the names of |
9017 | /// class/struct/union members. |
9018 | LookupMemberName, |
9019 | /// Look up of an operator name (e.g., operator+) for use with |
9020 | /// operator overloading. This lookup is similar to ordinary name |
9021 | /// lookup, but will ignore any declarations that are class members. |
9022 | LookupOperatorName, |
9023 | /// Look up a name following ~ in a destructor name. This is an ordinary |
9024 | /// lookup, but prefers tags to typedefs. |
9025 | LookupDestructorName, |
9026 | /// Look up of a name that precedes the '::' scope resolution |
9027 | /// operator in C++. This lookup completely ignores operator, object, |
9028 | /// function, and enumerator names (C++ [basic.lookup.qual]p1). |
9029 | LookupNestedNameSpecifierName, |
9030 | /// Look up a namespace name within a C++ using directive or |
9031 | /// namespace alias definition, ignoring non-namespace names (C++ |
9032 | /// [basic.lookup.udir]p1). |
9033 | LookupNamespaceName, |
9034 | /// Look up all declarations in a scope with the given name, |
9035 | /// including resolved using declarations. This is appropriate |
9036 | /// for checking redeclarations for a using declaration. |
9037 | LookupUsingDeclName, |
9038 | /// Look up an ordinary name that is going to be redeclared as a |
9039 | /// name with linkage. This lookup ignores any declarations that |
9040 | /// are outside of the current scope unless they have linkage. See |
9041 | /// C99 6.2.2p4-5 and C++ [basic.link]p6. |
9042 | LookupRedeclarationWithLinkage, |
9043 | /// Look up a friend of a local class. This lookup does not look |
9044 | /// outside the innermost non-class scope. See C++11 [class.friend]p11. |
9045 | LookupLocalFriendName, |
9046 | /// Look up the name of an Objective-C protocol. |
9047 | LookupObjCProtocolName, |
9048 | /// Look up implicit 'self' parameter of an objective-c method. |
9049 | LookupObjCImplicitSelfParam, |
9050 | /// Look up the name of an OpenMP user-defined reduction operation. |
9051 | LookupOMPReductionName, |
9052 | /// Look up the name of an OpenMP user-defined mapper. |
9053 | LookupOMPMapperName, |
9054 | /// Look up any declaration with any name. |
9055 | LookupAnyName |
9056 | }; |
9057 | |
9058 | /// The possible outcomes of name lookup for a literal operator. |
9059 | enum LiteralOperatorLookupResult { |
9060 | /// The lookup resulted in an error. |
9061 | LOLR_Error, |
9062 | /// The lookup found no match but no diagnostic was issued. |
9063 | LOLR_ErrorNoDiagnostic, |
9064 | /// The lookup found a single 'cooked' literal operator, which |
9065 | /// expects a normal literal to be built and passed to it. |
9066 | LOLR_Cooked, |
9067 | /// The lookup found a single 'raw' literal operator, which expects |
9068 | /// a string literal containing the spelling of the literal token. |
9069 | LOLR_Raw, |
9070 | /// The lookup found an overload set of literal operator templates, |
9071 | /// which expect the characters of the spelling of the literal token to be |
9072 | /// passed as a non-type template argument pack. |
9073 | LOLR_Template, |
9074 | /// The lookup found an overload set of literal operator templates, |
9075 | /// which expect the character type and characters of the spelling of the |
9076 | /// string literal token to be passed as template arguments. |
9077 | LOLR_StringTemplatePack, |
9078 | }; |
9079 | |
9080 | SpecialMemberOverloadResult |
9081 | LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, |
9082 | bool VolatileArg, bool RValueThis, bool ConstThis, |
9083 | bool VolatileThis); |
9084 | |
9085 | typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; |
9086 | typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> |
9087 | TypoRecoveryCallback; |
9088 | |
9089 | RedeclarationKind forRedeclarationInCurContext() const; |
9090 | |
9091 | /// Look up a name, looking for a single declaration. Return |
9092 | /// null if the results were absent, ambiguous, or overloaded. |
9093 | /// |
9094 | /// It is preferable to use the elaborated form and explicitly handle |
9095 | /// ambiguity and overloaded. |
9096 | NamedDecl *LookupSingleName( |
9097 | Scope *S, DeclarationName Name, SourceLocation Loc, |
9098 | LookupNameKind NameKind, |
9099 | RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration); |
9100 | |
9101 | /// Lookup a builtin function, when name lookup would otherwise |
9102 | /// fail. |
9103 | bool LookupBuiltin(LookupResult &R); |
9104 | void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); |
9105 | |
9106 | /// Perform unqualified name lookup starting from a given |
9107 | /// scope. |
9108 | /// |
9109 | /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is |
9110 | /// used to find names within the current scope. For example, 'x' in |
9111 | /// @code |
9112 | /// int x; |
9113 | /// int f() { |
9114 | /// return x; // unqualified name look finds 'x' in the global scope |
9115 | /// } |
9116 | /// @endcode |
9117 | /// |
9118 | /// Different lookup criteria can find different names. For example, a |
9119 | /// particular scope can have both a struct and a function of the same |
9120 | /// name, and each can be found by certain lookup criteria. For more |
9121 | /// information about lookup criteria, see the documentation for the |
9122 | /// class LookupCriteria. |
9123 | /// |
9124 | /// @param S The scope from which unqualified name lookup will |
9125 | /// begin. If the lookup criteria permits, name lookup may also search |
9126 | /// in the parent scopes. |
9127 | /// |
9128 | /// @param [in,out] R Specifies the lookup to perform (e.g., the name to |
9129 | /// look up and the lookup kind), and is updated with the results of lookup |
9130 | /// including zero or more declarations and possibly additional information |
9131 | /// used to diagnose ambiguities. |
9132 | /// |
9133 | /// @returns \c true if lookup succeeded and false otherwise. |
9134 | bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false, |
9135 | bool ForceNoCPlusPlus = false); |
9136 | |
9137 | /// Perform qualified name lookup into a given context. |
9138 | /// |
9139 | /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find |
9140 | /// names when the context of those names is explicit specified, e.g., |
9141 | /// "std::vector" or "x->member", or as part of unqualified name lookup. |
9142 | /// |
9143 | /// Different lookup criteria can find different names. For example, a |
9144 | /// particular scope can have both a struct and a function of the same |
9145 | /// name, and each can be found by certain lookup criteria. For more |
9146 | /// information about lookup criteria, see the documentation for the |
9147 | /// class LookupCriteria. |
9148 | /// |
9149 | /// \param R captures both the lookup criteria and any lookup results found. |
9150 | /// |
9151 | /// \param LookupCtx The context in which qualified name lookup will |
9152 | /// search. If the lookup criteria permits, name lookup may also search |
9153 | /// in the parent contexts or (for C++ classes) base classes. |
9154 | /// |
9155 | /// \param InUnqualifiedLookup true if this is qualified name lookup that |
9156 | /// occurs as part of unqualified name lookup. |
9157 | /// |
9158 | /// \returns true if lookup succeeded, false if it failed. |
9159 | bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, |
9160 | bool InUnqualifiedLookup = false); |
9161 | |
9162 | /// Performs qualified name lookup or special type of lookup for |
9163 | /// "__super::" scope specifier. |
9164 | /// |
9165 | /// This routine is a convenience overload meant to be called from contexts |
9166 | /// that need to perform a qualified name lookup with an optional C++ scope |
9167 | /// specifier that might require special kind of lookup. |
9168 | /// |
9169 | /// \param R captures both the lookup criteria and any lookup results found. |
9170 | /// |
9171 | /// \param LookupCtx The context in which qualified name lookup will |
9172 | /// search. |
9173 | /// |
9174 | /// \param SS An optional C++ scope-specifier. |
9175 | /// |
9176 | /// \returns true if lookup succeeded, false if it failed. |
9177 | bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, |
9178 | CXXScopeSpec &SS); |
9179 | |
9180 | /// Performs name lookup for a name that was parsed in the |
9181 | /// source code, and may contain a C++ scope specifier. |
9182 | /// |
9183 | /// This routine is a convenience routine meant to be called from |
9184 | /// contexts that receive a name and an optional C++ scope specifier |
9185 | /// (e.g., "N::M::x"). It will then perform either qualified or |
9186 | /// unqualified name lookup (with LookupQualifiedName or LookupName, |
9187 | /// respectively) on the given name and return those results. It will |
9188 | /// perform a special type of lookup for "__super::" scope specifier. |
9189 | /// |
9190 | /// @param S The scope from which unqualified name lookup will |
9191 | /// begin. |
9192 | /// |
9193 | /// @param SS An optional C++ scope-specifier, e.g., "::N::M". |
9194 | /// |
9195 | /// @param EnteringContext Indicates whether we are going to enter the |
9196 | /// context of the scope-specifier SS (if present). |
9197 | /// |
9198 | /// @returns True if any decls were found (but possibly ambiguous) |
9199 | bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, |
9200 | QualType ObjectType, bool AllowBuiltinCreation = false, |
9201 | bool EnteringContext = false); |
9202 | |
9203 | /// Perform qualified name lookup into all base classes of the given |
9204 | /// class. |
9205 | /// |
9206 | /// \param R captures both the lookup criteria and any lookup results found. |
9207 | /// |
9208 | /// \param Class The context in which qualified name lookup will |
9209 | /// search. Name lookup will search in all base classes merging the results. |
9210 | /// |
9211 | /// @returns True if any decls were found (but possibly ambiguous) |
9212 | bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); |
9213 | |
9214 | void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, |
9215 | UnresolvedSetImpl &Functions); |
9216 | |
9217 | /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. |
9218 | /// If GnuLabelLoc is a valid source location, then this is a definition |
9219 | /// of an __label__ label name, otherwise it is a normal label definition |
9220 | /// or use. |
9221 | LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, |
9222 | SourceLocation GnuLabelLoc = SourceLocation()); |
9223 | |
9224 | /// Look up the constructors for the given class. |
9225 | DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); |
9226 | |
9227 | /// Look up the default constructor for the given class. |
9228 | CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); |
9229 | |
9230 | /// Look up the copying constructor for the given class. |
9231 | CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, |
9232 | unsigned Quals); |
9233 | |
9234 | /// Look up the copying assignment operator for the given class. |
9235 | CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, |
9236 | bool RValueThis, unsigned ThisQuals); |
9237 | |
9238 | /// Look up the moving constructor for the given class. |
9239 | CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, |
9240 | unsigned Quals); |
9241 | |
9242 | /// Look up the moving assignment operator for the given class. |
9243 | CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, |
9244 | bool RValueThis, unsigned ThisQuals); |
9245 | |
9246 | /// Look for the destructor of the given class. |
9247 | /// |
9248 | /// During semantic analysis, this routine should be used in lieu of |
9249 | /// CXXRecordDecl::getDestructor(). |
9250 | /// |
9251 | /// \returns The destructor for this class. |
9252 | CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); |
9253 | |
9254 | /// Force the declaration of any implicitly-declared members of this |
9255 | /// class. |
9256 | void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); |
9257 | |
9258 | /// Make a merged definition of an existing hidden definition \p ND |
9259 | /// visible at the specified location. |
9260 | void makeMergedDefinitionVisible(NamedDecl *ND); |
9261 | |
9262 | /// Check ODR hashes for C/ObjC when merging types from modules. |
9263 | /// Differently from C++, actually parse the body and reject in case |
9264 | /// of a mismatch. |
9265 | template <typename T, |
9266 | typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>> |
9267 | bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) { |
9268 | if (Duplicate->getODRHash() != Previous->getODRHash()) |
9269 | return false; |
9270 | |
9271 | // Make the previous decl visible. |
9272 | makeMergedDefinitionVisible(ND: Previous); |
9273 | return true; |
9274 | } |
9275 | |
9276 | /// Get the set of additional modules that should be checked during |
9277 | /// name lookup. A module and its imports become visible when instanting a |
9278 | /// template defined within it. |
9279 | llvm::DenseSet<Module *> &getLookupModules(); |
9280 | |
9281 | bool hasVisibleMergedDefinition(const NamedDecl *Def); |
9282 | bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def); |
9283 | |
9284 | /// Determine if the template parameter \p D has a visible default argument. |
9285 | bool |
9286 | hasVisibleDefaultArgument(const NamedDecl *D, |
9287 | llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
9288 | /// Determine if the template parameter \p D has a reachable default argument. |
9289 | bool hasReachableDefaultArgument( |
9290 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
9291 | /// Determine if the template parameter \p D has a reachable default argument. |
9292 | bool hasAcceptableDefaultArgument(const NamedDecl *D, |
9293 | llvm::SmallVectorImpl<Module *> *Modules, |
9294 | Sema::AcceptableKind Kind); |
9295 | |
9296 | /// Determine if there is a visible declaration of \p D that is an explicit |
9297 | /// specialization declaration for a specialization of a template. (For a |
9298 | /// member specialization, use hasVisibleMemberSpecialization.) |
9299 | bool hasVisibleExplicitSpecialization( |
9300 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
9301 | /// Determine if there is a reachable declaration of \p D that is an explicit |
9302 | /// specialization declaration for a specialization of a template. (For a |
9303 | /// member specialization, use hasReachableMemberSpecialization.) |
9304 | bool hasReachableExplicitSpecialization( |
9305 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
9306 | |
9307 | /// Determine if there is a visible declaration of \p D that is a member |
9308 | /// specialization declaration (as opposed to an instantiated declaration). |
9309 | bool hasVisibleMemberSpecialization( |
9310 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
9311 | /// Determine if there is a reachable declaration of \p D that is a member |
9312 | /// specialization declaration (as opposed to an instantiated declaration). |
9313 | bool hasReachableMemberSpecialization( |
9314 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
9315 | |
9316 | bool isModuleVisible(const Module *M, bool ModulePrivate = false); |
9317 | |
9318 | /// Determine whether any declaration of an entity is visible. |
9319 | bool |
9320 | hasVisibleDeclaration(const NamedDecl *D, |
9321 | llvm::SmallVectorImpl<Module *> *Modules = nullptr) { |
9322 | return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); |
9323 | } |
9324 | |
9325 | bool hasVisibleDeclarationSlow(const NamedDecl *D, |
9326 | llvm::SmallVectorImpl<Module *> *Modules); |
9327 | /// Determine whether any declaration of an entity is reachable. |
9328 | bool |
9329 | hasReachableDeclaration(const NamedDecl *D, |
9330 | llvm::SmallVectorImpl<Module *> *Modules = nullptr) { |
9331 | return isReachable(D) || hasReachableDeclarationSlow(D, Modules); |
9332 | } |
9333 | bool hasReachableDeclarationSlow( |
9334 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
9335 | |
9336 | void diagnoseTypo(const TypoCorrection &Correction, |
9337 | const PartialDiagnostic &TypoDiag, |
9338 | bool ErrorRecovery = true); |
9339 | |
9340 | /// Diagnose a successfully-corrected typo. Separated from the correction |
9341 | /// itself to allow external validation of the result, etc. |
9342 | /// |
9343 | /// \param Correction The result of performing typo correction. |
9344 | /// \param TypoDiag The diagnostic to produce. This will have the corrected |
9345 | /// string added to it (and usually also a fixit). |
9346 | /// \param PrevNote A note to use when indicating the location of the entity |
9347 | /// to which we are correcting. Will have the correction string added |
9348 | /// to it. |
9349 | /// \param ErrorRecovery If \c true (the default), the caller is going to |
9350 | /// recover from the typo as if the corrected string had been typed. |
9351 | /// In this case, \c PDiag must be an error, and we will attach a fixit |
9352 | /// to it. |
9353 | void diagnoseTypo(const TypoCorrection &Correction, |
9354 | const PartialDiagnostic &TypoDiag, |
9355 | const PartialDiagnostic &PrevNote, |
9356 | bool ErrorRecovery = true); |
9357 | |
9358 | /// Find the associated classes and namespaces for |
9359 | /// argument-dependent lookup for a call with the given set of |
9360 | /// arguments. |
9361 | /// |
9362 | /// This routine computes the sets of associated classes and associated |
9363 | /// namespaces searched by argument-dependent lookup |
9364 | /// (C++ [basic.lookup.argdep]) for a given set of arguments. |
9365 | void FindAssociatedClassesAndNamespaces( |
9366 | SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, |
9367 | AssociatedNamespaceSet &AssociatedNamespaces, |
9368 | AssociatedClassSet &AssociatedClasses); |
9369 | |
9370 | /// Produce a diagnostic describing the ambiguity that resulted |
9371 | /// from name lookup. |
9372 | /// |
9373 | /// \param Result The result of the ambiguous lookup to be diagnosed. |
9374 | void DiagnoseAmbiguousLookup(LookupResult &Result); |
9375 | |
9376 | /// LookupLiteralOperator - Determine which literal operator should be used |
9377 | /// for a user-defined literal, per C++11 [lex.ext]. |
9378 | /// |
9379 | /// Normal overload resolution is not used to select which literal operator to |
9380 | /// call for a user-defined literal. Look up the provided literal operator |
9381 | /// name, and filter the results to the appropriate set for the given argument |
9382 | /// types. |
9383 | LiteralOperatorLookupResult |
9384 | LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, |
9385 | bool AllowRaw, bool AllowTemplate, |
9386 | bool AllowStringTemplate, bool DiagnoseMissing, |
9387 | StringLiteral *StringLit = nullptr); |
9388 | |
9389 | void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, |
9390 | ArrayRef<Expr *> Args, ADLResult &Functions); |
9391 | |
9392 | void LookupVisibleDecls(Scope *S, LookupNameKind Kind, |
9393 | VisibleDeclConsumer &Consumer, |
9394 | bool IncludeGlobalScope = true, |
9395 | bool LoadExternal = true); |
9396 | void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, |
9397 | VisibleDeclConsumer &Consumer, |
9398 | bool IncludeGlobalScope = true, |
9399 | bool IncludeDependentBases = false, |
9400 | bool LoadExternal = true); |
9401 | |
9402 | enum CorrectTypoKind { |
9403 | CTK_NonError, // CorrectTypo used in a non error recovery situation. |
9404 | CTK_ErrorRecovery // CorrectTypo used in normal error recovery. |
9405 | }; |
9406 | |
9407 | /// Try to "correct" a typo in the source code by finding |
9408 | /// visible declarations whose names are similar to the name that was |
9409 | /// present in the source code. |
9410 | /// |
9411 | /// \param TypoName the \c DeclarationNameInfo structure that contains |
9412 | /// the name that was present in the source code along with its location. |
9413 | /// |
9414 | /// \param LookupKind the name-lookup criteria used to search for the name. |
9415 | /// |
9416 | /// \param S the scope in which name lookup occurs. |
9417 | /// |
9418 | /// \param SS the nested-name-specifier that precedes the name we're |
9419 | /// looking for, if present. |
9420 | /// |
9421 | /// \param CCC A CorrectionCandidateCallback object that provides further |
9422 | /// validation of typo correction candidates. It also provides flags for |
9423 | /// determining the set of keywords permitted. |
9424 | /// |
9425 | /// \param MemberContext if non-NULL, the context in which to look for |
9426 | /// a member access expression. |
9427 | /// |
9428 | /// \param EnteringContext whether we're entering the context described by |
9429 | /// the nested-name-specifier SS. |
9430 | /// |
9431 | /// \param OPT when non-NULL, the search for visible declarations will |
9432 | /// also walk the protocols in the qualified interfaces of \p OPT. |
9433 | /// |
9434 | /// \returns a \c TypoCorrection containing the corrected name if the typo |
9435 | /// along with information such as the \c NamedDecl where the corrected name |
9436 | /// was declared, and any additional \c NestedNameSpecifier needed to access |
9437 | /// it (C++ only). The \c TypoCorrection is empty if there is no correction. |
9438 | TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, |
9439 | Sema::LookupNameKind LookupKind, Scope *S, |
9440 | CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, |
9441 | CorrectTypoKind Mode, |
9442 | DeclContext *MemberContext = nullptr, |
9443 | bool EnteringContext = false, |
9444 | const ObjCObjectPointerType *OPT = nullptr, |
9445 | bool RecordFailure = true); |
9446 | |
9447 | /// Try to "correct" a typo in the source code by finding |
9448 | /// visible declarations whose names are similar to the name that was |
9449 | /// present in the source code. |
9450 | /// |
9451 | /// \param TypoName the \c DeclarationNameInfo structure that contains |
9452 | /// the name that was present in the source code along with its location. |
9453 | /// |
9454 | /// \param LookupKind the name-lookup criteria used to search for the name. |
9455 | /// |
9456 | /// \param S the scope in which name lookup occurs. |
9457 | /// |
9458 | /// \param SS the nested-name-specifier that precedes the name we're |
9459 | /// looking for, if present. |
9460 | /// |
9461 | /// \param CCC A CorrectionCandidateCallback object that provides further |
9462 | /// validation of typo correction candidates. It also provides flags for |
9463 | /// determining the set of keywords permitted. |
9464 | /// |
9465 | /// \param TDG A TypoDiagnosticGenerator functor that will be used to print |
9466 | /// diagnostics when the actual typo correction is attempted. |
9467 | /// |
9468 | /// \param TRC A TypoRecoveryCallback functor that will be used to build an |
9469 | /// Expr from a typo correction candidate. |
9470 | /// |
9471 | /// \param MemberContext if non-NULL, the context in which to look for |
9472 | /// a member access expression. |
9473 | /// |
9474 | /// \param EnteringContext whether we're entering the context described by |
9475 | /// the nested-name-specifier SS. |
9476 | /// |
9477 | /// \param OPT when non-NULL, the search for visible declarations will |
9478 | /// also walk the protocols in the qualified interfaces of \p OPT. |
9479 | /// |
9480 | /// \returns a new \c TypoExpr that will later be replaced in the AST with an |
9481 | /// Expr representing the result of performing typo correction, or nullptr if |
9482 | /// typo correction is not possible. If nullptr is returned, no diagnostics |
9483 | /// will be emitted and it is the responsibility of the caller to emit any |
9484 | /// that are needed. |
9485 | TypoExpr *CorrectTypoDelayed( |
9486 | const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, |
9487 | Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, |
9488 | TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, |
9489 | CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, |
9490 | bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); |
9491 | |
9492 | /// Kinds of missing import. Note, the values of these enumerators correspond |
9493 | /// to %select values in diagnostics. |
9494 | enum class MissingImportKind { |
9495 | Declaration, |
9496 | Definition, |
9497 | DefaultArgument, |
9498 | ExplicitSpecialization, |
9499 | PartialSpecialization |
9500 | }; |
9501 | |
9502 | /// Diagnose that the specified declaration needs to be visible but |
9503 | /// isn't, and suggest a module import that would resolve the problem. |
9504 | void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, |
9505 | MissingImportKind MIK, bool Recover = true); |
9506 | void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, |
9507 | SourceLocation DeclLoc, ArrayRef<Module *> Modules, |
9508 | MissingImportKind MIK, bool Recover); |
9509 | |
9510 | struct TypoExprState { |
9511 | std::unique_ptr<TypoCorrectionConsumer> Consumer; |
9512 | TypoDiagnosticGenerator DiagHandler; |
9513 | TypoRecoveryCallback RecoveryHandler; |
9514 | TypoExprState(); |
9515 | TypoExprState(TypoExprState &&other) noexcept; |
9516 | TypoExprState &operator=(TypoExprState &&other) noexcept; |
9517 | }; |
9518 | |
9519 | const TypoExprState &getTypoExprState(TypoExpr *TE) const; |
9520 | |
9521 | /// Clears the state of the given TypoExpr. |
9522 | void clearDelayedTypo(TypoExpr *TE); |
9523 | |
9524 | /// Called on #pragma clang __debug dump II |
9525 | void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); |
9526 | |
9527 | /// Called on #pragma clang __debug dump E |
9528 | void ActOnPragmaDump(Expr *E); |
9529 | |
9530 | private: |
9531 | // The set of known/encountered (unique, canonicalized) NamespaceDecls. |
9532 | // |
9533 | // The boolean value will be true to indicate that the namespace was loaded |
9534 | // from an AST/PCH file, or false otherwise. |
9535 | llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces; |
9536 | |
9537 | /// Whether we have already loaded known namespaces from an extenal |
9538 | /// source. |
9539 | bool LoadedExternalKnownNamespaces; |
9540 | |
9541 | bool CppLookupName(LookupResult &R, Scope *S); |
9542 | |
9543 | /// Determine if we could use all the declarations in the module. |
9544 | bool isUsableModule(const Module *M); |
9545 | |
9546 | /// Helper for CorrectTypo and CorrectTypoDelayed used to create and |
9547 | /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction |
9548 | /// should be skipped entirely. |
9549 | std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer( |
9550 | const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, |
9551 | Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, |
9552 | DeclContext *MemberContext, bool EnteringContext, |
9553 | const ObjCObjectPointerType *OPT, bool ErrorRecovery); |
9554 | |
9555 | /// The set of unhandled TypoExprs and their associated state. |
9556 | llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; |
9557 | |
9558 | /// Creates a new TypoExpr AST node. |
9559 | TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, |
9560 | TypoDiagnosticGenerator TDG, |
9561 | TypoRecoveryCallback TRC, SourceLocation TypoLoc); |
9562 | |
9563 | /// Cache for module units which is usable for current module. |
9564 | llvm::DenseSet<const Module *> UsableModuleUnitsCache; |
9565 | |
9566 | /// Record the typo correction failure and return an empty correction. |
9567 | TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, |
9568 | bool RecordFailure = true) { |
9569 | if (RecordFailure) |
9570 | TypoCorrectionFailures[Typo].insert(V: TypoLoc); |
9571 | return TypoCorrection(); |
9572 | } |
9573 | |
9574 | bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind); |
9575 | |
9576 | /// Determine whether two declarations should be linked together, given that |
9577 | /// the old declaration might not be visible and the new declaration might |
9578 | /// not have external linkage. |
9579 | bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, |
9580 | const NamedDecl *New) { |
9581 | if (isVisible(D: Old)) |
9582 | return true; |
9583 | // See comment in below overload for why it's safe to compute the linkage |
9584 | // of the new declaration here. |
9585 | if (New->isExternallyDeclarable()) { |
9586 | assert(Old->isExternallyDeclarable() && |
9587 | "should not have found a non-externally-declarable previous decl" ); |
9588 | return true; |
9589 | } |
9590 | return false; |
9591 | } |
9592 | bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); |
9593 | |
9594 | ///@} |
9595 | |
9596 | // |
9597 | // |
9598 | // ------------------------------------------------------------------------- |
9599 | // |
9600 | // |
9601 | |
9602 | /// \name Modules |
9603 | /// Implementations are in SemaModule.cpp |
9604 | ///@{ |
9605 | |
9606 | public: |
9607 | /// Get the module unit whose scope we are currently within. |
9608 | Module *getCurrentModule() const { |
9609 | return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; |
9610 | } |
9611 | |
9612 | /// Is the module scope we are an implementation unit? |
9613 | bool currentModuleIsImplementation() const { |
9614 | return ModuleScopes.empty() |
9615 | ? false |
9616 | : ModuleScopes.back().Module->isModuleImplementation(); |
9617 | } |
9618 | |
9619 | // When loading a non-modular PCH files, this is used to restore module |
9620 | // visibility. |
9621 | void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { |
9622 | VisibleModules.setVisible(M: Mod, Loc: ImportLoc); |
9623 | } |
9624 | |
9625 | enum class ModuleDeclKind { |
9626 | Interface, ///< 'export module X;' |
9627 | Implementation, ///< 'module X;' |
9628 | PartitionInterface, ///< 'export module X:Y;' |
9629 | PartitionImplementation, ///< 'module X:Y;' |
9630 | }; |
9631 | |
9632 | /// An enumeration to represent the transition of states in parsing module |
9633 | /// fragments and imports. If we are not parsing a C++20 TU, or we find |
9634 | /// an error in state transition, the state is set to NotACXX20Module. |
9635 | enum class ModuleImportState { |
9636 | FirstDecl, ///< Parsing the first decl in a TU. |
9637 | GlobalFragment, ///< after 'module;' but before 'module X;' |
9638 | ImportAllowed, ///< after 'module X;' but before any non-import decl. |
9639 | ImportFinished, ///< after any non-import decl. |
9640 | PrivateFragmentImportAllowed, ///< after 'module :private;' but before any |
9641 | ///< non-import decl. |
9642 | PrivateFragmentImportFinished, ///< after 'module :private;' but a |
9643 | ///< non-import decl has already been seen. |
9644 | NotACXX20Module ///< Not a C++20 TU, or an invalid state was found. |
9645 | }; |
9646 | |
9647 | /// The parser has processed a module-declaration that begins the definition |
9648 | /// of a module interface or implementation. |
9649 | DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, |
9650 | SourceLocation ModuleLoc, ModuleDeclKind MDK, |
9651 | ModuleIdPath Path, ModuleIdPath Partition, |
9652 | ModuleImportState &ImportState); |
9653 | |
9654 | /// The parser has processed a global-module-fragment declaration that begins |
9655 | /// the definition of the global module fragment of the current module unit. |
9656 | /// \param ModuleLoc The location of the 'module' keyword. |
9657 | DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); |
9658 | |
9659 | /// The parser has processed a private-module-fragment declaration that begins |
9660 | /// the definition of the private module fragment of the current module unit. |
9661 | /// \param ModuleLoc The location of the 'module' keyword. |
9662 | /// \param PrivateLoc The location of the 'private' keyword. |
9663 | DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, |
9664 | SourceLocation PrivateLoc); |
9665 | |
9666 | /// The parser has processed a module import declaration. |
9667 | /// |
9668 | /// \param StartLoc The location of the first token in the declaration. This |
9669 | /// could be the location of an '@', 'export', or 'import'. |
9670 | /// \param ExportLoc The location of the 'export' keyword, if any. |
9671 | /// \param ImportLoc The location of the 'import' keyword. |
9672 | /// \param Path The module toplevel name as an access path. |
9673 | /// \param IsPartition If the name is for a partition. |
9674 | DeclResult ActOnModuleImport(SourceLocation StartLoc, |
9675 | SourceLocation ExportLoc, |
9676 | SourceLocation ImportLoc, ModuleIdPath Path, |
9677 | bool IsPartition = false); |
9678 | DeclResult ActOnModuleImport(SourceLocation StartLoc, |
9679 | SourceLocation ExportLoc, |
9680 | SourceLocation ImportLoc, Module *M, |
9681 | ModuleIdPath Path = {}); |
9682 | |
9683 | /// The parser has processed a module import translated from a |
9684 | /// #include or similar preprocessing directive. |
9685 | void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod); |
9686 | void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); |
9687 | |
9688 | /// The parsed has entered a submodule. |
9689 | void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod); |
9690 | /// The parser has left a submodule. |
9691 | void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod); |
9692 | |
9693 | /// Create an implicit import of the given module at the given |
9694 | /// source location, for error recovery, if possible. |
9695 | /// |
9696 | /// This routine is typically used when an entity found by name lookup |
9697 | /// is actually hidden within a module that we know about but the user |
9698 | /// has forgotten to import. |
9699 | void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, |
9700 | Module *Mod); |
9701 | |
9702 | /// We have parsed the start of an export declaration, including the '{' |
9703 | /// (if present). |
9704 | Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, |
9705 | SourceLocation LBraceLoc); |
9706 | |
9707 | /// Complete the definition of an export declaration. |
9708 | Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, |
9709 | SourceLocation RBraceLoc); |
9710 | |
9711 | private: |
9712 | /// The parser has begun a translation unit to be compiled as a C++20 |
9713 | /// Header Unit, helper for ActOnStartOfTranslationUnit() only. |
9714 | void HandleStartOfHeaderUnit(); |
9715 | |
9716 | struct ModuleScope { |
9717 | SourceLocation BeginLoc; |
9718 | clang::Module *Module = nullptr; |
9719 | VisibleModuleSet OuterVisibleModules; |
9720 | }; |
9721 | /// The modules we're currently parsing. |
9722 | llvm::SmallVector<ModuleScope, 16> ModuleScopes; |
9723 | |
9724 | /// For an interface unit, this is the implicitly imported interface unit. |
9725 | clang::Module *ThePrimaryInterface = nullptr; |
9726 | |
9727 | /// The explicit global module fragment of the current translation unit. |
9728 | /// The explicit Global Module Fragment, as specified in C++ |
9729 | /// [module.global.frag]. |
9730 | clang::Module *TheGlobalModuleFragment = nullptr; |
9731 | |
9732 | /// The implicit global module fragments of the current translation unit. |
9733 | /// |
9734 | /// The contents in the implicit global module fragment can't be discarded. |
9735 | clang::Module *TheImplicitGlobalModuleFragment = nullptr; |
9736 | |
9737 | /// Namespace definitions that we will export when they finish. |
9738 | llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces; |
9739 | |
9740 | /// In a C++ standard module, inline declarations require a definition to be |
9741 | /// present at the end of a definition domain. This set holds the decls to |
9742 | /// be checked at the end of the TU. |
9743 | llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls; |
9744 | |
9745 | /// Helper function to judge if we are in module purview. |
9746 | /// Return false if we are not in a module. |
9747 | bool isCurrentModulePurview() const; |
9748 | |
9749 | /// Enter the scope of the explicit global module fragment. |
9750 | Module *PushGlobalModuleFragment(SourceLocation BeginLoc); |
9751 | /// Leave the scope of the explicit global module fragment. |
9752 | void PopGlobalModuleFragment(); |
9753 | |
9754 | /// Enter the scope of an implicit global module fragment. |
9755 | Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc); |
9756 | /// Leave the scope of an implicit global module fragment. |
9757 | void PopImplicitGlobalModuleFragment(); |
9758 | |
9759 | VisibleModuleSet VisibleModules; |
9760 | |
9761 | ///@} |
9762 | |
9763 | // |
9764 | // |
9765 | // ------------------------------------------------------------------------- |
9766 | // |
9767 | // |
9768 | |
9769 | /// \name C++ Overloading |
9770 | /// Implementations are in SemaOverload.cpp |
9771 | ///@{ |
9772 | |
9773 | public: |
9774 | /// Whether deferrable diagnostics should be deferred. |
9775 | bool DeferDiags = false; |
9776 | |
9777 | /// RAII class to control scope of DeferDiags. |
9778 | class DeferDiagsRAII { |
9779 | Sema &S; |
9780 | bool SavedDeferDiags = false; |
9781 | |
9782 | public: |
9783 | DeferDiagsRAII(Sema &S, bool DeferDiags) |
9784 | : S(S), SavedDeferDiags(S.DeferDiags) { |
9785 | S.DeferDiags = DeferDiags; |
9786 | } |
9787 | ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; } |
9788 | }; |
9789 | |
9790 | /// Flag indicating if Sema is building a recovery call expression. |
9791 | /// |
9792 | /// This flag is used to avoid building recovery call expressions |
9793 | /// if Sema is already doing so, which would cause infinite recursions. |
9794 | bool IsBuildingRecoveryCallExpr; |
9795 | |
9796 | enum OverloadKind { |
9797 | /// This is a legitimate overload: the existing declarations are |
9798 | /// functions or function templates with different signatures. |
9799 | Ovl_Overload, |
9800 | |
9801 | /// This is not an overload because the signature exactly matches |
9802 | /// an existing declaration. |
9803 | Ovl_Match, |
9804 | |
9805 | /// This is not an overload because the lookup results contain a |
9806 | /// non-function. |
9807 | Ovl_NonFunction |
9808 | }; |
9809 | |
9810 | /// Determine whether the given New declaration is an overload of the |
9811 | /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if |
9812 | /// New and Old cannot be overloaded, e.g., if New has the same signature as |
9813 | /// some function in Old (C++ 1.3.10) or if the Old declarations aren't |
9814 | /// functions (or function templates) at all. When it does return Ovl_Match or |
9815 | /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be |
9816 | /// overloaded with. This decl may be a UsingShadowDecl on top of the |
9817 | /// underlying declaration. |
9818 | /// |
9819 | /// Example: Given the following input: |
9820 | /// |
9821 | /// void f(int, float); // #1 |
9822 | /// void f(int, int); // #2 |
9823 | /// int f(int, int); // #3 |
9824 | /// |
9825 | /// When we process #1, there is no previous declaration of "f", so IsOverload |
9826 | /// will not be used. |
9827 | /// |
9828 | /// When we process #2, Old contains only the FunctionDecl for #1. By |
9829 | /// comparing the parameter types, we see that #1 and #2 are overloaded (since |
9830 | /// they have different signatures), so this routine returns Ovl_Overload; |
9831 | /// MatchedDecl is unchanged. |
9832 | /// |
9833 | /// When we process #3, Old is an overload set containing #1 and #2. We |
9834 | /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing) |
9835 | /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return |
9836 | /// types of functions are not part of the signature), IsOverload returns |
9837 | /// Ovl_Match and MatchedDecl will be set to point to the FunctionDecl for #2. |
9838 | /// |
9839 | /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a |
9840 | /// class by a using declaration. The rules for whether to hide shadow |
9841 | /// declarations ignore some properties which otherwise figure into a function |
9842 | /// template's signature. |
9843 | OverloadKind CheckOverload(Scope *S, FunctionDecl *New, |
9844 | const LookupResult &OldDecls, NamedDecl *&OldDecl, |
9845 | bool UseMemberUsingDeclRules); |
9846 | bool IsOverload(FunctionDecl *New, FunctionDecl *Old, |
9847 | bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true); |
9848 | |
9849 | // Checks whether MD constitutes an override the base class method BaseMD. |
9850 | // When checking for overrides, the object object members are ignored. |
9851 | bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, |
9852 | bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true); |
9853 | |
9854 | enum class AllowedExplicit { |
9855 | /// Allow no explicit functions to be used. |
9856 | None, |
9857 | /// Allow explicit conversion functions but not explicit constructors. |
9858 | Conversions, |
9859 | /// Allow both explicit conversion functions and explicit constructors. |
9860 | All |
9861 | }; |
9862 | |
9863 | ImplicitConversionSequence TryImplicitConversion( |
9864 | Expr *From, QualType ToType, bool SuppressUserConversions, |
9865 | AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, |
9866 | bool AllowObjCWritebackConversion); |
9867 | |
9868 | /// PerformImplicitConversion - Perform an implicit conversion of the |
9869 | /// expression From to the type ToType. Returns the |
9870 | /// converted expression. Flavor is the kind of conversion we're |
9871 | /// performing, used in the error message. If @p AllowExplicit, |
9872 | /// explicit user-defined conversions are permitted. |
9873 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, |
9874 | AssignmentAction Action, |
9875 | bool AllowExplicit = false); |
9876 | |
9877 | /// IsIntegralPromotion - Determines whether the conversion from the |
9878 | /// expression From (whose potentially-adjusted type is FromType) to |
9879 | /// ToType is an integral promotion (C++ 4.5). If so, returns true and |
9880 | /// sets PromotedType to the promoted type. |
9881 | bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); |
9882 | |
9883 | /// IsFloatingPointPromotion - Determines whether the conversion from |
9884 | /// FromType to ToType is a floating point promotion (C++ 4.6). If so, |
9885 | /// returns true and sets PromotedType to the promoted type. |
9886 | bool IsFloatingPointPromotion(QualType FromType, QualType ToType); |
9887 | |
9888 | /// Determine if a conversion is a complex promotion. |
9889 | /// |
9890 | /// A complex promotion is defined as a complex -> complex conversion |
9891 | /// where the conversion between the underlying real types is a |
9892 | /// floating-point or integral promotion. |
9893 | bool IsComplexPromotion(QualType FromType, QualType ToType); |
9894 | |
9895 | /// IsPointerConversion - Determines whether the conversion of the |
9896 | /// expression From, which has the (possibly adjusted) type FromType, |
9897 | /// can be converted to the type ToType via a pointer conversion (C++ |
9898 | /// 4.10). If so, returns true and places the converted type (that |
9899 | /// might differ from ToType in its cv-qualifiers at some level) into |
9900 | /// ConvertedType. |
9901 | /// |
9902 | /// This routine also supports conversions to and from block pointers |
9903 | /// and conversions with Objective-C's 'id', 'id<protocols...>', and |
9904 | /// pointers to interfaces. FIXME: Once we've determined the |
9905 | /// appropriate overloading rules for Objective-C, we may want to |
9906 | /// split the Objective-C checks into a different routine; however, |
9907 | /// GCC seems to consider all of these conversions to be pointer |
9908 | /// conversions, so for now they live here. IncompatibleObjC will be |
9909 | /// set if the conversion is an allowed Objective-C conversion that |
9910 | /// should result in a warning. |
9911 | bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, |
9912 | bool InOverloadResolution, QualType &ConvertedType, |
9913 | bool &IncompatibleObjC); |
9914 | |
9915 | /// isObjCPointerConversion - Determines whether this is an |
9916 | /// Objective-C pointer conversion. Subroutine of IsPointerConversion, |
9917 | /// with the same arguments and return values. |
9918 | bool isObjCPointerConversion(QualType FromType, QualType ToType, |
9919 | QualType &ConvertedType, bool &IncompatibleObjC); |
9920 | bool IsBlockPointerConversion(QualType FromType, QualType ToType, |
9921 | QualType &ConvertedType); |
9922 | |
9923 | /// FunctionParamTypesAreEqual - This routine checks two function proto types |
9924 | /// for equality of their parameter types. Caller has already checked that |
9925 | /// they have same number of parameters. If the parameters are different, |
9926 | /// ArgPos will have the parameter index of the first different parameter. |
9927 | /// If `Reversed` is true, the parameters of `NewType` will be compared in |
9928 | /// reverse order. That's useful if one of the functions is being used as a |
9929 | /// C++20 synthesized operator overload with a reversed parameter order. |
9930 | bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old, |
9931 | ArrayRef<QualType> New, |
9932 | unsigned *ArgPos = nullptr, |
9933 | bool Reversed = false); |
9934 | |
9935 | bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, |
9936 | const FunctionProtoType *NewType, |
9937 | unsigned *ArgPos = nullptr, |
9938 | bool Reversed = false); |
9939 | |
9940 | bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, |
9941 | const FunctionDecl *NewFunction, |
9942 | unsigned *ArgPos = nullptr, |
9943 | bool Reversed = false); |
9944 | |
9945 | /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing |
9946 | /// function types. Catches different number of parameter, mismatch in |
9947 | /// parameter types, and different return types. |
9948 | void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, |
9949 | QualType ToType); |
9950 | |
9951 | /// CheckPointerConversion - Check the pointer conversion from the |
9952 | /// expression From to the type ToType. This routine checks for |
9953 | /// ambiguous or inaccessible derived-to-base pointer |
9954 | /// conversions for which IsPointerConversion has already returned |
9955 | /// true. It returns true and produces a diagnostic if there was an |
9956 | /// error, or returns false otherwise. |
9957 | bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, |
9958 | CXXCastPath &BasePath, bool IgnoreBaseAccess, |
9959 | bool Diagnose = true); |
9960 | |
9961 | /// IsMemberPointerConversion - Determines whether the conversion of the |
9962 | /// expression From, which has the (possibly adjusted) type FromType, can be |
9963 | /// converted to the type ToType via a member pointer conversion (C++ 4.11). |
9964 | /// If so, returns true and places the converted type (that might differ from |
9965 | /// ToType in its cv-qualifiers at some level) into ConvertedType. |
9966 | bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, |
9967 | bool InOverloadResolution, |
9968 | QualType &ConvertedType); |
9969 | |
9970 | /// CheckMemberPointerConversion - Check the member pointer conversion from |
9971 | /// the expression From to the type ToType. This routine checks for ambiguous |
9972 | /// or virtual or inaccessible base-to-derived member pointer conversions for |
9973 | /// which IsMemberPointerConversion has already returned true. It returns true |
9974 | /// and produces a diagnostic if there was an error, or returns false |
9975 | /// otherwise. |
9976 | bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, |
9977 | CXXCastPath &BasePath, |
9978 | bool IgnoreBaseAccess); |
9979 | |
9980 | /// IsQualificationConversion - Determines whether the conversion from |
9981 | /// an rvalue of type FromType to ToType is a qualification conversion |
9982 | /// (C++ 4.4). |
9983 | /// |
9984 | /// \param ObjCLifetimeConversion Output parameter that will be set to |
9985 | /// indicate when the qualification conversion involves a change in the |
9986 | /// Objective-C object lifetime. |
9987 | bool IsQualificationConversion(QualType FromType, QualType ToType, |
9988 | bool CStyle, bool &ObjCLifetimeConversion); |
9989 | |
9990 | /// Determine whether the conversion from FromType to ToType is a valid |
9991 | /// conversion that strips "noexcept" or "noreturn" off the nested function |
9992 | /// type. |
9993 | bool IsFunctionConversion(QualType FromType, QualType ToType, |
9994 | QualType &ResultTy); |
9995 | bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); |
9996 | void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, |
9997 | DeclarationName Name, |
9998 | OverloadCandidateSet &CandidateSet, |
9999 | FunctionDecl *Fn, MultiExprArg Args, |
10000 | bool IsMember = false); |
10001 | |
10002 | ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, |
10003 | FunctionDecl *Fun); |
10004 | ExprResult PerformImplicitObjectArgumentInitialization( |
10005 | Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, |
10006 | CXXMethodDecl *Method); |
10007 | |
10008 | /// PerformContextuallyConvertToBool - Perform a contextual conversion |
10009 | /// of the expression From to bool (C++0x [conv]p3). |
10010 | ExprResult PerformContextuallyConvertToBool(Expr *From); |
10011 | |
10012 | /// PerformContextuallyConvertToObjCPointer - Perform a contextual |
10013 | /// conversion of the expression From to an Objective-C pointer type. |
10014 | /// Returns a valid but null ExprResult if no conversion sequence exists. |
10015 | ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); |
10016 | |
10017 | /// Contexts in which a converted constant expression is required. |
10018 | enum CCEKind { |
10019 | CCEK_CaseValue, ///< Expression in a case label. |
10020 | CCEK_Enumerator, ///< Enumerator value with fixed underlying type. |
10021 | CCEK_TemplateArg, ///< Value of a non-type template parameter. |
10022 | CCEK_InjectedTTP, ///< Injected parameter of a template template parameter. |
10023 | CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. |
10024 | CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier. |
10025 | CCEK_Noexcept, ///< Condition in a noexcept(bool) specifier. |
10026 | CCEK_StaticAssertMessageSize, ///< Call to size() in a static assert |
10027 | ///< message. |
10028 | CCEK_StaticAssertMessageData, ///< Call to data() in a static assert |
10029 | ///< message. |
10030 | }; |
10031 | |
10032 | ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, |
10033 | CCEKind CCE, |
10034 | NamedDecl *Dest = nullptr); |
10035 | |
10036 | ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, |
10037 | llvm::APSInt &Value, CCEKind CCE); |
10038 | ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, |
10039 | APValue &Value, CCEKind CCE, |
10040 | NamedDecl *Dest = nullptr); |
10041 | |
10042 | /// EvaluateConvertedConstantExpression - Evaluate an Expression |
10043 | /// That is a converted constant expression |
10044 | /// (which was built with BuildConvertedConstantExpression) |
10045 | ExprResult |
10046 | EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, |
10047 | CCEKind CCE, bool RequireInt, |
10048 | const APValue &PreNarrowingValue); |
10049 | |
10050 | /// Abstract base class used to perform a contextual implicit |
10051 | /// conversion from an expression to any type passing a filter. |
10052 | class ContextualImplicitConverter { |
10053 | public: |
10054 | bool Suppress; |
10055 | bool SuppressConversion; |
10056 | |
10057 | ContextualImplicitConverter(bool Suppress = false, |
10058 | bool SuppressConversion = false) |
10059 | : Suppress(Suppress), SuppressConversion(SuppressConversion) {} |
10060 | |
10061 | /// Determine whether the specified type is a valid destination type |
10062 | /// for this conversion. |
10063 | virtual bool match(QualType T) = 0; |
10064 | |
10065 | /// Emits a diagnostic complaining that the expression does not have |
10066 | /// integral or enumeration type. |
10067 | virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, |
10068 | QualType T) = 0; |
10069 | |
10070 | /// Emits a diagnostic when the expression has incomplete class type. |
10071 | virtual SemaDiagnosticBuilder |
10072 | diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; |
10073 | |
10074 | /// Emits a diagnostic when the only matching conversion function |
10075 | /// is explicit. |
10076 | virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, |
10077 | SourceLocation Loc, |
10078 | QualType T, |
10079 | QualType ConvTy) = 0; |
10080 | |
10081 | /// Emits a note for the explicit conversion function. |
10082 | virtual SemaDiagnosticBuilder |
10083 | noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; |
10084 | |
10085 | /// Emits a diagnostic when there are multiple possible conversion |
10086 | /// functions. |
10087 | virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, |
10088 | QualType T) = 0; |
10089 | |
10090 | /// Emits a note for one of the candidate conversions. |
10091 | virtual SemaDiagnosticBuilder |
10092 | noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; |
10093 | |
10094 | /// Emits a diagnostic when we picked a conversion function |
10095 | /// (for cases when we are not allowed to pick a conversion function). |
10096 | virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, |
10097 | SourceLocation Loc, |
10098 | QualType T, |
10099 | QualType ConvTy) = 0; |
10100 | |
10101 | virtual ~ContextualImplicitConverter() {} |
10102 | }; |
10103 | |
10104 | class ICEConvertDiagnoser : public ContextualImplicitConverter { |
10105 | bool AllowScopedEnumerations; |
10106 | |
10107 | public: |
10108 | ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, |
10109 | bool SuppressConversion) |
10110 | : ContextualImplicitConverter(Suppress, SuppressConversion), |
10111 | AllowScopedEnumerations(AllowScopedEnumerations) {} |
10112 | |
10113 | /// Match an integral or (possibly scoped) enumeration type. |
10114 | bool match(QualType T) override; |
10115 | |
10116 | SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, |
10117 | QualType T) override { |
10118 | return diagnoseNotInt(S, Loc, T); |
10119 | } |
10120 | |
10121 | /// Emits a diagnostic complaining that the expression does not have |
10122 | /// integral or enumeration type. |
10123 | virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, |
10124 | QualType T) = 0; |
10125 | }; |
10126 | |
10127 | /// Perform a contextual implicit conversion. |
10128 | ExprResult |
10129 | PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, |
10130 | ContextualImplicitConverter &Converter); |
10131 | |
10132 | /// ReferenceCompareResult - Expresses the result of comparing two |
10133 | /// types (cv1 T1 and cv2 T2) to determine their compatibility for the |
10134 | /// purposes of initialization by reference (C++ [dcl.init.ref]p4). |
10135 | enum ReferenceCompareResult { |
10136 | /// Ref_Incompatible - The two types are incompatible, so direct |
10137 | /// reference binding is not possible. |
10138 | Ref_Incompatible = 0, |
10139 | /// Ref_Related - The two types are reference-related, which means |
10140 | /// that their unqualified forms (T1 and T2) are either the same |
10141 | /// or T1 is a base class of T2. |
10142 | Ref_Related, |
10143 | /// Ref_Compatible - The two types are reference-compatible. |
10144 | Ref_Compatible |
10145 | }; |
10146 | |
10147 | // Fake up a scoped enumeration that still contextually converts to bool. |
10148 | struct ReferenceConversionsScope { |
10149 | /// The conversions that would be performed on an lvalue of type T2 when |
10150 | /// binding a reference of type T1 to it, as determined when evaluating |
10151 | /// whether T1 is reference-compatible with T2. |
10152 | enum ReferenceConversions { |
10153 | Qualification = 0x1, |
10154 | NestedQualification = 0x2, |
10155 | Function = 0x4, |
10156 | DerivedToBase = 0x8, |
10157 | ObjC = 0x10, |
10158 | ObjCLifetime = 0x20, |
10159 | |
10160 | LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) |
10161 | }; |
10162 | }; |
10163 | using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; |
10164 | |
10165 | /// CompareReferenceRelationship - Compare the two types T1 and T2 to |
10166 | /// determine whether they are reference-compatible, |
10167 | /// reference-related, or incompatible, for use in C++ initialization by |
10168 | /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference |
10169 | /// type, and the first type (T1) is the pointee type of the reference |
10170 | /// type being initialized. |
10171 | ReferenceCompareResult |
10172 | CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, |
10173 | ReferenceConversions *Conv = nullptr); |
10174 | |
10175 | /// AddOverloadCandidate - Adds the given function to the set of |
10176 | /// candidate functions, using the given function call arguments. If |
10177 | /// @p SuppressUserConversions, then don't allow user-defined |
10178 | /// conversions via constructors or conversion operators. |
10179 | /// |
10180 | /// \param PartialOverloading true if we are performing "partial" overloading |
10181 | /// based on an incomplete set of function arguments. This feature is used by |
10182 | /// code completion. |
10183 | void AddOverloadCandidate( |
10184 | FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, |
10185 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, |
10186 | bool PartialOverloading = false, bool AllowExplicit = true, |
10187 | bool AllowExplicitConversion = false, |
10188 | ADLCallKind IsADLCandidate = ADLCallKind::NotADL, |
10189 | ConversionSequenceList EarlyConversions = {}, |
10190 | OverloadCandidateParamOrder PO = {}, |
10191 | bool AggregateCandidateDeduction = false, bool StrictPackMatch = false); |
10192 | |
10193 | /// Add all of the function declarations in the given function set to |
10194 | /// the overload candidate set. |
10195 | void AddFunctionCandidates( |
10196 | const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, |
10197 | OverloadCandidateSet &CandidateSet, |
10198 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, |
10199 | bool SuppressUserConversions = false, bool PartialOverloading = false, |
10200 | bool FirstArgumentIsBase = false); |
10201 | |
10202 | /// AddMethodCandidate - Adds a named decl (which is some kind of |
10203 | /// method) as a method candidate to the given overload set. |
10204 | void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, |
10205 | Expr::Classification ObjectClassification, |
10206 | ArrayRef<Expr *> Args, |
10207 | OverloadCandidateSet &CandidateSet, |
10208 | bool SuppressUserConversion = false, |
10209 | OverloadCandidateParamOrder PO = {}); |
10210 | |
10211 | /// AddMethodCandidate - Adds the given C++ member function to the set |
10212 | /// of candidate functions, using the given function call arguments |
10213 | /// and the object argument (@c Object). For example, in a call |
10214 | /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain |
10215 | /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't |
10216 | /// allow user-defined conversions via constructors or conversion |
10217 | /// operators. |
10218 | void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, |
10219 | CXXRecordDecl *ActingContext, QualType ObjectType, |
10220 | Expr::Classification ObjectClassification, |
10221 | ArrayRef<Expr *> Args, |
10222 | OverloadCandidateSet &CandidateSet, |
10223 | bool SuppressUserConversions = false, |
10224 | bool PartialOverloading = false, |
10225 | ConversionSequenceList EarlyConversions = {}, |
10226 | OverloadCandidateParamOrder PO = {}, |
10227 | bool StrictPackMatch = false); |
10228 | |
10229 | /// Add a C++ member function template as a candidate to the candidate |
10230 | /// set, using template argument deduction to produce an appropriate member |
10231 | /// function template specialization. |
10232 | void AddMethodTemplateCandidate( |
10233 | FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, |
10234 | CXXRecordDecl *ActingContext, |
10235 | TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, |
10236 | Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, |
10237 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, |
10238 | bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); |
10239 | |
10240 | /// Add a C++ function template specialization as a candidate |
10241 | /// in the candidate set, using template argument deduction to produce |
10242 | /// an appropriate function template specialization. |
10243 | void AddTemplateOverloadCandidate( |
10244 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
10245 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
10246 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, |
10247 | bool PartialOverloading = false, bool AllowExplicit = true, |
10248 | ADLCallKind IsADLCandidate = ADLCallKind::NotADL, |
10249 | OverloadCandidateParamOrder PO = {}, |
10250 | bool AggregateCandidateDeduction = false); |
10251 | |
10252 | /// Check that implicit conversion sequences can be formed for each argument |
10253 | /// whose corresponding parameter has a non-dependent type, per DR1391's |
10254 | /// [temp.deduct.call]p10. |
10255 | bool CheckNonDependentConversions( |
10256 | FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, |
10257 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, |
10258 | ConversionSequenceList &Conversions, bool SuppressUserConversions, |
10259 | CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), |
10260 | Expr::Classification ObjectClassification = {}, |
10261 | OverloadCandidateParamOrder PO = {}); |
10262 | |
10263 | /// AddConversionCandidate - Add a C++ conversion function as a |
10264 | /// candidate in the candidate set (C++ [over.match.conv], |
10265 | /// C++ [over.match.copy]). From is the expression we're converting from, |
10266 | /// and ToType is the type that we're eventually trying to convert to |
10267 | /// (which may or may not be the same type as the type that the |
10268 | /// conversion function produces). |
10269 | void AddConversionCandidate( |
10270 | CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, |
10271 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, |
10272 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
10273 | bool AllowExplicit, bool AllowResultConversion = true, |
10274 | bool StrictPackMatch = false); |
10275 | |
10276 | /// Adds a conversion function template specialization |
10277 | /// candidate to the overload set, using template argument deduction |
10278 | /// to deduce the template arguments of the conversion function |
10279 | /// template from the type that we are converting to (C++ |
10280 | /// [temp.deduct.conv]). |
10281 | void AddTemplateConversionCandidate( |
10282 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
10283 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, |
10284 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
10285 | bool AllowExplicit, bool AllowResultConversion = true); |
10286 | |
10287 | /// AddSurrogateCandidate - Adds a "surrogate" candidate function that |
10288 | /// converts the given @c Object to a function pointer via the |
10289 | /// conversion function @c Conversion, and then attempts to call it |
10290 | /// with the given arguments (C++ [over.call.object]p2-4). Proto is |
10291 | /// the type of function that we'll eventually be calling. |
10292 | void AddSurrogateCandidate(CXXConversionDecl *Conversion, |
10293 | DeclAccessPair FoundDecl, |
10294 | CXXRecordDecl *ActingContext, |
10295 | const FunctionProtoType *Proto, Expr *Object, |
10296 | ArrayRef<Expr *> Args, |
10297 | OverloadCandidateSet &CandidateSet); |
10298 | |
10299 | /// Add all of the non-member operator function declarations in the given |
10300 | /// function set to the overload candidate set. |
10301 | void AddNonMemberOperatorCandidates( |
10302 | const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, |
10303 | OverloadCandidateSet &CandidateSet, |
10304 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); |
10305 | |
10306 | /// Add overload candidates for overloaded operators that are |
10307 | /// member functions. |
10308 | /// |
10309 | /// Add the overloaded operator candidates that are member functions |
10310 | /// for the operator Op that was used in an operator expression such |
10311 | /// as "x Op y". , Args/NumArgs provides the operator arguments, and |
10312 | /// CandidateSet will store the added overload candidates. (C++ |
10313 | /// [over.match.oper]). |
10314 | void AddMemberOperatorCandidates(OverloadedOperatorKind Op, |
10315 | SourceLocation OpLoc, ArrayRef<Expr *> Args, |
10316 | OverloadCandidateSet &CandidateSet, |
10317 | OverloadCandidateParamOrder PO = {}); |
10318 | |
10319 | /// AddBuiltinCandidate - Add a candidate for a built-in |
10320 | /// operator. ResultTy and ParamTys are the result and parameter types |
10321 | /// of the built-in candidate, respectively. Args and NumArgs are the |
10322 | /// arguments being passed to the candidate. IsAssignmentOperator |
10323 | /// should be true when this built-in candidate is an assignment |
10324 | /// operator. NumContextualBoolArguments is the number of arguments |
10325 | /// (at the beginning of the argument list) that will be contextually |
10326 | /// converted to bool. |
10327 | void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, |
10328 | OverloadCandidateSet &CandidateSet, |
10329 | bool IsAssignmentOperator = false, |
10330 | unsigned NumContextualBoolArguments = 0); |
10331 | |
10332 | /// AddBuiltinOperatorCandidates - Add the appropriate built-in |
10333 | /// operator overloads to the candidate set (C++ [over.built]), based |
10334 | /// on the operator @p Op and the arguments given. For example, if the |
10335 | /// operator is a binary '+', this routine might add "int |
10336 | /// operator+(int, int)" to cover integer addition. |
10337 | void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, |
10338 | SourceLocation OpLoc, ArrayRef<Expr *> Args, |
10339 | OverloadCandidateSet &CandidateSet); |
10340 | |
10341 | /// Add function candidates found via argument-dependent lookup |
10342 | /// to the set of overloading candidates. |
10343 | /// |
10344 | /// This routine performs argument-dependent name lookup based on the |
10345 | /// given function name (which may also be an operator name) and adds |
10346 | /// all of the overload candidates found by ADL to the overload |
10347 | /// candidate set (C++ [basic.lookup.argdep]). |
10348 | void AddArgumentDependentLookupCandidates( |
10349 | DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, |
10350 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
10351 | OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); |
10352 | |
10353 | /// Check the enable_if expressions on the given function. Returns the first |
10354 | /// failing attribute, or NULL if they were all successful. |
10355 | EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, |
10356 | ArrayRef<Expr *> Args, |
10357 | bool MissingImplicitThis = false); |
10358 | |
10359 | /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any |
10360 | /// non-ArgDependent DiagnoseIfAttrs. |
10361 | /// |
10362 | /// Argument-dependent diagnose_if attributes should be checked each time a |
10363 | /// function is used as a direct callee of a function call. |
10364 | /// |
10365 | /// Returns true if any errors were emitted. |
10366 | bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, |
10367 | const Expr *ThisArg, |
10368 | ArrayRef<const Expr *> Args, |
10369 | SourceLocation Loc); |
10370 | |
10371 | /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any |
10372 | /// ArgDependent DiagnoseIfAttrs. |
10373 | /// |
10374 | /// Argument-independent diagnose_if attributes should be checked on every use |
10375 | /// of a function. |
10376 | /// |
10377 | /// Returns true if any errors were emitted. |
10378 | bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, |
10379 | SourceLocation Loc); |
10380 | |
10381 | /// Determine if \p A and \p B are equivalent internal linkage declarations |
10382 | /// from different modules, and thus an ambiguity error can be downgraded to |
10383 | /// an extension warning. |
10384 | bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, |
10385 | const NamedDecl *B); |
10386 | void diagnoseEquivalentInternalLinkageDeclarations( |
10387 | SourceLocation Loc, const NamedDecl *D, |
10388 | ArrayRef<const NamedDecl *> Equiv); |
10389 | |
10390 | // Emit as a 'note' the specific overload candidate |
10391 | void NoteOverloadCandidate( |
10392 | const NamedDecl *Found, const FunctionDecl *Fn, |
10393 | OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), |
10394 | QualType DestType = QualType(), bool TakingAddress = false); |
10395 | |
10396 | // Emit as a series of 'note's all template and non-templates identified by |
10397 | // the expression Expr |
10398 | void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), |
10399 | bool TakingAddress = false); |
10400 | |
10401 | /// Returns whether the given function's address can be taken or not, |
10402 | /// optionally emitting a diagnostic if the address can't be taken. |
10403 | /// |
10404 | /// Returns false if taking the address of the function is illegal. |
10405 | bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, |
10406 | bool Complain = false, |
10407 | SourceLocation Loc = SourceLocation()); |
10408 | |
10409 | // [PossiblyAFunctionType] --> [Return] |
10410 | // NonFunctionType --> NonFunctionType |
10411 | // R (A) --> R(A) |
10412 | // R (*)(A) --> R (A) |
10413 | // R (&)(A) --> R (A) |
10414 | // R (S::*)(A) --> R (A) |
10415 | QualType (QualType PossiblyAFunctionType); |
10416 | |
10417 | /// ResolveAddressOfOverloadedFunction - Try to resolve the address of |
10418 | /// an overloaded function (C++ [over.over]), where @p From is an |
10419 | /// expression with overloaded function type and @p ToType is the type |
10420 | /// we're trying to resolve to. For example: |
10421 | /// |
10422 | /// @code |
10423 | /// int f(double); |
10424 | /// int f(int); |
10425 | /// |
10426 | /// int (*pfd)(double) = f; // selects f(double) |
10427 | /// @endcode |
10428 | /// |
10429 | /// This routine returns the resulting FunctionDecl if it could be |
10430 | /// resolved, and NULL otherwise. When @p Complain is true, this |
10431 | /// routine will emit diagnostics if there is an error. |
10432 | FunctionDecl * |
10433 | ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, |
10434 | bool Complain, DeclAccessPair &Found, |
10435 | bool *pHadMultipleCandidates = nullptr); |
10436 | |
10437 | /// Given an expression that refers to an overloaded function, try to |
10438 | /// resolve that function to a single function that can have its address |
10439 | /// taken. This will modify `Pair` iff it returns non-null. |
10440 | /// |
10441 | /// This routine can only succeed if from all of the candidates in the |
10442 | /// overload set for SrcExpr that can have their addresses taken, there is one |
10443 | /// candidate that is more constrained than the rest. |
10444 | FunctionDecl * |
10445 | resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); |
10446 | |
10447 | /// Given an overloaded function, tries to turn it into a non-overloaded |
10448 | /// function reference using resolveAddressOfSingleOverloadCandidate. This |
10449 | /// will perform access checks, diagnose the use of the resultant decl, and, |
10450 | /// if requested, potentially perform a function-to-pointer decay. |
10451 | /// |
10452 | /// Returns false if resolveAddressOfSingleOverloadCandidate fails. |
10453 | /// Otherwise, returns true. This may emit diagnostics and return true. |
10454 | bool resolveAndFixAddressOfSingleOverloadCandidate( |
10455 | ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); |
10456 | |
10457 | /// Given an expression that refers to an overloaded function, try to |
10458 | /// resolve that overloaded function expression down to a single function. |
10459 | /// |
10460 | /// This routine can only resolve template-ids that refer to a single function |
10461 | /// template, where that template-id refers to a single template whose |
10462 | /// template arguments are either provided by the template-id or have |
10463 | /// defaults, as described in C++0x [temp.arg.explicit]p3. |
10464 | /// |
10465 | /// If no template-ids are found, no diagnostics are emitted and NULL is |
10466 | /// returned. |
10467 | FunctionDecl *ResolveSingleFunctionTemplateSpecialization( |
10468 | OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr, |
10469 | TemplateSpecCandidateSet *FailedTSC = nullptr); |
10470 | |
10471 | // Resolve and fix an overloaded expression that can be resolved |
10472 | // because it identifies a single function template specialization. |
10473 | // |
10474 | // Last three arguments should only be supplied if Complain = true |
10475 | // |
10476 | // Return true if it was logically possible to so resolve the |
10477 | // expression, regardless of whether or not it succeeded. Always |
10478 | // returns true if 'complain' is set. |
10479 | bool ResolveAndFixSingleFunctionTemplateSpecialization( |
10480 | ExprResult &SrcExpr, bool DoFunctionPointerConversion = false, |
10481 | bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), |
10482 | QualType DestTypeForComplaining = QualType(), |
10483 | unsigned DiagIDForComplaining = 0); |
10484 | |
10485 | /// Add the overload candidates named by callee and/or found by argument |
10486 | /// dependent lookup to the given overload set. |
10487 | void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, |
10488 | ArrayRef<Expr *> Args, |
10489 | OverloadCandidateSet &CandidateSet, |
10490 | bool PartialOverloading = false); |
10491 | |
10492 | /// Add the call candidates from the given set of lookup results to the given |
10493 | /// overload set. Non-function lookup results are ignored. |
10494 | void AddOverloadedCallCandidates( |
10495 | LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, |
10496 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); |
10497 | |
10498 | // An enum used to represent the different possible results of building a |
10499 | // range-based for loop. |
10500 | enum ForRangeStatus { |
10501 | FRS_Success, |
10502 | FRS_NoViableFunction, |
10503 | FRS_DiagnosticIssued |
10504 | }; |
10505 | |
10506 | /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the |
10507 | /// given LookupResult is non-empty, it is assumed to describe a member which |
10508 | /// will be invoked. Otherwise, the function will be found via argument |
10509 | /// dependent lookup. |
10510 | /// CallExpr is set to a valid expression and FRS_Success returned on success, |
10511 | /// otherwise CallExpr is set to ExprError() and some non-success value |
10512 | /// is returned. |
10513 | ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, |
10514 | SourceLocation RangeLoc, |
10515 | const DeclarationNameInfo &NameInfo, |
10516 | LookupResult &MemberLookup, |
10517 | OverloadCandidateSet *CandidateSet, |
10518 | Expr *Range, ExprResult *CallExpr); |
10519 | |
10520 | /// BuildOverloadedCallExpr - Given the call expression that calls Fn |
10521 | /// (which eventually refers to the declaration Func) and the call |
10522 | /// arguments Args/NumArgs, attempt to resolve the function call down |
10523 | /// to a specific function. If overload resolution succeeds, returns |
10524 | /// the call expression produced by overload resolution. |
10525 | /// Otherwise, emits diagnostics and returns ExprError. |
10526 | ExprResult BuildOverloadedCallExpr( |
10527 | Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, |
10528 | MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, |
10529 | bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false); |
10530 | |
10531 | /// Constructs and populates an OverloadedCandidateSet from |
10532 | /// the given function. |
10533 | /// \returns true when an the ExprResult output parameter has been set. |
10534 | bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, |
10535 | MultiExprArg Args, SourceLocation RParenLoc, |
10536 | OverloadCandidateSet *CandidateSet, |
10537 | ExprResult *Result); |
10538 | |
10539 | ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, |
10540 | NestedNameSpecifierLoc NNSLoc, |
10541 | DeclarationNameInfo DNI, |
10542 | const UnresolvedSetImpl &Fns, |
10543 | bool PerformADL = true); |
10544 | |
10545 | /// Create a unary operation that may resolve to an overloaded |
10546 | /// operator. |
10547 | /// |
10548 | /// \param OpLoc The location of the operator itself (e.g., '*'). |
10549 | /// |
10550 | /// \param Opc The UnaryOperatorKind that describes this operator. |
10551 | /// |
10552 | /// \param Fns The set of non-member functions that will be |
10553 | /// considered by overload resolution. The caller needs to build this |
10554 | /// set based on the context using, e.g., |
10555 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This |
10556 | /// set should not contain any member functions; those will be added |
10557 | /// by CreateOverloadedUnaryOp(). |
10558 | /// |
10559 | /// \param Input The input argument. |
10560 | ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, |
10561 | UnaryOperatorKind Opc, |
10562 | const UnresolvedSetImpl &Fns, Expr *input, |
10563 | bool RequiresADL = true); |
10564 | |
10565 | /// Perform lookup for an overloaded binary operator. |
10566 | void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, |
10567 | OverloadedOperatorKind Op, |
10568 | const UnresolvedSetImpl &Fns, |
10569 | ArrayRef<Expr *> Args, bool RequiresADL = true); |
10570 | |
10571 | /// Create a binary operation that may resolve to an overloaded |
10572 | /// operator. |
10573 | /// |
10574 | /// \param OpLoc The location of the operator itself (e.g., '+'). |
10575 | /// |
10576 | /// \param Opc The BinaryOperatorKind that describes this operator. |
10577 | /// |
10578 | /// \param Fns The set of non-member functions that will be |
10579 | /// considered by overload resolution. The caller needs to build this |
10580 | /// set based on the context using, e.g., |
10581 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This |
10582 | /// set should not contain any member functions; those will be added |
10583 | /// by CreateOverloadedBinOp(). |
10584 | /// |
10585 | /// \param LHS Left-hand argument. |
10586 | /// \param RHS Right-hand argument. |
10587 | /// \param PerformADL Whether to consider operator candidates found by ADL. |
10588 | /// \param AllowRewrittenCandidates Whether to consider candidates found by |
10589 | /// C++20 operator rewrites. |
10590 | /// \param DefaultedFn If we are synthesizing a defaulted operator function, |
10591 | /// the function in question. Such a function is never a candidate in |
10592 | /// our overload resolution. This also enables synthesizing a three-way |
10593 | /// comparison from < and == as described in C++20 [class.spaceship]p1. |
10594 | ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, |
10595 | const UnresolvedSetImpl &Fns, Expr *LHS, |
10596 | Expr *RHS, bool RequiresADL = true, |
10597 | bool AllowRewrittenCandidates = true, |
10598 | FunctionDecl *DefaultedFn = nullptr); |
10599 | ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, |
10600 | const UnresolvedSetImpl &Fns, |
10601 | Expr *LHS, Expr *RHS, |
10602 | FunctionDecl *DefaultedFn); |
10603 | |
10604 | ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, |
10605 | SourceLocation RLoc, Expr *Base, |
10606 | MultiExprArg Args); |
10607 | |
10608 | /// BuildCallToMemberFunction - Build a call to a member |
10609 | /// function. MemExpr is the expression that refers to the member |
10610 | /// function (and includes the object parameter), Args/NumArgs are the |
10611 | /// arguments to the function call (not including the object |
10612 | /// parameter). The caller needs to validate that the member |
10613 | /// expression refers to a non-static member function or an overloaded |
10614 | /// member function. |
10615 | ExprResult BuildCallToMemberFunction( |
10616 | Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, |
10617 | SourceLocation RParenLoc, Expr *ExecConfig = nullptr, |
10618 | bool IsExecConfig = false, bool AllowRecovery = false); |
10619 | |
10620 | /// BuildCallToObjectOfClassType - Build a call to an object of class |
10621 | /// type (C++ [over.call.object]), which can end up invoking an |
10622 | /// overloaded function call operator (@c operator()) or performing a |
10623 | /// user-defined conversion on the object argument. |
10624 | ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, |
10625 | SourceLocation LParenLoc, |
10626 | MultiExprArg Args, |
10627 | SourceLocation RParenLoc); |
10628 | |
10629 | /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> |
10630 | /// (if one exists), where @c Base is an expression of class type and |
10631 | /// @c Member is the name of the member we're trying to find. |
10632 | ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, |
10633 | SourceLocation OpLoc, |
10634 | bool *NoArrowOperatorFound = nullptr); |
10635 | |
10636 | ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, |
10637 | CXXConversionDecl *Method, |
10638 | bool HadMultipleCandidates); |
10639 | |
10640 | /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call |
10641 | /// to a literal operator described by the provided lookup results. |
10642 | ExprResult BuildLiteralOperatorCall( |
10643 | LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, |
10644 | SourceLocation LitEndLoc, |
10645 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); |
10646 | |
10647 | /// FixOverloadedFunctionReference - E is an expression that refers to |
10648 | /// a C++ overloaded function (possibly with some parentheses and |
10649 | /// perhaps a '&' around it). We have resolved the overloaded function |
10650 | /// to the function declaration Fn, so patch up the expression E to |
10651 | /// refer (possibly indirectly) to Fn. Returns the new expr. |
10652 | ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, |
10653 | FunctionDecl *Fn); |
10654 | ExprResult FixOverloadedFunctionReference(ExprResult, |
10655 | DeclAccessPair FoundDecl, |
10656 | FunctionDecl *Fn); |
10657 | |
10658 | /// - Returns a selector which best matches given argument list or |
10659 | /// nullptr if none could be found |
10660 | ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, |
10661 | bool IsInstance, |
10662 | SmallVectorImpl<ObjCMethodDecl *> &Methods); |
10663 | |
10664 | ///@} |
10665 | |
10666 | // |
10667 | // |
10668 | // ------------------------------------------------------------------------- |
10669 | // |
10670 | // |
10671 | |
10672 | /// \name Statements |
10673 | /// Implementations are in SemaStmt.cpp |
10674 | ///@{ |
10675 | |
10676 | public: |
10677 | /// Stack of active SEH __finally scopes. Can be empty. |
10678 | SmallVector<Scope *, 2> CurrentSEHFinally; |
10679 | |
10680 | StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); |
10681 | StmtResult ActOnExprStmtError(); |
10682 | |
10683 | StmtResult ActOnNullStmt(SourceLocation SemiLoc, |
10684 | bool HasLeadingEmptyMacro = false); |
10685 | |
10686 | StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, |
10687 | SourceLocation EndLoc); |
10688 | void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); |
10689 | |
10690 | /// DiagnoseDiscardedExprMarkedNodiscard - Given an expression that is |
10691 | /// semantically a discarded-value expression, diagnose if any [[nodiscard]] |
10692 | /// value has been discarded. |
10693 | void DiagnoseDiscardedExprMarkedNodiscard(const Expr *E); |
10694 | |
10695 | /// DiagnoseUnusedExprResult - If the statement passed in is an expression |
10696 | /// whose result is unused, warn. |
10697 | void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID); |
10698 | |
10699 | void ActOnStartOfCompoundStmt(bool IsStmtExpr); |
10700 | void ActOnAfterCompoundStatementLeadingPragmas(); |
10701 | void ActOnFinishOfCompoundStmt(); |
10702 | StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, |
10703 | ArrayRef<Stmt *> Elts, bool isStmtExpr); |
10704 | |
10705 | sema::CompoundScopeInfo &getCurCompoundScope() const; |
10706 | |
10707 | ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); |
10708 | StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, |
10709 | SourceLocation DotDotDotLoc, ExprResult RHS, |
10710 | SourceLocation ColonLoc); |
10711 | |
10712 | /// ActOnCaseStmtBody - This installs a statement as the body of a case. |
10713 | void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); |
10714 | |
10715 | StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, |
10716 | SourceLocation ColonLoc, Stmt *SubStmt, |
10717 | Scope *CurScope); |
10718 | StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, |
10719 | SourceLocation ColonLoc, Stmt *SubStmt); |
10720 | |
10721 | StmtResult BuildAttributedStmt(SourceLocation AttrsLoc, |
10722 | ArrayRef<const Attr *> Attrs, Stmt *SubStmt); |
10723 | StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList, |
10724 | Stmt *SubStmt); |
10725 | |
10726 | /// Check whether the given statement can have musttail applied to it, |
10727 | /// issuing a diagnostic and returning false if not. In the success case, |
10728 | /// the statement is rewritten to remove implicit nodes from the return |
10729 | /// value. |
10730 | bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA); |
10731 | |
10732 | StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, |
10733 | SourceLocation LParenLoc, Stmt *InitStmt, |
10734 | ConditionResult Cond, SourceLocation RParenLoc, |
10735 | Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); |
10736 | StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, |
10737 | SourceLocation LParenLoc, Stmt *InitStmt, |
10738 | ConditionResult Cond, SourceLocation RParenLoc, |
10739 | Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); |
10740 | |
10741 | ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); |
10742 | |
10743 | StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, |
10744 | SourceLocation LParenLoc, Stmt *InitStmt, |
10745 | ConditionResult Cond, |
10746 | SourceLocation RParenLoc); |
10747 | StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, |
10748 | Stmt *Body); |
10749 | |
10750 | /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant |
10751 | /// integer not in the range of enum values. |
10752 | void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, |
10753 | Expr *SrcExpr); |
10754 | |
10755 | StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, |
10756 | ConditionResult Cond, SourceLocation RParenLoc, |
10757 | Stmt *Body); |
10758 | StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, |
10759 | SourceLocation WhileLoc, SourceLocation CondLParen, |
10760 | Expr *Cond, SourceLocation CondRParen); |
10761 | |
10762 | StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, |
10763 | Stmt *First, ConditionResult Second, |
10764 | FullExprArg Third, SourceLocation RParenLoc, |
10765 | Stmt *Body); |
10766 | |
10767 | /// In an Objective C collection iteration statement: |
10768 | /// for (x in y) |
10769 | /// x can be an arbitrary l-value expression. Bind it up as a |
10770 | /// full-expression. |
10771 | StmtResult ActOnForEachLValueExpr(Expr *E); |
10772 | |
10773 | enum BuildForRangeKind { |
10774 | /// Initial building of a for-range statement. |
10775 | BFRK_Build, |
10776 | /// Instantiation or recovery rebuild of a for-range statement. Don't |
10777 | /// attempt any typo-correction. |
10778 | BFRK_Rebuild, |
10779 | /// Determining whether a for-range statement could be built. Avoid any |
10780 | /// unnecessary or irreversible actions. |
10781 | BFRK_Check |
10782 | }; |
10783 | |
10784 | /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement. |
10785 | /// |
10786 | /// C++11 [stmt.ranged]: |
10787 | /// A range-based for statement is equivalent to |
10788 | /// |
10789 | /// { |
10790 | /// auto && __range = range-init; |
10791 | /// for ( auto __begin = begin-expr, |
10792 | /// __end = end-expr; |
10793 | /// __begin != __end; |
10794 | /// ++__begin ) { |
10795 | /// for-range-declaration = *__begin; |
10796 | /// statement |
10797 | /// } |
10798 | /// } |
10799 | /// |
10800 | /// The body of the loop is not available yet, since it cannot be analysed |
10801 | /// until we have determined the type of the for-range-declaration. |
10802 | StmtResult ActOnCXXForRangeStmt( |
10803 | Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, |
10804 | Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, |
10805 | SourceLocation RParenLoc, BuildForRangeKind Kind, |
10806 | ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {}); |
10807 | |
10808 | /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement. |
10809 | StmtResult BuildCXXForRangeStmt( |
10810 | SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, |
10811 | SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, |
10812 | Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, |
10813 | BuildForRangeKind Kind, |
10814 | ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {}); |
10815 | |
10816 | /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. |
10817 | /// This is a separate step from ActOnCXXForRangeStmt because analysis of the |
10818 | /// body cannot be performed until after the type of the range variable is |
10819 | /// determined. |
10820 | StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); |
10821 | |
10822 | StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, |
10823 | LabelDecl *TheDecl); |
10824 | StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, |
10825 | SourceLocation StarLoc, Expr *DestExp); |
10826 | StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); |
10827 | StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); |
10828 | |
10829 | struct NamedReturnInfo { |
10830 | const VarDecl *Candidate; |
10831 | |
10832 | enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable }; |
10833 | Status S; |
10834 | |
10835 | bool isMoveEligible() const { return S != None; }; |
10836 | bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; } |
10837 | }; |
10838 | enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn }; |
10839 | |
10840 | /// Determine whether the given expression might be move-eligible or |
10841 | /// copy-elidable in either a (co_)return statement or throw expression, |
10842 | /// without considering function return type, if applicable. |
10843 | /// |
10844 | /// \param E The expression being returned from the function or block, |
10845 | /// being thrown, or being co_returned from a coroutine. This expression |
10846 | /// might be modified by the implementation. |
10847 | /// |
10848 | /// \param Mode Overrides detection of current language mode |
10849 | /// and uses the rules for C++23. |
10850 | /// |
10851 | /// \returns An aggregate which contains the Candidate and isMoveEligible |
10852 | /// and isCopyElidable methods. If Candidate is non-null, it means |
10853 | /// isMoveEligible() would be true under the most permissive language |
10854 | /// standard. |
10855 | NamedReturnInfo getNamedReturnInfo( |
10856 | Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal); |
10857 | |
10858 | /// Determine whether the given NRVO candidate variable is move-eligible or |
10859 | /// copy-elidable, without considering function return type. |
10860 | /// |
10861 | /// \param VD The NRVO candidate variable. |
10862 | /// |
10863 | /// \returns An aggregate which contains the Candidate and isMoveEligible |
10864 | /// and isCopyElidable methods. If Candidate is non-null, it means |
10865 | /// isMoveEligible() would be true under the most permissive language |
10866 | /// standard. |
10867 | NamedReturnInfo getNamedReturnInfo(const VarDecl *VD); |
10868 | |
10869 | /// Updates given NamedReturnInfo's move-eligible and |
10870 | /// copy-elidable statuses, considering the function |
10871 | /// return type criteria as applicable to return statements. |
10872 | /// |
10873 | /// \param Info The NamedReturnInfo object to update. |
10874 | /// |
10875 | /// \param ReturnType This is the return type of the function. |
10876 | /// \returns The copy elision candidate, in case the initial return expression |
10877 | /// was copy elidable, or nullptr otherwise. |
10878 | const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info, |
10879 | QualType ReturnType); |
10880 | |
10881 | /// Perform the initialization of a potentially-movable value, which |
10882 | /// is the result of return value. |
10883 | /// |
10884 | /// This routine implements C++20 [class.copy.elision]p3, which attempts to |
10885 | /// treat returned lvalues as rvalues in certain cases (to prefer move |
10886 | /// construction), then falls back to treating them as lvalues if that failed. |
10887 | ExprResult |
10888 | PerformMoveOrCopyInitialization(const InitializedEntity &Entity, |
10889 | const NamedReturnInfo &NRInfo, Expr *Value, |
10890 | bool SupressSimplerImplicitMoves = false); |
10891 | |
10892 | TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; |
10893 | |
10894 | /// Deduce the return type for a function from a returned expression, per |
10895 | /// C++1y [dcl.spec.auto]p6. |
10896 | bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, |
10897 | SourceLocation ReturnLoc, Expr *RetExpr, |
10898 | const AutoType *AT); |
10899 | |
10900 | StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, |
10901 | Scope *CurScope); |
10902 | StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, |
10903 | bool AllowRecovery = false); |
10904 | |
10905 | /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements |
10906 | /// for capturing scopes. |
10907 | StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, |
10908 | NamedReturnInfo &NRInfo, |
10909 | bool SupressSimplerImplicitMoves); |
10910 | |
10911 | /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block |
10912 | /// and creates a proper catch handler from them. |
10913 | StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, |
10914 | Stmt *HandlerBlock); |
10915 | |
10916 | /// ActOnCXXTryBlock - Takes a try compound-statement and a number of |
10917 | /// handlers and creates a try statement from them. |
10918 | StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, |
10919 | ArrayRef<Stmt *> Handlers); |
10920 | |
10921 | StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? |
10922 | SourceLocation TryLoc, Stmt *TryBlock, |
10923 | Stmt *Handler); |
10924 | StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, |
10925 | Stmt *Block); |
10926 | void ActOnStartSEHFinallyBlock(); |
10927 | void ActOnAbortSEHFinallyBlock(); |
10928 | StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); |
10929 | StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); |
10930 | |
10931 | StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, |
10932 | bool IsIfExists, |
10933 | NestedNameSpecifierLoc QualifierLoc, |
10934 | DeclarationNameInfo NameInfo, |
10935 | Stmt *Nested); |
10936 | StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, |
10937 | bool IsIfExists, CXXScopeSpec &SS, |
10938 | UnqualifiedId &Name, Stmt *Nested); |
10939 | |
10940 | void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, |
10941 | CapturedRegionKind Kind, unsigned NumParams); |
10942 | typedef std::pair<StringRef, QualType> CapturedParamNameType; |
10943 | void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, |
10944 | CapturedRegionKind Kind, |
10945 | ArrayRef<CapturedParamNameType> Params, |
10946 | unsigned OpenMPCaptureLevel = 0); |
10947 | StmtResult ActOnCapturedRegionEnd(Stmt *S); |
10948 | void ActOnCapturedRegionError(); |
10949 | RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, |
10950 | SourceLocation Loc, |
10951 | unsigned NumParams); |
10952 | |
10953 | private: |
10954 | /// Check whether the given statement can have musttail applied to it, |
10955 | /// issuing a diagnostic and returning false if not. |
10956 | bool checkMustTailAttr(const Stmt *St, const Attr &MTA); |
10957 | |
10958 | /// Check if the given expression contains 'break' or 'continue' |
10959 | /// statement that produces control flow different from GCC. |
10960 | void CheckBreakContinueBinding(Expr *E); |
10961 | |
10962 | ///@} |
10963 | |
10964 | // |
10965 | // |
10966 | // ------------------------------------------------------------------------- |
10967 | // |
10968 | // |
10969 | |
10970 | /// \name `inline asm` Statement |
10971 | /// Implementations are in SemaStmtAsm.cpp |
10972 | ///@{ |
10973 | |
10974 | public: |
10975 | StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, |
10976 | bool IsVolatile, unsigned NumOutputs, |
10977 | unsigned NumInputs, IdentifierInfo **Names, |
10978 | MultiExprArg Constraints, MultiExprArg Exprs, |
10979 | Expr *AsmString, MultiExprArg Clobbers, |
10980 | unsigned NumLabels, SourceLocation RParenLoc); |
10981 | |
10982 | void FillInlineAsmIdentifierInfo(Expr *Res, |
10983 | llvm::InlineAsmIdentifierInfo &Info); |
10984 | ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, |
10985 | SourceLocation TemplateKWLoc, |
10986 | UnqualifiedId &Id, |
10987 | bool IsUnevaluatedContext); |
10988 | bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, |
10989 | SourceLocation AsmLoc); |
10990 | ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, |
10991 | SourceLocation AsmLoc); |
10992 | StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, |
10993 | ArrayRef<Token> AsmToks, StringRef AsmString, |
10994 | unsigned NumOutputs, unsigned NumInputs, |
10995 | ArrayRef<StringRef> Constraints, |
10996 | ArrayRef<StringRef> Clobbers, |
10997 | ArrayRef<Expr *> Exprs, SourceLocation EndLoc); |
10998 | LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, |
10999 | SourceLocation Location, bool AlwaysCreate); |
11000 | |
11001 | ///@} |
11002 | |
11003 | // |
11004 | // |
11005 | // ------------------------------------------------------------------------- |
11006 | // |
11007 | // |
11008 | |
11009 | /// \name Statement Attribute Handling |
11010 | /// Implementations are in SemaStmtAttr.cpp |
11011 | ///@{ |
11012 | |
11013 | public: |
11014 | bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, |
11015 | const AttributeCommonInfo &A); |
11016 | bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, |
11017 | const AttributeCommonInfo &A); |
11018 | |
11019 | CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E); |
11020 | bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs); |
11021 | |
11022 | /// Process the attributes before creating an attributed statement. Returns |
11023 | /// the semantic attributes that have been processed. |
11024 | void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs, |
11025 | SmallVectorImpl<const Attr *> &OutAttrs); |
11026 | |
11027 | ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A, |
11028 | SourceRange Range); |
11029 | ExprResult BuildCXXAssumeExpr(Expr *Assumption, |
11030 | const IdentifierInfo *AttrName, |
11031 | SourceRange Range); |
11032 | |
11033 | ///@} |
11034 | |
11035 | // |
11036 | // |
11037 | // ------------------------------------------------------------------------- |
11038 | // |
11039 | // |
11040 | |
11041 | /// \name C++ Templates |
11042 | /// Implementations are in SemaTemplate.cpp |
11043 | ///@{ |
11044 | |
11045 | public: |
11046 | // Saves the current floating-point pragma stack and clear it in this Sema. |
11047 | class FpPragmaStackSaveRAII { |
11048 | public: |
11049 | FpPragmaStackSaveRAII(Sema &S) |
11050 | : S(S), SavedStack(std::move(S.FpPragmaStack)) { |
11051 | S.FpPragmaStack.Stack.clear(); |
11052 | } |
11053 | ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); } |
11054 | |
11055 | private: |
11056 | Sema &S; |
11057 | PragmaStack<FPOptionsOverride> SavedStack; |
11058 | }; |
11059 | |
11060 | void resetFPOptions(FPOptions FPO) { |
11061 | CurFPFeatures = FPO; |
11062 | FpPragmaStack.CurrentValue = FPO.getChangesFrom(Base: FPOptions(LangOpts)); |
11063 | } |
11064 | |
11065 | ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { |
11066 | return llvm::ArrayRef(InventedParameterInfos.begin() + |
11067 | InventedParameterInfosStart, |
11068 | InventedParameterInfos.end()); |
11069 | } |
11070 | |
11071 | /// The number of SFINAE diagnostics that have been trapped. |
11072 | unsigned NumSFINAEErrors; |
11073 | |
11074 | ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const { |
11075 | return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart, |
11076 | FunctionScopes.end()); |
11077 | } |
11078 | |
11079 | typedef llvm::MapVector<const FunctionDecl *, |
11080 | std::unique_ptr<LateParsedTemplate>> |
11081 | LateParsedTemplateMapT; |
11082 | LateParsedTemplateMapT LateParsedTemplateMap; |
11083 | |
11084 | /// Determine the number of levels of enclosing template parameters. This is |
11085 | /// only usable while parsing. Note that this does not include dependent |
11086 | /// contexts in which no template parameters have yet been declared, such as |
11087 | /// in a terse function template or generic lambda before the first 'auto' is |
11088 | /// encountered. |
11089 | unsigned getTemplateDepth(Scope *S) const; |
11090 | |
11091 | void FilterAcceptableTemplateNames(LookupResult &R, |
11092 | bool AllowFunctionTemplates = true, |
11093 | bool AllowDependent = true); |
11094 | bool hasAnyAcceptableTemplateNames(LookupResult &R, |
11095 | bool AllowFunctionTemplates = true, |
11096 | bool AllowDependent = true, |
11097 | bool AllowNonTemplateFunctions = false); |
11098 | /// Try to interpret the lookup result D as a template-name. |
11099 | /// |
11100 | /// \param D A declaration found by name lookup. |
11101 | /// \param AllowFunctionTemplates Whether function templates should be |
11102 | /// considered valid results. |
11103 | /// \param AllowDependent Whether unresolved using declarations (that might |
11104 | /// name templates) should be considered valid results. |
11105 | static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, |
11106 | bool AllowFunctionTemplates = true, |
11107 | bool AllowDependent = true); |
11108 | |
11109 | enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; |
11110 | /// Whether and why a template name is required in this lookup. |
11111 | class RequiredTemplateKind { |
11112 | public: |
11113 | /// Template name is required if TemplateKWLoc is valid. |
11114 | RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) |
11115 | : TemplateKW(TemplateKWLoc) {} |
11116 | /// Template name is unconditionally required. |
11117 | RequiredTemplateKind(TemplateNameIsRequiredTag) {} |
11118 | |
11119 | SourceLocation getTemplateKeywordLoc() const { |
11120 | return TemplateKW.value_or(u: SourceLocation()); |
11121 | } |
11122 | bool hasTemplateKeyword() const { |
11123 | return getTemplateKeywordLoc().isValid(); |
11124 | } |
11125 | bool isRequired() const { return TemplateKW != SourceLocation(); } |
11126 | explicit operator bool() const { return isRequired(); } |
11127 | |
11128 | private: |
11129 | std::optional<SourceLocation> TemplateKW; |
11130 | }; |
11131 | |
11132 | enum class AssumedTemplateKind { |
11133 | /// This is not assumed to be a template name. |
11134 | None, |
11135 | /// This is assumed to be a template name because lookup found nothing. |
11136 | FoundNothing, |
11137 | /// This is assumed to be a template name because lookup found one or more |
11138 | /// functions (but no function templates). |
11139 | FoundFunctions, |
11140 | }; |
11141 | |
11142 | bool |
11143 | LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, |
11144 | QualType ObjectType, bool EnteringContext, |
11145 | RequiredTemplateKind RequiredTemplate = SourceLocation(), |
11146 | AssumedTemplateKind *ATK = nullptr, |
11147 | bool AllowTypoCorrection = true); |
11148 | |
11149 | TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, |
11150 | bool hasTemplateKeyword, |
11151 | const UnqualifiedId &Name, |
11152 | ParsedType ObjectType, bool EnteringContext, |
11153 | TemplateTy &Template, |
11154 | bool &MemberOfUnknownSpecialization, |
11155 | bool Disambiguation = false); |
11156 | |
11157 | /// Try to resolve an undeclared template name as a type template. |
11158 | /// |
11159 | /// Sets II to the identifier corresponding to the template name, and updates |
11160 | /// Name to a corresponding (typo-corrected) type template name and TNK to |
11161 | /// the corresponding kind, if possible. |
11162 | void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, |
11163 | TemplateNameKind &TNK, |
11164 | SourceLocation NameLoc, |
11165 | IdentifierInfo *&II); |
11166 | |
11167 | bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, |
11168 | SourceLocation NameLoc, |
11169 | bool Diagnose = true); |
11170 | |
11171 | /// Determine whether a particular identifier might be the name in a C++1z |
11172 | /// deduction-guide declaration. |
11173 | bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, |
11174 | SourceLocation NameLoc, CXXScopeSpec &SS, |
11175 | ParsedTemplateTy *Template = nullptr); |
11176 | |
11177 | bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, |
11178 | SourceLocation IILoc, Scope *S, |
11179 | const CXXScopeSpec *SS, |
11180 | TemplateTy &SuggestedTemplate, |
11181 | TemplateNameKind &SuggestedKind); |
11182 | |
11183 | /// Determine whether we would be unable to instantiate this template (because |
11184 | /// it either has no definition, or is in the process of being instantiated). |
11185 | bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, |
11186 | NamedDecl *Instantiation, |
11187 | bool InstantiatedFromMember, |
11188 | const NamedDecl *Pattern, |
11189 | const NamedDecl *PatternDef, |
11190 | TemplateSpecializationKind TSK, |
11191 | bool Complain = true); |
11192 | |
11193 | /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining |
11194 | /// that the template parameter 'PrevDecl' is being shadowed by a new |
11195 | /// declaration at location Loc. Returns true to indicate that this is |
11196 | /// an error, and false otherwise. |
11197 | /// |
11198 | /// \param Loc The location of the declaration that shadows a template |
11199 | /// parameter. |
11200 | /// |
11201 | /// \param PrevDecl The template parameter that the declaration shadows. |
11202 | /// |
11203 | /// \param SupportedForCompatibility Whether to issue the diagnostic as |
11204 | /// a warning for compatibility with older versions of clang. |
11205 | /// Ignored when MSVC compatibility is enabled. |
11206 | void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, |
11207 | bool SupportedForCompatibility = false); |
11208 | |
11209 | /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset |
11210 | /// the parameter D to reference the templated declaration and return a |
11211 | /// pointer to the template declaration. Otherwise, do nothing to D and return |
11212 | /// null. |
11213 | TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); |
11214 | |
11215 | /// ActOnTypeParameter - Called when a C++ template type parameter |
11216 | /// (e.g., "typename T") has been parsed. Typename specifies whether |
11217 | /// the keyword "typename" was used to declare the type parameter |
11218 | /// (otherwise, "class" was used), and KeyLoc is the location of the |
11219 | /// "class" or "typename" keyword. ParamName is the name of the |
11220 | /// parameter (NULL indicates an unnamed template parameter) and |
11221 | /// ParamNameLoc is the location of the parameter name (if any). |
11222 | /// If the type parameter has a default argument, it will be added |
11223 | /// later via ActOnTypeParameterDefault. |
11224 | NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, |
11225 | SourceLocation EllipsisLoc, |
11226 | SourceLocation KeyLoc, |
11227 | IdentifierInfo *ParamName, |
11228 | SourceLocation ParamNameLoc, unsigned Depth, |
11229 | unsigned Position, SourceLocation EqualLoc, |
11230 | ParsedType DefaultArg, bool HasTypeConstraint); |
11231 | |
11232 | bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint); |
11233 | |
11234 | bool ActOnTypeConstraint(const CXXScopeSpec &SS, |
11235 | TemplateIdAnnotation *TypeConstraint, |
11236 | TemplateTypeParmDecl *ConstrainedParameter, |
11237 | SourceLocation EllipsisLoc); |
11238 | bool BuildTypeConstraint(const CXXScopeSpec &SS, |
11239 | TemplateIdAnnotation *TypeConstraint, |
11240 | TemplateTypeParmDecl *ConstrainedParameter, |
11241 | SourceLocation EllipsisLoc, |
11242 | bool AllowUnexpandedPack); |
11243 | |
11244 | /// Attach a type-constraint to a template parameter. |
11245 | /// \returns true if an error occurred. This can happen if the |
11246 | /// immediately-declared constraint could not be formed (e.g. incorrect number |
11247 | /// of arguments for the named concept). |
11248 | bool AttachTypeConstraint(NestedNameSpecifierLoc NS, |
11249 | DeclarationNameInfo NameInfo, |
11250 | ConceptDecl *NamedConcept, NamedDecl *FoundDecl, |
11251 | const TemplateArgumentListInfo *TemplateArgs, |
11252 | TemplateTypeParmDecl *ConstrainedParameter, |
11253 | QualType ConstrainedType, |
11254 | SourceLocation EllipsisLoc); |
11255 | |
11256 | bool AttachTypeConstraint(AutoTypeLoc TL, |
11257 | NonTypeTemplateParmDecl *NewConstrainedParm, |
11258 | NonTypeTemplateParmDecl *OrigConstrainedParm, |
11259 | SourceLocation EllipsisLoc); |
11260 | |
11261 | /// Require the given type to be a structural type, and diagnose if it is not. |
11262 | /// |
11263 | /// \return \c true if an error was produced. |
11264 | bool RequireStructuralType(QualType T, SourceLocation Loc); |
11265 | |
11266 | /// Check that the type of a non-type template parameter is |
11267 | /// well-formed. |
11268 | /// |
11269 | /// \returns the (possibly-promoted) parameter type if valid; |
11270 | /// otherwise, produces a diagnostic and returns a NULL type. |
11271 | QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, |
11272 | SourceLocation Loc); |
11273 | QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); |
11274 | |
11275 | NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, |
11276 | unsigned Depth, unsigned Position, |
11277 | SourceLocation EqualLoc, |
11278 | Expr *DefaultArg); |
11279 | |
11280 | /// ActOnTemplateTemplateParameter - Called when a C++ template template |
11281 | /// parameter (e.g. T in template <template \<typename> class T> class array) |
11282 | /// has been parsed. S is the current scope. |
11283 | NamedDecl *ActOnTemplateTemplateParameter( |
11284 | Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, |
11285 | bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, |
11286 | SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, |
11287 | SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); |
11288 | |
11289 | /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally |
11290 | /// constrained by RequiresClause, that contains the template parameters in |
11291 | /// Params. |
11292 | TemplateParameterList *ActOnTemplateParameterList( |
11293 | unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, |
11294 | SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, |
11295 | SourceLocation RAngleLoc, Expr *RequiresClause); |
11296 | |
11297 | /// The context in which we are checking a template parameter list. |
11298 | enum TemplateParamListContext { |
11299 | TPC_ClassTemplate, |
11300 | TPC_VarTemplate, |
11301 | TPC_FunctionTemplate, |
11302 | TPC_ClassTemplateMember, |
11303 | TPC_FriendClassTemplate, |
11304 | TPC_FriendFunctionTemplate, |
11305 | TPC_FriendFunctionTemplateDefinition, |
11306 | TPC_TypeAliasTemplate |
11307 | }; |
11308 | |
11309 | /// Checks the validity of a template parameter list, possibly |
11310 | /// considering the template parameter list from a previous |
11311 | /// declaration. |
11312 | /// |
11313 | /// If an "old" template parameter list is provided, it must be |
11314 | /// equivalent (per TemplateParameterListsAreEqual) to the "new" |
11315 | /// template parameter list. |
11316 | /// |
11317 | /// \param NewParams Template parameter list for a new template |
11318 | /// declaration. This template parameter list will be updated with any |
11319 | /// default arguments that are carried through from the previous |
11320 | /// template parameter list. |
11321 | /// |
11322 | /// \param OldParams If provided, template parameter list from a |
11323 | /// previous declaration of the same template. Default template |
11324 | /// arguments will be merged from the old template parameter list to |
11325 | /// the new template parameter list. |
11326 | /// |
11327 | /// \param TPC Describes the context in which we are checking the given |
11328 | /// template parameter list. |
11329 | /// |
11330 | /// \param SkipBody If we might have already made a prior merged definition |
11331 | /// of this template visible, the corresponding body-skipping information. |
11332 | /// Default argument redefinition is not an error when skipping such a body, |
11333 | /// because (under the ODR) we can assume the default arguments are the same |
11334 | /// as the prior merged definition. |
11335 | /// |
11336 | /// \returns true if an error occurred, false otherwise. |
11337 | bool CheckTemplateParameterList(TemplateParameterList *NewParams, |
11338 | TemplateParameterList *OldParams, |
11339 | TemplateParamListContext TPC, |
11340 | SkipBodyInfo *SkipBody = nullptr); |
11341 | |
11342 | /// Match the given template parameter lists to the given scope |
11343 | /// specifier, returning the template parameter list that applies to the |
11344 | /// name. |
11345 | /// |
11346 | /// \param DeclStartLoc the start of the declaration that has a scope |
11347 | /// specifier or a template parameter list. |
11348 | /// |
11349 | /// \param DeclLoc The location of the declaration itself. |
11350 | /// |
11351 | /// \param SS the scope specifier that will be matched to the given template |
11352 | /// parameter lists. This scope specifier precedes a qualified name that is |
11353 | /// being declared. |
11354 | /// |
11355 | /// \param TemplateId The template-id following the scope specifier, if there |
11356 | /// is one. Used to check for a missing 'template<>'. |
11357 | /// |
11358 | /// \param ParamLists the template parameter lists, from the outermost to the |
11359 | /// innermost template parameter lists. |
11360 | /// |
11361 | /// \param IsFriend Whether to apply the slightly different rules for |
11362 | /// matching template parameters to scope specifiers in friend |
11363 | /// declarations. |
11364 | /// |
11365 | /// \param IsMemberSpecialization will be set true if the scope specifier |
11366 | /// denotes a fully-specialized type, and therefore this is a declaration of |
11367 | /// a member specialization. |
11368 | /// |
11369 | /// \returns the template parameter list, if any, that corresponds to the |
11370 | /// name that is preceded by the scope specifier @p SS. This template |
11371 | /// parameter list may have template parameters (if we're declaring a |
11372 | /// template) or may have no template parameters (if we're declaring a |
11373 | /// template specialization), or may be NULL (if what we're declaring isn't |
11374 | /// itself a template). |
11375 | TemplateParameterList *MatchTemplateParametersToScopeSpecifier( |
11376 | SourceLocation DeclStartLoc, SourceLocation DeclLoc, |
11377 | const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, |
11378 | ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, |
11379 | bool &IsMemberSpecialization, bool &Invalid, |
11380 | bool SuppressDiagnostic = false); |
11381 | |
11382 | /// Returns the template parameter list with all default template argument |
11383 | /// information. |
11384 | TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD); |
11385 | |
11386 | DeclResult CheckClassTemplate( |
11387 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, |
11388 | CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, |
11389 | const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, |
11390 | AccessSpecifier AS, SourceLocation ModulePrivateLoc, |
11391 | SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, |
11392 | TemplateParameterList **OuterTemplateParamLists, |
11393 | SkipBodyInfo *SkipBody = nullptr); |
11394 | |
11395 | /// Translates template arguments as provided by the parser |
11396 | /// into template arguments used by semantic analysis. |
11397 | void translateTemplateArguments(const ASTTemplateArgsPtr &In, |
11398 | TemplateArgumentListInfo &Out); |
11399 | |
11400 | /// Convert a parsed type into a parsed template argument. This is mostly |
11401 | /// trivial, except that we may have parsed a C++17 deduced class template |
11402 | /// specialization type, in which case we should form a template template |
11403 | /// argument instead of a type template argument. |
11404 | ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); |
11405 | |
11406 | void NoteAllFoundTemplates(TemplateName Name); |
11407 | |
11408 | QualType CheckTemplateIdType(TemplateName Template, |
11409 | SourceLocation TemplateLoc, |
11410 | TemplateArgumentListInfo &TemplateArgs); |
11411 | |
11412 | TypeResult |
11413 | ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
11414 | TemplateTy Template, const IdentifierInfo *TemplateII, |
11415 | SourceLocation TemplateIILoc, SourceLocation LAngleLoc, |
11416 | ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, |
11417 | bool IsCtorOrDtorName = false, bool IsClassName = false, |
11418 | ImplicitTypenameContext AllowImplicitTypename = |
11419 | ImplicitTypenameContext::No); |
11420 | |
11421 | /// Parsed an elaborated-type-specifier that refers to a template-id, |
11422 | /// such as \c class T::template apply<U>. |
11423 | TypeResult ActOnTagTemplateIdType( |
11424 | TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, |
11425 | CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, |
11426 | SourceLocation TemplateLoc, SourceLocation LAngleLoc, |
11427 | ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); |
11428 | |
11429 | DeclResult ActOnVarTemplateSpecialization( |
11430 | Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, |
11431 | SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, |
11432 | StorageClass SC, bool IsPartialSpecialization); |
11433 | |
11434 | /// Get the specialization of the given variable template corresponding to |
11435 | /// the specified argument list, or a null-but-valid result if the arguments |
11436 | /// are dependent. |
11437 | DeclResult CheckVarTemplateId(VarTemplateDecl *Template, |
11438 | SourceLocation TemplateLoc, |
11439 | SourceLocation TemplateNameLoc, |
11440 | const TemplateArgumentListInfo &TemplateArgs); |
11441 | |
11442 | /// Form a reference to the specialization of the given variable template |
11443 | /// corresponding to the specified argument list, or a null-but-valid result |
11444 | /// if the arguments are dependent. |
11445 | ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, |
11446 | const DeclarationNameInfo &NameInfo, |
11447 | VarTemplateDecl *Template, NamedDecl *FoundD, |
11448 | SourceLocation TemplateLoc, |
11449 | const TemplateArgumentListInfo *TemplateArgs); |
11450 | |
11451 | ExprResult |
11452 | CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
11453 | const DeclarationNameInfo &ConceptNameInfo, |
11454 | NamedDecl *FoundDecl, ConceptDecl *NamedConcept, |
11455 | const TemplateArgumentListInfo *TemplateArgs); |
11456 | |
11457 | void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); |
11458 | void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS, |
11459 | bool TemplateKeyword, TemplateDecl *TD, |
11460 | SourceLocation Loc); |
11461 | |
11462 | ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, |
11463 | SourceLocation TemplateKWLoc, LookupResult &R, |
11464 | bool RequiresADL, |
11465 | const TemplateArgumentListInfo *TemplateArgs); |
11466 | |
11467 | // We actually only call this from template instantiation. |
11468 | ExprResult |
11469 | BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
11470 | const DeclarationNameInfo &NameInfo, |
11471 | const TemplateArgumentListInfo *TemplateArgs, |
11472 | bool IsAddressOfOperand); |
11473 | |
11474 | /// Form a template name from a name that is syntactically required to name a |
11475 | /// template, either due to use of the 'template' keyword or because a name in |
11476 | /// this syntactic context is assumed to name a template (C++ |
11477 | /// [temp.names]p2-4). |
11478 | /// |
11479 | /// This action forms a template name given the name of the template and its |
11480 | /// optional scope specifier. This is used when the 'template' keyword is used |
11481 | /// or when the parsing context unambiguously treats a following '<' as |
11482 | /// introducing a template argument list. Note that this may produce a |
11483 | /// non-dependent template name if we can perform the lookup now and identify |
11484 | /// the named template. |
11485 | /// |
11486 | /// For example, given "x.MetaFun::template apply", the scope specifier |
11487 | /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location |
11488 | /// of the "template" keyword, and "apply" is the \p Name. |
11489 | TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, |
11490 | SourceLocation TemplateKWLoc, |
11491 | const UnqualifiedId &Name, |
11492 | ParsedType ObjectType, |
11493 | bool EnteringContext, TemplateTy &Template, |
11494 | bool AllowInjectedClassName = false); |
11495 | |
11496 | DeclResult ActOnClassTemplateSpecialization( |
11497 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, |
11498 | SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, |
11499 | TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, |
11500 | MultiTemplateParamsArg TemplateParameterLists, |
11501 | SkipBodyInfo *SkipBody = nullptr); |
11502 | |
11503 | /// Check the non-type template arguments of a class template |
11504 | /// partial specialization according to C++ [temp.class.spec]p9. |
11505 | /// |
11506 | /// \param TemplateNameLoc the location of the template name. |
11507 | /// \param PrimaryTemplate the template parameters of the primary class |
11508 | /// template. |
11509 | /// \param NumExplicit the number of explicitly-specified template arguments. |
11510 | /// \param TemplateArgs the template arguments of the class template |
11511 | /// partial specialization. |
11512 | /// |
11513 | /// \returns \c true if there was an error, \c false otherwise. |
11514 | bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, |
11515 | TemplateDecl *PrimaryTemplate, |
11516 | unsigned NumExplicitArgs, |
11517 | ArrayRef<TemplateArgument> Args); |
11518 | void CheckTemplatePartialSpecialization( |
11519 | ClassTemplatePartialSpecializationDecl *Partial); |
11520 | void CheckTemplatePartialSpecialization( |
11521 | VarTemplatePartialSpecializationDecl *Partial); |
11522 | |
11523 | Decl *ActOnTemplateDeclarator(Scope *S, |
11524 | MultiTemplateParamsArg TemplateParameterLists, |
11525 | Declarator &D); |
11526 | |
11527 | /// Diagnose cases where we have an explicit template specialization |
11528 | /// before/after an explicit template instantiation, producing diagnostics |
11529 | /// for those cases where they are required and determining whether the |
11530 | /// new specialization/instantiation will have any effect. |
11531 | /// |
11532 | /// \param NewLoc the location of the new explicit specialization or |
11533 | /// instantiation. |
11534 | /// |
11535 | /// \param NewTSK the kind of the new explicit specialization or |
11536 | /// instantiation. |
11537 | /// |
11538 | /// \param PrevDecl the previous declaration of the entity. |
11539 | /// |
11540 | /// \param PrevTSK the kind of the old explicit specialization or |
11541 | /// instantiatin. |
11542 | /// |
11543 | /// \param PrevPointOfInstantiation if valid, indicates where the previous |
11544 | /// declaration was instantiated (either implicitly or explicitly). |
11545 | /// |
11546 | /// \param HasNoEffect will be set to true to indicate that the new |
11547 | /// specialization or instantiation has no effect and should be ignored. |
11548 | /// |
11549 | /// \returns true if there was an error that should prevent the introduction |
11550 | /// of the new declaration into the AST, false otherwise. |
11551 | bool CheckSpecializationInstantiationRedecl( |
11552 | SourceLocation NewLoc, |
11553 | TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, |
11554 | NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, |
11555 | SourceLocation PrevPtOfInstantiation, bool &SuppressNew); |
11556 | |
11557 | /// Perform semantic analysis for the given dependent function |
11558 | /// template specialization. |
11559 | /// |
11560 | /// The only possible way to get a dependent function template specialization |
11561 | /// is with a friend declaration, like so: |
11562 | /// |
11563 | /// \code |
11564 | /// template \<class T> void foo(T); |
11565 | /// template \<class T> class A { |
11566 | /// friend void foo<>(T); |
11567 | /// }; |
11568 | /// \endcode |
11569 | /// |
11570 | /// There really isn't any useful analysis we can do here, so we |
11571 | /// just store the information. |
11572 | bool CheckDependentFunctionTemplateSpecialization( |
11573 | FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, |
11574 | LookupResult &Previous); |
11575 | |
11576 | /// Perform semantic analysis for the given function template |
11577 | /// specialization. |
11578 | /// |
11579 | /// This routine performs all of the semantic analysis required for an |
11580 | /// explicit function template specialization. On successful completion, |
11581 | /// the function declaration \p FD will become a function template |
11582 | /// specialization. |
11583 | /// |
11584 | /// \param FD the function declaration, which will be updated to become a |
11585 | /// function template specialization. |
11586 | /// |
11587 | /// \param ExplicitTemplateArgs the explicitly-provided template arguments, |
11588 | /// if any. Note that this may be valid info even when 0 arguments are |
11589 | /// explicitly provided as in, e.g., \c void sort<>(char*, char*); |
11590 | /// as it anyway contains info on the angle brackets locations. |
11591 | /// |
11592 | /// \param Previous the set of declarations that may be specialized by |
11593 | /// this function specialization. |
11594 | /// |
11595 | /// \param QualifiedFriend whether this is a lookup for a qualified friend |
11596 | /// declaration with no explicit template argument list that might be |
11597 | /// befriending a function template specialization. |
11598 | bool CheckFunctionTemplateSpecialization( |
11599 | FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, |
11600 | LookupResult &Previous, bool QualifiedFriend = false); |
11601 | |
11602 | /// Perform semantic analysis for the given non-template member |
11603 | /// specialization. |
11604 | /// |
11605 | /// This routine performs all of the semantic analysis required for an |
11606 | /// explicit member function specialization. On successful completion, |
11607 | /// the function declaration \p FD will become a member function |
11608 | /// specialization. |
11609 | /// |
11610 | /// \param Member the member declaration, which will be updated to become a |
11611 | /// specialization. |
11612 | /// |
11613 | /// \param Previous the set of declarations, one of which may be specialized |
11614 | /// by this function specialization; the set will be modified to contain the |
11615 | /// redeclared member. |
11616 | bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); |
11617 | void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); |
11618 | |
11619 | // Explicit instantiation of a class template specialization |
11620 | DeclResult ActOnExplicitInstantiation( |
11621 | Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, |
11622 | unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, |
11623 | TemplateTy Template, SourceLocation TemplateNameLoc, |
11624 | SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, |
11625 | SourceLocation RAngleLoc, const ParsedAttributesView &Attr); |
11626 | |
11627 | // Explicit instantiation of a member class of a class template. |
11628 | DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, |
11629 | SourceLocation TemplateLoc, |
11630 | unsigned TagSpec, SourceLocation KWLoc, |
11631 | CXXScopeSpec &SS, IdentifierInfo *Name, |
11632 | SourceLocation NameLoc, |
11633 | const ParsedAttributesView &Attr); |
11634 | |
11635 | DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, |
11636 | SourceLocation TemplateLoc, |
11637 | Declarator &D); |
11638 | |
11639 | /// If the given template parameter has a default template |
11640 | /// argument, substitute into that default template argument and |
11641 | /// return the corresponding template argument. |
11642 | TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable( |
11643 | TemplateDecl *Template, SourceLocation TemplateLoc, |
11644 | SourceLocation RAngleLoc, Decl *Param, |
11645 | ArrayRef<TemplateArgument> SugaredConverted, |
11646 | ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg); |
11647 | |
11648 | /// Returns the top most location responsible for the definition of \p N. |
11649 | /// If \p N is a a template specialization, this is the location |
11650 | /// of the top of the instantiation stack. |
11651 | /// Otherwise, the location of \p N is returned. |
11652 | SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const; |
11653 | |
11654 | /// Specifies the context in which a particular template |
11655 | /// argument is being checked. |
11656 | enum CheckTemplateArgumentKind { |
11657 | /// The template argument was specified in the code or was |
11658 | /// instantiated with some deduced template arguments. |
11659 | CTAK_Specified, |
11660 | |
11661 | /// The template argument was deduced via template argument |
11662 | /// deduction. |
11663 | CTAK_Deduced, |
11664 | |
11665 | /// The template argument was deduced from an array bound |
11666 | /// via template argument deduction. |
11667 | CTAK_DeducedFromArrayBound |
11668 | }; |
11669 | |
11670 | struct CheckTemplateArgumentInfo { |
11671 | explicit CheckTemplateArgumentInfo(bool PartialOrdering = false, |
11672 | bool MatchingTTP = false) |
11673 | : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {} |
11674 | CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete; |
11675 | CheckTemplateArgumentInfo & |
11676 | operator=(const CheckTemplateArgumentInfo &) = delete; |
11677 | |
11678 | /// The checked, converted argument will be added to the |
11679 | /// end of these vectors. |
11680 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
11681 | |
11682 | /// The check is being performed in the context of partial ordering. |
11683 | bool PartialOrdering; |
11684 | |
11685 | /// If true, assume these template arguments are |
11686 | /// the injected template arguments for a template template parameter. |
11687 | /// This will relax the requirement that all its possible uses are valid: |
11688 | /// TTP checking is loose, and assumes that invalid uses will be diagnosed |
11689 | /// during instantiation. |
11690 | bool MatchingTTP; |
11691 | |
11692 | /// Is set to true when, in the context of TTP matching, a pack parameter |
11693 | /// matches non-pack arguments. |
11694 | bool StrictPackMatch = false; |
11695 | }; |
11696 | |
11697 | /// Check that the given template argument corresponds to the given |
11698 | /// template parameter. |
11699 | /// |
11700 | /// \param Param The template parameter against which the argument will be |
11701 | /// checked. |
11702 | /// |
11703 | /// \param Arg The template argument, which may be updated due to conversions. |
11704 | /// |
11705 | /// \param Template The template in which the template argument resides. |
11706 | /// |
11707 | /// \param TemplateLoc The location of the template name for the template |
11708 | /// whose argument list we're matching. |
11709 | /// |
11710 | /// \param RAngleLoc The location of the right angle bracket ('>') that closes |
11711 | /// the template argument list. |
11712 | /// |
11713 | /// \param ArgumentPackIndex The index into the argument pack where this |
11714 | /// argument will be placed. Only valid if the parameter is a parameter pack. |
11715 | /// |
11716 | /// \param CTAK Describes how we arrived at this particular template argument: |
11717 | /// explicitly written, deduced, etc. |
11718 | /// |
11719 | /// \returns true on error, false otherwise. |
11720 | bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, |
11721 | NamedDecl *Template, SourceLocation TemplateLoc, |
11722 | SourceLocation RAngleLoc, |
11723 | unsigned ArgumentPackIndex, |
11724 | CheckTemplateArgumentInfo &CTAI, |
11725 | CheckTemplateArgumentKind CTAK); |
11726 | |
11727 | /// Check that the given template arguments can be provided to |
11728 | /// the given template, converting the arguments along the way. |
11729 | /// |
11730 | /// \param Template The template to which the template arguments are being |
11731 | /// provided. |
11732 | /// |
11733 | /// \param TemplateLoc The location of the template name in the source. |
11734 | /// |
11735 | /// \param TemplateArgs The list of template arguments. If the template is |
11736 | /// a template template parameter, this function may extend the set of |
11737 | /// template arguments to also include substituted, defaulted template |
11738 | /// arguments. |
11739 | /// |
11740 | /// \param PartialTemplateArgs True if the list of template arguments is |
11741 | /// intentionally partial, e.g., because we're checking just the initial |
11742 | /// set of template arguments. |
11743 | /// |
11744 | /// \param Converted Will receive the converted, canonicalized template |
11745 | /// arguments. |
11746 | /// |
11747 | /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to |
11748 | /// contain the converted forms of the template arguments as written. |
11749 | /// Otherwise, \p TemplateArgs will not be modified. |
11750 | /// |
11751 | /// \param ConstraintsNotSatisfied If provided, and an error occurred, will |
11752 | /// receive true if the cause for the error is the associated constraints of |
11753 | /// the template not being satisfied by the template arguments. |
11754 | /// |
11755 | /// \param DefaultArgs any default arguments from template specialization |
11756 | /// deduction. |
11757 | /// |
11758 | /// \returns true if an error occurred, false otherwise. |
11759 | bool CheckTemplateArgumentList(TemplateDecl *Template, |
11760 | SourceLocation TemplateLoc, |
11761 | TemplateArgumentListInfo &TemplateArgs, |
11762 | const DefaultArguments &DefaultArgs, |
11763 | bool PartialTemplateArgs, |
11764 | CheckTemplateArgumentInfo &CTAI, |
11765 | bool UpdateArgsWithConversions = true, |
11766 | bool *ConstraintsNotSatisfied = nullptr); |
11767 | |
11768 | bool CheckTemplateTypeArgument( |
11769 | TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, |
11770 | SmallVectorImpl<TemplateArgument> &SugaredConverted, |
11771 | SmallVectorImpl<TemplateArgument> &CanonicalConverted); |
11772 | |
11773 | /// Check a template argument against its corresponding |
11774 | /// template type parameter. |
11775 | /// |
11776 | /// This routine implements the semantics of C++ [temp.arg.type]. It |
11777 | /// returns true if an error occurred, and false otherwise. |
11778 | bool CheckTemplateArgument(TypeSourceInfo *Arg); |
11779 | |
11780 | /// Check a template argument against its corresponding |
11781 | /// non-type template parameter. |
11782 | /// |
11783 | /// This routine implements the semantics of C++ [temp.arg.nontype]. |
11784 | /// If an error occurred, it returns ExprError(); otherwise, it |
11785 | /// returns the converted template argument. \p ParamType is the |
11786 | /// type of the non-type template parameter after it has been instantiated. |
11787 | ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, |
11788 | QualType InstantiatedParamType, Expr *Arg, |
11789 | TemplateArgument &SugaredConverted, |
11790 | TemplateArgument &CanonicalConverted, |
11791 | bool MatchingTTP, |
11792 | CheckTemplateArgumentKind CTAK); |
11793 | |
11794 | /// Check a template argument against its corresponding |
11795 | /// template template parameter. |
11796 | /// |
11797 | /// This routine implements the semantics of C++ [temp.arg.template]. |
11798 | /// It returns true if an error occurred, and false otherwise. |
11799 | bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, |
11800 | TemplateParameterList *Params, |
11801 | TemplateArgumentLoc &Arg, |
11802 | bool PartialOrdering, |
11803 | bool *StrictPackMatch); |
11804 | |
11805 | void NoteTemplateLocation(const NamedDecl &Decl, |
11806 | std::optional<SourceRange> ParamRange = {}); |
11807 | void NoteTemplateParameterLocation(const NamedDecl &Decl); |
11808 | |
11809 | /// Given a non-type template argument that refers to a |
11810 | /// declaration and the type of its corresponding non-type template |
11811 | /// parameter, produce an expression that properly refers to that |
11812 | /// declaration. |
11813 | /// FIXME: This is used in some contexts where the resulting expression |
11814 | /// doesn't need to live too long. It would be useful if this function |
11815 | /// could return a temporary expression. |
11816 | ExprResult BuildExpressionFromDeclTemplateArgument( |
11817 | const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, |
11818 | NamedDecl *TemplateParam = nullptr); |
11819 | ExprResult |
11820 | BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, |
11821 | SourceLocation Loc); |
11822 | |
11823 | /// Enumeration describing how template parameter lists are compared |
11824 | /// for equality. |
11825 | enum TemplateParameterListEqualKind { |
11826 | /// We are matching the template parameter lists of two templates |
11827 | /// that might be redeclarations. |
11828 | /// |
11829 | /// \code |
11830 | /// template<typename T> struct X; |
11831 | /// template<typename T> struct X; |
11832 | /// \endcode |
11833 | TPL_TemplateMatch, |
11834 | |
11835 | /// We are matching the template parameter lists of two template |
11836 | /// template parameters as part of matching the template parameter lists |
11837 | /// of two templates that might be redeclarations. |
11838 | /// |
11839 | /// \code |
11840 | /// template<template<int I> class TT> struct X; |
11841 | /// template<template<int Value> class Other> struct X; |
11842 | /// \endcode |
11843 | TPL_TemplateTemplateParmMatch, |
11844 | |
11845 | /// We are determining whether the template-parameters are equivalent |
11846 | /// according to C++ [temp.over.link]/6. This comparison does not consider |
11847 | /// constraints. |
11848 | /// |
11849 | /// \code |
11850 | /// template<C1 T> void f(T); |
11851 | /// template<C2 T> void f(T); |
11852 | /// \endcode |
11853 | TPL_TemplateParamsEquivalent, |
11854 | }; |
11855 | |
11856 | // A struct to represent the 'new' declaration, which is either itself just |
11857 | // the named decl, or the important information we need about it in order to |
11858 | // do constraint comparisons. |
11859 | class TemplateCompareNewDeclInfo { |
11860 | const NamedDecl *ND = nullptr; |
11861 | const DeclContext *DC = nullptr; |
11862 | const DeclContext *LexicalDC = nullptr; |
11863 | SourceLocation Loc; |
11864 | |
11865 | public: |
11866 | TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {} |
11867 | TemplateCompareNewDeclInfo(const DeclContext *DeclCtx, |
11868 | const DeclContext *LexicalDeclCtx, |
11869 | SourceLocation Loc) |
11870 | |
11871 | : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) { |
11872 | assert(DC && LexicalDC && |
11873 | "Constructor only for cases where we have the information to put " |
11874 | "in here" ); |
11875 | } |
11876 | |
11877 | // If this was constructed with no information, we cannot do substitution |
11878 | // for constraint comparison, so make sure we can check that. |
11879 | bool isInvalid() const { return !ND && !DC; } |
11880 | |
11881 | const NamedDecl *getDecl() const { return ND; } |
11882 | |
11883 | bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; } |
11884 | |
11885 | const DeclContext *getLexicalDeclContext() const { |
11886 | return ND ? ND->getLexicalDeclContext() : LexicalDC; |
11887 | } |
11888 | |
11889 | const DeclContext *getDeclContext() const { |
11890 | return ND ? ND->getDeclContext() : DC; |
11891 | } |
11892 | |
11893 | SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; } |
11894 | }; |
11895 | |
11896 | /// Determine whether the given template parameter lists are |
11897 | /// equivalent. |
11898 | /// |
11899 | /// \param New The new template parameter list, typically written in the |
11900 | /// source code as part of a new template declaration. |
11901 | /// |
11902 | /// \param Old The old template parameter list, typically found via |
11903 | /// name lookup of the template declared with this template parameter |
11904 | /// list. |
11905 | /// |
11906 | /// \param Complain If true, this routine will produce a diagnostic if |
11907 | /// the template parameter lists are not equivalent. |
11908 | /// |
11909 | /// \param Kind describes how we are to match the template parameter lists. |
11910 | /// |
11911 | /// \param TemplateArgLoc If this source location is valid, then we |
11912 | /// are actually checking the template parameter list of a template |
11913 | /// argument (New) against the template parameter list of its |
11914 | /// corresponding template template parameter (Old). We produce |
11915 | /// slightly different diagnostics in this scenario. |
11916 | /// |
11917 | /// \returns True if the template parameter lists are equal, false |
11918 | /// otherwise. |
11919 | bool TemplateParameterListsAreEqual( |
11920 | const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, |
11921 | const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, |
11922 | TemplateParameterListEqualKind Kind, |
11923 | SourceLocation TemplateArgLoc = SourceLocation()); |
11924 | |
11925 | bool TemplateParameterListsAreEqual( |
11926 | TemplateParameterList *New, TemplateParameterList *Old, bool Complain, |
11927 | TemplateParameterListEqualKind Kind, |
11928 | SourceLocation TemplateArgLoc = SourceLocation()) { |
11929 | return TemplateParameterListsAreEqual(NewInstFrom: nullptr, New, OldInstFrom: nullptr, Old, Complain, |
11930 | Kind, TemplateArgLoc); |
11931 | } |
11932 | |
11933 | /// Check whether a template can be declared within this scope. |
11934 | /// |
11935 | /// If the template declaration is valid in this scope, returns |
11936 | /// false. Otherwise, issues a diagnostic and returns true. |
11937 | bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); |
11938 | |
11939 | /// Called when the parser has parsed a C++ typename |
11940 | /// specifier, e.g., "typename T::type". |
11941 | /// |
11942 | /// \param S The scope in which this typename type occurs. |
11943 | /// \param TypenameLoc the location of the 'typename' keyword |
11944 | /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). |
11945 | /// \param II the identifier we're retrieving (e.g., 'type' in the example). |
11946 | /// \param IdLoc the location of the identifier. |
11947 | /// \param IsImplicitTypename context where T::type refers to a type. |
11948 | TypeResult ActOnTypenameType( |
11949 | Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, |
11950 | const IdentifierInfo &II, SourceLocation IdLoc, |
11951 | ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No); |
11952 | |
11953 | /// Called when the parser has parsed a C++ typename |
11954 | /// specifier that ends in a template-id, e.g., |
11955 | /// "typename MetaFun::template apply<T1, T2>". |
11956 | /// |
11957 | /// \param S The scope in which this typename type occurs. |
11958 | /// \param TypenameLoc the location of the 'typename' keyword |
11959 | /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). |
11960 | /// \param TemplateLoc the location of the 'template' keyword, if any. |
11961 | /// \param TemplateName The template name. |
11962 | /// \param TemplateII The identifier used to name the template. |
11963 | /// \param TemplateIILoc The location of the template name. |
11964 | /// \param LAngleLoc The location of the opening angle bracket ('<'). |
11965 | /// \param TemplateArgs The template arguments. |
11966 | /// \param RAngleLoc The location of the closing angle bracket ('>'). |
11967 | TypeResult |
11968 | ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, |
11969 | const CXXScopeSpec &SS, SourceLocation TemplateLoc, |
11970 | TemplateTy TemplateName, const IdentifierInfo *TemplateII, |
11971 | SourceLocation TemplateIILoc, SourceLocation LAngleLoc, |
11972 | ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); |
11973 | |
11974 | QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, |
11975 | SourceLocation KeywordLoc, |
11976 | NestedNameSpecifierLoc QualifierLoc, |
11977 | const IdentifierInfo &II, SourceLocation IILoc, |
11978 | TypeSourceInfo **TSI, bool DeducedTSTContext); |
11979 | |
11980 | QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, |
11981 | SourceLocation KeywordLoc, |
11982 | NestedNameSpecifierLoc QualifierLoc, |
11983 | const IdentifierInfo &II, SourceLocation IILoc, |
11984 | bool DeducedTSTContext = true); |
11985 | |
11986 | /// Rebuilds a type within the context of the current instantiation. |
11987 | /// |
11988 | /// The type \p T is part of the type of an out-of-line member definition of |
11989 | /// a class template (or class template partial specialization) that was |
11990 | /// parsed and constructed before we entered the scope of the class template |
11991 | /// (or partial specialization thereof). This routine will rebuild that type |
11992 | /// now that we have entered the declarator's scope, which may produce |
11993 | /// different canonical types, e.g., |
11994 | /// |
11995 | /// \code |
11996 | /// template<typename T> |
11997 | /// struct X { |
11998 | /// typedef T* pointer; |
11999 | /// pointer data(); |
12000 | /// }; |
12001 | /// |
12002 | /// template<typename T> |
12003 | /// typename X<T>::pointer X<T>::data() { ... } |
12004 | /// \endcode |
12005 | /// |
12006 | /// Here, the type "typename X<T>::pointer" will be created as a |
12007 | /// DependentNameType, since we do not know that we can look into X<T> when we |
12008 | /// parsed the type. This function will rebuild the type, performing the |
12009 | /// lookup of "pointer" in X<T> and returning an ElaboratedType whose |
12010 | /// canonical type is the same as the canonical type of T*, allowing the |
12011 | /// return types of the out-of-line definition and the declaration to match. |
12012 | TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, |
12013 | SourceLocation Loc, |
12014 | DeclarationName Name); |
12015 | bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); |
12016 | |
12017 | ExprResult RebuildExprInCurrentInstantiation(Expr *E); |
12018 | |
12019 | /// Rebuild the template parameters now that we know we're in a current |
12020 | /// instantiation. |
12021 | bool |
12022 | RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params); |
12023 | |
12024 | /// Produces a formatted string that describes the binding of |
12025 | /// template parameters to template arguments. |
12026 | std::string |
12027 | getTemplateArgumentBindingsText(const TemplateParameterList *Params, |
12028 | const TemplateArgumentList &Args); |
12029 | |
12030 | std::string |
12031 | getTemplateArgumentBindingsText(const TemplateParameterList *Params, |
12032 | const TemplateArgument *Args, |
12033 | unsigned NumArgs); |
12034 | |
12035 | void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, |
12036 | SourceLocation Less, |
12037 | SourceLocation Greater); |
12038 | |
12039 | /// ActOnDependentIdExpression - Handle a dependent id-expression that |
12040 | /// was just parsed. This is only possible with an explicit scope |
12041 | /// specifier naming a dependent type. |
12042 | ExprResult ActOnDependentIdExpression( |
12043 | const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
12044 | const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, |
12045 | const TemplateArgumentListInfo *TemplateArgs); |
12046 | |
12047 | ExprResult |
12048 | BuildDependentDeclRefExpr(const CXXScopeSpec &SS, |
12049 | SourceLocation TemplateKWLoc, |
12050 | const DeclarationNameInfo &NameInfo, |
12051 | const TemplateArgumentListInfo *TemplateArgs); |
12052 | |
12053 | // Calculates whether the expression Constraint depends on an enclosing |
12054 | // template, for the purposes of [temp.friend] p9. |
12055 | // TemplateDepth is the 'depth' of the friend function, which is used to |
12056 | // compare whether a declaration reference is referring to a containing |
12057 | // template, or just the current friend function. A 'lower' TemplateDepth in |
12058 | // the AST refers to a 'containing' template. As the constraint is |
12059 | // uninstantiated, this is relative to the 'top' of the TU. |
12060 | bool |
12061 | ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, |
12062 | unsigned TemplateDepth, |
12063 | const Expr *Constraint); |
12064 | |
12065 | /// Find the failed Boolean condition within a given Boolean |
12066 | /// constant expression, and describe it with a string. |
12067 | std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); |
12068 | |
12069 | void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); |
12070 | |
12071 | ConceptDecl *ActOnStartConceptDefinition( |
12072 | Scope *S, MultiTemplateParamsArg TemplateParameterLists, |
12073 | const IdentifierInfo *Name, SourceLocation NameLoc); |
12074 | |
12075 | ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, |
12076 | Expr *ConstraintExpr, |
12077 | const ParsedAttributesView &Attrs); |
12078 | |
12079 | void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, |
12080 | bool &AddToScope); |
12081 | bool CheckConceptUseInDefinition(ConceptDecl *Concept, SourceLocation Loc); |
12082 | |
12083 | TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, |
12084 | const CXXScopeSpec &SS, |
12085 | const IdentifierInfo *Name, |
12086 | SourceLocation TagLoc, SourceLocation NameLoc); |
12087 | |
12088 | void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, |
12089 | CachedTokens &Toks); |
12090 | void UnmarkAsLateParsedTemplate(FunctionDecl *FD); |
12091 | bool IsInsideALocalClassWithinATemplateFunction(); |
12092 | |
12093 | /// We've found a use of a templated declaration that would trigger an |
12094 | /// implicit instantiation. Check that any relevant explicit specializations |
12095 | /// and partial specializations are visible/reachable, and diagnose if not. |
12096 | void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); |
12097 | void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec); |
12098 | |
12099 | ///@} |
12100 | |
12101 | // |
12102 | // |
12103 | // ------------------------------------------------------------------------- |
12104 | // |
12105 | // |
12106 | |
12107 | /// \name C++ Template Argument Deduction |
12108 | /// Implementations are in SemaTemplateDeduction.cpp |
12109 | ///@{ |
12110 | |
12111 | public: |
12112 | /// When true, access checking violations are treated as SFINAE |
12113 | /// failures rather than hard errors. |
12114 | bool AccessCheckingSFINAE; |
12115 | |
12116 | /// RAII class used to determine whether SFINAE has |
12117 | /// trapped any errors that occur during template argument |
12118 | /// deduction. |
12119 | class SFINAETrap { |
12120 | Sema &SemaRef; |
12121 | unsigned PrevSFINAEErrors; |
12122 | bool PrevInNonInstantiationSFINAEContext; |
12123 | bool PrevAccessCheckingSFINAE; |
12124 | bool PrevLastDiagnosticIgnored; |
12125 | |
12126 | public: |
12127 | explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) |
12128 | : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), |
12129 | PrevInNonInstantiationSFINAEContext( |
12130 | SemaRef.InNonInstantiationSFINAEContext), |
12131 | PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), |
12132 | PrevLastDiagnosticIgnored( |
12133 | SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { |
12134 | if (!SemaRef.isSFINAEContext()) |
12135 | SemaRef.InNonInstantiationSFINAEContext = true; |
12136 | SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; |
12137 | } |
12138 | |
12139 | ~SFINAETrap() { |
12140 | SemaRef.NumSFINAEErrors = PrevSFINAEErrors; |
12141 | SemaRef.InNonInstantiationSFINAEContext = |
12142 | PrevInNonInstantiationSFINAEContext; |
12143 | SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; |
12144 | SemaRef.getDiagnostics().setLastDiagnosticIgnored( |
12145 | PrevLastDiagnosticIgnored); |
12146 | } |
12147 | |
12148 | /// Determine whether any SFINAE errors have been trapped. |
12149 | bool hasErrorOccurred() const { |
12150 | return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; |
12151 | } |
12152 | }; |
12153 | |
12154 | /// RAII class used to indicate that we are performing provisional |
12155 | /// semantic analysis to determine the validity of a construct, so |
12156 | /// typo-correction and diagnostics in the immediate context (not within |
12157 | /// implicitly-instantiated templates) should be suppressed. |
12158 | class TentativeAnalysisScope { |
12159 | Sema &SemaRef; |
12160 | // FIXME: Using a SFINAETrap for this is a hack. |
12161 | SFINAETrap Trap; |
12162 | bool PrevDisableTypoCorrection; |
12163 | |
12164 | public: |
12165 | explicit TentativeAnalysisScope(Sema &SemaRef) |
12166 | : SemaRef(SemaRef), Trap(SemaRef, true), |
12167 | PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { |
12168 | SemaRef.DisableTypoCorrection = true; |
12169 | } |
12170 | ~TentativeAnalysisScope() { |
12171 | SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; |
12172 | } |
12173 | }; |
12174 | |
12175 | /// For each declaration that involved template argument deduction, the |
12176 | /// set of diagnostics that were suppressed during that template argument |
12177 | /// deduction. |
12178 | /// |
12179 | /// FIXME: Serialize this structure to the AST file. |
12180 | typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>> |
12181 | SuppressedDiagnosticsMap; |
12182 | SuppressedDiagnosticsMap SuppressedDiagnostics; |
12183 | |
12184 | /// Compare types for equality with respect to possibly compatible |
12185 | /// function types (noreturn adjustment, implicit calling conventions). If any |
12186 | /// of parameter and argument is not a function, just perform type comparison. |
12187 | /// |
12188 | /// \param P the template parameter type. |
12189 | /// |
12190 | /// \param A the argument type. |
12191 | bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg); |
12192 | |
12193 | /// Allocate a TemplateArgumentLoc where all locations have |
12194 | /// been initialized to the given location. |
12195 | /// |
12196 | /// \param Arg The template argument we are producing template argument |
12197 | /// location information for. |
12198 | /// |
12199 | /// \param NTTPType For a declaration template argument, the type of |
12200 | /// the non-type template parameter that corresponds to this template |
12201 | /// argument. Can be null if no type sugar is available to add to the |
12202 | /// type from the template argument. |
12203 | /// |
12204 | /// \param Loc The source location to use for the resulting template |
12205 | /// argument. |
12206 | TemplateArgumentLoc |
12207 | getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, |
12208 | SourceLocation Loc, |
12209 | NamedDecl *TemplateParam = nullptr); |
12210 | |
12211 | /// Get a template argument mapping the given template parameter to itself, |
12212 | /// e.g. for X in \c template<int X>, this would return an expression template |
12213 | /// argument referencing X. |
12214 | TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, |
12215 | SourceLocation Location); |
12216 | |
12217 | /// Adjust the type \p ArgFunctionType to match the calling convention, |
12218 | /// noreturn, and optionally the exception specification of \p FunctionType. |
12219 | /// Deduction often wants to ignore these properties when matching function |
12220 | /// types. |
12221 | QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, |
12222 | bool AdjustExceptionSpec = false); |
12223 | |
12224 | TemplateDeductionResult |
12225 | DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, |
12226 | ArrayRef<TemplateArgument> TemplateArgs, |
12227 | sema::TemplateDeductionInfo &Info); |
12228 | |
12229 | TemplateDeductionResult |
12230 | DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, |
12231 | ArrayRef<TemplateArgument> TemplateArgs, |
12232 | sema::TemplateDeductionInfo &Info); |
12233 | |
12234 | /// Deduce the template arguments of the given template from \p FromType. |
12235 | /// Used to implement the IsDeducible constraint for alias CTAD per C++ |
12236 | /// [over.match.class.deduct]p4. |
12237 | /// |
12238 | /// It only supports class or type alias templates. |
12239 | TemplateDeductionResult |
12240 | DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, |
12241 | sema::TemplateDeductionInfo &Info); |
12242 | |
12243 | TemplateDeductionResult DeduceTemplateArguments( |
12244 | TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps, |
12245 | ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info, |
12246 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
12247 | bool NumberOfArgumentsMustMatch); |
12248 | |
12249 | /// Substitute the explicitly-provided template arguments into the |
12250 | /// given function template according to C++ [temp.arg.explicit]. |
12251 | /// |
12252 | /// \param FunctionTemplate the function template into which the explicit |
12253 | /// template arguments will be substituted. |
12254 | /// |
12255 | /// \param ExplicitTemplateArgs the explicitly-specified template |
12256 | /// arguments. |
12257 | /// |
12258 | /// \param Deduced the deduced template arguments, which will be populated |
12259 | /// with the converted and checked explicit template arguments. |
12260 | /// |
12261 | /// \param ParamTypes will be populated with the instantiated function |
12262 | /// parameters. |
12263 | /// |
12264 | /// \param FunctionType if non-NULL, the result type of the function template |
12265 | /// will also be instantiated and the pointed-to value will be updated with |
12266 | /// the instantiated function type. |
12267 | /// |
12268 | /// \param Info if substitution fails for any reason, this object will be |
12269 | /// populated with more information about the failure. |
12270 | /// |
12271 | /// \returns TemplateDeductionResult::Success if substitution was successful, |
12272 | /// or some failure condition. |
12273 | TemplateDeductionResult SubstituteExplicitTemplateArguments( |
12274 | FunctionTemplateDecl *FunctionTemplate, |
12275 | TemplateArgumentListInfo &ExplicitTemplateArgs, |
12276 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
12277 | SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, |
12278 | sema::TemplateDeductionInfo &Info); |
12279 | |
12280 | /// brief A function argument from which we performed template argument |
12281 | // deduction for a call. |
12282 | struct OriginalCallArg { |
12283 | OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, |
12284 | unsigned ArgIdx, QualType OriginalArgType) |
12285 | : OriginalParamType(OriginalParamType), |
12286 | DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), |
12287 | OriginalArgType(OriginalArgType) {} |
12288 | |
12289 | QualType OriginalParamType; |
12290 | bool DecomposedParam; |
12291 | unsigned ArgIdx; |
12292 | QualType OriginalArgType; |
12293 | }; |
12294 | |
12295 | /// Finish template argument deduction for a function template, |
12296 | /// checking the deduced template arguments for completeness and forming |
12297 | /// the function template specialization. |
12298 | /// |
12299 | /// \param OriginalCallArgs If non-NULL, the original call arguments against |
12300 | /// which the deduced argument types should be compared. |
12301 | TemplateDeductionResult FinishTemplateArgumentDeduction( |
12302 | FunctionTemplateDecl *FunctionTemplate, |
12303 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
12304 | unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, |
12305 | sema::TemplateDeductionInfo &Info, |
12306 | SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs, |
12307 | bool PartialOverloading, bool PartialOrdering, |
12308 | llvm::function_ref<bool()> CheckNonDependent = [] { return false; }); |
12309 | |
12310 | /// Perform template argument deduction from a function call |
12311 | /// (C++ [temp.deduct.call]). |
12312 | /// |
12313 | /// \param FunctionTemplate the function template for which we are performing |
12314 | /// template argument deduction. |
12315 | /// |
12316 | /// \param ExplicitTemplateArgs the explicit template arguments provided |
12317 | /// for this call. |
12318 | /// |
12319 | /// \param Args the function call arguments |
12320 | /// |
12321 | /// \param Specialization if template argument deduction was successful, |
12322 | /// this will be set to the function template specialization produced by |
12323 | /// template argument deduction. |
12324 | /// |
12325 | /// \param Info the argument will be updated to provide additional information |
12326 | /// about template argument deduction. |
12327 | /// |
12328 | /// \param CheckNonDependent A callback to invoke to check conversions for |
12329 | /// non-dependent parameters, between deduction and substitution, per DR1391. |
12330 | /// If this returns true, substitution will be skipped and we return |
12331 | /// TemplateDeductionResult::NonDependentConversionFailure. The callback is |
12332 | /// passed the parameter types (after substituting explicit template |
12333 | /// arguments). |
12334 | /// |
12335 | /// \returns the result of template argument deduction. |
12336 | TemplateDeductionResult DeduceTemplateArguments( |
12337 | FunctionTemplateDecl *FunctionTemplate, |
12338 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
12339 | FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, |
12340 | bool PartialOverloading, bool AggregateDeductionCandidate, |
12341 | bool PartialOrdering, QualType ObjectType, |
12342 | Expr::Classification ObjectClassification, |
12343 | llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); |
12344 | |
12345 | /// Deduce template arguments when taking the address of a function |
12346 | /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to |
12347 | /// a template. |
12348 | /// |
12349 | /// \param FunctionTemplate the function template for which we are performing |
12350 | /// template argument deduction. |
12351 | /// |
12352 | /// \param ExplicitTemplateArgs the explicitly-specified template |
12353 | /// arguments. |
12354 | /// |
12355 | /// \param ArgFunctionType the function type that will be used as the |
12356 | /// "argument" type (A) when performing template argument deduction from the |
12357 | /// function template's function type. This type may be NULL, if there is no |
12358 | /// argument type to compare against, in C++0x [temp.arg.explicit]p3. |
12359 | /// |
12360 | /// \param Specialization if template argument deduction was successful, |
12361 | /// this will be set to the function template specialization produced by |
12362 | /// template argument deduction. |
12363 | /// |
12364 | /// \param Info the argument will be updated to provide additional information |
12365 | /// about template argument deduction. |
12366 | /// |
12367 | /// \param IsAddressOfFunction If \c true, we are deducing as part of taking |
12368 | /// the address of a function template per [temp.deduct.funcaddr] and |
12369 | /// [over.over]. If \c false, we are looking up a function template |
12370 | /// specialization based on its signature, per [temp.deduct.decl]. |
12371 | /// |
12372 | /// \returns the result of template argument deduction. |
12373 | TemplateDeductionResult DeduceTemplateArguments( |
12374 | FunctionTemplateDecl *FunctionTemplate, |
12375 | TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, |
12376 | FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, |
12377 | bool IsAddressOfFunction = false); |
12378 | |
12379 | /// Deduce template arguments for a templated conversion |
12380 | /// function (C++ [temp.deduct.conv]) and, if successful, produce a |
12381 | /// conversion function template specialization. |
12382 | TemplateDeductionResult DeduceTemplateArguments( |
12383 | FunctionTemplateDecl *FunctionTemplate, QualType ObjectType, |
12384 | Expr::Classification ObjectClassification, QualType ToType, |
12385 | CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); |
12386 | |
12387 | /// Deduce template arguments for a function template when there is |
12388 | /// nothing to deduce against (C++0x [temp.arg.explicit]p3). |
12389 | /// |
12390 | /// \param FunctionTemplate the function template for which we are performing |
12391 | /// template argument deduction. |
12392 | /// |
12393 | /// \param ExplicitTemplateArgs the explicitly-specified template |
12394 | /// arguments. |
12395 | /// |
12396 | /// \param Specialization if template argument deduction was successful, |
12397 | /// this will be set to the function template specialization produced by |
12398 | /// template argument deduction. |
12399 | /// |
12400 | /// \param Info the argument will be updated to provide additional information |
12401 | /// about template argument deduction. |
12402 | /// |
12403 | /// \param IsAddressOfFunction If \c true, we are deducing as part of taking |
12404 | /// the address of a function template in a context where we do not have a |
12405 | /// target type, per [over.over]. If \c false, we are looking up a function |
12406 | /// template specialization based on its signature, which only happens when |
12407 | /// deducing a function parameter type from an argument that is a template-id |
12408 | /// naming a function template specialization. |
12409 | /// |
12410 | /// \returns the result of template argument deduction. |
12411 | TemplateDeductionResult |
12412 | DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, |
12413 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
12414 | FunctionDecl *&Specialization, |
12415 | sema::TemplateDeductionInfo &Info, |
12416 | bool IsAddressOfFunction = false); |
12417 | |
12418 | /// Substitute Replacement for \p auto in \p TypeWithAuto |
12419 | QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); |
12420 | /// Substitute Replacement for auto in TypeWithAuto |
12421 | TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, |
12422 | QualType Replacement); |
12423 | |
12424 | // Substitute auto in TypeWithAuto for a Dependent auto type |
12425 | QualType SubstAutoTypeDependent(QualType TypeWithAuto); |
12426 | |
12427 | // Substitute auto in TypeWithAuto for a Dependent auto type |
12428 | TypeSourceInfo * |
12429 | SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto); |
12430 | |
12431 | /// Completely replace the \c auto in \p TypeWithAuto by |
12432 | /// \p Replacement. This does not retain any \c auto type sugar. |
12433 | QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); |
12434 | TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, |
12435 | QualType Replacement); |
12436 | |
12437 | /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6) |
12438 | /// |
12439 | /// Note that this is done even if the initializer is dependent. (This is |
12440 | /// necessary to support partial ordering of templates using 'auto'.) |
12441 | /// A dependent type will be produced when deducing from a dependent type. |
12442 | /// |
12443 | /// \param Type the type pattern using the auto type-specifier. |
12444 | /// \param Init the initializer for the variable whose type is to be deduced. |
12445 | /// \param Result if type deduction was successful, this will be set to the |
12446 | /// deduced type. |
12447 | /// \param Info the argument will be updated to provide additional information |
12448 | /// about template argument deduction. |
12449 | /// \param DependentDeduction Set if we should permit deduction in |
12450 | /// dependent cases. This is necessary for template partial ordering |
12451 | /// with 'auto' template parameters. The template parameter depth to be |
12452 | /// used should be specified in the 'Info' parameter. |
12453 | /// \param IgnoreConstraints Set if we should not fail if the deduced type |
12454 | /// does not satisfy the type-constraint in the auto |
12455 | /// type. |
12456 | TemplateDeductionResult |
12457 | DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, |
12458 | sema::TemplateDeductionInfo &Info, |
12459 | bool DependentDeduction = false, |
12460 | bool IgnoreConstraints = false, |
12461 | TemplateSpecCandidateSet *FailedTSC = nullptr); |
12462 | void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init); |
12463 | bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, |
12464 | bool Diagnose = true); |
12465 | |
12466 | bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, |
12467 | SourceLocation Loc); |
12468 | |
12469 | /// Returns the more specialized class template partial specialization |
12470 | /// according to the rules of partial ordering of class template partial |
12471 | /// specializations (C++ [temp.class.order]). |
12472 | /// |
12473 | /// \param PS1 the first class template partial specialization |
12474 | /// |
12475 | /// \param PS2 the second class template partial specialization |
12476 | /// |
12477 | /// \returns the more specialized class template partial specialization. If |
12478 | /// neither partial specialization is more specialized, returns NULL. |
12479 | ClassTemplatePartialSpecializationDecl * |
12480 | getMoreSpecializedPartialSpecialization( |
12481 | ClassTemplatePartialSpecializationDecl *PS1, |
12482 | ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); |
12483 | |
12484 | bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, |
12485 | sema::TemplateDeductionInfo &Info); |
12486 | |
12487 | VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( |
12488 | VarTemplatePartialSpecializationDecl *PS1, |
12489 | VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); |
12490 | |
12491 | bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, |
12492 | sema::TemplateDeductionInfo &Info); |
12493 | |
12494 | bool isTemplateTemplateParameterAtLeastAsSpecializedAs( |
12495 | TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, |
12496 | const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, |
12497 | bool PartialOrdering, bool *StrictPackMatch); |
12498 | |
12499 | /// Mark which template parameters are used in a given expression. |
12500 | /// |
12501 | /// \param E the expression from which template parameters will be deduced. |
12502 | /// |
12503 | /// \param Used a bit vector whose elements will be set to \c true |
12504 | /// to indicate when the corresponding template parameter will be |
12505 | /// deduced. |
12506 | void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, |
12507 | unsigned Depth, llvm::SmallBitVector &Used); |
12508 | |
12509 | /// Mark which template parameters can be deduced from a given |
12510 | /// template argument list. |
12511 | /// |
12512 | /// \param TemplateArgs the template argument list from which template |
12513 | /// parameters will be deduced. |
12514 | /// |
12515 | /// \param Used a bit vector whose elements will be set to \c true |
12516 | /// to indicate when the corresponding template parameter will be |
12517 | /// deduced. |
12518 | void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, |
12519 | bool OnlyDeduced, unsigned Depth, |
12520 | llvm::SmallBitVector &Used); |
12521 | void |
12522 | MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, |
12523 | llvm::SmallBitVector &Deduced) { |
12524 | return MarkDeducedTemplateParameters(Ctx&: Context, FunctionTemplate, Deduced); |
12525 | } |
12526 | |
12527 | /// Marks all of the template parameters that will be deduced by a |
12528 | /// call to the given function template. |
12529 | static void |
12530 | MarkDeducedTemplateParameters(ASTContext &Ctx, |
12531 | const FunctionTemplateDecl *FunctionTemplate, |
12532 | llvm::SmallBitVector &Deduced); |
12533 | |
12534 | /// Returns the more specialized function template according |
12535 | /// to the rules of function template partial ordering (C++ |
12536 | /// [temp.func.order]). |
12537 | /// |
12538 | /// \param FT1 the first function template |
12539 | /// |
12540 | /// \param FT2 the second function template |
12541 | /// |
12542 | /// \param TPOC the context in which we are performing partial ordering of |
12543 | /// function templates. |
12544 | /// |
12545 | /// \param NumCallArguments1 The number of arguments in the call to FT1, used |
12546 | /// only when \c TPOC is \c TPOC_Call. Does not include the object argument |
12547 | /// when calling a member function. |
12548 | /// |
12549 | /// \param RawObj1Ty The type of the object parameter of FT1 if a member |
12550 | /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function |
12551 | /// template from a member function |
12552 | /// |
12553 | /// \param RawObj2Ty The type of the object parameter of FT2 if a member |
12554 | /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function |
12555 | /// template from a member function |
12556 | /// |
12557 | /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload |
12558 | /// candidate with a reversed parameter order. In this case, the corresponding |
12559 | /// P/A pairs between FT1 and FT2 are reversed. |
12560 | /// |
12561 | /// \returns the more specialized function template. If neither |
12562 | /// template is more specialized, returns NULL. |
12563 | FunctionTemplateDecl *getMoreSpecializedTemplate( |
12564 | FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, |
12565 | TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, |
12566 | QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false); |
12567 | |
12568 | /// Retrieve the most specialized of the given function template |
12569 | /// specializations. |
12570 | /// |
12571 | /// \param SpecBegin the start iterator of the function template |
12572 | /// specializations that we will be comparing. |
12573 | /// |
12574 | /// \param SpecEnd the end iterator of the function template |
12575 | /// specializations, paired with \p SpecBegin. |
12576 | /// |
12577 | /// \param Loc the location where the ambiguity or no-specializations |
12578 | /// diagnostic should occur. |
12579 | /// |
12580 | /// \param NoneDiag partial diagnostic used to diagnose cases where there are |
12581 | /// no matching candidates. |
12582 | /// |
12583 | /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one |
12584 | /// occurs. |
12585 | /// |
12586 | /// \param CandidateDiag partial diagnostic used for each function template |
12587 | /// specialization that is a candidate in the ambiguous ordering. One |
12588 | /// parameter in this diagnostic should be unbound, which will correspond to |
12589 | /// the string describing the template arguments for the function template |
12590 | /// specialization. |
12591 | /// |
12592 | /// \returns the most specialized function template specialization, if |
12593 | /// found. Otherwise, returns SpecEnd. |
12594 | UnresolvedSetIterator |
12595 | getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, |
12596 | TemplateSpecCandidateSet &FailedCandidates, |
12597 | SourceLocation Loc, const PartialDiagnostic &NoneDiag, |
12598 | const PartialDiagnostic &AmbigDiag, |
12599 | const PartialDiagnostic &CandidateDiag, |
12600 | bool Complain = true, QualType TargetType = QualType()); |
12601 | |
12602 | /// Returns the more constrained function according to the rules of |
12603 | /// partial ordering by constraints (C++ [temp.constr.order]). |
12604 | /// |
12605 | /// \param FD1 the first function |
12606 | /// |
12607 | /// \param FD2 the second function |
12608 | /// |
12609 | /// \returns the more constrained function. If neither function is |
12610 | /// more constrained, returns NULL. |
12611 | FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1, |
12612 | FunctionDecl *FD2); |
12613 | |
12614 | ///@} |
12615 | |
12616 | // |
12617 | // |
12618 | // ------------------------------------------------------------------------- |
12619 | // |
12620 | // |
12621 | |
12622 | /// \name C++ Template Deduction Guide |
12623 | /// Implementations are in SemaTemplateDeductionGuide.cpp |
12624 | ///@{ |
12625 | |
12626 | /// Declare implicit deduction guides for a class template if we've |
12627 | /// not already done so. |
12628 | void DeclareImplicitDeductionGuides(TemplateDecl *Template, |
12629 | SourceLocation Loc); |
12630 | |
12631 | FunctionTemplateDecl *DeclareAggregateDeductionGuideFromInitList( |
12632 | TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes, |
12633 | SourceLocation Loc); |
12634 | |
12635 | ///@} |
12636 | |
12637 | // |
12638 | // |
12639 | // ------------------------------------------------------------------------- |
12640 | // |
12641 | // |
12642 | |
12643 | /// \name C++ Template Instantiation |
12644 | /// Implementations are in SemaTemplateInstantiate.cpp |
12645 | ///@{ |
12646 | |
12647 | public: |
12648 | /// A helper class for building up ExtParameterInfos. |
12649 | class ExtParameterInfoBuilder { |
12650 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; |
12651 | bool HasInteresting = false; |
12652 | |
12653 | public: |
12654 | /// Set the ExtParameterInfo for the parameter at the given index, |
12655 | /// |
12656 | void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { |
12657 | assert(Infos.size() <= index); |
12658 | Infos.resize(N: index); |
12659 | Infos.push_back(Elt: info); |
12660 | |
12661 | if (!HasInteresting) |
12662 | HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); |
12663 | } |
12664 | |
12665 | /// Return a pointer (suitable for setting in an ExtProtoInfo) to the |
12666 | /// ExtParameterInfo array we've built up. |
12667 | const FunctionProtoType::ExtParameterInfo * |
12668 | getPointerOrNull(unsigned numParams) { |
12669 | if (!HasInteresting) |
12670 | return nullptr; |
12671 | Infos.resize(N: numParams); |
12672 | return Infos.data(); |
12673 | } |
12674 | }; |
12675 | |
12676 | /// The current instantiation scope used to store local |
12677 | /// variables. |
12678 | LocalInstantiationScope *CurrentInstantiationScope; |
12679 | |
12680 | typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> |
12681 | UnparsedDefaultArgInstantiationsMap; |
12682 | |
12683 | /// A mapping from parameters with unparsed default arguments to the |
12684 | /// set of instantiations of each parameter. |
12685 | /// |
12686 | /// This mapping is a temporary data structure used when parsing |
12687 | /// nested class templates or nested classes of class templates, |
12688 | /// where we might end up instantiating an inner class before the |
12689 | /// default arguments of its methods have been parsed. |
12690 | UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; |
12691 | |
12692 | /// A context in which code is being synthesized (where a source location |
12693 | /// alone is not sufficient to identify the context). This covers template |
12694 | /// instantiation and various forms of implicitly-generated functions. |
12695 | struct CodeSynthesisContext { |
12696 | /// The kind of template instantiation we are performing |
12697 | enum SynthesisKind { |
12698 | /// We are instantiating a template declaration. The entity is |
12699 | /// the declaration we're instantiating (e.g., a CXXRecordDecl). |
12700 | TemplateInstantiation, |
12701 | |
12702 | /// We are instantiating a default argument for a template |
12703 | /// parameter. The Entity is the template parameter whose argument is |
12704 | /// being instantiated, the Template is the template, and the |
12705 | /// TemplateArgs/NumTemplateArguments provide the template arguments as |
12706 | /// specified. |
12707 | DefaultTemplateArgumentInstantiation, |
12708 | |
12709 | /// We are instantiating a default argument for a function. |
12710 | /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs |
12711 | /// provides the template arguments as specified. |
12712 | DefaultFunctionArgumentInstantiation, |
12713 | |
12714 | /// We are substituting explicit template arguments provided for |
12715 | /// a function template. The entity is a FunctionTemplateDecl. |
12716 | ExplicitTemplateArgumentSubstitution, |
12717 | |
12718 | /// We are substituting template argument determined as part of |
12719 | /// template argument deduction for either a class template |
12720 | /// partial specialization or a function template. The |
12721 | /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or |
12722 | /// a TemplateDecl. |
12723 | DeducedTemplateArgumentSubstitution, |
12724 | |
12725 | /// We are substituting into a lambda expression. |
12726 | LambdaExpressionSubstitution, |
12727 | |
12728 | /// We are substituting prior template arguments into a new |
12729 | /// template parameter. The template parameter itself is either a |
12730 | /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. |
12731 | PriorTemplateArgumentSubstitution, |
12732 | |
12733 | /// We are checking the validity of a default template argument that |
12734 | /// has been used when naming a template-id. |
12735 | DefaultTemplateArgumentChecking, |
12736 | |
12737 | /// We are computing the exception specification for a defaulted special |
12738 | /// member function. |
12739 | ExceptionSpecEvaluation, |
12740 | |
12741 | /// We are instantiating the exception specification for a function |
12742 | /// template which was deferred until it was needed. |
12743 | ExceptionSpecInstantiation, |
12744 | |
12745 | /// We are instantiating a requirement of a requires expression. |
12746 | RequirementInstantiation, |
12747 | |
12748 | /// We are checking the satisfaction of a nested requirement of a requires |
12749 | /// expression. |
12750 | NestedRequirementConstraintsCheck, |
12751 | |
12752 | /// We are declaring an implicit special member function. |
12753 | DeclaringSpecialMember, |
12754 | |
12755 | /// We are declaring an implicit 'operator==' for a defaulted |
12756 | /// 'operator<=>'. |
12757 | DeclaringImplicitEqualityComparison, |
12758 | |
12759 | /// We are defining a synthesized function (such as a defaulted special |
12760 | /// member). |
12761 | DefiningSynthesizedFunction, |
12762 | |
12763 | // We are checking the constraints associated with a constrained entity or |
12764 | // the constraint expression of a concept. This includes the checks that |
12765 | // atomic constraints have the type 'bool' and that they can be constant |
12766 | // evaluated. |
12767 | ConstraintsCheck, |
12768 | |
12769 | // We are substituting template arguments into a constraint expression. |
12770 | ConstraintSubstitution, |
12771 | |
12772 | // We are normalizing a constraint expression. |
12773 | ConstraintNormalization, |
12774 | |
12775 | // Instantiating a Requires Expression parameter clause. |
12776 | RequirementParameterInstantiation, |
12777 | |
12778 | // We are substituting into the parameter mapping of an atomic constraint |
12779 | // during normalization. |
12780 | ParameterMappingSubstitution, |
12781 | |
12782 | /// We are rewriting a comparison operator in terms of an operator<=>. |
12783 | RewritingOperatorAsSpaceship, |
12784 | |
12785 | /// We are initializing a structured binding. |
12786 | InitializingStructuredBinding, |
12787 | |
12788 | /// We are marking a class as __dllexport. |
12789 | MarkingClassDllexported, |
12790 | |
12791 | /// We are building an implied call from __builtin_dump_struct. The |
12792 | /// arguments are in CallArgs. |
12793 | BuildingBuiltinDumpStructCall, |
12794 | |
12795 | /// Added for Template instantiation observation. |
12796 | /// Memoization means we are _not_ instantiating a template because |
12797 | /// it is already instantiated (but we entered a context where we |
12798 | /// would have had to if it was not already instantiated). |
12799 | Memoization, |
12800 | |
12801 | /// We are building deduction guides for a class. |
12802 | BuildingDeductionGuides, |
12803 | |
12804 | /// We are instantiating a type alias template declaration. |
12805 | TypeAliasTemplateInstantiation, |
12806 | |
12807 | /// We are performing partial ordering for template template parameters. |
12808 | PartialOrderingTTP, |
12809 | } Kind; |
12810 | |
12811 | /// Was the enclosing context a non-instantiation SFINAE context? |
12812 | bool SavedInNonInstantiationSFINAEContext; |
12813 | |
12814 | /// The point of instantiation or synthesis within the source code. |
12815 | SourceLocation PointOfInstantiation; |
12816 | |
12817 | /// The entity that is being synthesized. |
12818 | Decl *Entity; |
12819 | |
12820 | /// The template (or partial specialization) in which we are |
12821 | /// performing the instantiation, for substitutions of prior template |
12822 | /// arguments. |
12823 | NamedDecl *Template; |
12824 | |
12825 | union { |
12826 | /// The list of template arguments we are substituting, if they |
12827 | /// are not part of the entity. |
12828 | const TemplateArgument *TemplateArgs; |
12829 | |
12830 | /// The list of argument expressions in a synthesized call. |
12831 | const Expr *const *CallArgs; |
12832 | }; |
12833 | |
12834 | // FIXME: Wrap this union around more members, or perhaps store the |
12835 | // kind-specific members in the RAII object owning the context. |
12836 | union { |
12837 | /// The number of template arguments in TemplateArgs. |
12838 | unsigned NumTemplateArgs; |
12839 | |
12840 | /// The number of expressions in CallArgs. |
12841 | unsigned NumCallArgs; |
12842 | |
12843 | /// The special member being declared or defined. |
12844 | CXXSpecialMemberKind SpecialMember; |
12845 | }; |
12846 | |
12847 | ArrayRef<TemplateArgument> template_arguments() const { |
12848 | assert(Kind != DeclaringSpecialMember); |
12849 | return {TemplateArgs, NumTemplateArgs}; |
12850 | } |
12851 | |
12852 | /// The template deduction info object associated with the |
12853 | /// substitution or checking of explicit or deduced template arguments. |
12854 | sema::TemplateDeductionInfo *DeductionInfo; |
12855 | |
12856 | /// The source range that covers the construct that cause |
12857 | /// the instantiation, e.g., the template-id that causes a class |
12858 | /// template instantiation. |
12859 | SourceRange InstantiationRange; |
12860 | |
12861 | CodeSynthesisContext() |
12862 | : Kind(TemplateInstantiation), |
12863 | SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), |
12864 | Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), |
12865 | DeductionInfo(nullptr) {} |
12866 | |
12867 | /// Determines whether this template is an actual instantiation |
12868 | /// that should be counted toward the maximum instantiation depth. |
12869 | bool isInstantiationRecord() const; |
12870 | }; |
12871 | |
12872 | /// A stack object to be created when performing template |
12873 | /// instantiation. |
12874 | /// |
12875 | /// Construction of an object of type \c InstantiatingTemplate |
12876 | /// pushes the current instantiation onto the stack of active |
12877 | /// instantiations. If the size of this stack exceeds the maximum |
12878 | /// number of recursive template instantiations, construction |
12879 | /// produces an error and evaluates true. |
12880 | /// |
12881 | /// Destruction of this object will pop the named instantiation off |
12882 | /// the stack. |
12883 | struct InstantiatingTemplate { |
12884 | /// Note that we are instantiating a class template, |
12885 | /// function template, variable template, alias template, |
12886 | /// or a member thereof. |
12887 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12888 | Decl *Entity, |
12889 | SourceRange InstantiationRange = SourceRange()); |
12890 | |
12891 | struct ExceptionSpecification {}; |
12892 | /// Note that we are instantiating an exception specification |
12893 | /// of a function template. |
12894 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12895 | FunctionDecl *Entity, ExceptionSpecification, |
12896 | SourceRange InstantiationRange = SourceRange()); |
12897 | |
12898 | /// Note that we are instantiating a type alias template declaration. |
12899 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12900 | TypeAliasTemplateDecl *Entity, |
12901 | ArrayRef<TemplateArgument> TemplateArgs, |
12902 | SourceRange InstantiationRange = SourceRange()); |
12903 | |
12904 | /// Note that we are instantiating a default argument in a |
12905 | /// template-id. |
12906 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12907 | TemplateParameter Param, TemplateDecl *Template, |
12908 | ArrayRef<TemplateArgument> TemplateArgs, |
12909 | SourceRange InstantiationRange = SourceRange()); |
12910 | |
12911 | /// Note that we are substituting either explicitly-specified or |
12912 | /// deduced template arguments during function template argument deduction. |
12913 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12914 | FunctionTemplateDecl *FunctionTemplate, |
12915 | ArrayRef<TemplateArgument> TemplateArgs, |
12916 | CodeSynthesisContext::SynthesisKind Kind, |
12917 | sema::TemplateDeductionInfo &DeductionInfo, |
12918 | SourceRange InstantiationRange = SourceRange()); |
12919 | |
12920 | /// Note that we are instantiating as part of template |
12921 | /// argument deduction for a class template declaration. |
12922 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12923 | TemplateDecl *Template, |
12924 | ArrayRef<TemplateArgument> TemplateArgs, |
12925 | sema::TemplateDeductionInfo &DeductionInfo, |
12926 | SourceRange InstantiationRange = SourceRange()); |
12927 | |
12928 | /// Note that we are instantiating as part of template |
12929 | /// argument deduction for a class template partial |
12930 | /// specialization. |
12931 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12932 | ClassTemplatePartialSpecializationDecl *PartialSpec, |
12933 | ArrayRef<TemplateArgument> TemplateArgs, |
12934 | sema::TemplateDeductionInfo &DeductionInfo, |
12935 | SourceRange InstantiationRange = SourceRange()); |
12936 | |
12937 | /// Note that we are instantiating as part of template |
12938 | /// argument deduction for a variable template partial |
12939 | /// specialization. |
12940 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12941 | VarTemplatePartialSpecializationDecl *PartialSpec, |
12942 | ArrayRef<TemplateArgument> TemplateArgs, |
12943 | sema::TemplateDeductionInfo &DeductionInfo, |
12944 | SourceRange InstantiationRange = SourceRange()); |
12945 | |
12946 | /// Note that we are instantiating a default argument for a function |
12947 | /// parameter. |
12948 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12949 | ParmVarDecl *Param, |
12950 | ArrayRef<TemplateArgument> TemplateArgs, |
12951 | SourceRange InstantiationRange = SourceRange()); |
12952 | |
12953 | /// Note that we are substituting prior template arguments into a |
12954 | /// non-type parameter. |
12955 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12956 | NamedDecl *Template, NonTypeTemplateParmDecl *Param, |
12957 | ArrayRef<TemplateArgument> TemplateArgs, |
12958 | SourceRange InstantiationRange); |
12959 | |
12960 | /// Note that we are substituting prior template arguments into a |
12961 | /// template template parameter. |
12962 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12963 | NamedDecl *Template, TemplateTemplateParmDecl *Param, |
12964 | ArrayRef<TemplateArgument> TemplateArgs, |
12965 | SourceRange InstantiationRange); |
12966 | |
12967 | /// Note that we are checking the default template argument |
12968 | /// against the template parameter for a given template-id. |
12969 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12970 | TemplateDecl *Template, NamedDecl *Param, |
12971 | ArrayRef<TemplateArgument> TemplateArgs, |
12972 | SourceRange InstantiationRange); |
12973 | |
12974 | struct ConstraintsCheck {}; |
12975 | /// \brief Note that we are checking the constraints associated with some |
12976 | /// constrained entity (a concept declaration or a template with associated |
12977 | /// constraints). |
12978 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12979 | ConstraintsCheck, NamedDecl *Template, |
12980 | ArrayRef<TemplateArgument> TemplateArgs, |
12981 | SourceRange InstantiationRange); |
12982 | |
12983 | struct ConstraintSubstitution {}; |
12984 | /// \brief Note that we are checking a constraint expression associated |
12985 | /// with a template declaration or as part of the satisfaction check of a |
12986 | /// concept. |
12987 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12988 | ConstraintSubstitution, NamedDecl *Template, |
12989 | sema::TemplateDeductionInfo &DeductionInfo, |
12990 | SourceRange InstantiationRange); |
12991 | |
12992 | struct ConstraintNormalization {}; |
12993 | /// \brief Note that we are normalizing a constraint expression. |
12994 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
12995 | ConstraintNormalization, NamedDecl *Template, |
12996 | SourceRange InstantiationRange); |
12997 | |
12998 | struct ParameterMappingSubstitution {}; |
12999 | /// \brief Note that we are subtituting into the parameter mapping of an |
13000 | /// atomic constraint during constraint normalization. |
13001 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
13002 | ParameterMappingSubstitution, NamedDecl *Template, |
13003 | SourceRange InstantiationRange); |
13004 | |
13005 | /// \brief Note that we are substituting template arguments into a part of |
13006 | /// a requirement of a requires expression. |
13007 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
13008 | concepts::Requirement *Req, |
13009 | sema::TemplateDeductionInfo &DeductionInfo, |
13010 | SourceRange InstantiationRange = SourceRange()); |
13011 | |
13012 | /// \brief Note that we are checking the satisfaction of the constraint |
13013 | /// expression inside of a nested requirement. |
13014 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
13015 | concepts::NestedRequirement *Req, ConstraintsCheck, |
13016 | SourceRange InstantiationRange = SourceRange()); |
13017 | |
13018 | /// \brief Note that we are checking a requires clause. |
13019 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
13020 | const RequiresExpr *E, |
13021 | sema::TemplateDeductionInfo &DeductionInfo, |
13022 | SourceRange InstantiationRange); |
13023 | |
13024 | struct BuildingDeductionGuidesTag {}; |
13025 | /// \brief Note that we are building deduction guides. |
13026 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
13027 | TemplateDecl *Entity, BuildingDeductionGuidesTag, |
13028 | SourceRange InstantiationRange = SourceRange()); |
13029 | |
13030 | struct PartialOrderingTTP {}; |
13031 | /// \brief Note that we are partial ordering template template parameters. |
13032 | InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc, |
13033 | PartialOrderingTTP, TemplateDecl *PArg, |
13034 | SourceRange InstantiationRange = SourceRange()); |
13035 | |
13036 | /// Note that we have finished instantiating this template. |
13037 | void Clear(); |
13038 | |
13039 | ~InstantiatingTemplate() { Clear(); } |
13040 | |
13041 | /// Determines whether we have exceeded the maximum |
13042 | /// recursive template instantiations. |
13043 | bool isInvalid() const { return Invalid; } |
13044 | |
13045 | /// Determine whether we are already instantiating this |
13046 | /// specialization in some surrounding active instantiation. |
13047 | bool isAlreadyInstantiating() const { return AlreadyInstantiating; } |
13048 | |
13049 | private: |
13050 | Sema &SemaRef; |
13051 | bool Invalid; |
13052 | bool AlreadyInstantiating; |
13053 | bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, |
13054 | SourceRange InstantiationRange); |
13055 | |
13056 | InstantiatingTemplate(Sema &SemaRef, |
13057 | CodeSynthesisContext::SynthesisKind Kind, |
13058 | SourceLocation PointOfInstantiation, |
13059 | SourceRange InstantiationRange, Decl *Entity, |
13060 | NamedDecl *Template = nullptr, |
13061 | ArrayRef<TemplateArgument> TemplateArgs = {}, |
13062 | sema::TemplateDeductionInfo *DeductionInfo = nullptr); |
13063 | |
13064 | InstantiatingTemplate(const InstantiatingTemplate &) = delete; |
13065 | |
13066 | InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete; |
13067 | }; |
13068 | |
13069 | bool SubstTemplateArgument(const TemplateArgumentLoc &Input, |
13070 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13071 | TemplateArgumentLoc &Output, |
13072 | SourceLocation Loc = {}, |
13073 | const DeclarationName &Entity = {}); |
13074 | bool |
13075 | SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, |
13076 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13077 | TemplateArgumentListInfo &Outputs); |
13078 | |
13079 | /// Retrieve the template argument list(s) that should be used to |
13080 | /// instantiate the definition of the given declaration. |
13081 | /// |
13082 | /// \param ND the declaration for which we are computing template |
13083 | /// instantiation arguments. |
13084 | /// |
13085 | /// \param DC In the event we don't HAVE a declaration yet, we instead provide |
13086 | /// the decl context where it will be created. In this case, the `Innermost` |
13087 | /// should likely be provided. If ND is non-null, this is ignored. |
13088 | /// |
13089 | /// \param Innermost if non-NULL, specifies a template argument list for the |
13090 | /// template declaration passed as ND. |
13091 | /// |
13092 | /// \param RelativeToPrimary true if we should get the template |
13093 | /// arguments relative to the primary template, even when we're |
13094 | /// dealing with a specialization. This is only relevant for function |
13095 | /// template specializations. |
13096 | /// |
13097 | /// \param Pattern If non-NULL, indicates the pattern from which we will be |
13098 | /// instantiating the definition of the given declaration, \p ND. This is |
13099 | /// used to determine the proper set of template instantiation arguments for |
13100 | /// friend function template specializations. |
13101 | /// |
13102 | /// \param ForConstraintInstantiation when collecting arguments, |
13103 | /// ForConstraintInstantiation indicates we should continue looking when |
13104 | /// encountering a lambda generic call operator, and continue looking for |
13105 | /// arguments on an enclosing class template. |
13106 | /// |
13107 | /// \param SkipForSpecialization when specified, any template specializations |
13108 | /// in a traversal would be ignored. |
13109 | /// \param ForDefaultArgumentSubstitution indicates we should continue looking |
13110 | /// when encountering a specialized member function template, rather than |
13111 | /// returning immediately. |
13112 | MultiLevelTemplateArgumentList getTemplateInstantiationArgs( |
13113 | const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false, |
13114 | std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt, |
13115 | bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr, |
13116 | bool ForConstraintInstantiation = false, |
13117 | bool SkipForSpecialization = false, |
13118 | bool ForDefaultArgumentSubstitution = false); |
13119 | |
13120 | /// RAII object to handle the state changes required to synthesize |
13121 | /// a function body. |
13122 | class SynthesizedFunctionScope { |
13123 | Sema &S; |
13124 | Sema::ContextRAII SavedContext; |
13125 | bool PushedCodeSynthesisContext = false; |
13126 | |
13127 | public: |
13128 | SynthesizedFunctionScope(Sema &S, DeclContext *DC) |
13129 | : S(S), SavedContext(S, DC) { |
13130 | auto *FD = dyn_cast<FunctionDecl>(Val: DC); |
13131 | S.PushFunctionScope(); |
13132 | S.PushExpressionEvaluationContext( |
13133 | NewContext: (FD && FD->isImmediateFunction()) |
13134 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
13135 | : ExpressionEvaluationContext::PotentiallyEvaluated); |
13136 | if (FD) { |
13137 | auto &Current = S.currentEvaluationContext(); |
13138 | const auto &Parent = S.parentEvaluationContext(); |
13139 | |
13140 | FD->setWillHaveBody(true); |
13141 | Current.InImmediateFunctionContext = |
13142 | FD->isImmediateFunction() || |
13143 | (isLambdaMethod(FD) && (Parent.isConstantEvaluated() || |
13144 | Parent.isImmediateFunctionContext())); |
13145 | |
13146 | Current.InImmediateEscalatingFunctionContext = |
13147 | S.getLangOpts().CPlusPlus20 && FD->isImmediateEscalating(); |
13148 | } else |
13149 | assert(isa<ObjCMethodDecl>(DC)); |
13150 | } |
13151 | |
13152 | void addContextNote(SourceLocation UseLoc) { |
13153 | assert(!PushedCodeSynthesisContext); |
13154 | |
13155 | Sema::CodeSynthesisContext Ctx; |
13156 | Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; |
13157 | Ctx.PointOfInstantiation = UseLoc; |
13158 | Ctx.Entity = cast<Decl>(Val: S.CurContext); |
13159 | S.pushCodeSynthesisContext(Ctx); |
13160 | |
13161 | PushedCodeSynthesisContext = true; |
13162 | } |
13163 | |
13164 | ~SynthesizedFunctionScope() { |
13165 | if (PushedCodeSynthesisContext) |
13166 | S.popCodeSynthesisContext(); |
13167 | if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) { |
13168 | FD->setWillHaveBody(false); |
13169 | S.CheckImmediateEscalatingFunctionDefinition(FD, FSI: S.getCurFunction()); |
13170 | } |
13171 | S.PopExpressionEvaluationContext(); |
13172 | S.PopFunctionScopeInfo(); |
13173 | } |
13174 | }; |
13175 | |
13176 | /// List of active code synthesis contexts. |
13177 | /// |
13178 | /// This vector is treated as a stack. As synthesis of one entity requires |
13179 | /// synthesis of another, additional contexts are pushed onto the stack. |
13180 | SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; |
13181 | |
13182 | /// Specializations whose definitions are currently being instantiated. |
13183 | llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; |
13184 | |
13185 | /// Non-dependent types used in templates that have already been instantiated |
13186 | /// by some template instantiation. |
13187 | llvm::DenseSet<QualType> InstantiatedNonDependentTypes; |
13188 | |
13189 | /// Extra modules inspected when performing a lookup during a template |
13190 | /// instantiation. Computed lazily. |
13191 | SmallVector<Module *, 16> CodeSynthesisContextLookupModules; |
13192 | |
13193 | /// Cache of additional modules that should be used for name lookup |
13194 | /// within the current template instantiation. Computed lazily; use |
13195 | /// getLookupModules() to get a complete set. |
13196 | llvm::DenseSet<Module *> LookupModulesCache; |
13197 | |
13198 | /// Map from the most recent declaration of a namespace to the most |
13199 | /// recent visible declaration of that namespace. |
13200 | llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache; |
13201 | |
13202 | /// Whether we are in a SFINAE context that is not associated with |
13203 | /// template instantiation. |
13204 | /// |
13205 | /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside |
13206 | /// of a template instantiation or template argument deduction. |
13207 | bool InNonInstantiationSFINAEContext; |
13208 | |
13209 | /// The number of \p CodeSynthesisContexts that are not template |
13210 | /// instantiations and, therefore, should not be counted as part of the |
13211 | /// instantiation depth. |
13212 | /// |
13213 | /// When the instantiation depth reaches the user-configurable limit |
13214 | /// \p LangOptions::InstantiationDepth we will abort instantiation. |
13215 | // FIXME: Should we have a similar limit for other forms of synthesis? |
13216 | unsigned NonInstantiationEntries; |
13217 | |
13218 | /// The depth of the context stack at the point when the most recent |
13219 | /// error or warning was produced. |
13220 | /// |
13221 | /// This value is used to suppress printing of redundant context stacks |
13222 | /// when there are multiple errors or warnings in the same instantiation. |
13223 | // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. |
13224 | unsigned LastEmittedCodeSynthesisContextDepth = 0; |
13225 | |
13226 | /// The template instantiation callbacks to trace or track |
13227 | /// instantiations (objects can be chained). |
13228 | /// |
13229 | /// This callbacks is used to print, trace or track template |
13230 | /// instantiations as they are being constructed. |
13231 | std::vector<std::unique_ptr<TemplateInstantiationCallback>> |
13232 | TemplateInstCallbacks; |
13233 | |
13234 | /// The current index into pack expansion arguments that will be |
13235 | /// used for substitution of parameter packs. |
13236 | /// |
13237 | /// The pack expansion index will be -1 to indicate that parameter packs |
13238 | /// should be instantiated as themselves. Otherwise, the index specifies |
13239 | /// which argument within the parameter pack will be used for substitution. |
13240 | int ArgumentPackSubstitutionIndex; |
13241 | |
13242 | /// RAII object used to change the argument pack substitution index |
13243 | /// within a \c Sema object. |
13244 | /// |
13245 | /// See \c ArgumentPackSubstitutionIndex for more information. |
13246 | class ArgumentPackSubstitutionIndexRAII { |
13247 | Sema &Self; |
13248 | int OldSubstitutionIndex; |
13249 | |
13250 | public: |
13251 | ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) |
13252 | : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { |
13253 | Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; |
13254 | } |
13255 | |
13256 | ~ArgumentPackSubstitutionIndexRAII() { |
13257 | Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; |
13258 | } |
13259 | }; |
13260 | |
13261 | friend class ArgumentPackSubstitutionRAII; |
13262 | |
13263 | void pushCodeSynthesisContext(CodeSynthesisContext Ctx); |
13264 | void popCodeSynthesisContext(); |
13265 | |
13266 | void PrintContextStack() { |
13267 | if (!CodeSynthesisContexts.empty() && |
13268 | CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { |
13269 | PrintInstantiationStack(); |
13270 | LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); |
13271 | } |
13272 | if (PragmaAttributeCurrentTargetDecl) |
13273 | PrintPragmaAttributeInstantiationPoint(); |
13274 | } |
13275 | /// Prints the current instantiation stack through a series of |
13276 | /// notes. |
13277 | void PrintInstantiationStack(); |
13278 | |
13279 | /// Determines whether we are currently in a context where |
13280 | /// template argument substitution failures are not considered |
13281 | /// errors. |
13282 | /// |
13283 | /// \returns An empty \c Optional if we're not in a SFINAE context. |
13284 | /// Otherwise, contains a pointer that, if non-NULL, contains the nearest |
13285 | /// template-deduction context object, which can be used to capture |
13286 | /// diagnostics that will be suppressed. |
13287 | std::optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; |
13288 | |
13289 | /// Perform substitution on the type T with a given set of template |
13290 | /// arguments. |
13291 | /// |
13292 | /// This routine substitutes the given template arguments into the |
13293 | /// type T and produces the instantiated type. |
13294 | /// |
13295 | /// \param T the type into which the template arguments will be |
13296 | /// substituted. If this type is not dependent, it will be returned |
13297 | /// immediately. |
13298 | /// |
13299 | /// \param Args the template arguments that will be |
13300 | /// substituted for the top-level template parameters within T. |
13301 | /// |
13302 | /// \param Loc the location in the source code where this substitution |
13303 | /// is being performed. It will typically be the location of the |
13304 | /// declarator (if we're instantiating the type of some declaration) |
13305 | /// or the location of the type in the source code (if, e.g., we're |
13306 | /// instantiating the type of a cast expression). |
13307 | /// |
13308 | /// \param Entity the name of the entity associated with a declaration |
13309 | /// being instantiated (if any). May be empty to indicate that there |
13310 | /// is no such entity (if, e.g., this is a type that occurs as part of |
13311 | /// a cast expression) or that the entity has no name (e.g., an |
13312 | /// unnamed function parameter). |
13313 | /// |
13314 | /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is |
13315 | /// acceptable as the top level type of the result. |
13316 | /// |
13317 | /// \param IsIncompleteSubstitution If provided, the pointee will be set |
13318 | /// whenever substitution would perform a replacement with a null or |
13319 | /// non-existent template argument. |
13320 | /// |
13321 | /// \returns If the instantiation succeeds, the instantiated |
13322 | /// type. Otherwise, produces diagnostics and returns a NULL type. |
13323 | TypeSourceInfo *SubstType(TypeSourceInfo *T, |
13324 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13325 | SourceLocation Loc, DeclarationName Entity, |
13326 | bool AllowDeducedTST = false); |
13327 | |
13328 | QualType SubstType(QualType T, |
13329 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13330 | SourceLocation Loc, DeclarationName Entity, |
13331 | bool *IsIncompleteSubstitution = nullptr); |
13332 | |
13333 | TypeSourceInfo *SubstType(TypeLoc TL, |
13334 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13335 | SourceLocation Loc, DeclarationName Entity); |
13336 | |
13337 | /// A form of SubstType intended specifically for instantiating the |
13338 | /// type of a FunctionDecl. Its purpose is solely to force the |
13339 | /// instantiation of default-argument expressions and to avoid |
13340 | /// instantiating an exception-specification. |
13341 | TypeSourceInfo *SubstFunctionDeclType( |
13342 | TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, |
13343 | SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, |
13344 | Qualifiers ThisTypeQuals, bool EvaluateConstraints = true); |
13345 | void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, |
13346 | const MultiLevelTemplateArgumentList &Args); |
13347 | bool SubstExceptionSpec(SourceLocation Loc, |
13348 | FunctionProtoType::ExceptionSpecInfo &ESI, |
13349 | SmallVectorImpl<QualType> &ExceptionStorage, |
13350 | const MultiLevelTemplateArgumentList &Args); |
13351 | ParmVarDecl * |
13352 | SubstParmVarDecl(ParmVarDecl *D, |
13353 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13354 | int indexAdjustment, std::optional<unsigned> NumExpansions, |
13355 | bool ExpectParameterPack, bool EvaluateConstraints = true); |
13356 | |
13357 | /// Substitute the given template arguments into the given set of |
13358 | /// parameters, producing the set of parameter types that would be generated |
13359 | /// from such a substitution. |
13360 | bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, |
13361 | const FunctionProtoType::ExtParameterInfo *ExtParamInfos, |
13362 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13363 | SmallVectorImpl<QualType> &ParamTypes, |
13364 | SmallVectorImpl<ParmVarDecl *> *OutParams, |
13365 | ExtParameterInfoBuilder &ParamInfos); |
13366 | |
13367 | /// Substitute the given template arguments into the default argument. |
13368 | bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, |
13369 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13370 | bool ForCallExpr = false); |
13371 | ExprResult SubstExpr(Expr *E, |
13372 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13373 | |
13374 | // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator |
13375 | // to disable constraint evaluation, then restore the state. |
13376 | template <typename InstTy> struct ConstraintEvalRAII { |
13377 | InstTy &TI; |
13378 | bool OldValue; |
13379 | |
13380 | ConstraintEvalRAII(InstTy &TI) |
13381 | : TI(TI), OldValue(TI.getEvaluateConstraints()) { |
13382 | TI.setEvaluateConstraints(false); |
13383 | } |
13384 | ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); } |
13385 | }; |
13386 | |
13387 | // Must be used instead of SubstExpr at 'constraint checking' time. |
13388 | ExprResult |
13389 | SubstConstraintExpr(Expr *E, |
13390 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13391 | // Unlike the above, this does not evaluates constraints. |
13392 | ExprResult SubstConstraintExprWithoutSatisfaction( |
13393 | Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); |
13394 | |
13395 | /// Substitute the given template arguments into a list of |
13396 | /// expressions, expanding pack expansions if required. |
13397 | /// |
13398 | /// \param Exprs The list of expressions to substitute into. |
13399 | /// |
13400 | /// \param IsCall Whether this is some form of call, in which case |
13401 | /// default arguments will be dropped. |
13402 | /// |
13403 | /// \param TemplateArgs The set of template arguments to substitute. |
13404 | /// |
13405 | /// \param Outputs Will receive all of the substituted arguments. |
13406 | /// |
13407 | /// \returns true if an error occurred, false otherwise. |
13408 | bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, |
13409 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13410 | SmallVectorImpl<Expr *> &Outputs); |
13411 | |
13412 | StmtResult SubstStmt(Stmt *S, |
13413 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13414 | |
13415 | ExprResult |
13416 | SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, |
13417 | bool CXXDirectInit); |
13418 | |
13419 | /// Perform substitution on the base class specifiers of the |
13420 | /// given class template specialization. |
13421 | /// |
13422 | /// Produces a diagnostic and returns true on error, returns false and |
13423 | /// attaches the instantiated base classes to the class template |
13424 | /// specialization if successful. |
13425 | bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, |
13426 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13427 | |
13428 | /// Instantiate the definition of a class from a given pattern. |
13429 | /// |
13430 | /// \param PointOfInstantiation The point of instantiation within the |
13431 | /// source code. |
13432 | /// |
13433 | /// \param Instantiation is the declaration whose definition is being |
13434 | /// instantiated. This will be either a class template specialization |
13435 | /// or a member class of a class template specialization. |
13436 | /// |
13437 | /// \param Pattern is the pattern from which the instantiation |
13438 | /// occurs. This will be either the declaration of a class template or |
13439 | /// the declaration of a member class of a class template. |
13440 | /// |
13441 | /// \param TemplateArgs The template arguments to be substituted into |
13442 | /// the pattern. |
13443 | /// |
13444 | /// \param TSK the kind of implicit or explicit instantiation to perform. |
13445 | /// |
13446 | /// \param Complain whether to complain if the class cannot be instantiated |
13447 | /// due to the lack of a definition. |
13448 | /// |
13449 | /// \returns true if an error occurred, false otherwise. |
13450 | bool InstantiateClass(SourceLocation PointOfInstantiation, |
13451 | CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, |
13452 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13453 | TemplateSpecializationKind TSK, bool Complain = true); |
13454 | |
13455 | /// Instantiate the definition of an enum from a given pattern. |
13456 | /// |
13457 | /// \param PointOfInstantiation The point of instantiation within the |
13458 | /// source code. |
13459 | /// \param Instantiation is the declaration whose definition is being |
13460 | /// instantiated. This will be a member enumeration of a class |
13461 | /// temploid specialization, or a local enumeration within a |
13462 | /// function temploid specialization. |
13463 | /// \param Pattern The templated declaration from which the instantiation |
13464 | /// occurs. |
13465 | /// \param TemplateArgs The template arguments to be substituted into |
13466 | /// the pattern. |
13467 | /// \param TSK The kind of implicit or explicit instantiation to perform. |
13468 | /// |
13469 | /// \return \c true if an error occurred, \c false otherwise. |
13470 | bool InstantiateEnum(SourceLocation PointOfInstantiation, |
13471 | EnumDecl *Instantiation, EnumDecl *Pattern, |
13472 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13473 | TemplateSpecializationKind TSK); |
13474 | |
13475 | /// Instantiate the definition of a field from the given pattern. |
13476 | /// |
13477 | /// \param PointOfInstantiation The point of instantiation within the |
13478 | /// source code. |
13479 | /// \param Instantiation is the declaration whose definition is being |
13480 | /// instantiated. This will be a class of a class temploid |
13481 | /// specialization, or a local enumeration within a function temploid |
13482 | /// specialization. |
13483 | /// \param Pattern The templated declaration from which the instantiation |
13484 | /// occurs. |
13485 | /// \param TemplateArgs The template arguments to be substituted into |
13486 | /// the pattern. |
13487 | /// |
13488 | /// \return \c true if an error occurred, \c false otherwise. |
13489 | bool InstantiateInClassInitializer( |
13490 | SourceLocation PointOfInstantiation, FieldDecl *Instantiation, |
13491 | FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); |
13492 | |
13493 | bool usesPartialOrExplicitSpecialization( |
13494 | SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); |
13495 | |
13496 | bool InstantiateClassTemplateSpecialization( |
13497 | SourceLocation PointOfInstantiation, |
13498 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
13499 | TemplateSpecializationKind TSK, bool Complain, |
13500 | bool PrimaryStrictPackMatch); |
13501 | |
13502 | /// Instantiates the definitions of all of the member |
13503 | /// of the given class, which is an instantiation of a class template |
13504 | /// or a member class of a template. |
13505 | void |
13506 | InstantiateClassMembers(SourceLocation PointOfInstantiation, |
13507 | CXXRecordDecl *Instantiation, |
13508 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13509 | TemplateSpecializationKind TSK); |
13510 | |
13511 | /// Instantiate the definitions of all of the members of the |
13512 | /// given class template specialization, which was named as part of an |
13513 | /// explicit instantiation. |
13514 | void InstantiateClassTemplateSpecializationMembers( |
13515 | SourceLocation PointOfInstantiation, |
13516 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
13517 | TemplateSpecializationKind TSK); |
13518 | |
13519 | NestedNameSpecifierLoc SubstNestedNameSpecifierLoc( |
13520 | NestedNameSpecifierLoc NNS, |
13521 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13522 | |
13523 | /// Do template substitution on declaration name info. |
13524 | DeclarationNameInfo |
13525 | SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, |
13526 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13527 | TemplateName |
13528 | SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, |
13529 | SourceLocation Loc, |
13530 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13531 | |
13532 | bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, |
13533 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13534 | bool EvaluateConstraint); |
13535 | |
13536 | /// Determine whether we are currently performing template instantiation. |
13537 | bool inTemplateInstantiation() const { |
13538 | return CodeSynthesisContexts.size() > NonInstantiationEntries; |
13539 | } |
13540 | |
13541 | using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>; |
13542 | |
13543 | /// \brief create a Requirement::SubstitutionDiagnostic with only a |
13544 | /// SubstitutedEntity and DiagLoc using ASTContext's allocator. |
13545 | concepts::Requirement::SubstitutionDiagnostic * |
13546 | createSubstDiagAt(SourceLocation Location, EntityPrinter Printer); |
13547 | |
13548 | ///@} |
13549 | |
13550 | // |
13551 | // |
13552 | // ------------------------------------------------------------------------- |
13553 | // |
13554 | // |
13555 | |
13556 | /// \name C++ Template Declaration Instantiation |
13557 | /// Implementations are in SemaTemplateInstantiateDecl.cpp |
13558 | ///@{ |
13559 | |
13560 | public: |
13561 | /// An entity for which implicit template instantiation is required. |
13562 | /// |
13563 | /// The source location associated with the declaration is the first place in |
13564 | /// the source code where the declaration was "used". It is not necessarily |
13565 | /// the point of instantiation (which will be either before or after the |
13566 | /// namespace-scope declaration that triggered this implicit instantiation), |
13567 | /// However, it is the location that diagnostics should generally refer to, |
13568 | /// because users will need to know what code triggered the instantiation. |
13569 | typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; |
13570 | |
13571 | /// The queue of implicit template instantiations that are required |
13572 | /// but have not yet been performed. |
13573 | std::deque<PendingImplicitInstantiation> PendingInstantiations; |
13574 | |
13575 | /// Queue of implicit template instantiations that cannot be performed |
13576 | /// eagerly. |
13577 | SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; |
13578 | |
13579 | SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses; |
13580 | SmallVector<std::deque<PendingImplicitInstantiation>, 8> |
13581 | SavedPendingInstantiations; |
13582 | |
13583 | /// The queue of implicit template instantiations that are required |
13584 | /// and must be performed within the current local scope. |
13585 | /// |
13586 | /// This queue is only used for member functions of local classes in |
13587 | /// templates, which must be instantiated in the same scope as their |
13588 | /// enclosing function, so that they can reference function-local |
13589 | /// types, static variables, enumerators, etc. |
13590 | std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; |
13591 | |
13592 | class LocalEagerInstantiationScope { |
13593 | public: |
13594 | LocalEagerInstantiationScope(Sema &S) : S(S) { |
13595 | SavedPendingLocalImplicitInstantiations.swap( |
13596 | x&: S.PendingLocalImplicitInstantiations); |
13597 | } |
13598 | |
13599 | void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: true); } |
13600 | |
13601 | ~LocalEagerInstantiationScope() { |
13602 | assert(S.PendingLocalImplicitInstantiations.empty() && |
13603 | "there shouldn't be any pending local implicit instantiations" ); |
13604 | SavedPendingLocalImplicitInstantiations.swap( |
13605 | x&: S.PendingLocalImplicitInstantiations); |
13606 | } |
13607 | |
13608 | private: |
13609 | Sema &S; |
13610 | std::deque<PendingImplicitInstantiation> |
13611 | SavedPendingLocalImplicitInstantiations; |
13612 | }; |
13613 | |
13614 | /// Records and restores the CurFPFeatures state on entry/exit of compound |
13615 | /// statements. |
13616 | class FPFeaturesStateRAII { |
13617 | public: |
13618 | FPFeaturesStateRAII(Sema &S); |
13619 | ~FPFeaturesStateRAII(); |
13620 | FPOptionsOverride getOverrides() { return OldOverrides; } |
13621 | |
13622 | private: |
13623 | Sema &S; |
13624 | FPOptions OldFPFeaturesState; |
13625 | FPOptionsOverride OldOverrides; |
13626 | LangOptions::FPEvalMethodKind OldEvalMethod; |
13627 | SourceLocation OldFPPragmaLocation; |
13628 | }; |
13629 | |
13630 | class GlobalEagerInstantiationScope { |
13631 | public: |
13632 | GlobalEagerInstantiationScope(Sema &S, bool Enabled) |
13633 | : S(S), Enabled(Enabled) { |
13634 | if (!Enabled) |
13635 | return; |
13636 | |
13637 | S.SavedPendingInstantiations.emplace_back(); |
13638 | S.SavedPendingInstantiations.back().swap(x&: S.PendingInstantiations); |
13639 | |
13640 | S.SavedVTableUses.emplace_back(); |
13641 | S.SavedVTableUses.back().swap(RHS&: S.VTableUses); |
13642 | } |
13643 | |
13644 | void perform() { |
13645 | if (Enabled) { |
13646 | S.DefineUsedVTables(); |
13647 | S.PerformPendingInstantiations(); |
13648 | } |
13649 | } |
13650 | |
13651 | ~GlobalEagerInstantiationScope() { |
13652 | if (!Enabled) |
13653 | return; |
13654 | |
13655 | // Restore the set of pending vtables. |
13656 | assert(S.VTableUses.empty() && |
13657 | "VTableUses should be empty before it is discarded." ); |
13658 | S.VTableUses.swap(RHS&: S.SavedVTableUses.back()); |
13659 | S.SavedVTableUses.pop_back(); |
13660 | |
13661 | // Restore the set of pending implicit instantiations. |
13662 | if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { |
13663 | assert(S.PendingInstantiations.empty() && |
13664 | "PendingInstantiations should be empty before it is discarded." ); |
13665 | S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back()); |
13666 | S.SavedPendingInstantiations.pop_back(); |
13667 | } else { |
13668 | // Template instantiations in the PCH may be delayed until the TU. |
13669 | S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back()); |
13670 | S.PendingInstantiations.insert( |
13671 | position: S.PendingInstantiations.end(), |
13672 | first: S.SavedPendingInstantiations.back().begin(), |
13673 | last: S.SavedPendingInstantiations.back().end()); |
13674 | S.SavedPendingInstantiations.pop_back(); |
13675 | } |
13676 | } |
13677 | |
13678 | private: |
13679 | Sema &S; |
13680 | bool Enabled; |
13681 | }; |
13682 | |
13683 | ExplicitSpecifier instantiateExplicitSpecifier( |
13684 | const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES); |
13685 | |
13686 | struct LateInstantiatedAttribute { |
13687 | const Attr *TmplAttr; |
13688 | LocalInstantiationScope *Scope; |
13689 | Decl *NewDecl; |
13690 | |
13691 | LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, |
13692 | Decl *D) |
13693 | : TmplAttr(A), Scope(S), NewDecl(D) {} |
13694 | }; |
13695 | typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; |
13696 | |
13697 | void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, |
13698 | const Decl *Pattern, Decl *Inst, |
13699 | LateInstantiatedAttrVec *LateAttrs = nullptr, |
13700 | LocalInstantiationScope *OuterMostScope = nullptr); |
13701 | |
13702 | /// Update instantiation attributes after template was late parsed. |
13703 | /// |
13704 | /// Some attributes are evaluated based on the body of template. If it is |
13705 | /// late parsed, such attributes cannot be evaluated when declaration is |
13706 | /// instantiated. This function is used to update instantiation attributes |
13707 | /// when template definition is ready. |
13708 | void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst); |
13709 | |
13710 | void |
13711 | InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, |
13712 | const Decl *Pattern, Decl *Inst, |
13713 | LateInstantiatedAttrVec *LateAttrs = nullptr, |
13714 | LocalInstantiationScope *OuterMostScope = nullptr); |
13715 | |
13716 | /// In the MS ABI, we need to instantiate default arguments of dllexported |
13717 | /// default constructors along with the constructor definition. This allows IR |
13718 | /// gen to emit a constructor closure which calls the default constructor with |
13719 | /// its default arguments. |
13720 | void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); |
13721 | |
13722 | bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, |
13723 | ParmVarDecl *Param); |
13724 | void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, |
13725 | FunctionDecl *Function); |
13726 | |
13727 | /// Instantiate (or find existing instantiation of) a function template with a |
13728 | /// given set of template arguments. |
13729 | /// |
13730 | /// Usually this should not be used, and template argument deduction should be |
13731 | /// used in its place. |
13732 | FunctionDecl *InstantiateFunctionDeclaration( |
13733 | FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, |
13734 | SourceLocation Loc, |
13735 | CodeSynthesisContext::SynthesisKind CSC = |
13736 | CodeSynthesisContext::ExplicitTemplateArgumentSubstitution); |
13737 | |
13738 | /// Instantiate the definition of the given function from its |
13739 | /// template. |
13740 | /// |
13741 | /// \param PointOfInstantiation the point at which the instantiation was |
13742 | /// required. Note that this is not precisely a "point of instantiation" |
13743 | /// for the function, but it's close. |
13744 | /// |
13745 | /// \param Function the already-instantiated declaration of a |
13746 | /// function template specialization or member function of a class template |
13747 | /// specialization. |
13748 | /// |
13749 | /// \param Recursive if true, recursively instantiates any functions that |
13750 | /// are required by this instantiation. |
13751 | /// |
13752 | /// \param DefinitionRequired if true, then we are performing an explicit |
13753 | /// instantiation where the body of the function is required. Complain if |
13754 | /// there is no such body. |
13755 | void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, |
13756 | FunctionDecl *Function, |
13757 | bool Recursive = false, |
13758 | bool DefinitionRequired = false, |
13759 | bool AtEndOfTU = false); |
13760 | VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( |
13761 | VarTemplateDecl *VarTemplate, VarDecl *FromVar, |
13762 | const TemplateArgumentList *PartialSpecArgs, |
13763 | const TemplateArgumentListInfo &TemplateArgsInfo, |
13764 | SmallVectorImpl<TemplateArgument> &Converted, |
13765 | SourceLocation PointOfInstantiation, |
13766 | LateInstantiatedAttrVec *LateAttrs = nullptr, |
13767 | LocalInstantiationScope *StartingScope = nullptr); |
13768 | |
13769 | /// Instantiates a variable template specialization by completing it |
13770 | /// with appropriate type information and initializer. |
13771 | VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( |
13772 | VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, |
13773 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13774 | |
13775 | /// BuildVariableInstantiation - Used after a new variable has been created. |
13776 | /// Sets basic variable data and decides whether to postpone the |
13777 | /// variable instantiation. |
13778 | void |
13779 | BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, |
13780 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13781 | LateInstantiatedAttrVec *LateAttrs, |
13782 | DeclContext *Owner, |
13783 | LocalInstantiationScope *StartingScope, |
13784 | bool InstantiatingVarTemplate = false, |
13785 | VarTemplateSpecializationDecl *PrevVTSD = nullptr); |
13786 | |
13787 | /// Instantiate the initializer of a variable. |
13788 | void InstantiateVariableInitializer( |
13789 | VarDecl *Var, VarDecl *OldVar, |
13790 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13791 | |
13792 | /// Instantiate the definition of the given variable from its |
13793 | /// template. |
13794 | /// |
13795 | /// \param PointOfInstantiation the point at which the instantiation was |
13796 | /// required. Note that this is not precisely a "point of instantiation" |
13797 | /// for the variable, but it's close. |
13798 | /// |
13799 | /// \param Var the already-instantiated declaration of a templated variable. |
13800 | /// |
13801 | /// \param Recursive if true, recursively instantiates any functions that |
13802 | /// are required by this instantiation. |
13803 | /// |
13804 | /// \param DefinitionRequired if true, then we are performing an explicit |
13805 | /// instantiation where a definition of the variable is required. Complain |
13806 | /// if there is no such definition. |
13807 | void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, |
13808 | VarDecl *Var, bool Recursive = false, |
13809 | bool DefinitionRequired = false, |
13810 | bool AtEndOfTU = false); |
13811 | |
13812 | void InstantiateMemInitializers( |
13813 | CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, |
13814 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13815 | |
13816 | /// Find the instantiation of the given declaration within the |
13817 | /// current instantiation. |
13818 | /// |
13819 | /// This routine is intended to be used when \p D is a declaration |
13820 | /// referenced from within a template, that needs to mapped into the |
13821 | /// corresponding declaration within an instantiation. For example, |
13822 | /// given: |
13823 | /// |
13824 | /// \code |
13825 | /// template<typename T> |
13826 | /// struct X { |
13827 | /// enum Kind { |
13828 | /// KnownValue = sizeof(T) |
13829 | /// }; |
13830 | /// |
13831 | /// bool getKind() const { return KnownValue; } |
13832 | /// }; |
13833 | /// |
13834 | /// template struct X<int>; |
13835 | /// \endcode |
13836 | /// |
13837 | /// In the instantiation of X<int>::getKind(), we need to map the \p |
13838 | /// EnumConstantDecl for \p KnownValue (which refers to |
13839 | /// X<T>::<Kind>::KnownValue) to its instantiation |
13840 | /// (X<int>::<Kind>::KnownValue). |
13841 | /// \p FindInstantiatedDecl performs this mapping from within the |
13842 | /// instantiation of X<int>. |
13843 | NamedDecl * |
13844 | FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, |
13845 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13846 | bool FindingInstantiatedContext = false); |
13847 | |
13848 | /// Finds the instantiation of the given declaration context |
13849 | /// within the current instantiation. |
13850 | /// |
13851 | /// \returns NULL if there was an error |
13852 | DeclContext * |
13853 | FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, |
13854 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13855 | |
13856 | Decl *SubstDecl(Decl *D, DeclContext *Owner, |
13857 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13858 | |
13859 | /// Substitute the name and return type of a defaulted 'operator<=>' to form |
13860 | /// an implicit 'operator=='. |
13861 | FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, |
13862 | FunctionDecl *Spaceship); |
13863 | |
13864 | /// Performs template instantiation for all implicit template |
13865 | /// instantiations we have seen until this point. |
13866 | void PerformPendingInstantiations(bool LocalOnly = false); |
13867 | |
13868 | TemplateParameterList * |
13869 | SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, |
13870 | const MultiLevelTemplateArgumentList &TemplateArgs, |
13871 | bool EvaluateConstraints = true); |
13872 | |
13873 | void PerformDependentDiagnostics( |
13874 | const DeclContext *Pattern, |
13875 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13876 | |
13877 | private: |
13878 | /// Introduce the instantiated local variables into the local |
13879 | /// instantiation scope. |
13880 | void addInstantiatedLocalVarsToScope(FunctionDecl *Function, |
13881 | const FunctionDecl *PatternDecl, |
13882 | LocalInstantiationScope &Scope); |
13883 | /// Introduce the instantiated function parameters into the local |
13884 | /// instantiation scope, and set the parameter names to those used |
13885 | /// in the template. |
13886 | bool addInstantiatedParametersToScope( |
13887 | FunctionDecl *Function, const FunctionDecl *PatternDecl, |
13888 | LocalInstantiationScope &Scope, |
13889 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13890 | |
13891 | /// Introduce the instantiated captures of the lambda into the local |
13892 | /// instantiation scope. |
13893 | bool addInstantiatedCapturesToScope( |
13894 | FunctionDecl *Function, const FunctionDecl *PatternDecl, |
13895 | LocalInstantiationScope &Scope, |
13896 | const MultiLevelTemplateArgumentList &TemplateArgs); |
13897 | |
13898 | int ParsingClassDepth = 0; |
13899 | |
13900 | class SavePendingParsedClassStateRAII { |
13901 | public: |
13902 | SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } |
13903 | |
13904 | ~SavePendingParsedClassStateRAII() { |
13905 | assert(S.DelayedOverridingExceptionSpecChecks.empty() && |
13906 | "there shouldn't be any pending delayed exception spec checks" ); |
13907 | assert(S.DelayedEquivalentExceptionSpecChecks.empty() && |
13908 | "there shouldn't be any pending delayed exception spec checks" ); |
13909 | swapSavedState(); |
13910 | } |
13911 | |
13912 | private: |
13913 | Sema &S; |
13914 | decltype(DelayedOverridingExceptionSpecChecks) |
13915 | SavedOverridingExceptionSpecChecks; |
13916 | decltype(DelayedEquivalentExceptionSpecChecks) |
13917 | SavedEquivalentExceptionSpecChecks; |
13918 | |
13919 | void swapSavedState() { |
13920 | SavedOverridingExceptionSpecChecks.swap( |
13921 | RHS&: S.DelayedOverridingExceptionSpecChecks); |
13922 | SavedEquivalentExceptionSpecChecks.swap( |
13923 | RHS&: S.DelayedEquivalentExceptionSpecChecks); |
13924 | } |
13925 | }; |
13926 | |
13927 | ///@} |
13928 | |
13929 | // |
13930 | // |
13931 | // ------------------------------------------------------------------------- |
13932 | // |
13933 | // |
13934 | |
13935 | /// \name C++ Variadic Templates |
13936 | /// Implementations are in SemaTemplateVariadic.cpp |
13937 | ///@{ |
13938 | |
13939 | public: |
13940 | /// Determine whether an unexpanded parameter pack might be permitted in this |
13941 | /// location. Useful for error recovery. |
13942 | bool isUnexpandedParameterPackPermitted(); |
13943 | |
13944 | /// The context in which an unexpanded parameter pack is |
13945 | /// being diagnosed. |
13946 | /// |
13947 | /// Note that the values of this enumeration line up with the first |
13948 | /// argument to the \c err_unexpanded_parameter_pack diagnostic. |
13949 | enum UnexpandedParameterPackContext { |
13950 | /// An arbitrary expression. |
13951 | UPPC_Expression = 0, |
13952 | |
13953 | /// The base type of a class type. |
13954 | UPPC_BaseType, |
13955 | |
13956 | /// The type of an arbitrary declaration. |
13957 | UPPC_DeclarationType, |
13958 | |
13959 | /// The type of a data member. |
13960 | UPPC_DataMemberType, |
13961 | |
13962 | /// The size of a bit-field. |
13963 | UPPC_BitFieldWidth, |
13964 | |
13965 | /// The expression in a static assertion. |
13966 | UPPC_StaticAssertExpression, |
13967 | |
13968 | /// The fixed underlying type of an enumeration. |
13969 | UPPC_FixedUnderlyingType, |
13970 | |
13971 | /// The enumerator value. |
13972 | UPPC_EnumeratorValue, |
13973 | |
13974 | /// A using declaration. |
13975 | UPPC_UsingDeclaration, |
13976 | |
13977 | /// A friend declaration. |
13978 | UPPC_FriendDeclaration, |
13979 | |
13980 | /// A declaration qualifier. |
13981 | UPPC_DeclarationQualifier, |
13982 | |
13983 | /// An initializer. |
13984 | UPPC_Initializer, |
13985 | |
13986 | /// A default argument. |
13987 | UPPC_DefaultArgument, |
13988 | |
13989 | /// The type of a non-type template parameter. |
13990 | UPPC_NonTypeTemplateParameterType, |
13991 | |
13992 | /// The type of an exception. |
13993 | UPPC_ExceptionType, |
13994 | |
13995 | /// Explicit specialization. |
13996 | UPPC_ExplicitSpecialization, |
13997 | |
13998 | /// Partial specialization. |
13999 | UPPC_PartialSpecialization, |
14000 | |
14001 | /// Microsoft __if_exists. |
14002 | UPPC_IfExists, |
14003 | |
14004 | /// Microsoft __if_not_exists. |
14005 | UPPC_IfNotExists, |
14006 | |
14007 | /// Lambda expression. |
14008 | UPPC_Lambda, |
14009 | |
14010 | /// Block expression. |
14011 | UPPC_Block, |
14012 | |
14013 | /// A type constraint. |
14014 | UPPC_TypeConstraint, |
14015 | |
14016 | // A requirement in a requires-expression. |
14017 | UPPC_Requirement, |
14018 | |
14019 | // A requires-clause. |
14020 | UPPC_RequiresClause, |
14021 | }; |
14022 | |
14023 | /// Diagnose unexpanded parameter packs. |
14024 | /// |
14025 | /// \param Loc The location at which we should emit the diagnostic. |
14026 | /// |
14027 | /// \param UPPC The context in which we are diagnosing unexpanded |
14028 | /// parameter packs. |
14029 | /// |
14030 | /// \param Unexpanded the set of unexpanded parameter packs. |
14031 | /// |
14032 | /// \returns true if an error occurred, false otherwise. |
14033 | bool DiagnoseUnexpandedParameterPacks( |
14034 | SourceLocation Loc, UnexpandedParameterPackContext UPPC, |
14035 | ArrayRef<UnexpandedParameterPack> Unexpanded); |
14036 | |
14037 | /// If the given type contains an unexpanded parameter pack, |
14038 | /// diagnose the error. |
14039 | /// |
14040 | /// \param Loc The source location where a diagnostc should be emitted. |
14041 | /// |
14042 | /// \param T The type that is being checked for unexpanded parameter |
14043 | /// packs. |
14044 | /// |
14045 | /// \returns true if an error occurred, false otherwise. |
14046 | bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, |
14047 | UnexpandedParameterPackContext UPPC); |
14048 | |
14049 | /// If the given expression contains an unexpanded parameter |
14050 | /// pack, diagnose the error. |
14051 | /// |
14052 | /// \param E The expression that is being checked for unexpanded |
14053 | /// parameter packs. |
14054 | /// |
14055 | /// \returns true if an error occurred, false otherwise. |
14056 | bool DiagnoseUnexpandedParameterPack( |
14057 | Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); |
14058 | |
14059 | /// If the given requirees-expression contains an unexpanded reference to one |
14060 | /// of its own parameter packs, diagnose the error. |
14061 | /// |
14062 | /// \param RE The requiress-expression that is being checked for unexpanded |
14063 | /// parameter packs. |
14064 | /// |
14065 | /// \returns true if an error occurred, false otherwise. |
14066 | bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); |
14067 | |
14068 | /// If the given nested-name-specifier contains an unexpanded |
14069 | /// parameter pack, diagnose the error. |
14070 | /// |
14071 | /// \param SS The nested-name-specifier that is being checked for |
14072 | /// unexpanded parameter packs. |
14073 | /// |
14074 | /// \returns true if an error occurred, false otherwise. |
14075 | bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, |
14076 | UnexpandedParameterPackContext UPPC); |
14077 | |
14078 | /// If the given name contains an unexpanded parameter pack, |
14079 | /// diagnose the error. |
14080 | /// |
14081 | /// \param NameInfo The name (with source location information) that |
14082 | /// is being checked for unexpanded parameter packs. |
14083 | /// |
14084 | /// \returns true if an error occurred, false otherwise. |
14085 | bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, |
14086 | UnexpandedParameterPackContext UPPC); |
14087 | |
14088 | /// If the given template name contains an unexpanded parameter pack, |
14089 | /// diagnose the error. |
14090 | /// |
14091 | /// \param Loc The location of the template name. |
14092 | /// |
14093 | /// \param Template The template name that is being checked for unexpanded |
14094 | /// parameter packs. |
14095 | /// |
14096 | /// \returns true if an error occurred, false otherwise. |
14097 | bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, |
14098 | TemplateName Template, |
14099 | UnexpandedParameterPackContext UPPC); |
14100 | |
14101 | /// If the given template argument contains an unexpanded parameter |
14102 | /// pack, diagnose the error. |
14103 | /// |
14104 | /// \param Arg The template argument that is being checked for unexpanded |
14105 | /// parameter packs. |
14106 | /// |
14107 | /// \returns true if an error occurred, false otherwise. |
14108 | bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, |
14109 | UnexpandedParameterPackContext UPPC); |
14110 | |
14111 | /// Collect the set of unexpanded parameter packs within the given |
14112 | /// template argument. |
14113 | /// |
14114 | /// \param Arg The template argument that will be traversed to find |
14115 | /// unexpanded parameter packs. |
14116 | void collectUnexpandedParameterPacks( |
14117 | TemplateArgument Arg, |
14118 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
14119 | |
14120 | /// Collect the set of unexpanded parameter packs within the given |
14121 | /// template argument. |
14122 | /// |
14123 | /// \param Arg The template argument that will be traversed to find |
14124 | /// unexpanded parameter packs. |
14125 | void collectUnexpandedParameterPacks( |
14126 | TemplateArgumentLoc Arg, |
14127 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
14128 | |
14129 | /// Collect the set of unexpanded parameter packs within the given |
14130 | /// type. |
14131 | /// |
14132 | /// \param T The type that will be traversed to find |
14133 | /// unexpanded parameter packs. |
14134 | void collectUnexpandedParameterPacks( |
14135 | QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
14136 | |
14137 | /// Collect the set of unexpanded parameter packs within the given |
14138 | /// type. |
14139 | /// |
14140 | /// \param TL The type that will be traversed to find |
14141 | /// unexpanded parameter packs. |
14142 | void collectUnexpandedParameterPacks( |
14143 | TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
14144 | |
14145 | /// Collect the set of unexpanded parameter packs within the given |
14146 | /// nested-name-specifier. |
14147 | /// |
14148 | /// \param NNS The nested-name-specifier that will be traversed to find |
14149 | /// unexpanded parameter packs. |
14150 | void collectUnexpandedParameterPacks( |
14151 | NestedNameSpecifierLoc NNS, |
14152 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
14153 | |
14154 | /// Collect the set of unexpanded parameter packs within the given |
14155 | /// name. |
14156 | /// |
14157 | /// \param NameInfo The name that will be traversed to find |
14158 | /// unexpanded parameter packs. |
14159 | void collectUnexpandedParameterPacks( |
14160 | const DeclarationNameInfo &NameInfo, |
14161 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
14162 | |
14163 | /// Collect the set of unexpanded parameter packs within the given |
14164 | /// expression. |
14165 | static void collectUnexpandedParameterPacks( |
14166 | Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
14167 | |
14168 | /// Invoked when parsing a template argument followed by an |
14169 | /// ellipsis, which creates a pack expansion. |
14170 | /// |
14171 | /// \param Arg The template argument preceding the ellipsis, which |
14172 | /// may already be invalid. |
14173 | /// |
14174 | /// \param EllipsisLoc The location of the ellipsis. |
14175 | ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, |
14176 | SourceLocation EllipsisLoc); |
14177 | |
14178 | /// Invoked when parsing a type followed by an ellipsis, which |
14179 | /// creates a pack expansion. |
14180 | /// |
14181 | /// \param Type The type preceding the ellipsis, which will become |
14182 | /// the pattern of the pack expansion. |
14183 | /// |
14184 | /// \param EllipsisLoc The location of the ellipsis. |
14185 | TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); |
14186 | |
14187 | /// Construct a pack expansion type from the pattern of the pack |
14188 | /// expansion. |
14189 | TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, |
14190 | SourceLocation EllipsisLoc, |
14191 | std::optional<unsigned> NumExpansions); |
14192 | |
14193 | /// Construct a pack expansion type from the pattern of the pack |
14194 | /// expansion. |
14195 | QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, |
14196 | SourceLocation EllipsisLoc, |
14197 | std::optional<unsigned> NumExpansions); |
14198 | |
14199 | /// Invoked when parsing an expression followed by an ellipsis, which |
14200 | /// creates a pack expansion. |
14201 | /// |
14202 | /// \param Pattern The expression preceding the ellipsis, which will become |
14203 | /// the pattern of the pack expansion. |
14204 | /// |
14205 | /// \param EllipsisLoc The location of the ellipsis. |
14206 | ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); |
14207 | |
14208 | /// Invoked when parsing an expression followed by an ellipsis, which |
14209 | /// creates a pack expansion. |
14210 | /// |
14211 | /// \param Pattern The expression preceding the ellipsis, which will become |
14212 | /// the pattern of the pack expansion. |
14213 | /// |
14214 | /// \param EllipsisLoc The location of the ellipsis. |
14215 | ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, |
14216 | std::optional<unsigned> NumExpansions); |
14217 | |
14218 | /// Determine whether we could expand a pack expansion with the |
14219 | /// given set of parameter packs into separate arguments by repeatedly |
14220 | /// transforming the pattern. |
14221 | /// |
14222 | /// \param EllipsisLoc The location of the ellipsis that identifies the |
14223 | /// pack expansion. |
14224 | /// |
14225 | /// \param PatternRange The source range that covers the entire pattern of |
14226 | /// the pack expansion. |
14227 | /// |
14228 | /// \param Unexpanded The set of unexpanded parameter packs within the |
14229 | /// pattern. |
14230 | /// |
14231 | /// \param ShouldExpand Will be set to \c true if the transformer should |
14232 | /// expand the corresponding pack expansions into separate arguments. When |
14233 | /// set, \c NumExpansions must also be set. |
14234 | /// |
14235 | /// \param RetainExpansion Whether the caller should add an unexpanded |
14236 | /// pack expansion after all of the expanded arguments. This is used |
14237 | /// when extending explicitly-specified template argument packs per |
14238 | /// C++0x [temp.arg.explicit]p9. |
14239 | /// |
14240 | /// \param NumExpansions The number of separate arguments that will be in |
14241 | /// the expanded form of the corresponding pack expansion. This is both an |
14242 | /// input and an output parameter, which can be set by the caller if the |
14243 | /// number of expansions is known a priori (e.g., due to a prior substitution) |
14244 | /// and will be set by the callee when the number of expansions is known. |
14245 | /// The callee must set this value when \c ShouldExpand is \c true; it may |
14246 | /// set this value in other cases. |
14247 | /// |
14248 | /// \returns true if an error occurred (e.g., because the parameter packs |
14249 | /// are to be instantiated with arguments of different lengths), false |
14250 | /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) |
14251 | /// must be set. |
14252 | bool CheckParameterPacksForExpansion( |
14253 | SourceLocation EllipsisLoc, SourceRange PatternRange, |
14254 | ArrayRef<UnexpandedParameterPack> Unexpanded, |
14255 | const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, |
14256 | bool &RetainExpansion, std::optional<unsigned> &NumExpansions); |
14257 | |
14258 | /// Determine the number of arguments in the given pack expansion |
14259 | /// type. |
14260 | /// |
14261 | /// This routine assumes that the number of arguments in the expansion is |
14262 | /// consistent across all of the unexpanded parameter packs in its pattern. |
14263 | /// |
14264 | /// Returns an empty Optional if the type can't be expanded. |
14265 | std::optional<unsigned> getNumArgumentsInExpansion( |
14266 | QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); |
14267 | |
14268 | std::optional<unsigned> getNumArgumentsInExpansionFromUnexpanded( |
14269 | llvm::ArrayRef<UnexpandedParameterPack> Unexpanded, |
14270 | const MultiLevelTemplateArgumentList &TemplateArgs); |
14271 | |
14272 | /// Determine whether the given declarator contains any unexpanded |
14273 | /// parameter packs. |
14274 | /// |
14275 | /// This routine is used by the parser to disambiguate function declarators |
14276 | /// with an ellipsis prior to the ')', e.g., |
14277 | /// |
14278 | /// \code |
14279 | /// void f(T...); |
14280 | /// \endcode |
14281 | /// |
14282 | /// To determine whether we have an (unnamed) function parameter pack or |
14283 | /// a variadic function. |
14284 | /// |
14285 | /// \returns true if the declarator contains any unexpanded parameter packs, |
14286 | /// false otherwise. |
14287 | bool containsUnexpandedParameterPacks(Declarator &D); |
14288 | |
14289 | /// Returns the pattern of the pack expansion for a template argument. |
14290 | /// |
14291 | /// \param OrigLoc The template argument to expand. |
14292 | /// |
14293 | /// \param Ellipsis Will be set to the location of the ellipsis. |
14294 | /// |
14295 | /// \param NumExpansions Will be set to the number of expansions that will |
14296 | /// be generated from this pack expansion, if known a priori. |
14297 | TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( |
14298 | TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, |
14299 | std::optional<unsigned> &NumExpansions) const; |
14300 | |
14301 | /// Given a template argument that contains an unexpanded parameter pack, but |
14302 | /// which has already been substituted, attempt to determine the number of |
14303 | /// elements that will be produced once this argument is fully-expanded. |
14304 | /// |
14305 | /// This is intended for use when transforming 'sizeof...(Arg)' in order to |
14306 | /// avoid actually expanding the pack where possible. |
14307 | std::optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); |
14308 | |
14309 | /// Called when an expression computing the size of a parameter pack |
14310 | /// is parsed. |
14311 | /// |
14312 | /// \code |
14313 | /// template<typename ...Types> struct count { |
14314 | /// static const unsigned value = sizeof...(Types); |
14315 | /// }; |
14316 | /// \endcode |
14317 | /// |
14318 | // |
14319 | /// \param OpLoc The location of the "sizeof" keyword. |
14320 | /// \param Name The name of the parameter pack whose size will be determined. |
14321 | /// \param NameLoc The source location of the name of the parameter pack. |
14322 | /// \param RParenLoc The location of the closing parentheses. |
14323 | ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, |
14324 | IdentifierInfo &Name, |
14325 | SourceLocation NameLoc, |
14326 | SourceLocation RParenLoc); |
14327 | |
14328 | ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression, |
14329 | SourceLocation EllipsisLoc, |
14330 | SourceLocation LSquareLoc, Expr *IndexExpr, |
14331 | SourceLocation RSquareLoc); |
14332 | |
14333 | ExprResult BuildPackIndexingExpr(Expr *PackExpression, |
14334 | SourceLocation EllipsisLoc, Expr *IndexExpr, |
14335 | SourceLocation RSquareLoc, |
14336 | ArrayRef<Expr *> ExpandedExprs = {}, |
14337 | bool FullySubstituted = false); |
14338 | |
14339 | /// Handle a C++1z fold-expression: ( expr op ... op expr ). |
14340 | ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, |
14341 | tok::TokenKind Operator, |
14342 | SourceLocation EllipsisLoc, Expr *RHS, |
14343 | SourceLocation RParenLoc); |
14344 | ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, |
14345 | SourceLocation LParenLoc, Expr *LHS, |
14346 | BinaryOperatorKind Operator, |
14347 | SourceLocation EllipsisLoc, Expr *RHS, |
14348 | SourceLocation RParenLoc, |
14349 | std::optional<unsigned> NumExpansions); |
14350 | ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, |
14351 | BinaryOperatorKind Operator); |
14352 | |
14353 | ///@} |
14354 | |
14355 | // |
14356 | // |
14357 | // ------------------------------------------------------------------------- |
14358 | // |
14359 | // |
14360 | |
14361 | /// \name Constraints and Concepts |
14362 | /// Implementations are in SemaConcept.cpp |
14363 | ///@{ |
14364 | |
14365 | public: |
14366 | void PushSatisfactionStackEntry(const NamedDecl *D, |
14367 | const llvm::FoldingSetNodeID &ID) { |
14368 | const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl()); |
14369 | SatisfactionStack.emplace_back(Args&: Can, Args: ID); |
14370 | } |
14371 | |
14372 | void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); } |
14373 | |
14374 | bool SatisfactionStackContains(const NamedDecl *D, |
14375 | const llvm::FoldingSetNodeID &ID) const { |
14376 | const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl()); |
14377 | return llvm::find(Range: SatisfactionStack, Val: SatisfactionStackEntryTy{Can, ID}) != |
14378 | SatisfactionStack.end(); |
14379 | } |
14380 | |
14381 | using SatisfactionStackEntryTy = |
14382 | std::pair<const NamedDecl *, llvm::FoldingSetNodeID>; |
14383 | |
14384 | // Resets the current SatisfactionStack for cases where we are instantiating |
14385 | // constraints as a 'side effect' of normal instantiation in a way that is not |
14386 | // indicative of recursive definition. |
14387 | class SatisfactionStackResetRAII { |
14388 | llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack; |
14389 | Sema &SemaRef; |
14390 | |
14391 | public: |
14392 | SatisfactionStackResetRAII(Sema &S) : SemaRef(S) { |
14393 | SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack); |
14394 | } |
14395 | |
14396 | ~SatisfactionStackResetRAII() { |
14397 | SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack); |
14398 | } |
14399 | }; |
14400 | |
14401 | void SwapSatisfactionStack( |
14402 | llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) { |
14403 | SatisfactionStack.swap(RHS&: NewSS); |
14404 | } |
14405 | |
14406 | /// Check whether the given expression is a valid constraint expression. |
14407 | /// A diagnostic is emitted if it is not, false is returned, and |
14408 | /// PossibleNonPrimary will be set to true if the failure might be due to a |
14409 | /// non-primary expression being used as an atomic constraint. |
14410 | bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), |
14411 | bool *PossibleNonPrimary = nullptr, |
14412 | bool IsTrailingRequiresClause = false); |
14413 | |
14414 | /// \brief Check whether the given list of constraint expressions are |
14415 | /// satisfied (as if in a 'conjunction') given template arguments. |
14416 | /// \param Template the template-like entity that triggered the constraints |
14417 | /// check (either a concept or a constrained entity). |
14418 | /// \param ConstraintExprs a list of constraint expressions, treated as if |
14419 | /// they were 'AND'ed together. |
14420 | /// \param TemplateArgLists the list of template arguments to substitute into |
14421 | /// the constraint expression. |
14422 | /// \param TemplateIDRange The source range of the template id that |
14423 | /// caused the constraints check. |
14424 | /// \param Satisfaction if true is returned, will contain details of the |
14425 | /// satisfaction, with enough information to diagnose an unsatisfied |
14426 | /// expression. |
14427 | /// \returns true if an error occurred and satisfaction could not be checked, |
14428 | /// false otherwise. |
14429 | bool CheckConstraintSatisfaction( |
14430 | const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, |
14431 | const MultiLevelTemplateArgumentList &TemplateArgLists, |
14432 | SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) { |
14433 | llvm::SmallVector<Expr *, 4> Converted; |
14434 | return CheckConstraintSatisfaction(Template, ConstraintExprs, ConvertedConstraints&: Converted, |
14435 | TemplateArgList: TemplateArgLists, TemplateIDRange, |
14436 | Satisfaction); |
14437 | } |
14438 | |
14439 | /// \brief Check whether the given list of constraint expressions are |
14440 | /// satisfied (as if in a 'conjunction') given template arguments. |
14441 | /// Additionally, takes an empty list of Expressions which is populated with |
14442 | /// the instantiated versions of the ConstraintExprs. |
14443 | /// \param Template the template-like entity that triggered the constraints |
14444 | /// check (either a concept or a constrained entity). |
14445 | /// \param ConstraintExprs a list of constraint expressions, treated as if |
14446 | /// they were 'AND'ed together. |
14447 | /// \param ConvertedConstraints a out parameter that will get populated with |
14448 | /// the instantiated version of the ConstraintExprs if we successfully checked |
14449 | /// satisfaction. |
14450 | /// \param TemplateArgList the multi-level list of template arguments to |
14451 | /// substitute into the constraint expression. This should be relative to the |
14452 | /// top-level (hence multi-level), since we need to instantiate fully at the |
14453 | /// time of checking. |
14454 | /// \param TemplateIDRange The source range of the template id that |
14455 | /// caused the constraints check. |
14456 | /// \param Satisfaction if true is returned, will contain details of the |
14457 | /// satisfaction, with enough information to diagnose an unsatisfied |
14458 | /// expression. |
14459 | /// \returns true if an error occurred and satisfaction could not be checked, |
14460 | /// false otherwise. |
14461 | bool CheckConstraintSatisfaction( |
14462 | const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, |
14463 | llvm::SmallVectorImpl<Expr *> &ConvertedConstraints, |
14464 | const MultiLevelTemplateArgumentList &TemplateArgList, |
14465 | SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); |
14466 | |
14467 | /// \brief Check whether the given non-dependent constraint expression is |
14468 | /// satisfied. Returns false and updates Satisfaction with the satisfaction |
14469 | /// verdict if successful, emits a diagnostic and returns true if an error |
14470 | /// occurred and satisfaction could not be determined. |
14471 | /// |
14472 | /// \returns true if an error occurred, false otherwise. |
14473 | bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, |
14474 | ConstraintSatisfaction &Satisfaction); |
14475 | |
14476 | /// Check whether the given function decl's trailing requires clause is |
14477 | /// satisfied, if any. Returns false and updates Satisfaction with the |
14478 | /// satisfaction verdict if successful, emits a diagnostic and returns true if |
14479 | /// an error occurred and satisfaction could not be determined. |
14480 | /// |
14481 | /// \returns true if an error occurred, false otherwise. |
14482 | bool CheckFunctionConstraints(const FunctionDecl *FD, |
14483 | ConstraintSatisfaction &Satisfaction, |
14484 | SourceLocation UsageLoc = SourceLocation(), |
14485 | bool ForOverloadResolution = false); |
14486 | |
14487 | // Calculates whether two constraint expressions are equal irrespective of a |
14488 | // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and |
14489 | // 'New', which are the "source" of the constraint, since this is necessary |
14490 | // for figuring out the relative 'depth' of the constraint. The depth of the |
14491 | // 'primary template' and the 'instantiated from' templates aren't necessarily |
14492 | // the same, such as a case when one is a 'friend' defined in a class. |
14493 | bool AreConstraintExpressionsEqual(const NamedDecl *Old, |
14494 | const Expr *OldConstr, |
14495 | const TemplateCompareNewDeclInfo &New, |
14496 | const Expr *NewConstr); |
14497 | |
14498 | // Calculates whether the friend function depends on an enclosing template for |
14499 | // the purposes of [temp.friend] p9. |
14500 | bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD); |
14501 | |
14502 | /// \brief Ensure that the given template arguments satisfy the constraints |
14503 | /// associated with the given template, emitting a diagnostic if they do not. |
14504 | /// |
14505 | /// \param Template The template to which the template arguments are being |
14506 | /// provided. |
14507 | /// |
14508 | /// \param TemplateArgs The converted, canonicalized template arguments. |
14509 | /// |
14510 | /// \param TemplateIDRange The source range of the template id that |
14511 | /// caused the constraints check. |
14512 | /// |
14513 | /// \returns true if the constrains are not satisfied or could not be checked |
14514 | /// for satisfaction, false if the constraints are satisfied. |
14515 | bool EnsureTemplateArgumentListConstraints( |
14516 | TemplateDecl *Template, |
14517 | const MultiLevelTemplateArgumentList &TemplateArgs, |
14518 | SourceRange TemplateIDRange); |
14519 | |
14520 | bool CheckInstantiatedFunctionTemplateConstraints( |
14521 | SourceLocation PointOfInstantiation, FunctionDecl *Decl, |
14522 | ArrayRef<TemplateArgument> TemplateArgs, |
14523 | ConstraintSatisfaction &Satisfaction); |
14524 | |
14525 | /// \brief Emit diagnostics explaining why a constraint expression was deemed |
14526 | /// unsatisfied. |
14527 | /// \param First whether this is the first time an unsatisfied constraint is |
14528 | /// diagnosed for this error. |
14529 | void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, |
14530 | bool First = true); |
14531 | |
14532 | /// \brief Emit diagnostics explaining why a constraint expression was deemed |
14533 | /// unsatisfied. |
14534 | void |
14535 | DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, |
14536 | bool First = true); |
14537 | |
14538 | const NormalizedConstraint *getNormalizedAssociatedConstraints( |
14539 | NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); |
14540 | |
14541 | /// \brief Check whether the given declaration's associated constraints are |
14542 | /// at least as constrained than another declaration's according to the |
14543 | /// partial ordering of constraints. |
14544 | /// |
14545 | /// \param Result If no error occurred, receives the result of true if D1 is |
14546 | /// at least constrained than D2, and false otherwise. |
14547 | /// |
14548 | /// \returns true if an error occurred, false otherwise. |
14549 | bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef<const Expr *> AC1, |
14550 | NamedDecl *D2, MutableArrayRef<const Expr *> AC2, |
14551 | bool &Result); |
14552 | |
14553 | /// If D1 was not at least as constrained as D2, but would've been if a pair |
14554 | /// of atomic constraints involved had been declared in a concept and not |
14555 | /// repeated in two separate places in code. |
14556 | /// \returns true if such a diagnostic was emitted, false otherwise. |
14557 | bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic( |
14558 | NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, |
14559 | ArrayRef<const Expr *> AC2); |
14560 | |
14561 | private: |
14562 | /// Caches pairs of template-like decls whose associated constraints were |
14563 | /// checked for subsumption and whether or not the first's constraints did in |
14564 | /// fact subsume the second's. |
14565 | llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; |
14566 | /// Caches the normalized associated constraints of declarations (concepts or |
14567 | /// constrained declarations). If an error occurred while normalizing the |
14568 | /// associated constraints of the template or concept, nullptr will be cached |
14569 | /// here. |
14570 | llvm::DenseMap<NamedDecl *, NormalizedConstraint *> NormalizationCache; |
14571 | |
14572 | llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> |
14573 | SatisfactionCache; |
14574 | |
14575 | // The current stack of constraint satisfactions, so we can exit-early. |
14576 | llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack; |
14577 | |
14578 | /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the |
14579 | /// LocalInstantiationScope of the current non-lambda function. For lambdas, |
14580 | /// use LambdaScopeForCallOperatorInstantiationRAII. |
14581 | bool |
14582 | SetupConstraintScope(FunctionDecl *FD, |
14583 | std::optional<ArrayRef<TemplateArgument>> TemplateArgs, |
14584 | const MultiLevelTemplateArgumentList &MLTAL, |
14585 | LocalInstantiationScope &Scope); |
14586 | |
14587 | /// Used during constraint checking, sets up the constraint template argument |
14588 | /// lists, and calls SetupConstraintScope to set up the |
14589 | /// LocalInstantiationScope to have the proper set of ParVarDecls configured. |
14590 | std::optional<MultiLevelTemplateArgumentList> |
14591 | SetupConstraintCheckingTemplateArgumentsAndScope( |
14592 | FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs, |
14593 | LocalInstantiationScope &Scope); |
14594 | |
14595 | ///@} |
14596 | |
14597 | // |
14598 | // |
14599 | // ------------------------------------------------------------------------- |
14600 | // |
14601 | // |
14602 | |
14603 | /// \name Types |
14604 | /// Implementations are in SemaType.cpp |
14605 | ///@{ |
14606 | |
14607 | public: |
14608 | /// A mapping that describes the nullability we've seen in each header file. |
14609 | FileNullabilityMap NullabilityMap; |
14610 | |
14611 | static int getPrintable(int I) { return I; } |
14612 | static unsigned getPrintable(unsigned I) { return I; } |
14613 | static bool getPrintable(bool B) { return B; } |
14614 | static const char *getPrintable(const char *S) { return S; } |
14615 | static StringRef getPrintable(StringRef S) { return S; } |
14616 | static const std::string &getPrintable(const std::string &S) { return S; } |
14617 | static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { |
14618 | return II; |
14619 | } |
14620 | static DeclarationName getPrintable(DeclarationName N) { return N; } |
14621 | static QualType getPrintable(QualType T) { return T; } |
14622 | static SourceRange getPrintable(SourceRange R) { return R; } |
14623 | static SourceRange getPrintable(SourceLocation L) { return L; } |
14624 | static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } |
14625 | static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); } |
14626 | |
14627 | enum class CompleteTypeKind { |
14628 | /// Apply the normal rules for complete types. In particular, |
14629 | /// treat all sizeless types as incomplete. |
14630 | Normal, |
14631 | |
14632 | /// Relax the normal rules for complete types so that they include |
14633 | /// sizeless built-in types. |
14634 | AcceptSizeless, |
14635 | |
14636 | // FIXME: Eventually we should flip the default to Normal and opt in |
14637 | // to AcceptSizeless rather than opt out of it. |
14638 | Default = AcceptSizeless |
14639 | }; |
14640 | |
14641 | QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, |
14642 | const DeclSpec *DS = nullptr); |
14643 | QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, |
14644 | const DeclSpec *DS = nullptr); |
14645 | |
14646 | /// Build a pointer type. |
14647 | /// |
14648 | /// \param T The type to which we'll be building a pointer. |
14649 | /// |
14650 | /// \param Loc The location of the entity whose type involves this |
14651 | /// pointer type or, if there is no such entity, the location of the |
14652 | /// type that will have pointer type. |
14653 | /// |
14654 | /// \param Entity The name of the entity that involves the pointer |
14655 | /// type, if known. |
14656 | /// |
14657 | /// \returns A suitable pointer type, if there are no |
14658 | /// errors. Otherwise, returns a NULL type. |
14659 | QualType BuildPointerType(QualType T, SourceLocation Loc, |
14660 | DeclarationName Entity); |
14661 | |
14662 | /// Build a reference type. |
14663 | /// |
14664 | /// \param T The type to which we'll be building a reference. |
14665 | /// |
14666 | /// \param Loc The location of the entity whose type involves this |
14667 | /// reference type or, if there is no such entity, the location of the |
14668 | /// type that will have reference type. |
14669 | /// |
14670 | /// \param Entity The name of the entity that involves the reference |
14671 | /// type, if known. |
14672 | /// |
14673 | /// \returns A suitable reference type, if there are no |
14674 | /// errors. Otherwise, returns a NULL type. |
14675 | QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, |
14676 | DeclarationName Entity); |
14677 | |
14678 | /// Build an array type. |
14679 | /// |
14680 | /// \param T The type of each element in the array. |
14681 | /// |
14682 | /// \param ASM C99 array size modifier (e.g., '*', 'static'). |
14683 | /// |
14684 | /// \param ArraySize Expression describing the size of the array. |
14685 | /// |
14686 | /// \param Brackets The range from the opening '[' to the closing ']'. |
14687 | /// |
14688 | /// \param Entity The name of the entity that involves the array |
14689 | /// type, if known. |
14690 | /// |
14691 | /// \returns A suitable array type, if there are no errors. Otherwise, |
14692 | /// returns a NULL type. |
14693 | QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize, |
14694 | unsigned Quals, SourceRange Brackets, |
14695 | DeclarationName Entity); |
14696 | QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); |
14697 | |
14698 | /// Build an ext-vector type. |
14699 | /// |
14700 | /// Run the required checks for the extended vector type. |
14701 | QualType BuildExtVectorType(QualType T, Expr *ArraySize, |
14702 | SourceLocation AttrLoc); |
14703 | QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, |
14704 | SourceLocation AttrLoc); |
14705 | |
14706 | QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy, |
14707 | Expr *CountExpr, |
14708 | bool CountInBytes, |
14709 | bool OrNull); |
14710 | |
14711 | /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an |
14712 | /// expression is uninstantiated. If instantiated it will apply the |
14713 | /// appropriate address space to the type. This function allows dependent |
14714 | /// template variables to be used in conjunction with the address_space |
14715 | /// attribute |
14716 | QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, |
14717 | SourceLocation AttrLoc); |
14718 | |
14719 | /// Same as above, but constructs the AddressSpace index if not provided. |
14720 | QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, |
14721 | SourceLocation AttrLoc); |
14722 | |
14723 | bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); |
14724 | |
14725 | bool CheckFunctionReturnType(QualType T, SourceLocation Loc); |
14726 | |
14727 | /// Build a function type. |
14728 | /// |
14729 | /// This routine checks the function type according to C++ rules and |
14730 | /// under the assumption that the result type and parameter types have |
14731 | /// just been instantiated from a template. It therefore duplicates |
14732 | /// some of the behavior of GetTypeForDeclarator, but in a much |
14733 | /// simpler form that is only suitable for this narrow use case. |
14734 | /// |
14735 | /// \param T The return type of the function. |
14736 | /// |
14737 | /// \param ParamTypes The parameter types of the function. This array |
14738 | /// will be modified to account for adjustments to the types of the |
14739 | /// function parameters. |
14740 | /// |
14741 | /// \param Loc The location of the entity whose type involves this |
14742 | /// function type or, if there is no such entity, the location of the |
14743 | /// type that will have function type. |
14744 | /// |
14745 | /// \param Entity The name of the entity that involves the function |
14746 | /// type, if known. |
14747 | /// |
14748 | /// \param EPI Extra information about the function type. Usually this will |
14749 | /// be taken from an existing function with the same prototype. |
14750 | /// |
14751 | /// \returns A suitable function type, if there are no errors. The |
14752 | /// unqualified type will always be a FunctionProtoType. |
14753 | /// Otherwise, returns a NULL type. |
14754 | QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, |
14755 | SourceLocation Loc, DeclarationName Entity, |
14756 | const FunctionProtoType::ExtProtoInfo &EPI); |
14757 | |
14758 | /// Build a member pointer type \c T Class::*. |
14759 | /// |
14760 | /// \param T the type to which the member pointer refers. |
14761 | /// \param Class the class type into which the member pointer points. |
14762 | /// \param Loc the location where this type begins |
14763 | /// \param Entity the name of the entity that will have this member pointer |
14764 | /// type |
14765 | /// |
14766 | /// \returns a member pointer type, if successful, or a NULL type if there was |
14767 | /// an error. |
14768 | QualType BuildMemberPointerType(QualType T, QualType Class, |
14769 | SourceLocation Loc, DeclarationName Entity); |
14770 | |
14771 | /// Build a block pointer type. |
14772 | /// |
14773 | /// \param T The type to which we'll be building a block pointer. |
14774 | /// |
14775 | /// \param Loc The source location, used for diagnostics. |
14776 | /// |
14777 | /// \param Entity The name of the entity that involves the block pointer |
14778 | /// type, if known. |
14779 | /// |
14780 | /// \returns A suitable block pointer type, if there are no |
14781 | /// errors. Otherwise, returns a NULL type. |
14782 | QualType BuildBlockPointerType(QualType T, SourceLocation Loc, |
14783 | DeclarationName Entity); |
14784 | |
14785 | /// Build a paren type including \p T. |
14786 | QualType BuildParenType(QualType T); |
14787 | QualType BuildAtomicType(QualType T, SourceLocation Loc); |
14788 | |
14789 | /// Build a Read-only Pipe type. |
14790 | /// |
14791 | /// \param T The type to which we'll be building a Pipe. |
14792 | /// |
14793 | /// \param Loc We do not use it for now. |
14794 | /// |
14795 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns |
14796 | /// a NULL type. |
14797 | QualType BuildReadPipeType(QualType T, SourceLocation Loc); |
14798 | |
14799 | /// Build a Write-only Pipe type. |
14800 | /// |
14801 | /// \param T The type to which we'll be building a Pipe. |
14802 | /// |
14803 | /// \param Loc We do not use it for now. |
14804 | /// |
14805 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns |
14806 | /// a NULL type. |
14807 | QualType BuildWritePipeType(QualType T, SourceLocation Loc); |
14808 | |
14809 | /// Build a bit-precise integer type. |
14810 | /// |
14811 | /// \param IsUnsigned Boolean representing the signedness of the type. |
14812 | /// |
14813 | /// \param BitWidth Size of this int type in bits, or an expression |
14814 | /// representing that. |
14815 | /// |
14816 | /// \param Loc Location of the keyword. |
14817 | QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); |
14818 | |
14819 | /// GetTypeForDeclarator - Convert the type for the specified |
14820 | /// declarator to Type instances. |
14821 | /// |
14822 | /// The result of this call will never be null, but the associated |
14823 | /// type may be a null type if there's an unrecoverable error. |
14824 | TypeSourceInfo *GetTypeForDeclarator(Declarator &D); |
14825 | TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); |
14826 | |
14827 | /// Package the given type and TSI into a ParsedType. |
14828 | ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); |
14829 | static QualType GetTypeFromParser(ParsedType Ty, |
14830 | TypeSourceInfo **TInfo = nullptr); |
14831 | |
14832 | TypeResult ActOnTypeName(Declarator &D); |
14833 | |
14834 | // Check whether the size of array element of type \p EltTy is a multiple of |
14835 | // its alignment and return false if it isn't. |
14836 | bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc); |
14837 | |
14838 | void |
14839 | diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, |
14840 | SourceLocation FallbackLoc, |
14841 | SourceLocation ConstQualLoc = SourceLocation(), |
14842 | SourceLocation VolatileQualLoc = SourceLocation(), |
14843 | SourceLocation RestrictQualLoc = SourceLocation(), |
14844 | SourceLocation AtomicQualLoc = SourceLocation(), |
14845 | SourceLocation UnalignedQualLoc = SourceLocation()); |
14846 | |
14847 | /// Retrieve the keyword associated |
14848 | IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); |
14849 | |
14850 | /// Adjust the calling convention of a method to be the ABI default if it |
14851 | /// wasn't specified explicitly. This handles method types formed from |
14852 | /// function type typedefs and typename template arguments. |
14853 | void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, |
14854 | bool IsCtorOrDtor, SourceLocation Loc); |
14855 | |
14856 | // Check if there is an explicit attribute, but only look through parens. |
14857 | // The intent is to look for an attribute on the current declarator, but not |
14858 | // one that came from a typedef. |
14859 | bool hasExplicitCallingConv(QualType T); |
14860 | |
14861 | /// Check whether a nullability type specifier can be added to the given |
14862 | /// type through some means not written in source (e.g. API notes). |
14863 | /// |
14864 | /// \param Type The type to which the nullability specifier will be |
14865 | /// added. On success, this type will be updated appropriately. |
14866 | /// |
14867 | /// \param Nullability The nullability specifier to add. |
14868 | /// |
14869 | /// \param DiagLoc The location to use for diagnostics. |
14870 | /// |
14871 | /// \param AllowArrayTypes Whether to accept nullability specifiers on an |
14872 | /// array type (e.g., because it will decay to a pointer). |
14873 | /// |
14874 | /// \param OverrideExisting Whether to override an existing, locally-specified |
14875 | /// nullability specifier rather than complaining about the conflict. |
14876 | /// |
14877 | /// \returns true if nullability cannot be applied, false otherwise. |
14878 | bool CheckImplicitNullabilityTypeSpecifier(QualType &Type, |
14879 | NullabilityKind Nullability, |
14880 | SourceLocation DiagLoc, |
14881 | bool AllowArrayTypes, |
14882 | bool OverrideExisting); |
14883 | |
14884 | /// Get the type of expression E, triggering instantiation to complete the |
14885 | /// type if necessary -- that is, if the expression refers to a templated |
14886 | /// static data member of incomplete array type. |
14887 | /// |
14888 | /// May still return an incomplete type if instantiation was not possible or |
14889 | /// if the type is incomplete for a different reason. Use |
14890 | /// RequireCompleteExprType instead if a diagnostic is expected for an |
14891 | /// incomplete expression type. |
14892 | QualType getCompletedType(Expr *E); |
14893 | |
14894 | void completeExprArrayBound(Expr *E); |
14895 | |
14896 | /// Ensure that the type of the given expression is complete. |
14897 | /// |
14898 | /// This routine checks whether the expression \p E has a complete type. If |
14899 | /// the expression refers to an instantiable construct, that instantiation is |
14900 | /// performed as needed to complete its type. Furthermore |
14901 | /// Sema::RequireCompleteType is called for the expression's type (or in the |
14902 | /// case of a reference type, the referred-to type). |
14903 | /// |
14904 | /// \param E The expression whose type is required to be complete. |
14905 | /// \param Kind Selects which completeness rules should be applied. |
14906 | /// \param Diagnoser The object that will emit a diagnostic if the type is |
14907 | /// incomplete. |
14908 | /// |
14909 | /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false |
14910 | /// otherwise. |
14911 | bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, |
14912 | TypeDiagnoser &Diagnoser); |
14913 | bool RequireCompleteExprType(Expr *E, unsigned DiagID); |
14914 | |
14915 | template <typename... Ts> |
14916 | bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { |
14917 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
14918 | return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); |
14919 | } |
14920 | |
14921 | /// Retrieve a version of the type 'T' that is elaborated by Keyword, |
14922 | /// qualified by the nested-name-specifier contained in SS, and that is |
14923 | /// (re)declared by OwnedTagDecl, which is nullptr if this is not a |
14924 | /// (re)declaration. |
14925 | QualType getElaboratedType(ElaboratedTypeKeyword Keyword, |
14926 | const CXXScopeSpec &SS, QualType T, |
14927 | TagDecl *OwnedTagDecl = nullptr); |
14928 | |
14929 | // Returns the underlying type of a decltype with the given expression. |
14930 | QualType getDecltypeForExpr(Expr *E); |
14931 | |
14932 | QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind); |
14933 | /// If AsUnevaluated is false, E is treated as though it were an evaluated |
14934 | /// context, such as when building a type for decltype(auto). |
14935 | QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true); |
14936 | |
14937 | QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, |
14938 | SourceLocation Loc, |
14939 | SourceLocation EllipsisLoc); |
14940 | QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, |
14941 | SourceLocation Loc, SourceLocation EllipsisLoc, |
14942 | bool FullySubstituted = false, |
14943 | ArrayRef<QualType> Expansions = {}); |
14944 | |
14945 | using UTTKind = UnaryTransformType::UTTKind; |
14946 | QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind, |
14947 | SourceLocation Loc); |
14948 | QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc); |
14949 | QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc); |
14950 | QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc); |
14951 | QualType BuiltinDecay(QualType BaseType, SourceLocation Loc); |
14952 | QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, |
14953 | SourceLocation Loc); |
14954 | QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, |
14955 | SourceLocation Loc); |
14956 | QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind, |
14957 | SourceLocation Loc); |
14958 | QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, |
14959 | SourceLocation Loc); |
14960 | QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, |
14961 | SourceLocation Loc); |
14962 | |
14963 | /// Ensure that the type T is a literal type. |
14964 | /// |
14965 | /// This routine checks whether the type @p T is a literal type. If @p T is an |
14966 | /// incomplete type, an attempt is made to complete it. If @p T is a literal |
14967 | /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, |
14968 | /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving |
14969 | /// it the type @p T), along with notes explaining why the type is not a |
14970 | /// literal type, and returns true. |
14971 | /// |
14972 | /// @param Loc The location in the source that the non-literal type |
14973 | /// diagnostic should refer to. |
14974 | /// |
14975 | /// @param T The type that this routine is examining for literalness. |
14976 | /// |
14977 | /// @param Diagnoser Emits a diagnostic if T is not a literal type. |
14978 | /// |
14979 | /// @returns @c true if @p T is not a literal type and a diagnostic was |
14980 | /// emitted, @c false otherwise. |
14981 | bool RequireLiteralType(SourceLocation Loc, QualType T, |
14982 | TypeDiagnoser &Diagnoser); |
14983 | bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); |
14984 | |
14985 | template <typename... Ts> |
14986 | bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, |
14987 | const Ts &...Args) { |
14988 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
14989 | return RequireLiteralType(Loc, T, Diagnoser); |
14990 | } |
14991 | |
14992 | bool isCompleteType(SourceLocation Loc, QualType T, |
14993 | CompleteTypeKind Kind = CompleteTypeKind::Default) { |
14994 | return !RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: nullptr); |
14995 | } |
14996 | |
14997 | /// Ensure that the type T is a complete type. |
14998 | /// |
14999 | /// This routine checks whether the type @p T is complete in any |
15000 | /// context where a complete type is required. If @p T is a complete |
15001 | /// type, returns false. If @p T is a class template specialization, |
15002 | /// this routine then attempts to perform class template |
15003 | /// instantiation. If instantiation fails, or if @p T is incomplete |
15004 | /// and cannot be completed, issues the diagnostic @p diag (giving it |
15005 | /// the type @p T) and returns true. |
15006 | /// |
15007 | /// @param Loc The location in the source that the incomplete type |
15008 | /// diagnostic should refer to. |
15009 | /// |
15010 | /// @param T The type that this routine is examining for completeness. |
15011 | /// |
15012 | /// @param Kind Selects which completeness rules should be applied. |
15013 | /// |
15014 | /// @returns @c true if @p T is incomplete and a diagnostic was emitted, |
15015 | /// @c false otherwise. |
15016 | bool RequireCompleteType(SourceLocation Loc, QualType T, |
15017 | CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); |
15018 | bool RequireCompleteType(SourceLocation Loc, QualType T, |
15019 | CompleteTypeKind Kind, unsigned DiagID); |
15020 | |
15021 | bool RequireCompleteType(SourceLocation Loc, QualType T, |
15022 | TypeDiagnoser &Diagnoser) { |
15023 | return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, Diagnoser); |
15024 | } |
15025 | bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { |
15026 | return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, DiagID); |
15027 | } |
15028 | |
15029 | template <typename... Ts> |
15030 | bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, |
15031 | const Ts &...Args) { |
15032 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
15033 | return RequireCompleteType(Loc, T, Diagnoser); |
15034 | } |
15035 | |
15036 | /// Determine whether a declaration is visible to name lookup. |
15037 | bool isVisible(const NamedDecl *D) { |
15038 | return D->isUnconditionallyVisible() || |
15039 | isAcceptableSlow(D, Kind: AcceptableKind::Visible); |
15040 | } |
15041 | |
15042 | /// Determine whether a declaration is reachable. |
15043 | bool isReachable(const NamedDecl *D) { |
15044 | // All visible declarations are reachable. |
15045 | return D->isUnconditionallyVisible() || |
15046 | isAcceptableSlow(D, Kind: AcceptableKind::Reachable); |
15047 | } |
15048 | |
15049 | /// Determine whether a declaration is acceptable (visible/reachable). |
15050 | bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) { |
15051 | return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D); |
15052 | } |
15053 | |
15054 | /// Determine if \p D and \p Suggested have a structurally compatible |
15055 | /// layout as described in C11 6.2.7/1. |
15056 | bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); |
15057 | |
15058 | /// Determine if \p D has a visible definition. If not, suggest a declaration |
15059 | /// that should be made visible to expose the definition. |
15060 | bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, |
15061 | bool OnlyNeedComplete = false); |
15062 | bool hasVisibleDefinition(const NamedDecl *D) { |
15063 | NamedDecl *Hidden; |
15064 | return hasVisibleDefinition(D: const_cast<NamedDecl *>(D), Suggested: &Hidden); |
15065 | } |
15066 | |
15067 | /// Determine if \p D has a reachable definition. If not, suggest a |
15068 | /// declaration that should be made reachable to expose the definition. |
15069 | bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, |
15070 | bool OnlyNeedComplete = false); |
15071 | bool hasReachableDefinition(NamedDecl *D) { |
15072 | NamedDecl *Hidden; |
15073 | return hasReachableDefinition(D, Suggested: &Hidden); |
15074 | } |
15075 | |
15076 | bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, |
15077 | AcceptableKind Kind, |
15078 | bool OnlyNeedComplete = false); |
15079 | bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) { |
15080 | NamedDecl *Hidden; |
15081 | return hasAcceptableDefinition(D, Suggested: &Hidden, Kind); |
15082 | } |
15083 | |
15084 | /// Try to parse the conditional expression attached to an effect attribute |
15085 | /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty |
15086 | /// optional on error. |
15087 | std::optional<FunctionEffectMode> |
15088 | ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName); |
15089 | |
15090 | private: |
15091 | /// The implementation of RequireCompleteType |
15092 | bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, |
15093 | CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); |
15094 | |
15095 | /// Nullability type specifiers. |
15096 | IdentifierInfo *Ident__Nonnull = nullptr; |
15097 | IdentifierInfo *Ident__Nullable = nullptr; |
15098 | IdentifierInfo *Ident__Nullable_result = nullptr; |
15099 | IdentifierInfo *Ident__Null_unspecified = nullptr; |
15100 | |
15101 | ///@} |
15102 | |
15103 | // |
15104 | // |
15105 | // ------------------------------------------------------------------------- |
15106 | // |
15107 | // |
15108 | |
15109 | /// \name FixIt Helpers |
15110 | /// Implementations are in SemaFixItUtils.cpp |
15111 | ///@{ |
15112 | |
15113 | public: |
15114 | /// Get a string to suggest for zero-initialization of a type. |
15115 | std::string getFixItZeroInitializerForType(QualType T, |
15116 | SourceLocation Loc) const; |
15117 | std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; |
15118 | |
15119 | ///@} |
15120 | |
15121 | // |
15122 | // |
15123 | // ------------------------------------------------------------------------- |
15124 | // |
15125 | // |
15126 | |
15127 | /// \name Function Effects |
15128 | /// Implementations are in SemaFunctionEffects.cpp |
15129 | ///@{ |
15130 | public: |
15131 | struct FunctionEffectDiff { |
15132 | enum class Kind { Added, Removed, ConditionMismatch }; |
15133 | |
15134 | FunctionEffect::Kind EffectKind; |
15135 | Kind DiffKind; |
15136 | std::optional<FunctionEffectWithCondition> |
15137 | Old; // Invalid when 'Kind' is 'Added'. |
15138 | std::optional<FunctionEffectWithCondition> |
15139 | New; // Invalid when 'Kind' is 'Removed'. |
15140 | |
15141 | StringRef effectName() const { |
15142 | if (Old) |
15143 | return Old.value().Effect.name(); |
15144 | return New.value().Effect.name(); |
15145 | } |
15146 | |
15147 | /// Describes the result of effects differing between a base class's virtual |
15148 | /// method and an overriding method in a subclass. |
15149 | enum class OverrideResult { |
15150 | NoAction, |
15151 | Warn, |
15152 | Merge // Merge missing effect from base to derived. |
15153 | }; |
15154 | |
15155 | /// Return true if adding or removing the effect as part of a type |
15156 | /// conversion should generate a diagnostic. |
15157 | bool shouldDiagnoseConversion(QualType SrcType, |
15158 | const FunctionEffectsRef &SrcFX, |
15159 | QualType DstType, |
15160 | const FunctionEffectsRef &DstFX) const; |
15161 | |
15162 | /// Return true if adding or removing the effect in a redeclaration should |
15163 | /// generate a diagnostic. |
15164 | bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction, |
15165 | const FunctionEffectsRef &OldFX, |
15166 | const FunctionDecl &NewFunction, |
15167 | const FunctionEffectsRef &NewFX) const; |
15168 | |
15169 | /// Return true if adding or removing the effect in a C++ virtual method |
15170 | /// override should generate a diagnostic. |
15171 | OverrideResult shouldDiagnoseMethodOverride( |
15172 | const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX, |
15173 | const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const; |
15174 | }; |
15175 | |
15176 | struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> { |
15177 | /// Caller should short-circuit by checking for equality first. |
15178 | FunctionEffectDiffVector(const FunctionEffectsRef &Old, |
15179 | const FunctionEffectsRef &New); |
15180 | }; |
15181 | |
15182 | /// All functions/lambdas/blocks which have bodies and which have a non-empty |
15183 | /// FunctionEffectsRef to be verified. |
15184 | SmallVector<const Decl *> DeclsWithEffectsToVerify; |
15185 | |
15186 | /// The union of all effects present on DeclsWithEffectsToVerify. Conditions |
15187 | /// are all null. |
15188 | FunctionEffectKindSet AllEffectsToVerify; |
15189 | |
15190 | public: |
15191 | /// Warn and return true if adding a function effect to a set would create a |
15192 | /// conflict. |
15193 | bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, |
15194 | const FunctionEffectWithCondition &EC, |
15195 | SourceLocation NewAttrLoc); |
15196 | |
15197 | // Report a failure to merge function effects between declarations due to a |
15198 | // conflict. |
15199 | void |
15200 | diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, |
15201 | SourceLocation NewLoc, |
15202 | SourceLocation OldLoc); |
15203 | |
15204 | /// Inline checks from the start of maybeAddDeclWithEffects, to |
15205 | /// minimize performance impact on code not using effects. |
15206 | template <class FuncOrBlockDecl> |
15207 | void maybeAddDeclWithEffects(FuncOrBlockDecl *D) { |
15208 | if (Context.hasAnyFunctionEffects()) |
15209 | if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty()) |
15210 | maybeAddDeclWithEffects(D, FX); |
15211 | } |
15212 | |
15213 | /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify. |
15214 | void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX); |
15215 | |
15216 | /// Unconditionally add a Decl to DeclsWithEfffectsToVerify. |
15217 | void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX); |
15218 | |
15219 | void performFunctionEffectAnalysis(TranslationUnitDecl *TU); |
15220 | |
15221 | ///@} |
15222 | }; |
15223 | |
15224 | DeductionFailureInfo |
15225 | MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, |
15226 | sema::TemplateDeductionInfo &Info); |
15227 | |
15228 | /// Contains a late templated function. |
15229 | /// Will be parsed at the end of the translation unit, used by Sema & Parser. |
15230 | struct LateParsedTemplate { |
15231 | CachedTokens Toks; |
15232 | /// The template function declaration to be late parsed. |
15233 | Decl *D; |
15234 | /// Floating-point options in the point of definition. |
15235 | FPOptions FPO; |
15236 | }; |
15237 | |
15238 | template <> |
15239 | void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, |
15240 | PragmaMsStackAction Action, |
15241 | llvm::StringRef StackSlotLabel, |
15242 | AlignPackInfo Value); |
15243 | } // end namespace clang |
15244 | |
15245 | #endif |
15246 | |