Debian Codegraph @

clang/lib/Sema/Sema.cpp

raw
1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
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 implements the actions class which performs semantic analysis and
10 // builds an AST out of a parse stream.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/PrettyDeclStackTrace.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/DarwinSDKInfo.h"
27 #include "clang/Basic/DiagnosticOptions.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/HeaderSearchOptions.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/CXXFieldCollector.h"
35 #include "clang/Sema/EnterExpressionEvaluationContext.h"
36 #include "clang/Sema/ExternalSemaSource.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/MultiplexExternalSemaSource.h"
39 #include "clang/Sema/ObjCMethodList.h"
40 #include "clang/Sema/RISCVIntrinsicManager.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaAMDGPU.h"
44 #include "clang/Sema/SemaARM.h"
45 #include "clang/Sema/SemaAVR.h"
46 #include "clang/Sema/SemaBPF.h"
47 #include "clang/Sema/SemaCUDA.h"
48 #include "clang/Sema/SemaCodeCompletion.h"
49 #include "clang/Sema/SemaConsumer.h"
50 #include "clang/Sema/SemaDirectX.h"
51 #include "clang/Sema/SemaHLSL.h"
52 #include "clang/Sema/SemaHexagon.h"
53 #include "clang/Sema/SemaLoongArch.h"
54 #include "clang/Sema/SemaM68k.h"
55 #include "clang/Sema/SemaMIPS.h"
56 #include "clang/Sema/SemaMSP430.h"
57 #include "clang/Sema/SemaNVPTX.h"
58 #include "clang/Sema/SemaObjC.h"
59 #include "clang/Sema/SemaOpenACC.h"
60 #include "clang/Sema/SemaOpenCL.h"
61 #include "clang/Sema/SemaOpenMP.h"
62 #include "clang/Sema/SemaPPC.h"
63 #include "clang/Sema/SemaPseudoObject.h"
64 #include "clang/Sema/SemaRISCV.h"
65 #include "clang/Sema/SemaSPIRV.h"
66 #include "clang/Sema/SemaSYCL.h"
67 #include "clang/Sema/SemaSwift.h"
68 #include "clang/Sema/SemaSystemZ.h"
69 #include "clang/Sema/SemaWasm.h"
70 #include "clang/Sema/SemaX86.h"
71 #include "clang/Sema/TemplateDeduction.h"
72 #include "clang/Sema/TemplateInstCallback.h"
73 #include "clang/Sema/TypoCorrection.h"
74 #include "llvm/ADT/DenseMap.h"
75 #include "llvm/ADT/STLExtras.h"
76 #include "llvm/ADT/SmallPtrSet.h"
77 #include "llvm/Support/TimeProfiler.h"
78 #include <optional>
79
80 using namespace clang;
81 using namespace sema;
82
83 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
84 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
85 }
86
87 SourceRange
88 Sema::getRangeForNextToken(SourceLocation Loc, bool IncludeMacros,
89 bool IncludeComments,
90 std::optional<tok::TokenKind> ExpectedToken) {
91 if (!Loc.isValid())
92 return SourceRange();
93 std::optional<Token> NextToken =
94 Lexer::findNextToken(Loc, SourceMgr, LangOpts, IncludeComments);
95 if (!NextToken)
96 return SourceRange();
97 if (ExpectedToken && NextToken->getKind() != *ExpectedToken)
98 return SourceRange();
99 SourceLocation TokenStart = NextToken->getLocation();
100 SourceLocation TokenEnd = NextToken->getLastLoc();
101 if (!TokenStart.isValid() || !TokenEnd.isValid())
102 return SourceRange();
103 if (!IncludeMacros && (TokenStart.isMacroID() || TokenEnd.isMacroID()))
104 return SourceRange();
105
106 return SourceRange(TokenStart, TokenEnd);
107 }
108
109 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
110
111 DarwinSDKInfo *
112 Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
113 StringRef Platform) {
114 auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking();
115 if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
116 Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
117 << Platform;
118 WarnedDarwinSDKInfoMissing = true;
119 }
120 return SDKInfo;
121 }
122
123 DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() {
124 if (CachedDarwinSDKInfo)
125 return CachedDarwinSDKInfo->get();
126 auto SDKInfo = parseDarwinSDKInfo(
127 PP.getFileManager().getVirtualFileSystem(),
128 PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
129 if (SDKInfo && *SDKInfo) {
130 CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
131 return CachedDarwinSDKInfo->get();
132 }
133 if (!SDKInfo)
134 llvm::consumeError(SDKInfo.takeError());
135 CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
136 return nullptr;
137 }
138
139 IdentifierInfo *Sema::InventAbbreviatedTemplateParameterTypeName(
140 const IdentifierInfo *ParamName, unsigned int Index) {
141 std::string InventedName;
142 llvm::raw_string_ostream OS(InventedName);
143
144 if (!ParamName)
145 OS << "auto:" << Index + 1;
146 else
147 OS << ParamName->getName() << ":auto";
148
149 return &Context.Idents.get(OS.str());
150 }
151
152 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
153 const Preprocessor &PP) {
154 PrintingPolicy Policy = Context.getPrintingPolicy();
155 // In diagnostics, we print _Bool as bool if the latter is defined as the
156 // former.
157 Policy.Bool = Context.getLangOpts().Bool;
158 if (!Policy.Bool) {
159 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
160 Policy.Bool = BoolMacro->isObjectLike() &&
161 BoolMacro->getNumTokens() == 1 &&
162 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
163 }
164 }
165
166 // Shorten the data output if needed
167 Policy.EntireContentsOfLargeArray = false;
168
169 return Policy;
170 }
171
172 void Sema::ActOnTranslationUnitScope(Scope *S) {
173 TUScope = S;
174 PushDeclContext(S, Context.getTranslationUnitDecl());
175 }
176
177 namespace clang {
178 namespace sema {
179
180 class SemaPPCallbacks : public PPCallbacks {
181 Sema *S = nullptr;
182 llvm::SmallVector<SourceLocation, 8> IncludeStack;
183 llvm::SmallVector<llvm::TimeTraceProfilerEntry *, 8> ProfilerStack;
184
185 public:
186 void set(Sema &S) { this->S = &S; }
187
188 void reset() { S = nullptr; }
189
190 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
191 SrcMgr::CharacteristicKind FileType,
192 FileID PrevFID) override {
193 if (!S)
194 return;
195 switch (Reason) {
196 case EnterFile: {
197 SourceManager &SM = S->getSourceManager();
198 SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
199 if (IncludeLoc.isValid()) {
200 if (llvm::timeTraceProfilerEnabled()) {
201 OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getFileID(Loc));
202 ProfilerStack.push_back(llvm::timeTraceAsyncProfilerBegin(
203 "Source", FE ? FE->getName() : StringRef("<unknown>")));
204 }
205
206 IncludeStack.push_back(IncludeLoc);
207 S->DiagnoseNonDefaultPragmaAlignPack(
208 Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,
209 IncludeLoc);
210 }
211 break;
212 }
213 case ExitFile:
214 if (!IncludeStack.empty()) {
215 if (llvm::timeTraceProfilerEnabled())
216 llvm::timeTraceProfilerEnd(ProfilerStack.pop_back_val());
217
218 S->DiagnoseNonDefaultPragmaAlignPack(
219 Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,
220 IncludeStack.pop_back_val());
221 }
222 break;
223 default:
224 break;
225 }
226 }
227 void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
228 diag::Severity Mapping, StringRef Str) override {
229 // If one of the analysis-based diagnostics was enabled while processing
230 // a function, we want to note it in the analysis-based warnings so they
231 // can be run at the end of the function body even if the analysis warnings
232 // are disabled at that point.
233 SmallVector<diag::kind, 256> GroupDiags;
234 diag::Flavor Flavor =
235 Str[1] == 'W' ? diag::Flavor::WarningOrError : diag::Flavor::Remark;
236 StringRef Group = Str.substr(2);
237
238 if (S->PP.getDiagnostics().getDiagnosticIDs()->getDiagnosticsInGroup(
239 Flavor, Group, GroupDiags))
240 return;
241
242 for (diag::kind K : GroupDiags) {
243 // Note: the cases in this switch should be kept in sync with the
244 // diagnostics in AnalysisBasedWarnings::getPolicyInEffectAt().
245 AnalysisBasedWarnings::Policy &Override =
246 S->AnalysisWarnings.getPolicyOverrides();
247 switch (K) {
248 default: break;
249 case diag::warn_unreachable:
250 case diag::warn_unreachable_break:
251 case diag::warn_unreachable_return:
252 case diag::warn_unreachable_loop_increment:
253 Override.enableCheckUnreachable = true;
254 break;
255 case diag::warn_double_lock:
256 Override.enableThreadSafetyAnalysis = true;
257 break;
258 case diag::warn_use_in_invalid_state:
259 Override.enableConsumedAnalysis = true;
260 break;
261 }
262 }
263 }
264 };
265
266 } // end namespace sema
267 } // end namespace clang
268
269 const unsigned Sema::MaxAlignmentExponent;
270 const uint64_t Sema::MaximumAlignment;
271
272 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
273 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
274 : SemaBase(*this), CollectStats(false), TUKind(TUKind),
275 CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
276 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
277 SourceMgr(PP.getSourceManager()), APINotes(SourceMgr, LangOpts),
278 AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),
279 LateTemplateParser(nullptr), OpaqueParser(nullptr), CurContext(nullptr),
280 ExternalSource(nullptr), StackHandler(Diags), CurScope(nullptr),
281 Ident_super(nullptr), AMDGPUPtr(std::make_unique<SemaAMDGPU>(*this)),
282 ARMPtr(std::make_unique<SemaARM>(*this)),
283 AVRPtr(std::make_unique<SemaAVR>(*this)),
284 BPFPtr(std::make_unique<SemaBPF>(*this)),
285 CodeCompletionPtr(
286 std::make_unique<SemaCodeCompletion>(*this, CodeCompleter)),
287 CUDAPtr(std::make_unique<SemaCUDA>(*this)),
288 DirectXPtr(std::make_unique<SemaDirectX>(*this)),
289 HLSLPtr(std::make_unique<SemaHLSL>(*this)),
290 HexagonPtr(std::make_unique<SemaHexagon>(*this)),
291 LoongArchPtr(std::make_unique<SemaLoongArch>(*this)),
292 M68kPtr(std::make_unique<SemaM68k>(*this)),
293 MIPSPtr(std::make_unique<SemaMIPS>(*this)),
294 MSP430Ptr(std::make_unique<SemaMSP430>(*this)),
295 NVPTXPtr(std::make_unique<SemaNVPTX>(*this)),
296 ObjCPtr(std::make_unique<SemaObjC>(*this)),
297 OpenACCPtr(std::make_unique<SemaOpenACC>(*this)),
298 OpenCLPtr(std::make_unique<SemaOpenCL>(*this)),
299 OpenMPPtr(std::make_unique<SemaOpenMP>(*this)),
300 PPCPtr(std::make_unique<SemaPPC>(*this)),
301 PseudoObjectPtr(std::make_unique<SemaPseudoObject>(*this)),
302 RISCVPtr(std::make_unique<SemaRISCV>(*this)),
303 SPIRVPtr(std::make_unique<SemaSPIRV>(*this)),
304 SYCLPtr(std::make_unique<SemaSYCL>(*this)),
305 SwiftPtr(std::make_unique<SemaSwift>(*this)),
306 SystemZPtr(std::make_unique<SemaSystemZ>(*this)),
307 WasmPtr(std::make_unique<SemaWasm>(*this)),
308 X86Ptr(std::make_unique<SemaX86>(*this)),
309 MSPointerToMemberRepresentationMethod(
310 LangOpts.getMSPointerToMemberRepresentationMethod()),
311 MSStructPragmaOn(false), VtorDispStack(LangOpts.getVtorDispMode()),
312 AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
313 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
314 CodeSegStack(nullptr), StrictGuardStackCheckStack(false),
315 FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr),
316 VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),
317 StdCoroutineTraitsCache(nullptr), IdResolver(pp),
318 OriginalLexicalContext(nullptr), StdInitializerList(nullptr),
319 StdTypeIdentity(nullptr),
320 FullyCheckedComparisonCategories(
321 static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
322 StdSourceLocationImplDecl(nullptr), CXXTypeInfoDecl(nullptr),
323 GlobalNewDeleteDeclared(false), DisableTypoCorrection(false),
324 TyposCorrected(0), IsBuildingRecoveryCallExpr(false),
325 CurrentInstantiationScope(nullptr), NonInstantiationEntries(0),
326 ArgPackSubstIndex(std::nullopt), SatisfactionCache(Context) {
327 assert(pp.TUKind == TUKind);
328 TUScope = nullptr;
329
330 LoadedExternalKnownNamespaces = false;
331 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
332 ObjC().NSNumberLiteralMethods[I] = nullptr;
333
334 if (getLangOpts().ObjC)
335 ObjC().NSAPIObj.reset(new NSAPI(Context));
336
337 if (getLangOpts().CPlusPlus)
338 FieldCollector.reset(new CXXFieldCollector());
339
340 // Tell diagnostics how to render things from the AST library.
341 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
342
343 // This evaluation context exists to ensure that there's always at least one
344 // valid evaluation context available. It is never removed from the
345 // evaluation stack.
346 ExprEvalContexts.emplace_back(
347 ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
348 nullptr, ExpressionEvaluationContextRecord::EK_Other);
349
350 // Initialization of data sharing attributes stack for OpenMP
351 OpenMP().InitDataSharingAttributesStack();
352
353 std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
354 std::make_unique<sema::SemaPPCallbacks>();
355 SemaPPCallbackHandler = Callbacks.get();
356 PP.addPPCallbacks(std::move(Callbacks));
357 SemaPPCallbackHandler->set(*this);
358
359 CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
360 }
361
362 // Anchor Sema's type info to this TU.
363 void Sema::anchor() {}
364
365 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
366 DeclarationName DN = &Context.Idents.get(Name);
367 if (IdResolver.begin(DN) == IdResolver.end())
368 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
369 }
370
371 void Sema::Initialize() {
372 // Create BuiltinVaListDecl *before* ExternalSemaSource::InitializeSema(this)
373 // because during initialization ASTReader can emit globals that require
374 // name mangling. And the name mangling uses BuiltinVaListDecl.
375 if (Context.getTargetInfo().hasBuiltinMSVaList())
376 (void)Context.getBuiltinMSVaListDecl();
377 (void)Context.getBuiltinVaListDecl();
378
379 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
380 SC->InitializeSema(*this);
381
382 // Tell the external Sema source about this Sema object.
383 if (ExternalSemaSource *ExternalSema
384 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
385 ExternalSema->InitializeSema(*this);
386
387 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
388 // will not be able to merge any duplicate __va_list_tag decls correctly.
389 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
390
391 if (!TUScope)
392 return;
393
394 // Initialize predefined 128-bit integer types, if needed.
395 if (Context.getTargetInfo().hasInt128Type() ||
396 (Context.getAuxTargetInfo() &&
397 Context.getAuxTargetInfo()->hasInt128Type())) {
398 // If either of the 128-bit integer types are unavailable to name lookup,
399 // define them now.
400 DeclarationName Int128 = &Context.Idents.get("__int128_t");
401 if (IdResolver.begin(Int128) == IdResolver.end())
402 PushOnScopeChains(Context.getInt128Decl(), TUScope);
403
404 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
405 if (IdResolver.begin(UInt128) == IdResolver.end())
406 PushOnScopeChains(Context.getUInt128Decl(), TUScope);
407 }
408
409
410 // Initialize predefined Objective-C types:
411 if (getLangOpts().ObjC) {
412 // If 'SEL' does not yet refer to any declarations, make it refer to the
413 // predefined 'SEL'.
414 DeclarationName SEL = &Context.Idents.get("SEL");
415 if (IdResolver.begin(SEL) == IdResolver.end())
416 PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
417
418 // If 'id' does not yet refer to any declarations, make it refer to the
419 // predefined 'id'.
420 DeclarationName Id = &Context.Idents.get("id");
421 if (IdResolver.begin(Id) == IdResolver.end())
422 PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
423
424 // Create the built-in typedef for 'Class'.
425 DeclarationName Class = &Context.Idents.get("Class");
426 if (IdResolver.begin(Class) == IdResolver.end())
427 PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
428
429 // Create the built-in forward declaratino for 'Protocol'.
430 DeclarationName Protocol = &Context.Idents.get("Protocol");
431 if (IdResolver.begin(Protocol) == IdResolver.end())
432 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
433 }
434
435 // Create the internal type for the *StringMakeConstantString builtins.
436 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
437 if (IdResolver.begin(ConstantString) == IdResolver.end())
438 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
439
440 // Initialize Microsoft "predefined C++ types".
441 if (getLangOpts().MSVCCompat) {
442 if (getLangOpts().CPlusPlus &&
443 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
444 PushOnScopeChains(Context.getMSTypeInfoTagDecl(), TUScope);
445
446 addImplicitTypedef("size_t", Context.getSizeType());
447 }
448
449 // Initialize predefined OpenCL types and supported extensions and (optional)
450 // core features.
451 if (getLangOpts().OpenCL) {
452 getOpenCLOptions().addSupport(
453 Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
454 addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
455 addImplicitTypedef("event_t", Context.OCLEventTy);
456 auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
457 if (OCLCompatibleVersion >= 200) {
458 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
459 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
460 addImplicitTypedef("queue_t", Context.OCLQueueTy);
461 }
462 if (getLangOpts().OpenCLPipes)
463 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
464 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
465 addImplicitTypedef("atomic_uint",
466 Context.getAtomicType(Context.UnsignedIntTy));
467 addImplicitTypedef("atomic_float",
468 Context.getAtomicType(Context.FloatTy));
469 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
470 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
471 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
472
473
474 // OpenCL v2.0 s6.13.11.6:
475 // - The atomic_long and atomic_ulong types are supported if the
476 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
477 // extensions are supported.
478 // - The atomic_double type is only supported if double precision
479 // is supported and the cl_khr_int64_base_atomics and
480 // cl_khr_int64_extended_atomics extensions are supported.
481 // - If the device address space is 64-bits, the data types
482 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
483 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
484 // cl_khr_int64_extended_atomics extensions are supported.
485
486 auto AddPointerSizeDependentTypes = [&]() {
487 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
488 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
489 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
490 auto AtomicPtrDiffT =
491 Context.getAtomicType(Context.getPointerDiffType());
492 addImplicitTypedef("atomic_size_t", AtomicSizeT);
493 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
494 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
495 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
496 };
497
498 if (Context.getTypeSize(Context.getSizeType()) == 32) {
499 AddPointerSizeDependentTypes();
500 }
501
502 if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
503 auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
504 addImplicitTypedef("atomic_half", AtomicHalfT);
505 }
506
507 std::vector<QualType> Atomic64BitTypes;
508 if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
509 getLangOpts()) &&
510 getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
511 getLangOpts())) {
512 if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
513 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
514 addImplicitTypedef("atomic_double", AtomicDoubleT);
515 Atomic64BitTypes.push_back(AtomicDoubleT);
516 }
517 auto AtomicLongT = Context.getAtomicType(Context.LongTy);
518 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
519 addImplicitTypedef("atomic_long", AtomicLongT);
520 addImplicitTypedef("atomic_ulong", AtomicULongT);
521
522
523 if (Context.getTypeSize(Context.getSizeType()) == 64) {
524 AddPointerSizeDependentTypes();
525 }
526 }
527 }
528
529 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
530 if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \
531 addImplicitTypedef(#ExtType, Context.Id##Ty); \
532 }
533 #include "clang/Basic/OpenCLExtensionTypes.def"
534 }
535
536 if (Context.getTargetInfo().hasAArch64ACLETypes() ||
537 (Context.getAuxTargetInfo() &&
538 Context.getAuxTargetInfo()->hasAArch64ACLETypes())) {
539 #define SVE_TYPE(Name, Id, SingletonId) \
540 addImplicitTypedef(#Name, Context.SingletonId);
541 #define NEON_VECTOR_TYPE(Name, BaseType, ElBits, NumEls, VectorKind) \
542 addImplicitTypedef( \
543 #Name, Context.getVectorType(Context.BaseType, NumEls, VectorKind));
544 #include "clang/Basic/AArch64ACLETypes.def"
545 }
546
547 if (Context.getTargetInfo().getTriple().isPPC64()) {
548 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
549 addImplicitTypedef(#Name, Context.Id##Ty);
550 #include "clang/Basic/PPCTypes.def"
551 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
552 addImplicitTypedef(#Name, Context.Id##Ty);
553 #include "clang/Basic/PPCTypes.def"
554 }
555
556 if (Context.getTargetInfo().hasRISCVVTypes()) {
557 #define RVV_TYPE(Name, Id, SingletonId) \
558 addImplicitTypedef(Name, Context.SingletonId);
559 #include "clang/Basic/RISCVVTypes.def"
560 }
561
562 if (Context.getTargetInfo().getTriple().isWasm() &&
563 Context.getTargetInfo().hasFeature("reference-types")) {
564 #define WASM_TYPE(Name, Id, SingletonId) \
565 addImplicitTypedef(Name, Context.SingletonId);
566 #include "clang/Basic/WebAssemblyReferenceTypes.def"
567 }
568
569 if (Context.getTargetInfo().getTriple().isAMDGPU() ||
570 (Context.getAuxTargetInfo() &&
571 Context.getAuxTargetInfo()->getTriple().isAMDGPU())) {
572 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
573 addImplicitTypedef(Name, Context.SingletonId);
574 #include "clang/Basic/AMDGPUTypes.def"
575 }
576
577 if (Context.getTargetInfo().hasBuiltinMSVaList()) {
578 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
579 if (IdResolver.begin(MSVaList) == IdResolver.end())
580 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
581 }
582
583 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
584 if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
585 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
586 }
587
588 Sema::~Sema() {
589 assert(InstantiatingSpecializations.empty() &&
590 "failed to clean up an InstantiatingTemplate?");
591
592 if (VisContext) FreeVisContext();
593
594 // Kill all the active scopes.
595 for (sema::FunctionScopeInfo *FSI : FunctionScopes)
596 delete FSI;
597
598 // Tell the SemaConsumer to forget about us; we're going out of scope.
599 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
600 SC->ForgetSema();
601
602 // Detach from the external Sema source.
603 if (ExternalSemaSource *ExternalSema
604 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
605 ExternalSema->ForgetSema();
606
607 // Delete cached satisfactions.
608 std::vector<ConstraintSatisfaction *> Satisfactions;
609 Satisfactions.reserve(SatisfactionCache.size());
610 for (auto &Node : SatisfactionCache)
611 Satisfactions.push_back(&Node);
612 for (auto *Node : Satisfactions)
613 delete Node;
614
615 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
616
617 // Destroys data sharing attributes stack for OpenMP
618 OpenMP().DestroyDataSharingAttributesStack();
619
620 // Detach from the PP callback handler which outlives Sema since it's owned
621 // by the preprocessor.
622 SemaPPCallbackHandler->reset();
623 }
624
625 void Sema::runWithSufficientStackSpace(SourceLocation Loc,
626 llvm::function_ref<void()> Fn) {
627 StackHandler.runWithSufficientStackSpace(Loc, Fn);
628 }
629
630 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
631 UnavailableAttr::ImplicitReason reason) {
632 // If we're not in a function, it's an error.
633 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
634 if (!fn) return false;
635
636 // If we're in template instantiation, it's an error.
637 if (inTemplateInstantiation())
638 return false;
639
640 // If that function's not in a system header, it's an error.
641 if (!Context.getSourceManager().isInSystemHeader(loc))
642 return false;
643
644 // If the function is already unavailable, it's not an error.
645 if (fn->hasAttr<UnavailableAttr>()) return true;
646
647 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
648 return true;
649 }
650
651 ASTMutationListener *Sema::getASTMutationListener() const {
652 return getASTConsumer().GetASTMutationListener();
653 }
654
655 void Sema::addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E) {
656 assert(E && "Cannot use with NULL ptr");
657
658 if (!ExternalSource) {
659 ExternalSource = std::move(E);
660 return;
661 }
662
663 if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource.get()))
664 Ex->AddSource(std::move(E));
665 else
666 ExternalSource = llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
667 ExternalSource, std::move(E));
668 }
669
670 void Sema::PrintStats() const {
671 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
672 if (SFINAETrap *Trap = getSFINAEContext())
673 llvm::errs() << int(Trap->hasErrorOccurred())
674 << " SFINAE diagnostics trapped.\n";
675
676 BumpAlloc.PrintStats();
677 AnalysisWarnings.PrintStats();
678 }
679
680 void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
681 QualType SrcType,
682 SourceLocation Loc) {
683 std::optional<NullabilityKind> ExprNullability = SrcType->getNullability();
684 if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
685 *ExprNullability != NullabilityKind::NullableResult))
686 return;
687
688 std::optional<NullabilityKind> TypeNullability = DstType->getNullability();
689 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
690 return;
691
692 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
693 }
694
695 // Generate diagnostics when adding or removing effects in a type conversion.
696 void Sema::diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
697 SourceLocation Loc) {
698 const auto SrcFX = FunctionEffectsRef::get(SrcType);
699 const auto DstFX = FunctionEffectsRef::get(DstType);
700 if (SrcFX != DstFX) {
701 for (const auto &Diff : FunctionEffectDiffVector(SrcFX, DstFX)) {
702 if (Diff.shouldDiagnoseConversion(SrcType, SrcFX, DstType, DstFX))
703 Diag(Loc, diag::warn_invalid_add_func_effects) << Diff.effectName();
704 }
705 }
706 }
707
708 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E) {
709 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
710 if (!getLangOpts().CPlusPlus11)
711 return;
712
713 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
714 return;
715
716 const Expr *EStripped = E->IgnoreParenImpCasts();
717 if (EStripped->getType()->isNullPtrType())
718 return;
719 if (isa<GNUNullExpr>(EStripped))
720 return;
721
722 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
723 E->getBeginLoc()))
724 return;
725
726 // Don't diagnose the conversion from a 0 literal to a null pointer argument
727 // in a synthesized call to operator<=>.
728 if (!CodeSynthesisContexts.empty() &&
729 CodeSynthesisContexts.back().Kind ==
730 CodeSynthesisContext::RewritingOperatorAsSpaceship)
731 return;
732
733 // Ignore null pointers in defaulted comparison operators.
734 FunctionDecl *FD = getCurFunctionDecl();
735 if (FD && FD->isDefaulted()) {
736 return;
737 }
738
739 // If it is a macro from system header, and if the macro name is not "NULL",
740 // do not warn.
741 // Note that uses of "NULL" will be ignored above on systems that define it
742 // as __null.
743 SourceLocation MaybeMacroLoc = E->getBeginLoc();
744 if (Diags.getSuppressSystemWarnings() &&
745 SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
746 !findMacroSpelling(MaybeMacroLoc, "NULL"))
747 return;
748
749 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
750 << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
751 }
752
753 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
754 /// If there is already an implicit cast, merge into the existing one.
755 /// The result is of the given category.
756 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
757 CastKind Kind, ExprValueKind VK,
758 const CXXCastPath *BasePath,
759 CheckedConversionKind CCK) {
760 #ifndef NDEBUG
761 if (VK == VK_PRValue && !E->isPRValue()) {
762 switch (Kind) {
763 default:
764 llvm_unreachable(
765 ("can't implicitly cast glvalue to prvalue with this cast "
766 "kind: " +
767 std::string(CastExpr::getCastKindName(Kind)))
768 .c_str());
769 case CK_Dependent:
770 case CK_LValueToRValue:
771 case CK_ArrayToPointerDecay:
772 case CK_FunctionToPointerDecay:
773 case CK_ToVoid:
774 case CK_NonAtomicToAtomic:
775 case CK_HLSLArrayRValue:
776 case CK_HLSLAggregateSplatCast:
777 break;
778 }
779 }
780 assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
781 "can't cast prvalue to glvalue");
782 #endif
783
784 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
785 diagnoseZeroToNullptrConversion(Kind, E);
786 if (Context.hasAnyFunctionEffects() && !isCast(CCK) &&
787 Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
788 diagnoseFunctionEffectConversion(Ty, E->getType(), E->getBeginLoc());
789
790 QualType ExprTy = Context.getCanonicalType(E->getType());
791 QualType TypeTy = Context.getCanonicalType(Ty);
792
793 // This cast is used in place of a regular LValue to RValue cast for
794 // HLSL Array Parameter Types. It needs to be emitted even if
795 // ExprTy == TypeTy, except if E is an HLSLOutArgExpr
796 // Emitting a cast in that case will prevent HLSLOutArgExpr from
797 // being handled properly in EmitCallArg
798 if (Kind == CK_HLSLArrayRValue && !isa<HLSLOutArgExpr>(E))
799 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
800 CurFPFeatureOverrides());
801
802 if (ExprTy == TypeTy)
803 return E;
804
805 if (Kind == CK_ArrayToPointerDecay) {
806 // C++1z [conv.array]: The temporary materialization conversion is applied.
807 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
808 if (getLangOpts().CPlusPlus && E->isPRValue()) {
809 // The temporary is an lvalue in C++98 and an xvalue otherwise.
810 ExprResult Materialized = CreateMaterializeTemporaryExpr(
811 E->getType(), E, !getLangOpts().CPlusPlus11);
812 if (Materialized.isInvalid())
813 return ExprError();
814 E = Materialized.get();
815 }
816 // C17 6.7.1p6 footnote 124: The implementation can treat any register
817 // declaration simply as an auto declaration. However, whether or not
818 // addressable storage is actually used, the address of any part of an
819 // object declared with storage-class specifier register cannot be
820 // computed, either explicitly(by use of the unary & operator as discussed
821 // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
822 // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
823 // array declared with storage-class specifier register is sizeof.
824 if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {
825 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
826 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
827 if (VD->getStorageClass() == SC_Register) {
828 Diag(E->getExprLoc(), diag::err_typecheck_address_of)
829 << /*register variable*/ 3 << E->getSourceRange();
830 return ExprError();
831 }
832 }
833 }
834 }
835 }
836
837 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
838 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
839 ImpCast->setType(Ty);
840 ImpCast->setValueKind(VK);
841 return E;
842 }
843 }
844
845 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
846 CurFPFeatureOverrides());
847 }
848
849 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
850 switch (ScalarTy->getScalarTypeKind()) {
851 case Type::STK_Bool: return CK_NoOp;
852 case Type::STK_CPointer: return CK_PointerToBoolean;
853 case Type::STK_BlockPointer: return CK_PointerToBoolean;
854 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
855 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
856 case Type::STK_Integral: return CK_IntegralToBoolean;
857 case Type::STK_Floating: return CK_FloatingToBoolean;
858 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
859 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
860 case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
861 }
862 llvm_unreachable("unknown scalar type kind");
863 }
864
865 /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
866 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
867 if (D->getMostRecentDecl()->isUsed())
868 return true;
869
870 if (D->isExternallyVisible())
871 return true;
872
873 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
874 // If this is a function template and none of its specializations is used,
875 // we should warn.
876 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
877 for (const auto *Spec : Template->specializations())
878 if (ShouldRemoveFromUnused(SemaRef, Spec))
879 return true;
880
881 // UnusedFileScopedDecls stores the first declaration.
882 // The declaration may have become definition so check again.
883 const FunctionDecl *DeclToCheck;
884 if (FD->hasBody(DeclToCheck))
885 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
886
887 // Later redecls may add new information resulting in not having to warn,
888 // so check again.
889 DeclToCheck = FD->getMostRecentDecl();
890 if (DeclToCheck != FD)
891 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
892 }
893
894 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
895 // If a variable usable in constant expressions is referenced,
896 // don't warn if it isn't used: if the value of a variable is required
897 // for the computation of a constant expression, it doesn't make sense to
898 // warn even if the variable isn't odr-used. (isReferenced doesn't
899 // precisely reflect that, but it's a decent approximation.)
900 if (VD->isReferenced() &&
901 VD->mightBeUsableInConstantExpressions(SemaRef->Context))
902 return true;
903
904 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
905 // If this is a variable template and none of its specializations is used,
906 // we should warn.
907 for (const auto *Spec : Template->specializations())
908 if (ShouldRemoveFromUnused(SemaRef, Spec))
909 return true;
910
911 // UnusedFileScopedDecls stores the first declaration.
912 // The declaration may have become definition so check again.
913 const VarDecl *DeclToCheck = VD->getDefinition();
914 if (DeclToCheck)
915 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
916
917 // Later redecls may add new information resulting in not having to warn,
918 // so check again.
919 DeclToCheck = VD->getMostRecentDecl();
920 if (DeclToCheck != VD)
921 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
922 }
923
924 return false;
925 }
926
927 static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) {
928 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
929 return FD->isExternC();
930 return cast<VarDecl>(ND)->isExternC();
931 }
932
933 /// Determine whether ND is an external-linkage function or variable whose
934 /// type has no linkage.
935 bool Sema::isExternalWithNoLinkageType(const ValueDecl *VD) const {
936 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
937 // because we also want to catch the case where its type has VisibleNoLinkage,
938 // which does not affect the linkage of VD.
939 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
940 !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
941 !isFunctionOrVarDeclExternC(VD);
942 }
943
944 /// Obtains a sorted list of functions and variables that are undefined but
945 /// ODR-used.
946 void Sema::getUndefinedButUsed(
947 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
948 for (const auto &UndefinedUse : UndefinedButUsed) {
949 NamedDecl *ND = UndefinedUse.first;
950
951 // Ignore attributes that have become invalid.
952 if (ND->isInvalidDecl()) continue;
953
954 // __attribute__((weakref)) is basically a definition.
955 if (ND->hasAttr<WeakRefAttr>()) continue;
956
957 if (isa<CXXDeductionGuideDecl>(ND))
958 continue;
959
960 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
961 // An exported function will always be emitted when defined, so even if
962 // the function is inline, it doesn't have to be emitted in this TU. An
963 // imported function implies that it has been exported somewhere else.
964 continue;
965 }
966
967 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
968 if (FD->isDefined())
969 continue;
970 if (FD->isExternallyVisible() &&
971 !isExternalWithNoLinkageType(FD) &&
972 !FD->getMostRecentDecl()->isInlined() &&
973 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
974 continue;
975 if (FD->getBuiltinID())
976 continue;
977 } else {
978 const auto *VD = cast<VarDecl>(ND);
979 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
980 continue;
981 if (VD->isExternallyVisible() &&
982 !isExternalWithNoLinkageType(VD) &&
983 !VD->getMostRecentDecl()->isInline() &&
984 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
985 continue;
986
987 // Skip VarDecls that lack formal definitions but which we know are in
988 // fact defined somewhere.
989 if (VD->isKnownToBeDefined())
990 continue;
991 }
992
993 Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
994 }
995 }
996
997 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
998 /// or that are inline.
999 static void checkUndefinedButUsed(Sema &S) {
1000 if (S.UndefinedButUsed.empty()) return;
1001
1002 // Collect all the still-undefined entities with internal linkage.
1003 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
1004 S.getUndefinedButUsed(Undefined);
1005 S.UndefinedButUsed.clear();
1006 if (Undefined.empty()) return;
1007
1008 for (const auto &Undef : Undefined) {
1009 ValueDecl *VD = cast<ValueDecl>(Undef.first);
1010 SourceLocation UseLoc = Undef.second;
1011
1012 if (S.isExternalWithNoLinkageType(VD)) {
1013 // C++ [basic.link]p8:
1014 // A type without linkage shall not be used as the type of a variable
1015 // or function with external linkage unless
1016 // -- the entity has C language linkage
1017 // -- the entity is not odr-used or is defined in the same TU
1018 //
1019 // As an extension, accept this in cases where the type is externally
1020 // visible, since the function or variable actually can be defined in
1021 // another translation unit in that case.
1022 S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
1023 ? diag::ext_undefined_internal_type
1024 : diag::err_undefined_internal_type)
1025 << isa<VarDecl>(VD) << VD;
1026 } else if (!VD->isExternallyVisible()) {
1027 // FIXME: We can promote this to an error. The function or variable can't
1028 // be defined anywhere else, so the program must necessarily violate the
1029 // one definition rule.
1030 bool IsImplicitBase = false;
1031 if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
1032 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
1033 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
1034 llvm::omp::TraitProperty::
1035 implementation_extension_disable_implicit_base)) {
1036 const auto *Func = cast<FunctionDecl>(
1037 cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
1038 IsImplicitBase = BaseD->isImplicit() &&
1039 Func->getIdentifier()->isMangledOpenMPVariantName();
1040 }
1041 }
1042 if (!S.getLangOpts().OpenMP || !IsImplicitBase)
1043 S.Diag(VD->getLocation(), diag::warn_undefined_internal)
1044 << isa<VarDecl>(VD) << VD;
1045 } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
1046 (void)FD;
1047 assert(FD->getMostRecentDecl()->isInlined() &&
1048 "used object requires definition but isn't inline or internal?");
1049 // FIXME: This is ill-formed; we should reject.
1050 S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
1051 } else {
1052 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
1053 "used var requires definition but isn't inline or internal?");
1054 S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
1055 }
1056 if (UseLoc.isValid())
1057 S.Diag(UseLoc, diag::note_used_here);
1058 }
1059 }
1060
1061 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
1062 if (!ExternalSource)
1063 return;
1064
1065 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
1066 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
1067 for (auto &WeakID : WeakIDs)
1068 (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
1069 }
1070
1071
1072 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
1073
1074 /// Returns true, if all methods and nested classes of the given
1075 /// CXXRecordDecl are defined in this translation unit.
1076 ///
1077 /// Should only be called from ActOnEndOfTranslationUnit so that all
1078 /// definitions are actually read.
1079 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
1080 RecordCompleteMap &MNCComplete) {
1081 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
1082 if (Cache != MNCComplete.end())
1083 return Cache->second;
1084 if (!RD->isCompleteDefinition())
1085 return false;
1086 bool Complete = true;
1087 for (DeclContext::decl_iterator I = RD->decls_begin(),
1088 E = RD->decls_end();
1089 I != E && Complete; ++I) {
1090 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
1091 Complete = M->isDefined() || M->isDefaulted() ||
1092 (M->isPureVirtual() && !isa<CXXDestructorDecl>(M));
1093 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
1094 // If the template function is marked as late template parsed at this
1095 // point, it has not been instantiated and therefore we have not
1096 // performed semantic analysis on it yet, so we cannot know if the type
1097 // can be considered complete.
1098 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
1099 F->getTemplatedDecl()->isDefined();
1100 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
1101 if (R->isInjectedClassName())
1102 continue;
1103 if (R->hasDefinition())
1104 Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
1105 MNCComplete);
1106 else
1107 Complete = false;
1108 }
1109 }
1110 MNCComplete[RD] = Complete;
1111 return Complete;
1112 }
1113
1114 /// Returns true, if the given CXXRecordDecl is fully defined in this
1115 /// translation unit, i.e. all methods are defined or pure virtual and all
1116 /// friends, friend functions and nested classes are fully defined in this
1117 /// translation unit.
1118 ///
1119 /// Should only be called from ActOnEndOfTranslationUnit so that all
1120 /// definitions are actually read.
1121 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
1122 RecordCompleteMap &RecordsComplete,
1123 RecordCompleteMap &MNCComplete) {
1124 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
1125 if (Cache != RecordsComplete.end())
1126 return Cache->second;
1127 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
1128 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
1129 E = RD->friend_end();
1130 I != E && Complete; ++I) {
1131 // Check if friend classes and methods are complete.
1132 if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
1133 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
1134 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
1135 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
1136 else
1137 Complete = false;
1138 } else {
1139 // Friend functions are available through the NamedDecl of FriendDecl.
1140 if (const FunctionDecl *FD =
1141 dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
1142 Complete = FD->isDefined();
1143 else
1144 // This is a template friend, give up.
1145 Complete = false;
1146 }
1147 }
1148 RecordsComplete[RD] = Complete;
1149 return Complete;
1150 }
1151
1152 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
1153 if (ExternalSource)
1154 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1155 UnusedLocalTypedefNameCandidates);
1156 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
1157 if (TD->isReferenced())
1158 continue;
1159 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1160 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1161 }
1162 UnusedLocalTypedefNameCandidates.clear();
1163 }
1164
1165 void Sema::ActOnStartOfTranslationUnit() {
1166 if (getLangOpts().CPlusPlusModules &&
1167 getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
1168 HandleStartOfHeaderUnit();
1169 }
1170
1171 void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
1172 if (Kind == TUFragmentKind::Global) {
1173 // Perform Pending Instantiations at the end of global module fragment so
1174 // that the module ownership of TU-level decls won't get messed.
1175 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1176 PerformPendingInstantiations();
1177 return;
1178 }
1179
1180 // Transfer late parsed template instantiations over to the pending template
1181 // instantiation list. During normal compilation, the late template parser
1182 // will be installed and instantiating these templates will succeed.
1183 //
1184 // If we are building a TU prefix for serialization, it is also safe to
1185 // transfer these over, even though they are not parsed. The end of the TU
1186 // should be outside of any eager template instantiation scope, so when this
1187 // AST is deserialized, these templates will not be parsed until the end of
1188 // the combined TU.
1189 PendingInstantiations.insert(PendingInstantiations.end(),
1190 LateParsedInstantiations.begin(),
1191 LateParsedInstantiations.end());
1192 LateParsedInstantiations.clear();
1193
1194 // If DefinedUsedVTables ends up marking any virtual member functions it
1195 // might lead to more pending template instantiations, which we then need
1196 // to instantiate.
1197 DefineUsedVTables();
1198
1199 // C++: Perform implicit template instantiations.
1200 //
1201 // FIXME: When we perform these implicit instantiations, we do not
1202 // carefully keep track of the point of instantiation (C++ [temp.point]).
1203 // This means that name lookup that occurs within the template
1204 // instantiation will always happen at the end of the translation unit,
1205 // so it will find some names that are not required to be found. This is
1206 // valid, but we could do better by diagnosing if an instantiation uses a
1207 // name that was not visible at its first point of instantiation.
1208 if (ExternalSource) {
1209 // Load pending instantiations from the external source.
1210 SmallVector<PendingImplicitInstantiation, 4> Pending;
1211 ExternalSource->ReadPendingInstantiations(Pending);
1212 for (auto PII : Pending)
1213 if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1214 Func->setInstantiationIsPending(true);
1215 PendingInstantiations.insert(PendingInstantiations.begin(),
1216 Pending.begin(), Pending.end());
1217 }
1218
1219 {
1220 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1221 PerformPendingInstantiations();
1222 }
1223
1224 emitDeferredDiags();
1225
1226 assert(LateParsedInstantiations.empty() &&
1227 "end of TU template instantiation should not create more "
1228 "late-parsed templates");
1229 }
1230
1231 void Sema::ActOnEndOfTranslationUnit() {
1232 assert(DelayedDiagnostics.getCurrentPool() == nullptr
1233 && "reached end of translation unit with a pool attached?");
1234
1235 // If code completion is enabled, don't perform any end-of-translation-unit
1236 // work.
1237 if (PP.isCodeCompletionEnabled())
1238 return;
1239
1240 // Complete translation units and modules define vtables and perform implicit
1241 // instantiations. PCH files do not.
1242 if (TUKind != TU_Prefix) {
1243 ObjC().DiagnoseUseOfUnimplementedSelectors();
1244
1245 ActOnEndOfTranslationUnitFragment(
1246 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1247 Module::PrivateModuleFragment
1248 ? TUFragmentKind::Private
1249 : TUFragmentKind::Normal);
1250
1251 CheckDelayedMemberExceptionSpecs();
1252 } else {
1253 // If we are building a TU prefix for serialization, it is safe to transfer
1254 // these over, even though they are not parsed. The end of the TU should be
1255 // outside of any eager template instantiation scope, so when this AST is
1256 // deserialized, these templates will not be parsed until the end of the
1257 // combined TU.
1258 PendingInstantiations.insert(PendingInstantiations.end(),
1259 LateParsedInstantiations.begin(),
1260 LateParsedInstantiations.end());
1261 LateParsedInstantiations.clear();
1262
1263 if (LangOpts.PCHInstantiateTemplates) {
1264 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1265 PerformPendingInstantiations();
1266 }
1267 }
1268
1269 DiagnoseUnterminatedPragmaAlignPack();
1270 DiagnoseUnterminatedPragmaAttribute();
1271 OpenMP().DiagnoseUnterminatedOpenMPDeclareTarget();
1272 DiagnosePrecisionLossInComplexDivision();
1273
1274 // All delayed member exception specs should be checked or we end up accepting
1275 // incompatible declarations.
1276 assert(DelayedOverridingExceptionSpecChecks.empty());
1277 assert(DelayedEquivalentExceptionSpecChecks.empty());
1278
1279 // All dllexport classes should have been processed already.
1280 assert(DelayedDllExportClasses.empty());
1281 assert(DelayedDllExportMemberFunctions.empty());
1282
1283 // Remove file scoped decls that turned out to be used.
1284 UnusedFileScopedDecls.erase(
1285 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1286 UnusedFileScopedDecls.end(),
1287 [this](const DeclaratorDecl *DD) {
1288 return ShouldRemoveFromUnused(this, DD);
1289 }),
1290 UnusedFileScopedDecls.end());
1291
1292 if (TUKind == TU_Prefix) {
1293 // Translation unit prefixes don't need any of the checking below.
1294 if (!PP.isIncrementalProcessingEnabled())
1295 TUScope = nullptr;
1296 return;
1297 }
1298
1299 // Check for #pragma weak identifiers that were never declared
1300 LoadExternalWeakUndeclaredIdentifiers();
1301 for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1302 if (WeakIDs.second.empty())
1303 continue;
1304
1305 Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
1306 LookupOrdinaryName);
1307 if (PrevDecl != nullptr &&
1308 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1309 for (const auto &WI : WeakIDs.second)
1310 Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1311 << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction;
1312 else
1313 for (const auto &WI : WeakIDs.second)
1314 Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1315 << WeakIDs.first;
1316 }
1317
1318 if (LangOpts.CPlusPlus11 &&
1319 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
1320 CheckDelegatingCtorCycles();
1321
1322 if (!Diags.hasErrorOccurred()) {
1323 if (ExternalSource)
1324 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1325 checkUndefinedButUsed(*this);
1326 }
1327
1328 // A global-module-fragment is only permitted within a module unit.
1329 if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1330 Module::ExplicitGlobalModuleFragment) {
1331 Diag(ModuleScopes.back().BeginLoc,
1332 diag::err_module_declaration_missing_after_global_module_introducer);
1333 } else if (getLangOpts().getCompilingModule() ==
1334 LangOptions::CMK_ModuleInterface &&
1335 // We can't use ModuleScopes here since ModuleScopes is always
1336 // empty if we're compiling the BMI.
1337 !getASTContext().getCurrentNamedModule()) {
1338 // If we are building a module interface unit, we should have seen the
1339 // module declaration.
1340 //
1341 // FIXME: Make a better guess as to where to put the module declaration.
1342 Diag(getSourceManager().getLocForStartOfFile(
1343 getSourceManager().getMainFileID()),
1344 diag::err_module_declaration_missing);
1345 }
1346
1347 // Now we can decide whether the modules we're building need an initializer.
1348 if (Module *CurrentModule = getCurrentModule();
1349 CurrentModule && CurrentModule->isInterfaceOrPartition()) {
1350 auto DoesModNeedInit = [this](Module *M) {
1351 if (!getASTContext().getModuleInitializers(M).empty())
1352 return true;
1353 for (auto [Exported, _] : M->Exports)
1354 if (Exported->isNamedModuleInterfaceHasInit())
1355 return true;
1356 for (Module *I : M->Imports)
1357 if (I->isNamedModuleInterfaceHasInit())
1358 return true;
1359
1360 return false;
1361 };
1362
1363 CurrentModule->NamedModuleHasInit =
1364 DoesModNeedInit(CurrentModule) ||
1365 llvm::any_of(CurrentModule->submodules(), DoesModNeedInit);
1366 }
1367
1368 if (TUKind == TU_ClangModule) {
1369 // If we are building a module, resolve all of the exported declarations
1370 // now.
1371 if (Module *CurrentModule = PP.getCurrentModule()) {
1372 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1373
1374 SmallVector<Module *, 2> Stack;
1375 Stack.push_back(CurrentModule);
1376 while (!Stack.empty()) {
1377 Module *Mod = Stack.pop_back_val();
1378
1379 // Resolve the exported declarations and conflicts.
1380 // FIXME: Actually complain, once we figure out how to teach the
1381 // diagnostic client to deal with complaints in the module map at this
1382 // point.
1383 ModMap.resolveExports(Mod, /*Complain=*/false);
1384 ModMap.resolveUses(Mod, /*Complain=*/false);
1385 ModMap.resolveConflicts(Mod, /*Complain=*/false);
1386
1387 // Queue the submodules, so their exports will also be resolved.
1388 auto SubmodulesRange = Mod->submodules();
1389 Stack.append(SubmodulesRange.begin(), SubmodulesRange.end());
1390 }
1391 }
1392
1393 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1394 // modules when they are built, not every time they are used.
1395 emitAndClearUnusedLocalTypedefWarnings();
1396 }
1397
1398 // C++ standard modules. Diagnose cases where a function is declared inline
1399 // in the module purview but has no definition before the end of the TU or
1400 // the start of a Private Module Fragment (if one is present).
1401 if (!PendingInlineFuncDecls.empty()) {
1402 for (auto *D : PendingInlineFuncDecls) {
1403 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1404 bool DefInPMF = false;
1405 if (auto *FDD = FD->getDefinition()) {
1406 DefInPMF = FDD->getOwningModule()->isPrivateModule();
1407 if (!DefInPMF)
1408 continue;
1409 }
1410 Diag(FD->getLocation(), diag::err_export_inline_not_defined)
1411 << DefInPMF;
1412 // If we have a PMF it should be at the end of the ModuleScopes.
1413 if (DefInPMF &&
1414 ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {
1415 Diag(ModuleScopes.back().BeginLoc,
1416 diag::note_private_module_fragment);
1417 }
1418 }
1419 }
1420 PendingInlineFuncDecls.clear();
1421 }
1422
1423 // C99 6.9.2p2:
1424 // A declaration of an identifier for an object that has file
1425 // scope without an initializer, and without a storage-class
1426 // specifier or with the storage-class specifier static,
1427 // constitutes a tentative definition. If a translation unit
1428 // contains one or more tentative definitions for an identifier,
1429 // and the translation unit contains no external definition for
1430 // that identifier, then the behavior is exactly as if the
1431 // translation unit contains a file scope declaration of that
1432 // identifier, with the composite type as of the end of the
1433 // translation unit, with an initializer equal to 0.
1434 llvm::SmallPtrSet<VarDecl *, 32> Seen;
1435 for (TentativeDefinitionsType::iterator
1436 T = TentativeDefinitions.begin(ExternalSource.get()),
1437 TEnd = TentativeDefinitions.end();
1438 T != TEnd; ++T) {
1439 VarDecl *VD = (*T)->getActingDefinition();
1440
1441 // If the tentative definition was completed, getActingDefinition() returns
1442 // null. If we've already seen this variable before, insert()'s second
1443 // return value is false.
1444 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
1445 continue;
1446
1447 if (const IncompleteArrayType *ArrayT
1448 = Context.getAsIncompleteArrayType(VD->getType())) {
1449 // Set the length of the array to 1 (C99 6.9.2p5).
1450 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1451 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1452 QualType T = Context.getConstantArrayType(
1453 ArrayT->getElementType(), One, nullptr, ArraySizeModifier::Normal, 0);
1454 VD->setType(T);
1455 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1456 diag::err_tentative_def_incomplete_type))
1457 VD->setInvalidDecl();
1458
1459 // No initialization is performed for a tentative definition.
1460 CheckCompleteVariableDeclaration(VD);
1461
1462 // In C, if the definition is const-qualified and has no initializer, it
1463 // is left uninitialized unless it has static or thread storage duration.
1464 QualType Type = VD->getType();
1465 if (!VD->isInvalidDecl() && !getLangOpts().CPlusPlus &&
1466 Type.isConstQualified() && !VD->getAnyInitializer()) {
1467 unsigned DiagID = diag::warn_default_init_const_unsafe;
1468 if (VD->getStorageDuration() == SD_Static ||
1469 VD->getStorageDuration() == SD_Thread)
1470 DiagID = diag::warn_default_init_const;
1471
1472 bool EmitCppCompat = !Diags.isIgnored(
1473 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
1474 VD->getLocation());
1475
1476 Diag(VD->getLocation(), DiagID) << Type << EmitCppCompat;
1477 }
1478
1479 // Notify the consumer that we've completed a tentative definition.
1480 if (!VD->isInvalidDecl())
1481 Consumer.CompleteTentativeDefinition(VD);
1482 }
1483
1484 // In incremental mode, tentative definitions belong to the current
1485 // partial translation unit (PTU). Once they have been completed and
1486 // emitted to codegen, drop them to prevent re-emission in future PTUs.
1487 if (PP.isIncrementalProcessingEnabled())
1488 TentativeDefinitions.erase(TentativeDefinitions.begin(ExternalSource.get()),
1489 TentativeDefinitions.end());
1490
1491 for (auto *D : ExternalDeclarations) {
1492 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1493 continue;
1494
1495 Consumer.CompleteExternalDeclaration(D);
1496 }
1497
1498 if (LangOpts.HLSL)
1499 HLSL().ActOnEndOfTranslationUnit(getASTContext().getTranslationUnitDecl());
1500 if (LangOpts.OpenACC)
1501 OpenACC().ActOnEndOfTranslationUnit(
1502 getASTContext().getTranslationUnitDecl());
1503
1504 // If there were errors, disable 'unused' warnings since they will mostly be
1505 // noise. Don't warn for a use from a module: either we should warn on all
1506 // file-scope declarations in modules or not at all, but whether the
1507 // declaration is used is immaterial.
1508 if (!Diags.hasErrorOccurred() && TUKind != TU_ClangModule) {
1509 // Output warning for unused file scoped decls.
1510 for (UnusedFileScopedDeclsType::iterator
1511 I = UnusedFileScopedDecls.begin(ExternalSource.get()),
1512 E = UnusedFileScopedDecls.end();
1513 I != E; ++I) {
1514 if (ShouldRemoveFromUnused(this, *I))
1515 continue;
1516
1517 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1518 const FunctionDecl *DiagD;
1519 if (!FD->hasBody(DiagD))
1520 DiagD = FD;
1521 if (DiagD->isDeleted())
1522 continue; // Deleted functions are supposed to be unused.
1523 SourceRange DiagRange = DiagD->getLocation();
1524 if (const ASTTemplateArgumentListInfo *ASTTAL =
1525 DiagD->getTemplateSpecializationArgsAsWritten())
1526 DiagRange.setEnd(ASTTAL->RAngleLoc);
1527 if (DiagD->isReferenced()) {
1528 if (isa<CXXMethodDecl>(DiagD))
1529 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1530 << DiagD << DiagRange;
1531 else {
1532 if (FD->getStorageClass() == SC_Static &&
1533 !FD->isInlineSpecified() &&
1534 !SourceMgr.isInMainFile(
1535 SourceMgr.getExpansionLoc(FD->getLocation())))
1536 Diag(DiagD->getLocation(),
1537 diag::warn_unneeded_static_internal_decl)
1538 << DiagD << DiagRange;
1539 else
1540 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1541 << /*function=*/0 << DiagD << DiagRange;
1542 }
1543 } else if (!FD->isTargetMultiVersion() ||
1544 FD->isTargetMultiVersionDefault()) {
1545 if (FD->getDescribedFunctionTemplate())
1546 Diag(DiagD->getLocation(), diag::warn_unused_template)
1547 << /*function=*/0 << DiagD << DiagRange;
1548 else
1549 Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1550 ? diag::warn_unused_member_function
1551 : diag::warn_unused_function)
1552 << DiagD << DiagRange;
1553 }
1554 } else {
1555 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1556 if (!DiagD)
1557 DiagD = cast<VarDecl>(*I);
1558 SourceRange DiagRange = DiagD->getLocation();
1559 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(DiagD)) {
1560 if (const ASTTemplateArgumentListInfo *ASTTAL =
1561 VTSD->getTemplateArgsAsWritten())
1562 DiagRange.setEnd(ASTTAL->RAngleLoc);
1563 }
1564 if (DiagD->isReferenced()) {
1565 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1566 << /*variable=*/1 << DiagD << DiagRange;
1567 } else if (DiagD->getDescribedVarTemplate()) {
1568 Diag(DiagD->getLocation(), diag::warn_unused_template)
1569 << /*variable=*/1 << DiagD << DiagRange;
1570 } else if (DiagD->getType().isConstQualified()) {
1571 const SourceManager &SM = SourceMgr;
1572 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1573 !PP.getLangOpts().IsHeaderFile)
1574 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1575 << DiagD << DiagRange;
1576 } else {
1577 Diag(DiagD->getLocation(), diag::warn_unused_variable)
1578 << DiagD << DiagRange;
1579 }
1580 }
1581 }
1582
1583 emitAndClearUnusedLocalTypedefWarnings();
1584 }
1585
1586 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1587 // FIXME: Load additional unused private field candidates from the external
1588 // source.
1589 RecordCompleteMap RecordsComplete;
1590 RecordCompleteMap MNCComplete;
1591 for (const NamedDecl *D : UnusedPrivateFields) {
1592 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1593 if (RD && !RD->isUnion() &&
1594 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1595 Diag(D->getLocation(), diag::warn_unused_private_field)
1596 << D->getDeclName();
1597 }
1598 }
1599 }
1600
1601 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1602 if (ExternalSource)
1603 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1604 for (const auto &DeletedFieldInfo : DeleteExprs) {
1605 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1606 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1607 DeleteExprLoc.second);
1608 }
1609 }
1610 }
1611
1612 AnalysisWarnings.IssueWarnings(Context.getTranslationUnitDecl());
1613
1614 if (Context.hasAnyFunctionEffects())
1615 performFunctionEffectAnalysis(Context.getTranslationUnitDecl());
1616
1617 // Check we've noticed that we're no longer parsing the initializer for every
1618 // variable. If we miss cases, then at best we have a performance issue and
1619 // at worst a rejects-valid bug.
1620 assert(ParsingInitForAutoVars.empty() &&
1621 "Didn't unmark var as having its initializer parsed");
1622
1623 if (!PP.isIncrementalProcessingEnabled())
1624 TUScope = nullptr;
1625
1626 checkExposure(Context.getTranslationUnitDecl());
1627 }
1628
1629
1630 //===----------------------------------------------------------------------===//
1631 // Helper functions.
1632 //===----------------------------------------------------------------------===//
1633
1634 DeclContext *Sema::getFunctionLevelDeclContext(bool AllowLambda) const {
1635 DeclContext *DC = CurContext;
1636
1637 while (true) {
1638 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
1639 isa<RequiresExprBodyDecl>(DC)) {
1640 DC = DC->getParent();
1641 } else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&
1642 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1643 cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1644 DC = DC->getParent()->getParent();
1645 } else break;
1646 }
1647
1648 return DC;
1649 }
1650
1651 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1652 /// to the function decl for the function being parsed. If we're currently
1653 /// in a 'block', this returns the containing context.
1654 FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const {
1655 DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1656 return dyn_cast<FunctionDecl>(DC);
1657 }
1658
1659 ObjCMethodDecl *Sema::getCurMethodDecl() {
1660 DeclContext *DC = getFunctionLevelDeclContext();
1661 while (isa<RecordDecl>(DC))
1662 DC = DC->getParent();
1663 return dyn_cast<ObjCMethodDecl>(DC);
1664 }
1665
1666 NamedDecl *Sema::getCurFunctionOrMethodDecl() const {
1667 DeclContext *DC = getFunctionLevelDeclContext();
1668 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1669 return cast<NamedDecl>(DC);
1670 return nullptr;
1671 }
1672
1673 LangAS Sema::getDefaultCXXMethodAddrSpace() const {
1674 if (getLangOpts().OpenCL)
1675 return getASTContext().getDefaultOpenCLPointeeAddrSpace();
1676 return LangAS::Default;
1677 }
1678
1679 void Sema::EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB) {
1680 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1681 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1682 // been made more painfully obvious by the refactor that introduced this
1683 // function, but it is possible that the incoming argument can be
1684 // eliminated. If it truly cannot be (for example, there is some reentrancy
1685 // issue I am not seeing yet), then there should at least be a clarifying
1686 // comment somewhere.
1687 Diagnostic DiagInfo(&Diags, DB);
1688 if (SFINAETrap *Trap = getSFINAEContext()) {
1689 sema::TemplateDeductionInfo *Info = Trap->getDeductionInfo();
1690 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(DiagInfo.getID())) {
1691 case DiagnosticIDs::SFINAE_Report:
1692 // We'll report the diagnostic below.
1693 break;
1694
1695 case DiagnosticIDs::SFINAE_SubstitutionFailure:
1696 // Count this failure so that we know that template argument deduction
1697 // has failed.
1698 Trap->setErrorOccurred();
1699
1700 // Make a copy of this suppressed diagnostic and store it with the
1701 // template-deduction information.
1702 if (Info && !Info->hasSFINAEDiagnostic())
1703 Info->addSFINAEDiagnostic(
1704 DiagInfo.getLocation(),
1705 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1706
1707 Diags.setLastDiagnosticIgnored(true);
1708 return;
1709
1710 case DiagnosticIDs::SFINAE_AccessControl: {
1711 // Per C++ Core Issue 1170, access control is part of SFINAE.
1712 // Additionally, the WithAccessChecking flag can be used to temporarily
1713 // make access control a part of SFINAE for the purposes of checking
1714 // type traits.
1715 if (!Trap->withAccessChecking() && !getLangOpts().CPlusPlus11)
1716 break;
1717
1718 SourceLocation Loc = DiagInfo.getLocation();
1719
1720 // Suppress this diagnostic.
1721 Trap->setErrorOccurred();
1722
1723 // Make a copy of this suppressed diagnostic and store it with the
1724 // template-deduction information.
1725 if (Info && !Info->hasSFINAEDiagnostic())
1726 Info->addSFINAEDiagnostic(
1727 DiagInfo.getLocation(),
1728 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1729
1730 Diags.setLastDiagnosticIgnored(true);
1731
1732 // Now produce a C++98 compatibility warning.
1733 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1734
1735 // The last diagnostic which Sema produced was ignored. Suppress any
1736 // notes attached to it.
1737 Diags.setLastDiagnosticIgnored(true);
1738 return;
1739 }
1740
1741 case DiagnosticIDs::SFINAE_Suppress:
1742 if (DiagnosticsEngine::Level Level = getDiagnostics().getDiagnosticLevel(
1743 DiagInfo.getID(), DiagInfo.getLocation());
1744 Level == DiagnosticsEngine::Ignored)
1745 return;
1746 // Make a copy of this suppressed diagnostic and store it with the
1747 // template-deduction information;
1748 if (Info) {
1749 Info->addSuppressedDiagnostic(
1750 DiagInfo.getLocation(),
1751 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1752 if (!Diags.getDiagnosticIDs()->isNote(DiagID))
1753 PrintContextStack([Info](SourceLocation Loc, PartialDiagnostic PD) {
1754 Info->addSuppressedDiagnostic(Loc, std::move(PD));
1755 });
1756 }
1757
1758 // Suppress this diagnostic.
1759 Diags.setLastDiagnosticIgnored(true);
1760 return;
1761 }
1762 }
1763
1764 // Copy the diagnostic printing policy over the ASTContext printing policy.
1765 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
1766 Context.setPrintingPolicy(getPrintingPolicy());
1767
1768 // Emit the diagnostic.
1769 if (!Diags.EmitDiagnostic(DB))
1770 return;
1771
1772 // If this is not a note, and we're in a template instantiation
1773 // that is different from the last template instantiation where
1774 // we emitted an error, print a template instantiation
1775 // backtrace.
1776 if (!Diags.getDiagnosticIDs()->isNote(DiagID))
1777 PrintContextStack();
1778 }
1779
1780 bool Sema::hasUncompilableErrorOccurred() const {
1781 if (getDiagnostics().hasUncompilableErrorOccurred())
1782 return true;
1783 auto *FD = dyn_cast<FunctionDecl>(CurContext);
1784 if (!FD)
1785 return false;
1786 auto Loc = DeviceDeferredDiags.find(FD);
1787 if (Loc == DeviceDeferredDiags.end())
1788 return false;
1789 for (auto PDAt : Loc->second) {
1790 if (Diags.getDiagnosticIDs()->isDefaultMappingAsError(
1791 PDAt.second.getDiagID()))
1792 return true;
1793 }
1794 return false;
1795 }
1796
1797 // Print notes showing how we can reach FD starting from an a priori
1798 // known-callable function.
1799 static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) {
1800 auto FnIt = S.CUDA().DeviceKnownEmittedFns.find(FD);
1801 while (FnIt != S.CUDA().DeviceKnownEmittedFns.end()) {
1802 // Respect error limit.
1803 if (S.Diags.hasFatalErrorOccurred())
1804 return;
1805 DiagnosticBuilder Builder(
1806 S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1807 Builder << FnIt->second.FD;
1808 FnIt = S.CUDA().DeviceKnownEmittedFns.find(FnIt->second.FD);
1809 }
1810 }
1811
1812 namespace {
1813
1814 /// Helper class that emits deferred diagnostic messages if an entity directly
1815 /// or indirectly using the function that causes the deferred diagnostic
1816 /// messages is known to be emitted.
1817 ///
1818 /// During parsing of AST, certain diagnostic messages are recorded as deferred
1819 /// diagnostics since it is unknown whether the functions containing such
1820 /// diagnostics will be emitted. A list of potentially emitted functions and
1821 /// variables that may potentially trigger emission of functions are also
1822 /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1823 /// by each function to emit deferred diagnostics.
1824 ///
1825 /// During the visit, certain OpenMP directives or initializer of variables
1826 /// with certain OpenMP attributes will cause subsequent visiting of any
1827 /// functions enter a state which is called OpenMP device context in this
1828 /// implementation. The state is exited when the directive or initializer is
1829 /// exited. This state can change the emission states of subsequent uses
1830 /// of functions.
1831 ///
1832 /// Conceptually the functions or variables to be visited form a use graph
1833 /// where the parent node uses the child node. At any point of the visit,
1834 /// the tree nodes traversed from the tree root to the current node form a use
1835 /// stack. The emission state of the current node depends on two factors:
1836 /// 1. the emission state of the root node
1837 /// 2. whether the current node is in OpenMP device context
1838 /// If the function is decided to be emitted, its contained deferred diagnostics
1839 /// are emitted, together with the information about the use stack.
1840 ///
1841 class DeferredDiagnosticsEmitter
1842 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1843 public:
1844 typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1845
1846 // Whether the function is already in the current use-path.
1847 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1848
1849 // The current use-path.
1850 llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1851
1852 // Whether the visiting of the function has been done. Done[0] is for the
1853 // case not in OpenMP device context. Done[1] is for the case in OpenMP
1854 // device context. We need two sets because diagnostics emission may be
1855 // different depending on whether it is in OpenMP device context.
1856 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
1857
1858 // Emission state of the root node of the current use graph.
1859 bool ShouldEmitRootNode;
1860
1861 // Current OpenMP device context level. It is initialized to 0 and each
1862 // entering of device context increases it by 1 and each exit decreases
1863 // it by 1. Non-zero value indicates it is currently in device context.
1864 unsigned InOMPDeviceContext;
1865
1866 DeferredDiagnosticsEmitter(Sema &S)
1867 : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1868
1869 bool shouldVisitDiscardedStmt() const { return false; }
1870
1871 void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1872 ++InOMPDeviceContext;
1873 Inherited::VisitOMPTargetDirective(Node);
1874 --InOMPDeviceContext;
1875 }
1876
1877 void visitUsedDecl(SourceLocation Loc, Decl *D) {
1878 if (isa<VarDecl>(D))
1879 return;
1880 if (auto *FD = dyn_cast<FunctionDecl>(D))
1881 checkFunc(Loc, FD);
1882 else
1883 Inherited::visitUsedDecl(Loc, D);
1884 }
1885
1886 // Visitor member and parent dtors called by this dtor.
1887 void VisitCalledDestructors(CXXDestructorDecl *DD) {
1888 const CXXRecordDecl *RD = DD->getParent();
1889
1890 // Visit the dtors of all members
1891 for (const FieldDecl *FD : RD->fields()) {
1892 QualType FT = FD->getType();
1893 if (const auto *ClassDecl = FT->getAsCXXRecordDecl();
1894 ClassDecl &&
1895 (ClassDecl->isBeingDefined() || ClassDecl->isCompleteDefinition()))
1896 if (CXXDestructorDecl *MemberDtor = ClassDecl->getDestructor())
1897 asImpl().visitUsedDecl(MemberDtor->getLocation(), MemberDtor);
1898 }
1899
1900 // Also visit base class dtors
1901 for (const auto &Base : RD->bases()) {
1902 QualType BaseType = Base.getType();
1903 if (const auto *BaseDecl = BaseType->getAsCXXRecordDecl();
1904 BaseDecl &&
1905 (BaseDecl->isBeingDefined() || BaseDecl->isCompleteDefinition()))
1906 if (CXXDestructorDecl *BaseDtor = BaseDecl->getDestructor())
1907 asImpl().visitUsedDecl(BaseDtor->getLocation(), BaseDtor);
1908 }
1909 }
1910
1911 void VisitDeclStmt(DeclStmt *DS) {
1912 // Visit dtors called by variables that need destruction
1913 for (auto *D : DS->decls())
1914 if (auto *VD = dyn_cast<VarDecl>(D))
1915 if (VD->isThisDeclarationADefinition() &&
1916 VD->needsDestruction(S.Context)) {
1917 QualType VT = VD->getType();
1918 if (const auto *ClassDecl = VT->getAsCXXRecordDecl();
1919 ClassDecl && (ClassDecl->isBeingDefined() ||
1920 ClassDecl->isCompleteDefinition()))
1921 if (CXXDestructorDecl *Dtor = ClassDecl->getDestructor())
1922 asImpl().visitUsedDecl(Dtor->getLocation(), Dtor);
1923 }
1924
1925 Inherited::VisitDeclStmt(DS);
1926 }
1927 void checkVar(VarDecl *VD) {
1928 assert(VD->isFileVarDecl() &&
1929 "Should only check file-scope variables");
1930 if (auto *Init = VD->getInit()) {
1931 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1932 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
1933 *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1934 if (IsDev)
1935 ++InOMPDeviceContext;
1936 this->Visit(Init);
1937 if (IsDev)
1938 --InOMPDeviceContext;
1939 }
1940 }
1941
1942 void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1943 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
1944 FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
1945 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
1946 S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
1947 return;
1948 // Finalize analysis of OpenMP-specific constructs.
1949 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
1950 (ShouldEmitRootNode || InOMPDeviceContext))
1951 S.OpenMP().finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1952 if (Caller)
1953 S.CUDA().DeviceKnownEmittedFns[FD] = {Caller, Loc};
1954 // Always emit deferred diagnostics for the direct users. This does not
1955 // lead to explosion of diagnostics since each user is visited at most
1956 // twice.
1957 if (ShouldEmitRootNode || InOMPDeviceContext)
1958 emitDeferredDiags(FD, Caller);
1959 // Do not revisit a function if the function body has been completely
1960 // visited before.
1961 if (!Done.insert(FD).second)
1962 return;
1963 InUsePath.insert(FD);
1964 UsePath.push_back(FD);
1965 if (auto *S = FD->getBody()) {
1966 this->Visit(S);
1967 }
1968 if (CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(FD))
1969 asImpl().VisitCalledDestructors(Dtor);
1970 UsePath.pop_back();
1971 InUsePath.erase(FD);
1972 }
1973
1974 void checkRecordedDecl(Decl *D) {
1975 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1976 ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1977 Sema::FunctionEmissionStatus::Emitted;
1978 checkFunc(SourceLocation(), FD);
1979 } else
1980 checkVar(cast<VarDecl>(D));
1981 }
1982
1983 // Emit any deferred diagnostics for FD
1984 void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
1985 auto It = S.DeviceDeferredDiags.find(FD);
1986 if (It == S.DeviceDeferredDiags.end())
1987 return;
1988 bool HasWarningOrError = false;
1989 bool FirstDiag = true;
1990 for (PartialDiagnosticAt &PDAt : It->second) {
1991 // Respect error limit.
1992 if (S.Diags.hasFatalErrorOccurred())
1993 return;
1994 const SourceLocation &Loc = PDAt.first;
1995 const PartialDiagnostic &PD = PDAt.second;
1996 HasWarningOrError |=
1997 S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
1998 DiagnosticsEngine::Warning;
1999 {
2000 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
2001 PD.Emit(Builder);
2002 }
2003 // Emit the note on the first diagnostic in case too many diagnostics
2004 // cause the note not emitted.
2005 if (FirstDiag && HasWarningOrError && ShowCallStack) {
2006 emitCallStackNotes(S, FD);
2007 FirstDiag = false;
2008 }
2009 }
2010 }
2011 };
2012 } // namespace
2013
2014 void Sema::emitDeferredDiags() {
2015 if (ExternalSource)
2016 ExternalSource->ReadDeclsToCheckForDeferredDiags(
2017 DeclsToCheckForDeferredDiags);
2018
2019 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
2020 DeclsToCheckForDeferredDiags.empty())
2021 return;
2022
2023 DeferredDiagnosticsEmitter DDE(*this);
2024 for (auto *D : DeclsToCheckForDeferredDiags)
2025 DDE.checkRecordedDecl(D);
2026 }
2027
2028 // In CUDA, there are some constructs which may appear in semantically-valid
2029 // code, but trigger errors if we ever generate code for the function in which
2030 // they appear. Essentially every construct you're not allowed to use on the
2031 // device falls into this category, because you are allowed to use these
2032 // constructs in a __host__ __device__ function, but only if that function is
2033 // never codegen'ed on the device.
2034 //
2035 // To handle semantic checking for these constructs, we keep track of the set of
2036 // functions we know will be emitted, either because we could tell a priori that
2037 // they would be emitted, or because they were transitively called by a
2038 // known-emitted function.
2039 //
2040 // We also keep a partial call graph of which not-known-emitted functions call
2041 // which other not-known-emitted functions.
2042 //
2043 // When we see something which is illegal if the current function is emitted
2044 // (usually by way of DiagIfDeviceCode, DiagIfHostCode, or
2045 // CheckCall), we first check if the current function is known-emitted. If
2046 // so, we immediately output the diagnostic.
2047 //
2048 // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
2049 // until we discover that the function is known-emitted, at which point we take
2050 // it out of this map and emit the diagnostic.
2051
2052 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
2053 unsigned DiagID,
2054 const FunctionDecl *Fn,
2055 Sema &S)
2056 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
2057 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
2058 switch (K) {
2059 case K_Nop:
2060 break;
2061 case K_Immediate:
2062 case K_ImmediateWithCallStack:
2063 ImmediateDiag.emplace(
2064 ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
2065 break;
2066 case K_Deferred:
2067 assert(Fn && "Must have a function to attach the deferred diag to.");
2068 auto &Diags = S.DeviceDeferredDiags[Fn];
2069 PartialDiagId.emplace(Diags.size());
2070 Diags.emplace_back(Loc, S.PDiag(DiagID));
2071 break;
2072 }
2073 }
2074
2075 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
2076 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
2077 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
2078 PartialDiagId(D.PartialDiagId) {
2079 // Clean the previous diagnostics.
2080 D.ShowCallStack = false;
2081 D.ImmediateDiag.reset();
2082 D.PartialDiagId.reset();
2083 }
2084
2085 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
2086 if (ImmediateDiag) {
2087 // Emit our diagnostic and, if it was a warning or error, output a callstack
2088 // if Fn isn't a priori known-emitted.
2089 ImmediateDiag.reset(); // Emit the immediate diag.
2090
2091 if (ShowCallStack) {
2092 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
2093 DiagID, Loc) >= DiagnosticsEngine::Warning;
2094 if (IsWarningOrError)
2095 emitCallStackNotes(S, Fn);
2096 }
2097 } else {
2098 assert((!PartialDiagId || ShowCallStack) &&
2099 "Must always show call stack for deferred diags.");
2100 }
2101 }
2102
2103 Sema::SemaDiagnosticBuilder
2104 Sema::targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD) {
2105 FD = FD ? FD : getCurFunctionDecl();
2106 if (LangOpts.OpenMP)
2107 return LangOpts.OpenMPIsTargetDevice
2108 ? OpenMP().diagIfOpenMPDeviceCode(Loc, DiagID, FD)
2109 : OpenMP().diagIfOpenMPHostCode(Loc, DiagID, FD);
2110 if (getLangOpts().CUDA)
2111 return getLangOpts().CUDAIsDevice ? CUDA().DiagIfDeviceCode(Loc, DiagID)
2112 : CUDA().DiagIfHostCode(Loc, DiagID);
2113
2114 if (getLangOpts().SYCLIsDevice)
2115 return SYCL().DiagIfDeviceCode(Loc, DiagID);
2116
2117 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
2118 FD, *this);
2119 }
2120
2121 void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
2122 if (isUnevaluatedContext() || Ty.isNull())
2123 return;
2124
2125 // The original idea behind checkTypeSupport function is that unused
2126 // declarations can be replaced with an array of bytes of the same size during
2127 // codegen, such replacement doesn't seem to be possible for types without
2128 // constant byte size like zero length arrays. So, do a deep check for SYCL.
2129 if (D && LangOpts.SYCLIsDevice) {
2130 llvm::DenseSet<QualType> Visited;
2131 SYCL().deepTypeCheckForDevice(Loc, Visited, D);
2132 }
2133
2134 Decl *C = cast<Decl>(getCurLexicalContext());
2135
2136 // Memcpy operations for structs containing a member with unsupported type
2137 // are ok, though.
2138 if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
2139 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
2140 MD->isTrivial())
2141 return;
2142
2143 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
2144 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
2145 return;
2146 }
2147
2148 // Try to associate errors with the lexical context, if that is a function, or
2149 // the value declaration otherwise.
2150 const FunctionDecl *FD = isa<FunctionDecl>(C)
2151 ? cast<FunctionDecl>(C)
2152 : dyn_cast_or_null<FunctionDecl>(D);
2153
2154 auto CheckDeviceType = [&](QualType Ty) {
2155 if (Ty->isDependentType())
2156 return;
2157
2158 if (Ty->isBitIntType()) {
2159 if (!Context.getTargetInfo().hasBitIntType()) {
2160 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2161 if (D)
2162 PD << D;
2163 else
2164 PD << "expression";
2165 targetDiag(Loc, PD, FD)
2166 << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
2167 << Ty << Context.getTargetInfo().getTriple().str();
2168 }
2169 return;
2170 }
2171
2172 // Check if we are dealing with two 'long double' but with different
2173 // semantics.
2174 bool LongDoubleMismatched = false;
2175 if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {
2176 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
2177 if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
2178 !Context.getTargetInfo().hasFloat128Type()) ||
2179 (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
2180 !Context.getTargetInfo().hasIbm128Type()))
2181 LongDoubleMismatched = true;
2182 }
2183
2184 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
2185 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
2186 (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) ||
2187 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
2188 !Context.getTargetInfo().hasInt128Type()) ||
2189 (Ty->isBFloat16Type() && !Context.getTargetInfo().hasBFloat16Type() &&
2190 !LangOpts.CUDAIsDevice) ||
2191 LongDoubleMismatched) {
2192 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2193 if (D)
2194 PD << D;
2195 else
2196 PD << "expression";
2197
2198 if (targetDiag(Loc, PD, FD)
2199 << true /*show bit size*/
2200 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
2201 << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
2202 if (D)
2203 D->setInvalidDecl();
2204 }
2205 if (D)
2206 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2207 }
2208 };
2209
2210 auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
2211 if (LangOpts.SYCLIsDevice ||
2212 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice) ||
2213 LangOpts.CUDAIsDevice)
2214 CheckDeviceType(Ty);
2215
2216 QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();
2217 const TargetInfo &TI = Context.getTargetInfo();
2218 if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
2219 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2220 if (D)
2221 PD << D;
2222 else
2223 PD << "expression";
2224
2225 if (Diag(Loc, PD) << false /*show bit size*/ << 0 << Ty
2226 << false /*return*/
2227 << TI.getTriple().str()) {
2228 if (D)
2229 D->setInvalidDecl();
2230 }
2231 if (D)
2232 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2233 }
2234
2235 bool IsDouble = UnqualTy == Context.DoubleTy;
2236 bool IsFloat = UnqualTy == Context.FloatTy;
2237 if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
2238 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2239 if (D)
2240 PD << D;
2241 else
2242 PD << "expression";
2243
2244 if (Diag(Loc, PD) << false /*show bit size*/ << 0 << Ty << true /*return*/
2245 << TI.getTriple().str()) {
2246 if (D)
2247 D->setInvalidDecl();
2248 }
2249 if (D)
2250 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2251 }
2252
2253 if (TI.hasRISCVVTypes() && Ty->isRVVSizelessBuiltinType() && FD) {
2254 llvm::StringMap<bool> CallerFeatureMap;
2255 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2256 RISCV().checkRVVTypeSupport(Ty, Loc, D, CallerFeatureMap);
2257 }
2258
2259 // Don't allow SVE types in functions without a SVE target.
2260 if (Ty->isSVESizelessBuiltinType() && FD) {
2261 llvm::StringMap<bool> CallerFeatureMap;
2262 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2263 ARM().checkSVETypeSupport(Ty, Loc, FD, CallerFeatureMap);
2264 }
2265
2266 if (auto *VT = Ty->getAs<VectorType>();
2267 VT && FD &&
2268 (VT->getVectorKind() == VectorKind::SveFixedLengthData ||
2269 VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
2270 (LangOpts.VScaleMin != LangOpts.VScaleStreamingMin ||
2271 LangOpts.VScaleMax != LangOpts.VScaleStreamingMax)) {
2272 if (IsArmStreamingFunction(FD, /*IncludeLocallyStreaming=*/true)) {
2273 Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function)
2274 << Ty << /*Streaming*/ 0;
2275 } else if (const auto *FTy = FD->getType()->getAs<FunctionProtoType>()) {
2276 if (FTy->getAArch64SMEAttributes() &
2277 FunctionType::SME_PStateSMCompatibleMask) {
2278 Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function)
2279 << Ty << /*StreamingCompatible*/ 1;
2280 }
2281 }
2282 }
2283 };
2284
2285 CheckType(Ty);
2286 if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
2287 for (const auto &ParamTy : FPTy->param_types())
2288 CheckType(ParamTy);
2289 CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
2290 }
2291 if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2292 CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2293 }
2294
2295 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
2296 SourceLocation loc = locref;
2297 if (!loc.isMacroID()) return false;
2298
2299 // There's no good way right now to look at the intermediate
2300 // expansions, so just jump to the expansion location.
2301 loc = getSourceManager().getExpansionLoc(loc);
2302
2303 // If that's written with the name, stop here.
2304 SmallString<16> buffer;
2305 if (getPreprocessor().getSpelling(loc, buffer) == name) {
2306 locref = loc;
2307 return true;
2308 }
2309 return false;
2310 }
2311
2312 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
2313
2314 if (!Ctx)
2315 return nullptr;
2316
2317 Ctx = Ctx->getPrimaryContext();
2318 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2319 // Ignore scopes that cannot have declarations. This is important for
2320 // out-of-line definitions of static class members.
2321 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
2322 if (DeclContext *Entity = S->getEntity())
2323 if (Ctx == Entity->getPrimaryContext())
2324 return S;
2325 }
2326
2327 return nullptr;
2328 }
2329
2330 /// Enter a new function scope
2331 void Sema::PushFunctionScope() {
2332 if (FunctionScopes.empty() && CachedFunctionScope) {
2333 // Use CachedFunctionScope to avoid allocating memory when possible.
2334 CachedFunctionScope->Clear();
2335 FunctionScopes.push_back(CachedFunctionScope.release());
2336 } else {
2337 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
2338 }
2339 if (LangOpts.OpenMP)
2340 OpenMP().pushOpenMPFunctionRegion();
2341 }
2342
2343 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
2344 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
2345 BlockScope, Block));
2346 CapturingFunctionScopes++;
2347 }
2348
2349 LambdaScopeInfo *Sema::PushLambdaScope() {
2350 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
2351 FunctionScopes.push_back(LSI);
2352 CapturingFunctionScopes++;
2353 return LSI;
2354 }
2355
2356 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
2357 if (LambdaScopeInfo *const LSI = getCurLambda()) {
2358 LSI->AutoTemplateParameterDepth = Depth;
2359 return;
2360 }
2361 llvm_unreachable(
2362 "Remove assertion if intentionally called in a non-lambda context.");
2363 }
2364
2365 // Check that the type of the VarDecl has an accessible copy constructor and
2366 // resolve its destructor's exception specification.
2367 // This also performs initialization of block variables when they are moved
2368 // to the heap. It uses the same rules as applicable for implicit moves
2369 // according to the C++ standard in effect ([class.copy.elision]p3).
2370 static void checkEscapingByref(VarDecl *VD, Sema &S) {
2371 QualType T = VD->getType();
2372 EnterExpressionEvaluationContext scope(
2373 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2374 SourceLocation Loc = VD->getLocation();
2375 Expr *VarRef =
2376 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2377 ExprResult Result;
2378 auto IE = InitializedEntity::InitializeBlock(Loc, T);
2379 if (S.getLangOpts().CPlusPlus23) {
2380 auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2381 VK_XValue, FPOptionsOverride());
2382 Result = S.PerformCopyInitialization(IE, SourceLocation(), E);
2383 } else {
2384 Result = S.PerformMoveOrCopyInitialization(
2385 IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible},
2386 VarRef);
2387 }
2388
2389 if (!Result.isInvalid()) {
2390 Result = S.MaybeCreateExprWithCleanups(Result);
2391 Expr *Init = Result.getAs<Expr>();
2392 S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
2393 }
2394
2395 // The destructor's exception specification is needed when IRGen generates
2396 // block copy/destroy functions. Resolve it here.
2397 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2398 if (CXXDestructorDecl *DD = RD->getDestructor()) {
2399 auto *FPT = DD->getType()->castAs<FunctionProtoType>();
2400 S.ResolveExceptionSpec(Loc, FPT);
2401 }
2402 }
2403
2404 static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2405 // Set the EscapingByref flag of __block variables captured by
2406 // escaping blocks.
2407 for (const BlockDecl *BD : FSI.Blocks) {
2408 for (const BlockDecl::Capture &BC : BD->captures()) {
2409 VarDecl *VD = BC.getVariable();
2410 if (VD->hasAttr<BlocksAttr>()) {
2411 // Nothing to do if this is a __block variable captured by a
2412 // non-escaping block.
2413 if (BD->doesNotEscape())
2414 continue;
2415 VD->setEscapingByref();
2416 }
2417 // Check whether the captured variable is or contains an object of
2418 // non-trivial C union type.
2419 QualType CapType = BC.getVariable()->getType();
2420 if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
2421 CapType.hasNonTrivialToPrimitiveCopyCUnion())
2422 S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2423 BD->getCaretLocation(),
2424 NonTrivialCUnionContext::BlockCapture,
2425 Sema::NTCUK_Destruct | Sema::NTCUK_Copy);
2426 }
2427 }
2428
2429 for (VarDecl *VD : FSI.ByrefBlockVars) {
2430 // __block variables might require us to capture a copy-initializer.
2431 if (!VD->isEscapingByref())
2432 continue;
2433 // It's currently invalid to ever have a __block variable with an
2434 // array type; should we diagnose that here?
2435 // Regardless, we don't want to ignore array nesting when
2436 // constructing this copy.
2437 if (VD->getType()->isStructureOrClassType())
2438 checkEscapingByref(VD, S);
2439 }
2440 }
2441
2442 Sema::PoppedFunctionScopePtr
2443 Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, Decl *D,
2444 QualType BlockType) {
2445 assert(!FunctionScopes.empty() && "mismatched push/pop!");
2446
2447 markEscapingByrefs(*FunctionScopes.back(), *this);
2448
2449 PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
2450 PoppedFunctionScopeDeleter(this));
2451
2452 if (LangOpts.OpenMP)
2453 OpenMP().popOpenMPFunctionRegion(Scope.get());
2454
2455 // Issue any analysis-based warnings.
2456 if (WP && D) {
2457 inferNoReturnAttr(*this, D);
2458 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2459 } else
2460 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2461 Diag(PUD.Loc, PUD.PD);
2462
2463 return Scope;
2464 }
2465
2466 void Sema::PoppedFunctionScopeDeleter::
2467 operator()(sema::FunctionScopeInfo *Scope) const {
2468 if (!Scope->isPlainFunction())
2469 Self->CapturingFunctionScopes--;
2470 // Stash the function scope for later reuse if it's for a normal function.
2471 if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
2472 Self->CachedFunctionScope.reset(Scope);
2473 else
2474 delete Scope;
2475 }
2476
2477 void Sema::PushCompoundScope(bool IsStmtExpr) {
2478 getCurFunction()->CompoundScopes.push_back(
2479 CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
2480 }
2481
2482 void Sema::PopCompoundScope() {
2483 FunctionScopeInfo *CurFunction = getCurFunction();
2484 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2485
2486 CurFunction->CompoundScopes.pop_back();
2487 }
2488
2489 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2490 return getCurFunction()->hasUnrecoverableErrorOccurred();
2491 }
2492
2493 void Sema::setFunctionHasBranchIntoScope() {
2494 if (!FunctionScopes.empty())
2495 FunctionScopes.back()->setHasBranchIntoScope();
2496 }
2497
2498 void Sema::setFunctionHasBranchProtectedScope() {
2499 if (!FunctionScopes.empty())
2500 FunctionScopes.back()->setHasBranchProtectedScope();
2501 }
2502
2503 void Sema::setFunctionHasIndirectGoto() {
2504 if (!FunctionScopes.empty())
2505 FunctionScopes.back()->setHasIndirectGoto();
2506 }
2507
2508 void Sema::setFunctionHasMustTail() {
2509 if (!FunctionScopes.empty())
2510 FunctionScopes.back()->setHasMustTail();
2511 }
2512
2513 BlockScopeInfo *Sema::getCurBlock() {
2514 if (FunctionScopes.empty())
2515 return nullptr;
2516
2517 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2518 if (CurBSI && CurBSI->TheDecl &&
2519 !CurBSI->TheDecl->Encloses(CurContext)) {
2520 // We have switched contexts due to template instantiation.
2521 assert(!CodeSynthesisContexts.empty());
2522 return nullptr;
2523 }
2524
2525 return CurBSI;
2526 }
2527
2528 FunctionScopeInfo *Sema::getEnclosingFunction() const {
2529 if (FunctionScopes.empty())
2530 return nullptr;
2531
2532 for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2533 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
2534 continue;
2535 return FunctionScopes[e];
2536 }
2537 return nullptr;
2538 }
2539
2540 CapturingScopeInfo *Sema::getEnclosingLambdaOrBlock() const {
2541 for (auto *Scope : llvm::reverse(FunctionScopes)) {
2542 if (auto *CSI = dyn_cast<CapturingScopeInfo>(Scope)) {
2543 auto *LSI = dyn_cast<LambdaScopeInfo>(CSI);
2544 if (LSI && LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
2545 LSI->AfterParameterList) {
2546 // We have switched contexts due to template instantiation.
2547 // FIXME: We should swap out the FunctionScopes during code synthesis
2548 // so that we don't need to check for this.
2549 assert(!CodeSynthesisContexts.empty());
2550 return nullptr;
2551 }
2552 return CSI;
2553 }
2554 }
2555 return nullptr;
2556 }
2557
2558 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2559 if (FunctionScopes.empty())
2560 return nullptr;
2561
2562 auto I = FunctionScopes.rbegin();
2563 if (IgnoreNonLambdaCapturingScope) {
2564 auto E = FunctionScopes.rend();
2565 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
2566 ++I;
2567 if (I == E)
2568 return nullptr;
2569 }
2570 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2571 if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&
2572 !CurLSI->Lambda->Encloses(CurContext) && CurLSI->AfterParameterList) {
2573 // We have switched contexts due to template instantiation.
2574 assert(!CodeSynthesisContexts.empty());
2575 return nullptr;
2576 }
2577
2578 return CurLSI;
2579 }
2580
2581 // We have a generic lambda if we parsed auto parameters, or we have
2582 // an associated template parameter list.
2583 LambdaScopeInfo *Sema::getCurGenericLambda() {
2584 if (LambdaScopeInfo *LSI = getCurLambda()) {
2585 return (LSI->TemplateParams.size() ||
2586 LSI->GLTemplateParameterList) ? LSI : nullptr;
2587 }
2588 return nullptr;
2589 }
2590
2591
2592 void Sema::ActOnComment(SourceRange Comment) {
2593 if (!LangOpts.RetainCommentsFromSystemHeaders &&
2594 SourceMgr.isInSystemHeader(Comment.getBegin()))
2595 return;
2596 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2597 if (RC.isAlmostTrailingComment() || RC.hasUnsupportedSplice(SourceMgr)) {
2598 SourceRange MagicMarkerRange(Comment.getBegin(),
2599 Comment.getBegin().getLocWithOffset(3));
2600 StringRef MagicMarkerText;
2601 switch (RC.getKind()) {
2602 case RawComment::RCK_OrdinaryBCPL:
2603 MagicMarkerText = "///<";
2604 break;
2605 case RawComment::RCK_OrdinaryC:
2606 MagicMarkerText = "/**<";
2607 break;
2608 case RawComment::RCK_Invalid:
2609 // FIXME: are there other scenarios that could produce an invalid
2610 // raw comment here?
2611 Diag(Comment.getBegin(), diag::warn_splice_in_doxygen_comment);
2612 return;
2613 default:
2614 llvm_unreachable("if this is an almost Doxygen comment, "
2615 "it should be ordinary");
2616 }
2617 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2618 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2619 }
2620 Context.addComment(RC);
2621 }
2622
2623 // Pin this vtable to this file.
2624 ExternalSemaSource::~ExternalSemaSource() {}
2625 char ExternalSemaSource::ID;
2626
2627 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
2628 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
2629
2630 void ExternalSemaSource::ReadKnownNamespaces(
2631 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
2632 }
2633
2634 void ExternalSemaSource::ReadUndefinedButUsed(
2635 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2636
2637 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
2638 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2639
2640 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2641 UnresolvedSetImpl &OverloadSet) {
2642 ZeroArgCallReturnTy = QualType();
2643 OverloadSet.clear();
2644
2645 const OverloadExpr *Overloads = nullptr;
2646 bool IsMemExpr = false;
2647 if (E.getType() == Context.OverloadTy) {
2648 OverloadExpr::FindResult FR = OverloadExpr::find(&E);
2649
2650 // Ignore overloads that are pointer-to-member constants.
2651 if (FR.HasFormOfMemberPointer)
2652 return false;
2653
2654 Overloads = FR.Expression;
2655 } else if (E.getType() == Context.BoundMemberTy) {
2656 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2657 IsMemExpr = true;
2658 }
2659
2660 bool Ambiguous = false;
2661 bool IsMV = false;
2662
2663 if (Overloads) {
2664 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2665 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
2666 OverloadSet.addDecl(*it);
2667
2668 // Check whether the function is a non-template, non-member which takes no
2669 // arguments.
2670 if (IsMemExpr)
2671 continue;
2672 if (const FunctionDecl *OverloadDecl
2673 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2674 if (OverloadDecl->getMinRequiredArguments() == 0) {
2675 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
2676 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2677 OverloadDecl->isCPUSpecificMultiVersion()))) {
2678 ZeroArgCallReturnTy = QualType();
2679 Ambiguous = true;
2680 } else {
2681 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2682 IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2683 OverloadDecl->isCPUSpecificMultiVersion();
2684 }
2685 }
2686 }
2687 }
2688
2689 // If it's not a member, use better machinery to try to resolve the call
2690 if (!IsMemExpr)
2691 return !ZeroArgCallReturnTy.isNull();
2692 }
2693
2694 // Attempt to call the member with no arguments - this will correctly handle
2695 // member templates with defaults/deduction of template arguments, overloads
2696 // with default arguments, etc.
2697 if (IsMemExpr && !E.isTypeDependent()) {
2698 Sema::TentativeAnalysisScope Trap(*this);
2699 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(), {},
2700 SourceLocation());
2701 if (R.isUsable()) {
2702 ZeroArgCallReturnTy = R.get()->getType();
2703 return true;
2704 }
2705 return false;
2706 }
2707
2708 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2709 if (const auto *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2710 if (Fun->getMinRequiredArguments() == 0)
2711 ZeroArgCallReturnTy = Fun->getReturnType();
2712 return true;
2713 }
2714 }
2715
2716 // We don't have an expression that's convenient to get a FunctionDecl from,
2717 // but we can at least check if the type is "function of 0 arguments".
2718 QualType ExprTy = E.getType();
2719 const FunctionType *FunTy = nullptr;
2720 QualType PointeeTy = ExprTy->getPointeeType();
2721 if (!PointeeTy.isNull())
2722 FunTy = PointeeTy->getAs<FunctionType>();
2723 if (!FunTy)
2724 FunTy = ExprTy->getAs<FunctionType>();
2725
2726 if (const auto *FPT = dyn_cast_if_present<FunctionProtoType>(FunTy)) {
2727 if (FPT->getNumParams() == 0)
2728 ZeroArgCallReturnTy = FunTy->getReturnType();
2729 return true;
2730 }
2731 return false;
2732 }
2733
2734 /// Give notes for a set of overloads.
2735 ///
2736 /// A companion to tryExprAsCall. In cases when the name that the programmer
2737 /// wrote was an overloaded function, we may be able to make some guesses about
2738 /// plausible overloads based on their return types; such guesses can be handed
2739 /// off to this method to be emitted as notes.
2740 ///
2741 /// \param Overloads - The overloads to note.
2742 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2743 /// -fshow-overloads=best, this is the location to attach to the note about too
2744 /// many candidates. Typically this will be the location of the original
2745 /// ill-formed expression.
2746 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2747 const SourceLocation FinalNoteLoc) {
2748 unsigned ShownOverloads = 0;
2749 unsigned SuppressedOverloads = 0;
2750 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2751 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2752 if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
2753 ++SuppressedOverloads;
2754 continue;
2755 }
2756
2757 const NamedDecl *Fn = (*It)->getUnderlyingDecl();
2758 // Don't print overloads for non-default multiversioned functions.
2759 if (const auto *FD = Fn->getAsFunction()) {
2760 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
2761 !FD->getAttr<TargetAttr>()->isDefaultVersion())
2762 continue;
2763 if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&
2764 !FD->getAttr<TargetVersionAttr>()->isDefaultVersion())
2765 continue;
2766 }
2767 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2768 ++ShownOverloads;
2769 }
2770
2771 S.Diags.overloadCandidatesShown(ShownOverloads);
2772
2773 if (SuppressedOverloads)
2774 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2775 << SuppressedOverloads;
2776 }
2777
2778 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
2779 const UnresolvedSetImpl &Overloads,
2780 bool (*IsPlausibleResult)(QualType)) {
2781 if (!IsPlausibleResult)
2782 return noteOverloads(S, Overloads, Loc);
2783
2784 UnresolvedSet<2> PlausibleOverloads;
2785 for (OverloadExpr::decls_iterator It = Overloads.begin(),
2786 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2787 const auto *OverloadDecl = cast<FunctionDecl>(*It);
2788 QualType OverloadResultTy = OverloadDecl->getReturnType();
2789 if (IsPlausibleResult(OverloadResultTy))
2790 PlausibleOverloads.addDecl(It.getDecl());
2791 }
2792 noteOverloads(S, PlausibleOverloads, Loc);
2793 }
2794
2795 /// Determine whether the given expression can be called by just
2796 /// putting parentheses after it. Notably, expressions with unary
2797 /// operators can't be because the unary operator will start parsing
2798 /// outside the call.
2799 static bool IsCallableWithAppend(const Expr *E) {
2800 E = E->IgnoreImplicit();
2801 return (!isa<CStyleCastExpr>(E) &&
2802 !isa<UnaryOperator>(E) &&
2803 !isa<BinaryOperator>(E) &&
2804 !isa<CXXOperatorCallExpr>(E));
2805 }
2806
2807 static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
2808 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2809 E = UO->getSubExpr();
2810
2811 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2812 if (ULE->getNumDecls() == 0)
2813 return false;
2814
2815 const NamedDecl *ND = *ULE->decls_begin();
2816 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2817 return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
2818 }
2819 return false;
2820 }
2821
2822 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2823 bool ForceComplain,
2824 bool (*IsPlausibleResult)(QualType)) {
2825 SourceLocation Loc = E.get()->getExprLoc();
2826 SourceRange Range = E.get()->getSourceRange();
2827 UnresolvedSet<4> Overloads;
2828
2829 // If this is a SFINAE context, don't try anything that might trigger ADL
2830 // prematurely.
2831 if (!isSFINAEContext()) {
2832 QualType ZeroArgCallTy;
2833 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2834 !ZeroArgCallTy.isNull() &&
2835 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
2836 // At this point, we know E is potentially callable with 0
2837 // arguments and that it returns something of a reasonable type,
2838 // so we can emit a fixit and carry on pretending that E was
2839 // actually a CallExpr.
2840 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2841 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2842 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2843 << (IsCallableWithAppend(E.get())
2844 ? FixItHint::CreateInsertion(ParenInsertionLoc,
2845 "()")
2846 : FixItHint());
2847 if (!IsMV)
2848 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2849
2850 // FIXME: Try this before emitting the fixit, and suppress diagnostics
2851 // while doing so.
2852 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), {},
2853 Range.getEnd().getLocWithOffset(1));
2854 return true;
2855 }
2856 }
2857 if (!ForceComplain) return false;
2858
2859 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2860 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2861 if (!IsMV)
2862 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2863 E = ExprError();
2864 return true;
2865 }
2866
2867 IdentifierInfo *Sema::getSuperIdentifier() const {
2868 if (!Ident_super)
2869 Ident_super = &Context.Idents.get("super");
2870 return Ident_super;
2871 }
2872
2873 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
2874 CapturedRegionKind K,
2875 unsigned OpenMPCaptureLevel) {
2876 auto *CSI = new CapturedRegionScopeInfo(
2877 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2878 (getLangOpts().OpenMP && K == CR_OpenMP)
2879 ? OpenMP().getOpenMPNestingLevel()
2880 : 0,
2881 OpenMPCaptureLevel);
2882 CSI->ReturnType = Context.VoidTy;
2883 FunctionScopes.push_back(CSI);
2884 CapturingFunctionScopes++;
2885 }
2886
2887 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
2888 if (FunctionScopes.empty())
2889 return nullptr;
2890
2891 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2892 }
2893
2894 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
2895 Sema::getMismatchingDeleteExpressions() const {
2896 return DeleteExprs;
2897 }
2898
2899 Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S)
2900 : S(S), OldFPFeaturesState(S.CurFPFeatures),
2901 OldOverrides(S.FpPragmaStack.CurrentValue),
2902 OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
2903 OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
2904
2905 Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {
2906 S.CurFPFeatures = OldFPFeaturesState;
2907 S.FpPragmaStack.CurrentValue = OldOverrides;
2908 S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
2909 }
2910
2911 bool Sema::isDeclaratorFunctionLike(Declarator &D) {
2912 assert(D.getCXXScopeSpec().isSet() &&
2913 "can only be called for qualified names");
2914
2915 auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
2916 LookupOrdinaryName, forRedeclarationInCurContext());
2917 DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(),
2918 !D.getDeclSpec().isFriendSpecified());
2919 if (!DC)
2920 return false;
2921
2922 LookupQualifiedName(LR, DC);
2923 bool Result = llvm::all_of(LR, [](Decl *Dcl) {
2924 if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
2925 ND = ND->getUnderlyingDecl();
2926 return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
2927 isa<UsingDecl>(ND);
2928 }
2929 return false;
2930 });
2931 return Result;
2932 }
2933
2934 Attr *Sema::CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
2935 MutableArrayRef<Expr *> Args) {
2936
2937 auto *A = AnnotateAttr::Create(Context, Annot, Args.data(), Args.size(), CI);
2938 if (!ConstantFoldAttrArgs(
2939 CI, MutableArrayRef<Expr *>(A->args_begin(), A->args_end()))) {
2940 return nullptr;
2941 }
2942 return A;
2943 }
2944
2945 Attr *Sema::CreateAnnotationAttr(const ParsedAttr &AL) {
2946 // Make sure that there is a string literal as the annotation's first
2947 // argument.
2948 StringRef Str;
2949 if (!checkStringLiteralArgumentAttr(AL, 0, Str))
2950 return nullptr;
2951
2952 llvm::SmallVector<Expr *, 4> Args;
2953 Args.reserve(AL.getNumArgs() - 1);
2954 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
2955 assert(!AL.isArgIdent(Idx));
2956 Args.push_back(AL.getArgAsExpr(Idx));
2957 }
2958
2959 return CreateAnnotationAttr(AL, Str, Args);
2960 }