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/DeclCXX.h"
18 #include "clang/AST/DeclFriend.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/PrettyDeclStackTrace.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/Basic/DiagnosticOptions.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/Stack.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/HeaderSearch.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DelayedDiagnostic.h"
33 #include "clang/Sema/ExternalSemaSource.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/MultiplexExternalSemaSource.h"
36 #include "clang/Sema/ObjCMethodList.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaConsumer.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "clang/Sema/TemplateDeduction.h"
42 #include "clang/Sema/TemplateInstCallback.h"
43 #include "clang/Sema/TypoCorrection.h"
44 #include "llvm/ADT/DenseMap.h"
45 #include "llvm/ADT/SmallSet.h"
46 #include "llvm/Support/TimeProfiler.h"
47
48 using namespace clang;
49 using namespace sema;
50
getLocForEndOfToken(SourceLocation Loc,unsigned Offset)51 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
52 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
53 }
54
getModuleLoader() const55 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
56
57 IdentifierInfo *
InventAbbreviatedTemplateParameterTypeName(IdentifierInfo * ParamName,unsigned int Index)58 Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
59 unsigned int Index) {
60 std::string InventedName;
61 llvm::raw_string_ostream OS(InventedName);
62
63 if (!ParamName)
64 OS << "auto:" << Index + 1;
65 else
66 OS << ParamName->getName() << ":auto";
67
68 OS.flush();
69 return &Context.Idents.get(OS.str());
70 }
71
getPrintingPolicy(const ASTContext & Context,const Preprocessor & PP)72 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
73 const Preprocessor &PP) {
74 PrintingPolicy Policy = Context.getPrintingPolicy();
75 // In diagnostics, we print _Bool as bool if the latter is defined as the
76 // former.
77 Policy.Bool = Context.getLangOpts().Bool;
78 if (!Policy.Bool) {
79 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
80 Policy.Bool = BoolMacro->isObjectLike() &&
81 BoolMacro->getNumTokens() == 1 &&
82 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
83 }
84 }
85
86 return Policy;
87 }
88
ActOnTranslationUnitScope(Scope * S)89 void Sema::ActOnTranslationUnitScope(Scope *S) {
90 TUScope = S;
91 PushDeclContext(S, Context.getTranslationUnitDecl());
92 }
93
94 namespace clang {
95 namespace sema {
96
97 class SemaPPCallbacks : public PPCallbacks {
98 Sema *S = nullptr;
99 llvm::SmallVector<SourceLocation, 8> IncludeStack;
100
101 public:
set(Sema & S)102 void set(Sema &S) { this->S = &S; }
103
reset()104 void reset() { S = nullptr; }
105
FileChanged(SourceLocation Loc,FileChangeReason Reason,SrcMgr::CharacteristicKind FileType,FileID PrevFID)106 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
107 SrcMgr::CharacteristicKind FileType,
108 FileID PrevFID) override {
109 if (!S)
110 return;
111 switch (Reason) {
112 case EnterFile: {
113 SourceManager &SM = S->getSourceManager();
114 SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
115 if (IncludeLoc.isValid()) {
116 if (llvm::timeTraceProfilerEnabled()) {
117 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
118 llvm::timeTraceProfilerBegin(
119 "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
120 }
121
122 IncludeStack.push_back(IncludeLoc);
123 S->DiagnoseNonDefaultPragmaPack(
124 Sema::PragmaPackDiagnoseKind::NonDefaultStateAtInclude, IncludeLoc);
125 }
126 break;
127 }
128 case ExitFile:
129 if (!IncludeStack.empty()) {
130 if (llvm::timeTraceProfilerEnabled())
131 llvm::timeTraceProfilerEnd();
132
133 S->DiagnoseNonDefaultPragmaPack(
134 Sema::PragmaPackDiagnoseKind::ChangedStateAtExit,
135 IncludeStack.pop_back_val());
136 }
137 break;
138 default:
139 break;
140 }
141 }
142 };
143
144 } // end namespace sema
145 } // end namespace clang
146
147 const unsigned Sema::MaxAlignmentExponent;
148 const unsigned Sema::MaximumAlignment;
149
Sema(Preprocessor & pp,ASTContext & ctxt,ASTConsumer & consumer,TranslationUnitKind TUKind,CodeCompleteConsumer * CodeCompleter)150 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
151 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
152 : ExternalSource(nullptr), isMultiplexExternalSource(false),
153 CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
154 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
155 SourceMgr(PP.getSourceManager()), CollectStats(false),
156 CodeCompleter(CodeCompleter), CurContext(nullptr),
157 OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
158 MSPointerToMemberRepresentationMethod(
159 LangOpts.getMSPointerToMemberRepresentationMethod()),
160 VtorDispStack(LangOpts.getVtorDispMode()), PackStack(0),
161 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
162 CodeSegStack(nullptr), FpPragmaStack(0xffffffff), CurInitSeg(nullptr),
163 VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),
164 IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
165 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
166 StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
167 StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
168 MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), NSValueDecl(nullptr),
169 NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
170 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
171 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
172 DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
173 TUKind(TUKind), NumSFINAEErrors(0),
174 FullyCheckedComparisonCategories(
175 static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
176 SatisfactionCache(Context), AccessCheckingSFINAE(false),
177 InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
178 ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
179 DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
180 ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
181 CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
182 TUScope = nullptr;
183 isConstantEvaluatedOverride = false;
184
185 LoadedExternalKnownNamespaces = false;
186 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
187 NSNumberLiteralMethods[I] = nullptr;
188
189 if (getLangOpts().ObjC)
190 NSAPIObj.reset(new NSAPI(Context));
191
192 if (getLangOpts().CPlusPlus)
193 FieldCollector.reset(new CXXFieldCollector());
194
195 // Tell diagnostics how to render things from the AST library.
196 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
197
198 ExprEvalContexts.emplace_back(
199 ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
200 nullptr, ExpressionEvaluationContextRecord::EK_Other);
201
202 // Initialization of data sharing attributes stack for OpenMP
203 InitDataSharingAttributesStack();
204
205 PointerInterpretation = Context.getDefaultPointerInterpretation();
206
207 std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
208 std::make_unique<sema::SemaPPCallbacks>();
209 SemaPPCallbackHandler = Callbacks.get();
210 PP.addPPCallbacks(std::move(Callbacks));
211 SemaPPCallbackHandler->set(*this);
212 }
213
214 // Anchor Sema's type info to this TU.
anchor()215 void Sema::anchor() {}
216
addImplicitTypedef(StringRef Name,QualType T)217 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
218 DeclarationName DN = &Context.Idents.get(Name);
219 if (IdResolver.begin(DN) == IdResolver.end())
220 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
221 }
222
Initialize()223 void Sema::Initialize() {
224 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
225 SC->InitializeSema(*this);
226
227 // Tell the external Sema source about this Sema object.
228 if (ExternalSemaSource *ExternalSema
229 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
230 ExternalSema->InitializeSema(*this);
231
232 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
233 // will not be able to merge any duplicate __va_list_tag decls correctly.
234 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
235
236 if (!TUScope)
237 return;
238
239 // Initialize predefined 128-bit integer types, if needed.
240 if (Context.getTargetInfo().hasInt128Type()) {
241 // If either of the 128-bit integer types are unavailable to name lookup,
242 // define them now.
243 DeclarationName Int128 = &Context.Idents.get("__int128_t");
244 if (IdResolver.begin(Int128) == IdResolver.end())
245 PushOnScopeChains(Context.getInt128Decl(), TUScope);
246
247 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
248 if (IdResolver.begin(UInt128) == IdResolver.end())
249 PushOnScopeChains(Context.getUInt128Decl(), TUScope);
250 }
251
252 // If the target supports capabilities, add capability-as-integer builtin
253 // types.
254 if (PP.getTargetInfo().SupportsCapabilities()) {
255 DeclarationName IntCap = &Context.Idents.get("__intcap_t");
256 if (IdResolver.begin(IntCap) == IdResolver.end())
257 PushOnScopeChains(Context.getIntCapDecl(), TUScope);
258
259 DeclarationName UIntCap = &Context.Idents.get("__uintcap_t");
260 if (IdResolver.begin(UIntCap) == IdResolver.end())
261 PushOnScopeChains(Context.getUIntCapDecl(), TUScope);
262 }
263
264
265 // Initialize predefined Objective-C types:
266 if (getLangOpts().ObjC) {
267 // If 'SEL' does not yet refer to any declarations, make it refer to the
268 // predefined 'SEL'.
269 DeclarationName SEL = &Context.Idents.get("SEL");
270 if (IdResolver.begin(SEL) == IdResolver.end())
271 PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
272
273 // If 'id' does not yet refer to any declarations, make it refer to the
274 // predefined 'id'.
275 DeclarationName Id = &Context.Idents.get("id");
276 if (IdResolver.begin(Id) == IdResolver.end())
277 PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
278
279 // Create the built-in typedef for 'Class'.
280 DeclarationName Class = &Context.Idents.get("Class");
281 if (IdResolver.begin(Class) == IdResolver.end())
282 PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
283
284 // Create the built-in forward declaratino for 'Protocol'.
285 DeclarationName Protocol = &Context.Idents.get("Protocol");
286 if (IdResolver.begin(Protocol) == IdResolver.end())
287 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
288 }
289
290 // Create the internal type for the *StringMakeConstantString builtins.
291 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
292 if (IdResolver.begin(ConstantString) == IdResolver.end())
293 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
294
295 // Initialize Microsoft "predefined C++ types".
296 if (getLangOpts().MSVCCompat) {
297 if (getLangOpts().CPlusPlus &&
298 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
299 PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
300 TUScope);
301
302 addImplicitTypedef("size_t", Context.getSizeType());
303 }
304
305 // Initialize predefined OpenCL types and supported extensions and (optional)
306 // core features.
307 if (getLangOpts().OpenCL) {
308 getOpenCLOptions().addSupport(
309 Context.getTargetInfo().getSupportedOpenCLOpts());
310 getOpenCLOptions().enableSupportedCore(getLangOpts());
311 addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
312 addImplicitTypedef("event_t", Context.OCLEventTy);
313 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) {
314 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
315 addImplicitTypedef("queue_t", Context.OCLQueueTy);
316 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
317 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
318 addImplicitTypedef("atomic_uint",
319 Context.getAtomicType(Context.UnsignedIntTy));
320 auto AtomicLongT = Context.getAtomicType(Context.LongTy);
321 addImplicitTypedef("atomic_long", AtomicLongT);
322 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
323 addImplicitTypedef("atomic_ulong", AtomicULongT);
324 addImplicitTypedef("atomic_float",
325 Context.getAtomicType(Context.FloatTy));
326 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
327 addImplicitTypedef("atomic_double", AtomicDoubleT);
328 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
329 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
330 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
331 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
332 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
333 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
334 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
335 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
336 addImplicitTypedef("atomic_size_t", AtomicSizeT);
337 auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
338 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
339
340 // OpenCL v2.0 s6.13.11.6:
341 // - The atomic_long and atomic_ulong types are supported if the
342 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
343 // extensions are supported.
344 // - The atomic_double type is only supported if double precision
345 // is supported and the cl_khr_int64_base_atomics and
346 // cl_khr_int64_extended_atomics extensions are supported.
347 // - If the device address space is 64-bits, the data types
348 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
349 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
350 // cl_khr_int64_extended_atomics extensions are supported.
351 std::vector<QualType> Atomic64BitTypes;
352 Atomic64BitTypes.push_back(AtomicLongT);
353 Atomic64BitTypes.push_back(AtomicULongT);
354 Atomic64BitTypes.push_back(AtomicDoubleT);
355 if (Context.getTypeSize(AtomicSizeT) == 64) {
356 Atomic64BitTypes.push_back(AtomicSizeT);
357 Atomic64BitTypes.push_back(AtomicIntPtrT);
358 Atomic64BitTypes.push_back(AtomicUIntPtrT);
359 Atomic64BitTypes.push_back(AtomicPtrDiffT);
360 }
361 for (auto &I : Atomic64BitTypes)
362 setOpenCLExtensionForType(I,
363 "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
364
365 setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
366 }
367
368 setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
369
370 #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
371 setOpenCLExtensionForType(Context.Id, Ext);
372 #include "clang/Basic/OpenCLImageTypes.def"
373 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
374 addImplicitTypedef(#ExtType, Context.Id##Ty); \
375 setOpenCLExtensionForType(Context.Id##Ty, #Ext);
376 #include "clang/Basic/OpenCLExtensionTypes.def"
377 }
378
379 if (Context.getTargetInfo().hasAArch64SVETypes()) {
380 #define SVE_TYPE(Name, Id, SingletonId) \
381 addImplicitTypedef(Name, Context.SingletonId);
382 #include "clang/Basic/AArch64SVEACLETypes.def"
383 }
384
385 if (Context.getTargetInfo().hasBuiltinMSVaList()) {
386 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
387 if (IdResolver.begin(MSVaList) == IdResolver.end())
388 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
389 }
390
391 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
392 if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
393 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
394 }
395
~Sema()396 Sema::~Sema() {
397 if (VisContext) FreeVisContext();
398
399 // Kill all the active scopes.
400 for (sema::FunctionScopeInfo *FSI : FunctionScopes)
401 delete FSI;
402
403 // Tell the SemaConsumer to forget about us; we're going out of scope.
404 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
405 SC->ForgetSema();
406
407 // Detach from the external Sema source.
408 if (ExternalSemaSource *ExternalSema
409 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
410 ExternalSema->ForgetSema();
411
412 // If Sema's ExternalSource is the multiplexer - we own it.
413 if (isMultiplexExternalSource)
414 delete ExternalSource;
415
416 // Delete cached satisfactions.
417 std::vector<ConstraintSatisfaction *> Satisfactions;
418 Satisfactions.reserve(Satisfactions.size());
419 for (auto &Node : SatisfactionCache)
420 Satisfactions.push_back(&Node);
421 for (auto *Node : Satisfactions)
422 delete Node;
423
424 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
425
426 // Destroys data sharing attributes stack for OpenMP
427 DestroyDataSharingAttributesStack();
428
429 // Detach from the PP callback handler which outlives Sema since it's owned
430 // by the preprocessor.
431 SemaPPCallbackHandler->reset();
432 }
433
warnStackExhausted(SourceLocation Loc)434 void Sema::warnStackExhausted(SourceLocation Loc) {
435 // Only warn about this once.
436 if (!WarnedStackExhausted) {
437 Diag(Loc, diag::warn_stack_exhausted);
438 WarnedStackExhausted = true;
439 }
440 }
441
runWithSufficientStackSpace(SourceLocation Loc,llvm::function_ref<void ()> Fn)442 void Sema::runWithSufficientStackSpace(SourceLocation Loc,
443 llvm::function_ref<void()> Fn) {
444 clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn);
445 }
446
447 /// makeUnavailableInSystemHeader - There is an error in the current
448 /// context. If we're still in a system header, and we can plausibly
449 /// make the relevant declaration unavailable instead of erroring, do
450 /// so and return true.
makeUnavailableInSystemHeader(SourceLocation loc,UnavailableAttr::ImplicitReason reason)451 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
452 UnavailableAttr::ImplicitReason reason) {
453 // If we're not in a function, it's an error.
454 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
455 if (!fn) return false;
456
457 // If we're in template instantiation, it's an error.
458 if (inTemplateInstantiation())
459 return false;
460
461 // If that function's not in a system header, it's an error.
462 if (!Context.getSourceManager().isInSystemHeader(loc))
463 return false;
464
465 // If the function is already unavailable, it's not an error.
466 if (fn->hasAttr<UnavailableAttr>()) return true;
467
468 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
469 return true;
470 }
471
getASTMutationListener() const472 ASTMutationListener *Sema::getASTMutationListener() const {
473 return getASTConsumer().GetASTMutationListener();
474 }
475
476 ///Registers an external source. If an external source already exists,
477 /// creates a multiplex external source and appends to it.
478 ///
479 ///\param[in] E - A non-null external sema source.
480 ///
addExternalSource(ExternalSemaSource * E)481 void Sema::addExternalSource(ExternalSemaSource *E) {
482 assert(E && "Cannot use with NULL ptr");
483
484 if (!ExternalSource) {
485 ExternalSource = E;
486 return;
487 }
488
489 if (isMultiplexExternalSource)
490 static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
491 else {
492 ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
493 isMultiplexExternalSource = true;
494 }
495 }
496
497 /// Print out statistics about the semantic analysis.
PrintStats() const498 void Sema::PrintStats() const {
499 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
500 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
501
502 BumpAlloc.PrintStats();
503 AnalysisWarnings.PrintStats();
504 }
505
diagnoseNullableToNonnullConversion(QualType DstType,QualType SrcType,SourceLocation Loc)506 void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
507 QualType SrcType,
508 SourceLocation Loc) {
509 Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
510 if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
511 return;
512
513 Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
514 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
515 return;
516
517 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
518 }
519
diagnoseZeroToNullptrConversion(CastKind Kind,const Expr * E)520 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
521 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
522 E->getBeginLoc()))
523 return;
524 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
525 if (!getLangOpts().CPlusPlus11)
526 return;
527
528 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
529 return;
530 if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
531 return;
532
533 // If it is a macro from system header, and if the macro name is not "NULL",
534 // do not warn.
535 SourceLocation MaybeMacroLoc = E->getBeginLoc();
536 if (Diags.getSuppressSystemWarnings() &&
537 SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
538 !findMacroSpelling(MaybeMacroLoc, "NULL"))
539 return;
540
541 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
542 << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
543 }
544
545 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
546 /// If there is already an implicit cast, merge into the existing one.
547 /// The result is of the given category.
ImpCastExprToType(Expr * E,QualType Ty,CastKind Kind,ExprValueKind VK,const CXXCastPath * BasePath,CheckedConversionKind CCK)548 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
549 CastKind Kind, ExprValueKind VK,
550 const CXXCastPath *BasePath,
551 CheckedConversionKind CCK) {
552 #ifndef NDEBUG
553 if (VK == VK_RValue && !E->isRValue()) {
554 switch (Kind) {
555 default:
556 llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
557 "kind");
558 case CK_Dependent:
559 case CK_LValueToRValue:
560 case CK_ArrayToPointerDecay:
561 case CK_FunctionToPointerDecay:
562 case CK_ToVoid:
563 case CK_NonAtomicToAtomic:
564 break;
565 }
566 }
567 assert((VK == VK_RValue || Kind == CK_Dependent || !E->isRValue()) &&
568 "can't cast rvalue to lvalue");
569 #endif
570
571 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
572 diagnoseZeroToNullptrConversion(Kind, E);
573
574 QualType ExprTy = Context.getCanonicalType(E->getType());
575 QualType TypeTy = Context.getCanonicalType(Ty);
576
577 if (ExprTy.getQualifiers().hasOutput() &&
578 !TypeTy.getQualifiers().hasOutput())
579 return ExprError(Diag(E->getExprLoc(), diag::err_typecheck_read_output)
580 << E->getSourceRange());
581
582 if (ExprTy == TypeTy)
583 return E;
584
585 // C++1z [conv.array]: The temporary materialization conversion is applied.
586 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
587 if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
588 E->getValueKind() == VK_RValue) {
589 // The temporary is an lvalue in C++98 and an xvalue otherwise.
590 ExprResult Materialized = CreateMaterializeTemporaryExpr(
591 E->getType(), E, !getLangOpts().CPlusPlus11);
592 if (Materialized.isInvalid())
593 return ExprError();
594 E = Materialized.get();
595 }
596
597 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
598 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
599 // We need to update the no-provenance check here since we are changing
600 // the type without calling ImplicitCastExpr::Create()
601 ImpCast->setType(Ty, Context, ImpCast->getSubExpr());
602 ImpCast->setValueKind(VK);
603 return E;
604 }
605 }
606
607 // Check for conversions between capabilities and integers.
608 // We only allow implicit casts from pointers to CHERI capabilities
609 // for the following cases:
610 //
611 // - String literal
612 // - Null literal
613 // - address-of (&) expressions and types are compatible
614 // - array/function to pointer decay and types are compatible
615 // Note: we skip this check for uintcap_t conversions, since those should
616 // be handled differently
617 ExprTy = E->getType();
618 auto ShouldCheckCastForCapConversion = [](CastKind CK) {
619 // We don't need to check for cap <-> non-cap conversions for the following
620 // cast kinds. For the decay this is required to avoid infinite recursion.
621 switch (CK) {
622 case CK_NullToPointer: // always valid
623 case CK_NullToMemberPointer: // always valid
624 case CK_FunctionToPointerDecay: // Checked in CastConsistency()
625 case CK_ArrayToPointerDecay: // Checked in CastConsistency()
626 case CK_BuiltinFnToFnPtr: // Checked in CastConsistency()
627 case CK_IntegralToPointer: // Checked later
628 return false;
629 default:
630 return true;
631 }
632 };
633 if (Ty->isPointerType() && ShouldCheckCastForCapConversion(Kind)) {
634 const bool FromIsCap =
635 ExprTy->isCHERICapabilityType(Context, /*IncludeIntCap=*/false);
636 const bool ResultIsCap =
637 TypeTy->isCHERICapabilityType(Context, /*IncludeIntCap=*/false);
638 Optional<unsigned> DiagID;
639 if (FromIsCap && !ResultIsCap && ExprTy->isPointerType()) {
640 // T* __capability -> T* is never allowed implicitly.
641 DiagID = diag::err_typecheck_convert_cap_to_ptr;
642 } else if (ResultIsCap && !FromIsCap) {
643 // ImpCastPointerToCHERICapability can create new implicit
644 // CK_FunctionToPointerDecay/CK_ArrayToPointerDecay so we need to avoid
645 // infinite recursion here
646 if (!ImpCastPointerToCHERICapability(ExprTy, TypeTy, E, true))
647 return ExprError(); // diagnostics already emitted
648 DiagID = None; // got a permitted explicit conversion
649 Kind = CK_PointerToCHERICapability; // update cast-kind for the new cast
650 }
651 if (DiagID) {
652 // Note: ImpCastPointerToCHERICapability may have changed E, so we must
653 // use E->getType() instead of ExprTy
654 auto Fixit = FixItHint::CreateInsertion(
655 E->getBeginLoc(), "(__cheri_" +
656 std::string(FromIsCap ? "from" : "to") +
657 "cap " + TypeTy.getAsString() + ")");
658 return ExprError(Diag(E->getBeginLoc(), *DiagID)
659 << E->getType() << TypeTy << false << Fixit);
660 }
661 }
662
663 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
664 }
665
ImpCastPointerToCHERICapability(QualType FromTy,QualType ToTy,Expr * & From,bool Diagnose)666 bool Sema::ImpCastPointerToCHERICapability(QualType FromTy, QualType ToTy,
667 Expr *&From, bool Diagnose) {
668 assert(ToTy->isPointerType() && "Target types should be PointerType");
669 assert(ToTy->getAs<PointerType>()->isCHERICapability() &&
670 "Target type must be a capability pointer");
671 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) {
672 return true; // NULL constants are always fine
673 }
674 // Don't perform any checking for dependent types
675 if (FromTy->isDependentType()) {
676 return true;
677 }
678 bool StrLit = dyn_cast<StringLiteral>(From->IgnoreImpCasts()) != nullptr;
679 bool AddrOf = false;
680 bool Decayed = false;
681
682 // Function-to-pointer and array-to-pointer decay
683 ExprResult DecayedExpr = DefaultFunctionArrayConversion(From, Diagnose);
684 if (DecayedExpr.isUsable() && !DecayedExpr.isInvalid()) {
685 From = DecayedExpr.get();
686 FromTy = From->getType();
687 }
688
689 auto ImplicitConversionFailure = [&](bool CompatTypes) {
690 if (Diagnose) {
691 // Converting to void* should always print the compatible types warning.
692 if (ToTy->isVoidPointerType())
693 CompatTypes = true;
694 Diag(From->getExprLoc(),
695 CompatTypes ? diag::err_typecheck_convert_ptr_to_cap
696 : diag::err_typecheck_convert_ptr_to_cap_unrelated_type)
697 << From->getType() << ToTy << false;
698 }
699 return false;
700 };
701
702 // FIXME: clean up control-flow in this function
703 if (!FromTy->isPointerType()) {
704 // Implicit casts can never be valid for non-pointer types
705 return ImplicitConversionFailure(/*CompatTypes=*/false);
706 }
707 if (getLangOpts().getCheriIntToCap() != LangOptions::CapInt_Relative) {
708 // All pointer -> capability conversions must be explicit unless we are
709 // compiling in "relative" mode.
710 bool CompatTypes = CheckCHERIAssignCompatible(ToTy, FromTy, From, false);
711 // Note: this check comes after the decay check to get char* instead of
712 // char (&)[N] in diagnostics messages for C++.
713 return ImplicitConversionFailure(CompatTypes);
714 }
715
716 bool CompatTypes = false;
717 if (ImplicitCastExpr *Imp = dyn_cast<ImplicitCastExpr>(From)) {
718 if (Imp->getCastKind() == CK_ArrayToPointerDecay
719 || Imp->getCastKind() == CK_FunctionToPointerDecay) {
720 Decayed = true;
721 CompatTypes = CheckCHERIAssignCompatible(ToTy, FromTy, From);
722 }
723 }
724
725 // address-of (&)
726 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From)) {
727 if (UnOp->getOpcode() == UO_AddrOf) {
728 AddrOf = true;
729 CompatTypes = CheckCHERIAssignCompatible(ToTy, FromTy, From);
730 }
731 }
732
733 // The type check for address-of (&) could have failed above but may
734 // still succeed below when we look at pointee types
735 if (!(StrLit || Decayed || (AddrOf && CompatTypes))) {
736 // Check if pointee types are assign compatible
737 QualType TPointee = ToTy->getAs<PointerType>()->getPointeeType();
738 QualType EPointee = FromTy->getAs<PointerType>()->getPointeeType();
739 if (CheckCHERIAssignCompatible(TPointee, EPointee, From, false)) {
740 if (Diagnose)
741 Diag(From->getExprLoc(), diag::warn_typecheck_convert_ptr_to_cap)
742 << From->getType() << ToTy
743 << FixItHint::CreateInsertion(From->getExprLoc(),
744 "(__cheri_tocap " +
745 ToTy.getAsString() + ")");
746 CompatTypes = true;
747 } else {
748 // Check for integer pointee types with differences only in sign
749 // (if they were exactly the same integer type then the above if-test
750 // would have succeeded)
751 if (TPointee->isIntegerType() && EPointee->isIntegerType()) {
752 if (TPointee->isSignedIntegerType())
753 TPointee = Context.getCorrespondingUnsignedType(TPointee);
754 if (EPointee->isSignedIntegerType())
755 EPointee = Context.getCorrespondingUnsignedType(EPointee);
756
757 if (TPointee == EPointee) {
758 // Output a warning, as unsigned types are the same but the only difference is sign
759 if (Diagnose)
760 Diag(From->getExprLoc(), diag::warn_typecheck_convert_ptr_to_cap_sign_difference) << FromTy << ToTy;
761 CompatTypes = true;
762 }
763 }
764 }
765 if (!(StrLit || Decayed || AddrOf || CompatTypes) || !CompatTypes) {
766 return ImplicitConversionFailure(CompatTypes);
767 }
768 }
769 return true;
770 }
771
772 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
773 /// to the conversion from scalar type ScalarTy to the Boolean type.
ScalarTypeToBooleanCastKind(QualType ScalarTy)774 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
775 switch (ScalarTy->getScalarTypeKind()) {
776 case Type::STK_Bool: return CK_NoOp;
777 case Type::STK_CPointer: return CK_PointerToBoolean;
778 case Type::STK_BlockPointer: return CK_PointerToBoolean;
779 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
780 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
781 case Type::STK_Integral: return CK_IntegralToBoolean;
782 case Type::STK_Floating: return CK_FloatingToBoolean;
783 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
784 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
785 case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
786 }
787 llvm_unreachable("unknown scalar type kind");
788 }
789
790 /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
ShouldRemoveFromUnused(Sema * SemaRef,const DeclaratorDecl * D)791 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
792 if (D->getMostRecentDecl()->isUsed())
793 return true;
794
795 if (D->isExternallyVisible())
796 return true;
797
798 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
799 // If this is a function template and none of its specializations is used,
800 // we should warn.
801 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
802 for (const auto *Spec : Template->specializations())
803 if (ShouldRemoveFromUnused(SemaRef, Spec))
804 return true;
805
806 // UnusedFileScopedDecls stores the first declaration.
807 // The declaration may have become definition so check again.
808 const FunctionDecl *DeclToCheck;
809 if (FD->hasBody(DeclToCheck))
810 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
811
812 // Later redecls may add new information resulting in not having to warn,
813 // so check again.
814 DeclToCheck = FD->getMostRecentDecl();
815 if (DeclToCheck != FD)
816 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
817 }
818
819 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
820 // If a variable usable in constant expressions is referenced,
821 // don't warn if it isn't used: if the value of a variable is required
822 // for the computation of a constant expression, it doesn't make sense to
823 // warn even if the variable isn't odr-used. (isReferenced doesn't
824 // precisely reflect that, but it's a decent approximation.)
825 if (VD->isReferenced() &&
826 VD->mightBeUsableInConstantExpressions(SemaRef->Context))
827 return true;
828
829 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
830 // If this is a variable template and none of its specializations is used,
831 // we should warn.
832 for (const auto *Spec : Template->specializations())
833 if (ShouldRemoveFromUnused(SemaRef, Spec))
834 return true;
835
836 // UnusedFileScopedDecls stores the first declaration.
837 // The declaration may have become definition so check again.
838 const VarDecl *DeclToCheck = VD->getDefinition();
839 if (DeclToCheck)
840 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
841
842 // Later redecls may add new information resulting in not having to warn,
843 // so check again.
844 DeclToCheck = VD->getMostRecentDecl();
845 if (DeclToCheck != VD)
846 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
847 }
848
849 return false;
850 }
851
isFunctionOrVarDeclExternC(NamedDecl * ND)852 static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
853 if (auto *FD = dyn_cast<FunctionDecl>(ND))
854 return FD->isExternC();
855 return cast<VarDecl>(ND)->isExternC();
856 }
857
858 /// Determine whether ND is an external-linkage function or variable whose
859 /// type has no linkage.
isExternalWithNoLinkageType(ValueDecl * VD)860 bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
861 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
862 // because we also want to catch the case where its type has VisibleNoLinkage,
863 // which does not affect the linkage of VD.
864 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
865 !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
866 !isFunctionOrVarDeclExternC(VD);
867 }
868
869 /// Obtains a sorted list of functions and variables that are undefined but
870 /// ODR-used.
getUndefinedButUsed(SmallVectorImpl<std::pair<NamedDecl *,SourceLocation>> & Undefined)871 void Sema::getUndefinedButUsed(
872 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
873 for (const auto &UndefinedUse : UndefinedButUsed) {
874 NamedDecl *ND = UndefinedUse.first;
875
876 // Ignore attributes that have become invalid.
877 if (ND->isInvalidDecl()) continue;
878
879 // __attribute__((weakref)) is basically a definition.
880 if (ND->hasAttr<WeakRefAttr>()) continue;
881
882 if (isa<CXXDeductionGuideDecl>(ND))
883 continue;
884
885 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
886 // An exported function will always be emitted when defined, so even if
887 // the function is inline, it doesn't have to be emitted in this TU. An
888 // imported function implies that it has been exported somewhere else.
889 continue;
890 }
891
892 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
893 if (FD->isDefined())
894 continue;
895 if (FD->isExternallyVisible() &&
896 !isExternalWithNoLinkageType(FD) &&
897 !FD->getMostRecentDecl()->isInlined() &&
898 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
899 continue;
900 if (FD->getBuiltinID())
901 continue;
902 } else {
903 auto *VD = cast<VarDecl>(ND);
904 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
905 continue;
906 if (VD->isExternallyVisible() &&
907 !isExternalWithNoLinkageType(VD) &&
908 !VD->getMostRecentDecl()->isInline() &&
909 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
910 continue;
911
912 // Skip VarDecls that lack formal definitions but which we know are in
913 // fact defined somewhere.
914 if (VD->isKnownToBeDefined())
915 continue;
916 }
917
918 Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
919 }
920 }
921
922 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
923 /// or that are inline.
checkUndefinedButUsed(Sema & S)924 static void checkUndefinedButUsed(Sema &S) {
925 if (S.UndefinedButUsed.empty()) return;
926
927 // Collect all the still-undefined entities with internal linkage.
928 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
929 S.getUndefinedButUsed(Undefined);
930 if (Undefined.empty()) return;
931
932 for (auto Undef : Undefined) {
933 ValueDecl *VD = cast<ValueDecl>(Undef.first);
934 SourceLocation UseLoc = Undef.second;
935
936 if (S.isExternalWithNoLinkageType(VD)) {
937 // C++ [basic.link]p8:
938 // A type without linkage shall not be used as the type of a variable
939 // or function with external linkage unless
940 // -- the entity has C language linkage
941 // -- the entity is not odr-used or is defined in the same TU
942 //
943 // As an extension, accept this in cases where the type is externally
944 // visible, since the function or variable actually can be defined in
945 // another translation unit in that case.
946 S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
947 ? diag::ext_undefined_internal_type
948 : diag::err_undefined_internal_type)
949 << isa<VarDecl>(VD) << VD;
950 } else if (!VD->isExternallyVisible()) {
951 // FIXME: We can promote this to an error. The function or variable can't
952 // be defined anywhere else, so the program must necessarily violate the
953 // one definition rule.
954 S.Diag(VD->getLocation(), diag::warn_undefined_internal)
955 << isa<VarDecl>(VD) << VD;
956 } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
957 (void)FD;
958 assert(FD->getMostRecentDecl()->isInlined() &&
959 "used object requires definition but isn't inline or internal?");
960 // FIXME: This is ill-formed; we should reject.
961 S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
962 } else {
963 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
964 "used var requires definition but isn't inline or internal?");
965 S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
966 }
967 if (UseLoc.isValid())
968 S.Diag(UseLoc, diag::note_used_here);
969 }
970
971 S.UndefinedButUsed.clear();
972 }
973
LoadExternalWeakUndeclaredIdentifiers()974 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
975 if (!ExternalSource)
976 return;
977
978 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
979 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
980 for (auto &WeakID : WeakIDs)
981 WeakUndeclaredIdentifiers.insert(WeakID);
982 }
983
984
985 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
986
987 /// Returns true, if all methods and nested classes of the given
988 /// CXXRecordDecl are defined in this translation unit.
989 ///
990 /// Should only be called from ActOnEndOfTranslationUnit so that all
991 /// definitions are actually read.
MethodsAndNestedClassesComplete(const CXXRecordDecl * RD,RecordCompleteMap & MNCComplete)992 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
993 RecordCompleteMap &MNCComplete) {
994 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
995 if (Cache != MNCComplete.end())
996 return Cache->second;
997 if (!RD->isCompleteDefinition())
998 return false;
999 bool Complete = true;
1000 for (DeclContext::decl_iterator I = RD->decls_begin(),
1001 E = RD->decls_end();
1002 I != E && Complete; ++I) {
1003 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
1004 Complete = M->isDefined() || M->isDefaulted() ||
1005 (M->isPure() && !isa<CXXDestructorDecl>(M));
1006 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
1007 // If the template function is marked as late template parsed at this
1008 // point, it has not been instantiated and therefore we have not
1009 // performed semantic analysis on it yet, so we cannot know if the type
1010 // can be considered complete.
1011 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
1012 F->getTemplatedDecl()->isDefined();
1013 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
1014 if (R->isInjectedClassName())
1015 continue;
1016 if (R->hasDefinition())
1017 Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
1018 MNCComplete);
1019 else
1020 Complete = false;
1021 }
1022 }
1023 MNCComplete[RD] = Complete;
1024 return Complete;
1025 }
1026
1027 /// Returns true, if the given CXXRecordDecl is fully defined in this
1028 /// translation unit, i.e. all methods are defined or pure virtual and all
1029 /// friends, friend functions and nested classes are fully defined in this
1030 /// translation unit.
1031 ///
1032 /// Should only be called from ActOnEndOfTranslationUnit so that all
1033 /// definitions are actually read.
IsRecordFullyDefined(const CXXRecordDecl * RD,RecordCompleteMap & RecordsComplete,RecordCompleteMap & MNCComplete)1034 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
1035 RecordCompleteMap &RecordsComplete,
1036 RecordCompleteMap &MNCComplete) {
1037 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
1038 if (Cache != RecordsComplete.end())
1039 return Cache->second;
1040 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
1041 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
1042 E = RD->friend_end();
1043 I != E && Complete; ++I) {
1044 // Check if friend classes and methods are complete.
1045 if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
1046 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
1047 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
1048 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
1049 else
1050 Complete = false;
1051 } else {
1052 // Friend functions are available through the NamedDecl of FriendDecl.
1053 if (const FunctionDecl *FD =
1054 dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
1055 Complete = FD->isDefined();
1056 else
1057 // This is a template friend, give up.
1058 Complete = false;
1059 }
1060 }
1061 RecordsComplete[RD] = Complete;
1062 return Complete;
1063 }
1064
emitAndClearUnusedLocalTypedefWarnings()1065 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
1066 if (ExternalSource)
1067 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1068 UnusedLocalTypedefNameCandidates);
1069 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
1070 if (TD->isReferenced())
1071 continue;
1072 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1073 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1074 }
1075 UnusedLocalTypedefNameCandidates.clear();
1076 }
1077
1078 /// This is called before the very first declaration in the translation unit
1079 /// is parsed. Note that the ASTContext may have already injected some
1080 /// declarations.
ActOnStartOfTranslationUnit()1081 void Sema::ActOnStartOfTranslationUnit() {
1082 if (getLangOpts().ModulesTS &&
1083 (getLangOpts().getCompilingModule() == LangOptions::CMK_ModuleInterface ||
1084 getLangOpts().getCompilingModule() == LangOptions::CMK_None)) {
1085 // We start in an implied global module fragment.
1086 SourceLocation StartOfTU =
1087 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1088 ActOnGlobalModuleFragmentDecl(StartOfTU);
1089 ModuleScopes.back().ImplicitGlobalModuleFragment = true;
1090 }
1091 }
1092
ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)1093 void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
1094 // No explicit actions are required at the end of the global module fragment.
1095 if (Kind == TUFragmentKind::Global)
1096 return;
1097
1098 // Transfer late parsed template instantiations over to the pending template
1099 // instantiation list. During normal compilation, the late template parser
1100 // will be installed and instantiating these templates will succeed.
1101 //
1102 // If we are building a TU prefix for serialization, it is also safe to
1103 // transfer these over, even though they are not parsed. The end of the TU
1104 // should be outside of any eager template instantiation scope, so when this
1105 // AST is deserialized, these templates will not be parsed until the end of
1106 // the combined TU.
1107 PendingInstantiations.insert(PendingInstantiations.end(),
1108 LateParsedInstantiations.begin(),
1109 LateParsedInstantiations.end());
1110 LateParsedInstantiations.clear();
1111
1112 // If DefinedUsedVTables ends up marking any virtual member functions it
1113 // might lead to more pending template instantiations, which we then need
1114 // to instantiate.
1115 DefineUsedVTables();
1116
1117 // C++: Perform implicit template instantiations.
1118 //
1119 // FIXME: When we perform these implicit instantiations, we do not
1120 // carefully keep track of the point of instantiation (C++ [temp.point]).
1121 // This means that name lookup that occurs within the template
1122 // instantiation will always happen at the end of the translation unit,
1123 // so it will find some names that are not required to be found. This is
1124 // valid, but we could do better by diagnosing if an instantiation uses a
1125 // name that was not visible at its first point of instantiation.
1126 if (ExternalSource) {
1127 // Load pending instantiations from the external source.
1128 SmallVector<PendingImplicitInstantiation, 4> Pending;
1129 ExternalSource->ReadPendingInstantiations(Pending);
1130 for (auto PII : Pending)
1131 if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1132 Func->setInstantiationIsPending(true);
1133 PendingInstantiations.insert(PendingInstantiations.begin(),
1134 Pending.begin(), Pending.end());
1135 }
1136
1137 {
1138 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1139 PerformPendingInstantiations();
1140 }
1141
1142 emitDeferredDiags();
1143
1144 assert(LateParsedInstantiations.empty() &&
1145 "end of TU template instantiation should not create more "
1146 "late-parsed templates");
1147
1148 // Report diagnostics for uncorrected delayed typos. Ideally all of them
1149 // should have been corrected by that time, but it is very hard to cover all
1150 // cases in practice.
1151 for (const auto &Typo : DelayedTypos) {
1152 // We pass an empty TypoCorrection to indicate no correction was performed.
1153 Typo.second.DiagHandler(TypoCorrection());
1154 }
1155 DelayedTypos.clear();
1156 }
1157
1158 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1159 /// translation unit when EOF is reached and all but the top-level scope is
1160 /// popped.
ActOnEndOfTranslationUnit()1161 void Sema::ActOnEndOfTranslationUnit() {
1162 assert(DelayedDiagnostics.getCurrentPool() == nullptr
1163 && "reached end of translation unit with a pool attached?");
1164
1165 // If code completion is enabled, don't perform any end-of-translation-unit
1166 // work.
1167 if (PP.isCodeCompletionEnabled())
1168 return;
1169
1170 // Complete translation units and modules define vtables and perform implicit
1171 // instantiations. PCH files do not.
1172 if (TUKind != TU_Prefix) {
1173 DiagnoseUseOfUnimplementedSelectors();
1174
1175 ActOnEndOfTranslationUnitFragment(
1176 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1177 Module::PrivateModuleFragment
1178 ? TUFragmentKind::Private
1179 : TUFragmentKind::Normal);
1180
1181 if (LateTemplateParserCleanup)
1182 LateTemplateParserCleanup(OpaqueParser);
1183
1184 CheckDelayedMemberExceptionSpecs();
1185 } else {
1186 // If we are building a TU prefix for serialization, it is safe to transfer
1187 // these over, even though they are not parsed. The end of the TU should be
1188 // outside of any eager template instantiation scope, so when this AST is
1189 // deserialized, these templates will not be parsed until the end of the
1190 // combined TU.
1191 PendingInstantiations.insert(PendingInstantiations.end(),
1192 LateParsedInstantiations.begin(),
1193 LateParsedInstantiations.end());
1194 LateParsedInstantiations.clear();
1195
1196 if (LangOpts.PCHInstantiateTemplates) {
1197 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1198 PerformPendingInstantiations();
1199 }
1200 }
1201
1202 DiagnoseUnterminatedPragmaPack();
1203 DiagnoseUnterminatedPragmaAttribute();
1204
1205 // All delayed member exception specs should be checked or we end up accepting
1206 // incompatible declarations.
1207 assert(DelayedOverridingExceptionSpecChecks.empty());
1208 assert(DelayedEquivalentExceptionSpecChecks.empty());
1209
1210 // All dllexport classes should have been processed already.
1211 assert(DelayedDllExportClasses.empty());
1212 assert(DelayedDllExportMemberFunctions.empty());
1213
1214 // Remove file scoped decls that turned out to be used.
1215 UnusedFileScopedDecls.erase(
1216 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1217 UnusedFileScopedDecls.end(),
1218 [this](const DeclaratorDecl *DD) {
1219 return ShouldRemoveFromUnused(this, DD);
1220 }),
1221 UnusedFileScopedDecls.end());
1222
1223 if (TUKind == TU_Prefix) {
1224 // Translation unit prefixes don't need any of the checking below.
1225 if (!PP.isIncrementalProcessingEnabled())
1226 TUScope = nullptr;
1227 return;
1228 }
1229
1230 // Check for #pragma weak identifiers that were never declared
1231 LoadExternalWeakUndeclaredIdentifiers();
1232 for (auto WeakID : WeakUndeclaredIdentifiers) {
1233 if (WeakID.second.getUsed())
1234 continue;
1235
1236 Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
1237 LookupOrdinaryName);
1238 if (PrevDecl != nullptr &&
1239 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1240 Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
1241 << "'weak'" << ExpectedVariableOrFunction;
1242 else
1243 Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
1244 << WeakID.first;
1245 }
1246
1247 if (LangOpts.CPlusPlus11 &&
1248 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
1249 CheckDelegatingCtorCycles();
1250
1251 if (!Diags.hasErrorOccurred()) {
1252 if (ExternalSource)
1253 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1254 checkUndefinedButUsed(*this);
1255 }
1256
1257 // A global-module-fragment is only permitted within a module unit.
1258 bool DiagnosedMissingModuleDeclaration = false;
1259 if (!ModuleScopes.empty() &&
1260 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment &&
1261 !ModuleScopes.back().ImplicitGlobalModuleFragment) {
1262 Diag(ModuleScopes.back().BeginLoc,
1263 diag::err_module_declaration_missing_after_global_module_introducer);
1264 DiagnosedMissingModuleDeclaration = true;
1265 }
1266
1267 if (TUKind == TU_Module) {
1268 // If we are building a module interface unit, we need to have seen the
1269 // module declaration by now.
1270 if (getLangOpts().getCompilingModule() ==
1271 LangOptions::CMK_ModuleInterface &&
1272 (ModuleScopes.empty() ||
1273 !ModuleScopes.back().Module->isModulePurview()) &&
1274 !DiagnosedMissingModuleDeclaration) {
1275 // FIXME: Make a better guess as to where to put the module declaration.
1276 Diag(getSourceManager().getLocForStartOfFile(
1277 getSourceManager().getMainFileID()),
1278 diag::err_module_declaration_missing);
1279 }
1280
1281 // If we are building a module, resolve all of the exported declarations
1282 // now.
1283 if (Module *CurrentModule = PP.getCurrentModule()) {
1284 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1285
1286 SmallVector<Module *, 2> Stack;
1287 Stack.push_back(CurrentModule);
1288 while (!Stack.empty()) {
1289 Module *Mod = Stack.pop_back_val();
1290
1291 // Resolve the exported declarations and conflicts.
1292 // FIXME: Actually complain, once we figure out how to teach the
1293 // diagnostic client to deal with complaints in the module map at this
1294 // point.
1295 ModMap.resolveExports(Mod, /*Complain=*/false);
1296 ModMap.resolveUses(Mod, /*Complain=*/false);
1297 ModMap.resolveConflicts(Mod, /*Complain=*/false);
1298
1299 // Queue the submodules, so their exports will also be resolved.
1300 Stack.append(Mod->submodule_begin(), Mod->submodule_end());
1301 }
1302 }
1303
1304 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1305 // modules when they are built, not every time they are used.
1306 emitAndClearUnusedLocalTypedefWarnings();
1307 }
1308
1309 // C99 6.9.2p2:
1310 // A declaration of an identifier for an object that has file
1311 // scope without an initializer, and without a storage-class
1312 // specifier or with the storage-class specifier static,
1313 // constitutes a tentative definition. If a translation unit
1314 // contains one or more tentative definitions for an identifier,
1315 // and the translation unit contains no external definition for
1316 // that identifier, then the behavior is exactly as if the
1317 // translation unit contains a file scope declaration of that
1318 // identifier, with the composite type as of the end of the
1319 // translation unit, with an initializer equal to 0.
1320 llvm::SmallSet<VarDecl *, 32> Seen;
1321 for (TentativeDefinitionsType::iterator
1322 T = TentativeDefinitions.begin(ExternalSource),
1323 TEnd = TentativeDefinitions.end();
1324 T != TEnd; ++T) {
1325 VarDecl *VD = (*T)->getActingDefinition();
1326
1327 // If the tentative definition was completed, getActingDefinition() returns
1328 // null. If we've already seen this variable before, insert()'s second
1329 // return value is false.
1330 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
1331 continue;
1332
1333 if (const IncompleteArrayType *ArrayT
1334 = Context.getAsIncompleteArrayType(VD->getType())) {
1335 // Set the length of the array to 1 (C99 6.9.2p5).
1336 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1337 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1338 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One,
1339 nullptr, ArrayType::Normal, 0);
1340 VD->setType(T);
1341 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1342 diag::err_tentative_def_incomplete_type))
1343 VD->setInvalidDecl();
1344
1345 // No initialization is performed for a tentative definition.
1346 CheckCompleteVariableDeclaration(VD);
1347
1348 // Notify the consumer that we've completed a tentative definition.
1349 if (!VD->isInvalidDecl())
1350 Consumer.CompleteTentativeDefinition(VD);
1351 }
1352
1353 for (auto D : ExternalDeclarations) {
1354 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1355 continue;
1356
1357 Consumer.CompleteExternalDeclaration(D);
1358 }
1359
1360 // If there were errors, disable 'unused' warnings since they will mostly be
1361 // noise. Don't warn for a use from a module: either we should warn on all
1362 // file-scope declarations in modules or not at all, but whether the
1363 // declaration is used is immaterial.
1364 if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
1365 // Output warning for unused file scoped decls.
1366 for (UnusedFileScopedDeclsType::iterator
1367 I = UnusedFileScopedDecls.begin(ExternalSource),
1368 E = UnusedFileScopedDecls.end(); I != E; ++I) {
1369 if (ShouldRemoveFromUnused(this, *I))
1370 continue;
1371
1372 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1373 const FunctionDecl *DiagD;
1374 if (!FD->hasBody(DiagD))
1375 DiagD = FD;
1376 if (DiagD->isDeleted())
1377 continue; // Deleted functions are supposed to be unused.
1378 if (DiagD->isReferenced()) {
1379 if (isa<CXXMethodDecl>(DiagD))
1380 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1381 << DiagD->getDeclName();
1382 else {
1383 if (FD->getStorageClass() == SC_Static &&
1384 !FD->isInlineSpecified() &&
1385 !SourceMgr.isInMainFile(
1386 SourceMgr.getExpansionLoc(FD->getLocation())))
1387 Diag(DiagD->getLocation(),
1388 diag::warn_unneeded_static_internal_decl)
1389 << DiagD->getDeclName();
1390 else
1391 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1392 << /*function*/0 << DiagD->getDeclName();
1393 }
1394 } else {
1395 if (FD->getDescribedFunctionTemplate())
1396 Diag(DiagD->getLocation(), diag::warn_unused_template)
1397 << /*function*/0 << DiagD->getDeclName();
1398 else
1399 Diag(DiagD->getLocation(),
1400 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
1401 : diag::warn_unused_function)
1402 << DiagD->getDeclName();
1403 }
1404 } else {
1405 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1406 if (!DiagD)
1407 DiagD = cast<VarDecl>(*I);
1408 if (DiagD->isReferenced()) {
1409 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1410 << /*variable*/1 << DiagD->getDeclName();
1411 } else if (DiagD->getType().isConstQualified()) {
1412 const SourceManager &SM = SourceMgr;
1413 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1414 !PP.getLangOpts().IsHeaderFile)
1415 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1416 << DiagD->getDeclName();
1417 } else {
1418 if (DiagD->getDescribedVarTemplate())
1419 Diag(DiagD->getLocation(), diag::warn_unused_template)
1420 << /*variable*/1 << DiagD->getDeclName();
1421 else
1422 Diag(DiagD->getLocation(), diag::warn_unused_variable)
1423 << DiagD->getDeclName();
1424 }
1425 }
1426 }
1427
1428 emitAndClearUnusedLocalTypedefWarnings();
1429 }
1430
1431 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1432 // FIXME: Load additional unused private field candidates from the external
1433 // source.
1434 RecordCompleteMap RecordsComplete;
1435 RecordCompleteMap MNCComplete;
1436 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
1437 E = UnusedPrivateFields.end(); I != E; ++I) {
1438 const NamedDecl *D = *I;
1439 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1440 if (RD && !RD->isUnion() &&
1441 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1442 Diag(D->getLocation(), diag::warn_unused_private_field)
1443 << D->getDeclName();
1444 }
1445 }
1446 }
1447
1448 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1449 if (ExternalSource)
1450 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1451 for (const auto &DeletedFieldInfo : DeleteExprs) {
1452 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1453 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1454 DeleteExprLoc.second);
1455 }
1456 }
1457 }
1458
1459 // Check we've noticed that we're no longer parsing the initializer for every
1460 // variable. If we miss cases, then at best we have a performance issue and
1461 // at worst a rejects-valid bug.
1462 assert(ParsingInitForAutoVars.empty() &&
1463 "Didn't unmark var as having its initializer parsed");
1464
1465 if (!PP.isIncrementalProcessingEnabled())
1466 TUScope = nullptr;
1467 }
1468
1469
1470 //===----------------------------------------------------------------------===//
1471 // Helper functions.
1472 //===----------------------------------------------------------------------===//
1473
getFunctionLevelDeclContext()1474 DeclContext *Sema::getFunctionLevelDeclContext() {
1475 DeclContext *DC = CurContext;
1476
1477 while (true) {
1478 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
1479 isa<RequiresExprBodyDecl>(DC)) {
1480 DC = DC->getParent();
1481 } else if (isa<CXXMethodDecl>(DC) &&
1482 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1483 cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1484 DC = DC->getParent()->getParent();
1485 }
1486 else break;
1487 }
1488
1489 return DC;
1490 }
1491
1492 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1493 /// to the function decl for the function being parsed. If we're currently
1494 /// in a 'block', this returns the containing context.
getCurFunctionDecl()1495 FunctionDecl *Sema::getCurFunctionDecl() {
1496 DeclContext *DC = getFunctionLevelDeclContext();
1497 return dyn_cast<FunctionDecl>(DC);
1498 }
1499
getCurMethodDecl()1500 ObjCMethodDecl *Sema::getCurMethodDecl() {
1501 DeclContext *DC = getFunctionLevelDeclContext();
1502 while (isa<RecordDecl>(DC))
1503 DC = DC->getParent();
1504 return dyn_cast<ObjCMethodDecl>(DC);
1505 }
1506
getCurFunctionOrMethodDecl()1507 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
1508 DeclContext *DC = getFunctionLevelDeclContext();
1509 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1510 return cast<NamedDecl>(DC);
1511 return nullptr;
1512 }
1513
getDefaultCXXMethodAddrSpace() const1514 LangAS Sema::getDefaultCXXMethodAddrSpace() const {
1515 if (getLangOpts().OpenCL)
1516 return LangAS::opencl_generic;
1517 return LangAS::Default;
1518 }
1519
EmitCurrentDiagnostic(unsigned DiagID)1520 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1521 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1522 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1523 // been made more painfully obvious by the refactor that introduced this
1524 // function, but it is possible that the incoming argument can be
1525 // eliminated. If it truly cannot be (for example, there is some reentrancy
1526 // issue I am not seeing yet), then there should at least be a clarifying
1527 // comment somewhere.
1528 if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
1529 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1530 Diags.getCurrentDiagID())) {
1531 case DiagnosticIDs::SFINAE_Report:
1532 // We'll report the diagnostic below.
1533 break;
1534
1535 case DiagnosticIDs::SFINAE_SubstitutionFailure:
1536 // Count this failure so that we know that template argument deduction
1537 // has failed.
1538 ++NumSFINAEErrors;
1539
1540 // Make a copy of this suppressed diagnostic and store it with the
1541 // template-deduction information.
1542 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1543 Diagnostic DiagInfo(&Diags);
1544 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1545 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1546 }
1547
1548 Diags.setLastDiagnosticIgnored(true);
1549 Diags.Clear();
1550 return;
1551
1552 case DiagnosticIDs::SFINAE_AccessControl: {
1553 // Per C++ Core Issue 1170, access control is part of SFINAE.
1554 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1555 // make access control a part of SFINAE for the purposes of checking
1556 // type traits.
1557 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
1558 break;
1559
1560 SourceLocation Loc = Diags.getCurrentDiagLoc();
1561
1562 // Suppress this diagnostic.
1563 ++NumSFINAEErrors;
1564
1565 // Make a copy of this suppressed diagnostic and store it with the
1566 // template-deduction information.
1567 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1568 Diagnostic DiagInfo(&Diags);
1569 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1570 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1571 }
1572
1573 Diags.setLastDiagnosticIgnored(true);
1574 Diags.Clear();
1575
1576 // Now the diagnostic state is clear, produce a C++98 compatibility
1577 // warning.
1578 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1579
1580 // The last diagnostic which Sema produced was ignored. Suppress any
1581 // notes attached to it.
1582 Diags.setLastDiagnosticIgnored(true);
1583 return;
1584 }
1585
1586 case DiagnosticIDs::SFINAE_Suppress:
1587 // Make a copy of this suppressed diagnostic and store it with the
1588 // template-deduction information;
1589 if (*Info) {
1590 Diagnostic DiagInfo(&Diags);
1591 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1592 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1593 }
1594
1595 // Suppress this diagnostic.
1596 Diags.setLastDiagnosticIgnored(true);
1597 Diags.Clear();
1598 return;
1599 }
1600 }
1601
1602 // Copy the diagnostic printing policy over the ASTContext printing policy.
1603 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
1604 Context.setPrintingPolicy(getPrintingPolicy());
1605
1606 // Emit the diagnostic.
1607 if (!Diags.EmitCurrentDiagnostic())
1608 return;
1609
1610 // If this is not a note, and we're in a template instantiation
1611 // that is different from the last template instantiation where
1612 // we emitted an error, print a template instantiation
1613 // backtrace.
1614 if (!DiagnosticIDs::isBuiltinNote(DiagID))
1615 PrintContextStack();
1616 }
1617
1618 Sema::SemaDiagnosticBuilder
Diag(SourceLocation Loc,const PartialDiagnostic & PD)1619 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
1620 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
1621 PD.Emit(Builder);
1622
1623 return Builder;
1624 }
1625
1626 // Print notes showing how we can reach FD starting from an a priori
1627 // known-callable function.
emitCallStackNotes(Sema & S,FunctionDecl * FD)1628 static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
1629 auto FnIt = S.DeviceKnownEmittedFns.find(FD);
1630 while (FnIt != S.DeviceKnownEmittedFns.end()) {
1631 // Respect error limit.
1632 if (S.Diags.hasFatalErrorOccurred())
1633 return;
1634 DiagnosticBuilder Builder(
1635 S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1636 Builder << FnIt->second.FD;
1637 FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
1638 }
1639 }
1640
1641 namespace {
1642
1643 /// Helper class that emits deferred diagnostic messages if an entity directly
1644 /// or indirectly using the function that causes the deferred diagnostic
1645 /// messages is known to be emitted.
1646 ///
1647 /// During parsing of AST, certain diagnostic messages are recorded as deferred
1648 /// diagnostics since it is unknown whether the functions containing such
1649 /// diagnostics will be emitted. A list of potentially emitted functions and
1650 /// variables that may potentially trigger emission of functions are also
1651 /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1652 /// by each function to emit deferred diagnostics.
1653 ///
1654 /// During the visit, certain OpenMP directives or initializer of variables
1655 /// with certain OpenMP attributes will cause subsequent visiting of any
1656 /// functions enter a state which is called OpenMP device context in this
1657 /// implementation. The state is exited when the directive or initializer is
1658 /// exited. This state can change the emission states of subsequent uses
1659 /// of functions.
1660 ///
1661 /// Conceptually the functions or variables to be visited form a use graph
1662 /// where the parent node uses the child node. At any point of the visit,
1663 /// the tree nodes traversed from the tree root to the current node form a use
1664 /// stack. The emission state of the current node depends on two factors:
1665 /// 1. the emission state of the root node
1666 /// 2. whether the current node is in OpenMP device context
1667 /// If the function is decided to be emitted, its contained deferred diagnostics
1668 /// are emitted, together with the information about the use stack.
1669 ///
1670 class DeferredDiagnosticsEmitter
1671 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1672 public:
1673 typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1674
1675 // Whether the function is already in the current use-path.
1676 llvm::SmallSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1677
1678 // The current use-path.
1679 llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1680
1681 // Whether the visiting of the function has been done. Done[0] is for the
1682 // case not in OpenMP device context. Done[1] is for the case in OpenMP
1683 // device context. We need two sets because diagnostics emission may be
1684 // different depending on whether it is in OpenMP device context.
1685 llvm::SmallSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
1686
1687 // Emission state of the root node of the current use graph.
1688 bool ShouldEmitRootNode;
1689
1690 // Current OpenMP device context level. It is initialized to 0 and each
1691 // entering of device context increases it by 1 and each exit decreases
1692 // it by 1. Non-zero value indicates it is currently in device context.
1693 unsigned InOMPDeviceContext;
1694
DeferredDiagnosticsEmitter(Sema & S)1695 DeferredDiagnosticsEmitter(Sema &S)
1696 : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1697
VisitOMPTargetDirective(OMPTargetDirective * Node)1698 void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1699 ++InOMPDeviceContext;
1700 Inherited::VisitOMPTargetDirective(Node);
1701 --InOMPDeviceContext;
1702 }
1703
visitUsedDecl(SourceLocation Loc,Decl * D)1704 void visitUsedDecl(SourceLocation Loc, Decl *D) {
1705 if (isa<VarDecl>(D))
1706 return;
1707 if (auto *FD = dyn_cast<FunctionDecl>(D))
1708 checkFunc(Loc, FD);
1709 else
1710 Inherited::visitUsedDecl(Loc, D);
1711 }
1712
checkVar(VarDecl * VD)1713 void checkVar(VarDecl *VD) {
1714 assert(VD->isFileVarDecl() &&
1715 "Should only check file-scope variables");
1716 if (auto *Init = VD->getInit()) {
1717 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1718 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
1719 *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1720 if (IsDev)
1721 ++InOMPDeviceContext;
1722 this->Visit(Init);
1723 if (IsDev)
1724 --InOMPDeviceContext;
1725 }
1726 }
1727
checkFunc(SourceLocation Loc,FunctionDecl * FD)1728 void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1729 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
1730 FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
1731 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
1732 S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
1733 return;
1734 // Finalize analysis of OpenMP-specific constructs.
1735 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1)
1736 S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1737 if (Caller)
1738 S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
1739 // Always emit deferred diagnostics for the direct users. This does not
1740 // lead to explosion of diagnostics since each user is visited at most
1741 // twice.
1742 if (ShouldEmitRootNode || InOMPDeviceContext)
1743 emitDeferredDiags(FD, Caller);
1744 // Do not revisit a function if the function body has been completely
1745 // visited before.
1746 if (!Done.insert(FD).second)
1747 return;
1748 InUsePath.insert(FD);
1749 UsePath.push_back(FD);
1750 if (auto *S = FD->getBody()) {
1751 this->Visit(S);
1752 }
1753 UsePath.pop_back();
1754 InUsePath.erase(FD);
1755 }
1756
checkRecordedDecl(Decl * D)1757 void checkRecordedDecl(Decl *D) {
1758 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1759 ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1760 Sema::FunctionEmissionStatus::Emitted;
1761 checkFunc(SourceLocation(), FD);
1762 } else
1763 checkVar(cast<VarDecl>(D));
1764 }
1765
1766 // Emit any deferred diagnostics for FD
emitDeferredDiags(FunctionDecl * FD,bool ShowCallStack)1767 void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
1768 auto It = S.DeviceDeferredDiags.find(FD);
1769 if (It == S.DeviceDeferredDiags.end())
1770 return;
1771 bool HasWarningOrError = false;
1772 bool FirstDiag = true;
1773 for (PartialDiagnosticAt &PDAt : It->second) {
1774 // Respect error limit.
1775 if (S.Diags.hasFatalErrorOccurred())
1776 return;
1777 const SourceLocation &Loc = PDAt.first;
1778 const PartialDiagnostic &PD = PDAt.second;
1779 HasWarningOrError |=
1780 S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
1781 DiagnosticsEngine::Warning;
1782 {
1783 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1784 PD.Emit(Builder);
1785 }
1786 // Emit the note on the first diagnostic in case too many diagnostics
1787 // cause the note not emitted.
1788 if (FirstDiag && HasWarningOrError && ShowCallStack) {
1789 emitCallStackNotes(S, FD);
1790 FirstDiag = false;
1791 }
1792 }
1793 }
1794 };
1795 } // namespace
1796
emitDeferredDiags()1797 void Sema::emitDeferredDiags() {
1798 if (ExternalSource)
1799 ExternalSource->ReadDeclsToCheckForDeferredDiags(
1800 DeclsToCheckForDeferredDiags);
1801
1802 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
1803 DeclsToCheckForDeferredDiags.empty())
1804 return;
1805
1806 DeferredDiagnosticsEmitter DDE(*this);
1807 for (auto D : DeclsToCheckForDeferredDiags)
1808 DDE.checkRecordedDecl(D);
1809 }
1810
1811 // In CUDA, there are some constructs which may appear in semantically-valid
1812 // code, but trigger errors if we ever generate code for the function in which
1813 // they appear. Essentially every construct you're not allowed to use on the
1814 // device falls into this category, because you are allowed to use these
1815 // constructs in a __host__ __device__ function, but only if that function is
1816 // never codegen'ed on the device.
1817 //
1818 // To handle semantic checking for these constructs, we keep track of the set of
1819 // functions we know will be emitted, either because we could tell a priori that
1820 // they would be emitted, or because they were transitively called by a
1821 // known-emitted function.
1822 //
1823 // We also keep a partial call graph of which not-known-emitted functions call
1824 // which other not-known-emitted functions.
1825 //
1826 // When we see something which is illegal if the current function is emitted
1827 // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1828 // CheckCUDACall), we first check if the current function is known-emitted. If
1829 // so, we immediately output the diagnostic.
1830 //
1831 // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
1832 // until we discover that the function is known-emitted, at which point we take
1833 // it out of this map and emit the diagnostic.
1834
DeviceDiagBuilder(Kind K,SourceLocation Loc,unsigned DiagID,FunctionDecl * Fn,Sema & S)1835 Sema::DeviceDiagBuilder::DeviceDiagBuilder(Kind K, SourceLocation Loc,
1836 unsigned DiagID, FunctionDecl *Fn,
1837 Sema &S)
1838 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1839 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1840 switch (K) {
1841 case K_Nop:
1842 break;
1843 case K_Immediate:
1844 case K_ImmediateWithCallStack:
1845 ImmediateDiag.emplace(S.Diag(Loc, DiagID));
1846 break;
1847 case K_Deferred:
1848 assert(Fn && "Must have a function to attach the deferred diag to.");
1849 auto &Diags = S.DeviceDeferredDiags[Fn];
1850 PartialDiagId.emplace(Diags.size());
1851 Diags.emplace_back(Loc, S.PDiag(DiagID));
1852 break;
1853 }
1854 }
1855
DeviceDiagBuilder(DeviceDiagBuilder && D)1856 Sema::DeviceDiagBuilder::DeviceDiagBuilder(DeviceDiagBuilder &&D)
1857 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1858 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1859 PartialDiagId(D.PartialDiagId) {
1860 // Clean the previous diagnostics.
1861 D.ShowCallStack = false;
1862 D.ImmediateDiag.reset();
1863 D.PartialDiagId.reset();
1864 }
1865
~DeviceDiagBuilder()1866 Sema::DeviceDiagBuilder::~DeviceDiagBuilder() {
1867 if (ImmediateDiag) {
1868 // Emit our diagnostic and, if it was a warning or error, output a callstack
1869 // if Fn isn't a priori known-emitted.
1870 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1871 DiagID, Loc) >= DiagnosticsEngine::Warning;
1872 ImmediateDiag.reset(); // Emit the immediate diag.
1873 if (IsWarningOrError && ShowCallStack)
1874 emitCallStackNotes(S, Fn);
1875 } else {
1876 assert((!PartialDiagId || ShowCallStack) &&
1877 "Must always show call stack for deferred diags.");
1878 }
1879 }
1880
targetDiag(SourceLocation Loc,unsigned DiagID)1881 Sema::DeviceDiagBuilder Sema::targetDiag(SourceLocation Loc, unsigned DiagID) {
1882 if (LangOpts.OpenMP)
1883 return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID)
1884 : diagIfOpenMPHostCode(Loc, DiagID);
1885 if (getLangOpts().CUDA)
1886 return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
1887 : CUDADiagIfHostCode(Loc, DiagID);
1888
1889 if (getLangOpts().SYCLIsDevice)
1890 return SYCLDiagIfDeviceCode(Loc, DiagID);
1891
1892 return DeviceDiagBuilder(DeviceDiagBuilder::K_Immediate, Loc, DiagID,
1893 getCurFunctionDecl(), *this);
1894 }
1895
checkDeviceDecl(const ValueDecl * D,SourceLocation Loc)1896 void Sema::checkDeviceDecl(const ValueDecl *D, SourceLocation Loc) {
1897 if (isUnevaluatedContext())
1898 return;
1899
1900 Decl *C = cast<Decl>(getCurLexicalContext());
1901
1902 // Memcpy operations for structs containing a member with unsupported type
1903 // are ok, though.
1904 if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
1905 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
1906 MD->isTrivial())
1907 return;
1908
1909 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
1910 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
1911 return;
1912 }
1913
1914 auto CheckType = [&](QualType Ty) {
1915 if (Ty->isDependentType())
1916 return;
1917
1918 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1919 ((Ty->isFloat128Type() ||
1920 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1921 !Context.getTargetInfo().hasFloat128Type()) ||
1922 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1923 !Context.getTargetInfo().hasInt128Type())) {
1924 targetDiag(Loc, diag::err_device_unsupported_type)
1925 << D << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1926 << Context.getTargetInfo().getTriple().str();
1927 targetDiag(D->getLocation(), diag::note_defined_here) << D;
1928 }
1929 };
1930
1931 QualType Ty = D->getType();
1932 CheckType(Ty);
1933
1934 if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
1935 for (const auto &ParamTy : FPTy->param_types())
1936 CheckType(ParamTy);
1937 CheckType(FPTy->getReturnType());
1938 }
1939 }
1940
1941 /// Looks through the macro-expansion chain for the given
1942 /// location, looking for a macro expansion with the given name.
1943 /// If one is found, returns true and sets the location to that
1944 /// expansion loc.
findMacroSpelling(SourceLocation & locref,StringRef name)1945 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1946 SourceLocation loc = locref;
1947 if (!loc.isMacroID()) return false;
1948
1949 // There's no good way right now to look at the intermediate
1950 // expansions, so just jump to the expansion location.
1951 loc = getSourceManager().getExpansionLoc(loc);
1952
1953 // If that's written with the name, stop here.
1954 SmallVector<char, 16> buffer;
1955 if (getPreprocessor().getSpelling(loc, buffer) == name) {
1956 locref = loc;
1957 return true;
1958 }
1959 return false;
1960 }
1961
1962 /// Determines the active Scope associated with the given declaration
1963 /// context.
1964 ///
1965 /// This routine maps a declaration context to the active Scope object that
1966 /// represents that declaration context in the parser. It is typically used
1967 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1968 /// declarations) that injects a name for name-lookup purposes and, therefore,
1969 /// must update the Scope.
1970 ///
1971 /// \returns The scope corresponding to the given declaraion context, or NULL
1972 /// if no such scope is open.
getScopeForContext(DeclContext * Ctx)1973 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
1974
1975 if (!Ctx)
1976 return nullptr;
1977
1978 Ctx = Ctx->getPrimaryContext();
1979 for (Scope *S = getCurScope(); S; S = S->getParent()) {
1980 // Ignore scopes that cannot have declarations. This is important for
1981 // out-of-line definitions of static class members.
1982 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1983 if (DeclContext *Entity = S->getEntity())
1984 if (Ctx == Entity->getPrimaryContext())
1985 return S;
1986 }
1987
1988 return nullptr;
1989 }
1990
1991 /// Enter a new function scope
PushFunctionScope()1992 void Sema::PushFunctionScope() {
1993 if (FunctionScopes.empty() && CachedFunctionScope) {
1994 // Use CachedFunctionScope to avoid allocating memory when possible.
1995 CachedFunctionScope->Clear();
1996 FunctionScopes.push_back(CachedFunctionScope.release());
1997 } else {
1998 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1999 }
2000 if (LangOpts.OpenMP)
2001 pushOpenMPFunctionRegion();
2002 }
2003
PushBlockScope(Scope * BlockScope,BlockDecl * Block)2004 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
2005 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
2006 BlockScope, Block));
2007 }
2008
PushLambdaScope()2009 LambdaScopeInfo *Sema::PushLambdaScope() {
2010 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
2011 FunctionScopes.push_back(LSI);
2012 return LSI;
2013 }
2014
RecordParsingTemplateParameterDepth(unsigned Depth)2015 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
2016 if (LambdaScopeInfo *const LSI = getCurLambda()) {
2017 LSI->AutoTemplateParameterDepth = Depth;
2018 return;
2019 }
2020 llvm_unreachable(
2021 "Remove assertion if intentionally called in a non-lambda context.");
2022 }
2023
2024 // Check that the type of the VarDecl has an accessible copy constructor and
2025 // resolve its destructor's exception specification.
checkEscapingByref(VarDecl * VD,Sema & S)2026 static void checkEscapingByref(VarDecl *VD, Sema &S) {
2027 QualType T = VD->getType();
2028 EnterExpressionEvaluationContext scope(
2029 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2030 SourceLocation Loc = VD->getLocation();
2031 Expr *VarRef =
2032 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2033 ExprResult Result = S.PerformMoveOrCopyInitialization(
2034 InitializedEntity::InitializeBlock(Loc, T, false), VD, VD->getType(),
2035 VarRef, /*AllowNRVO=*/true);
2036 if (!Result.isInvalid()) {
2037 Result = S.MaybeCreateExprWithCleanups(Result);
2038 Expr *Init = Result.getAs<Expr>();
2039 S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
2040 }
2041
2042 // The destructor's exception specification is needed when IRGen generates
2043 // block copy/destroy functions. Resolve it here.
2044 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2045 if (CXXDestructorDecl *DD = RD->getDestructor()) {
2046 auto *FPT = DD->getType()->getAs<FunctionProtoType>();
2047 S.ResolveExceptionSpec(Loc, FPT);
2048 }
2049 }
2050
markEscapingByrefs(const FunctionScopeInfo & FSI,Sema & S)2051 static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2052 // Set the EscapingByref flag of __block variables captured by
2053 // escaping blocks.
2054 for (const BlockDecl *BD : FSI.Blocks) {
2055 for (const BlockDecl::Capture &BC : BD->captures()) {
2056 VarDecl *VD = BC.getVariable();
2057 if (VD->hasAttr<BlocksAttr>()) {
2058 // Nothing to do if this is a __block variable captured by a
2059 // non-escaping block.
2060 if (BD->doesNotEscape())
2061 continue;
2062 VD->setEscapingByref();
2063 }
2064 // Check whether the captured variable is or contains an object of
2065 // non-trivial C union type.
2066 QualType CapType = BC.getVariable()->getType();
2067 if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
2068 CapType.hasNonTrivialToPrimitiveCopyCUnion())
2069 S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2070 BD->getCaretLocation(),
2071 Sema::NTCUC_BlockCapture,
2072 Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
2073 }
2074 }
2075
2076 for (VarDecl *VD : FSI.ByrefBlockVars) {
2077 // __block variables might require us to capture a copy-initializer.
2078 if (!VD->isEscapingByref())
2079 continue;
2080 // It's currently invalid to ever have a __block variable with an
2081 // array type; should we diagnose that here?
2082 // Regardless, we don't want to ignore array nesting when
2083 // constructing this copy.
2084 if (VD->getType()->isStructureOrClassType())
2085 checkEscapingByref(VD, S);
2086 }
2087 }
2088
2089 /// Pop a function (or block or lambda or captured region) scope from the stack.
2090 ///
2091 /// \param WP The warning policy to use for CFG-based warnings, or null if such
2092 /// warnings should not be produced.
2093 /// \param D The declaration corresponding to this function scope, if producing
2094 /// CFG-based warnings.
2095 /// \param BlockType The type of the block expression, if D is a BlockDecl.
2096 Sema::PoppedFunctionScopePtr
PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy * WP,const Decl * D,QualType BlockType)2097 Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
2098 const Decl *D, QualType BlockType) {
2099 assert(!FunctionScopes.empty() && "mismatched push/pop!");
2100
2101 markEscapingByrefs(*FunctionScopes.back(), *this);
2102
2103 PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
2104 PoppedFunctionScopeDeleter(this));
2105
2106 if (LangOpts.OpenMP)
2107 popOpenMPFunctionRegion(Scope.get());
2108
2109 // Issue any analysis-based warnings.
2110 if (WP && D)
2111 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2112 else
2113 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2114 Diag(PUD.Loc, PUD.PD);
2115
2116 return Scope;
2117 }
2118
2119 void Sema::PoppedFunctionScopeDeleter::
operator ()(sema::FunctionScopeInfo * Scope) const2120 operator()(sema::FunctionScopeInfo *Scope) const {
2121 // Stash the function scope for later reuse if it's for a normal function.
2122 if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
2123 Self->CachedFunctionScope.reset(Scope);
2124 else
2125 delete Scope;
2126 }
2127
PushCompoundScope(bool IsStmtExpr)2128 void Sema::PushCompoundScope(bool IsStmtExpr) {
2129 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr));
2130 }
2131
PopCompoundScope()2132 void Sema::PopCompoundScope() {
2133 FunctionScopeInfo *CurFunction = getCurFunction();
2134 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2135
2136 CurFunction->CompoundScopes.pop_back();
2137 }
2138
2139 /// Determine whether any errors occurred within this function/method/
2140 /// block.
hasAnyUnrecoverableErrorsInThisFunction() const2141 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2142 return getCurFunction()->hasUnrecoverableErrorOccurred();
2143 }
2144
setFunctionHasBranchIntoScope()2145 void Sema::setFunctionHasBranchIntoScope() {
2146 if (!FunctionScopes.empty())
2147 FunctionScopes.back()->setHasBranchIntoScope();
2148 }
2149
setFunctionHasBranchProtectedScope()2150 void Sema::setFunctionHasBranchProtectedScope() {
2151 if (!FunctionScopes.empty())
2152 FunctionScopes.back()->setHasBranchProtectedScope();
2153 }
2154
setFunctionHasIndirectGoto()2155 void Sema::setFunctionHasIndirectGoto() {
2156 if (!FunctionScopes.empty())
2157 FunctionScopes.back()->setHasIndirectGoto();
2158 }
2159
getCurBlock()2160 BlockScopeInfo *Sema::getCurBlock() {
2161 if (FunctionScopes.empty())
2162 return nullptr;
2163
2164 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2165 if (CurBSI && CurBSI->TheDecl &&
2166 !CurBSI->TheDecl->Encloses(CurContext)) {
2167 // We have switched contexts due to template instantiation.
2168 assert(!CodeSynthesisContexts.empty());
2169 return nullptr;
2170 }
2171
2172 return CurBSI;
2173 }
2174
getEnclosingFunction() const2175 FunctionScopeInfo *Sema::getEnclosingFunction() const {
2176 if (FunctionScopes.empty())
2177 return nullptr;
2178
2179 for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2180 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
2181 continue;
2182 return FunctionScopes[e];
2183 }
2184 return nullptr;
2185 }
2186
getEnclosingLambda() const2187 LambdaScopeInfo *Sema::getEnclosingLambda() const {
2188 for (auto *Scope : llvm::reverse(FunctionScopes)) {
2189 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
2190 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext)) {
2191 // We have switched contexts due to template instantiation.
2192 // FIXME: We should swap out the FunctionScopes during code synthesis
2193 // so that we don't need to check for this.
2194 assert(!CodeSynthesisContexts.empty());
2195 return nullptr;
2196 }
2197 return LSI;
2198 }
2199 }
2200 return nullptr;
2201 }
2202
getCurLambda(bool IgnoreNonLambdaCapturingScope)2203 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2204 if (FunctionScopes.empty())
2205 return nullptr;
2206
2207 auto I = FunctionScopes.rbegin();
2208 if (IgnoreNonLambdaCapturingScope) {
2209 auto E = FunctionScopes.rend();
2210 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
2211 ++I;
2212 if (I == E)
2213 return nullptr;
2214 }
2215 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2216 if (CurLSI && CurLSI->Lambda &&
2217 !CurLSI->Lambda->Encloses(CurContext)) {
2218 // We have switched contexts due to template instantiation.
2219 assert(!CodeSynthesisContexts.empty());
2220 return nullptr;
2221 }
2222
2223 return CurLSI;
2224 }
2225
2226 // We have a generic lambda if we parsed auto parameters, or we have
2227 // an associated template parameter list.
getCurGenericLambda()2228 LambdaScopeInfo *Sema::getCurGenericLambda() {
2229 if (LambdaScopeInfo *LSI = getCurLambda()) {
2230 return (LSI->TemplateParams.size() ||
2231 LSI->GLTemplateParameterList) ? LSI : nullptr;
2232 }
2233 return nullptr;
2234 }
2235
2236
ActOnComment(SourceRange Comment)2237 void Sema::ActOnComment(SourceRange Comment) {
2238 if (!LangOpts.RetainCommentsFromSystemHeaders &&
2239 SourceMgr.isInSystemHeader(Comment.getBegin()))
2240 return;
2241 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2242 if (RC.isAlmostTrailingComment()) {
2243 SourceRange MagicMarkerRange(Comment.getBegin(),
2244 Comment.getBegin().getLocWithOffset(3));
2245 StringRef MagicMarkerText;
2246 switch (RC.getKind()) {
2247 case RawComment::RCK_OrdinaryBCPL:
2248 MagicMarkerText = "///<";
2249 break;
2250 case RawComment::RCK_OrdinaryC:
2251 MagicMarkerText = "/**<";
2252 break;
2253 default:
2254 llvm_unreachable("if this is an almost Doxygen comment, "
2255 "it should be ordinary");
2256 }
2257 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2258 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2259 }
2260 Context.addComment(RC);
2261 }
2262
2263 // Pin this vtable to this file.
~ExternalSemaSource()2264 ExternalSemaSource::~ExternalSemaSource() {}
2265 char ExternalSemaSource::ID;
2266
ReadMethodPool(Selector Sel)2267 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
updateOutOfDateSelector(Selector Sel)2268 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
2269
ReadKnownNamespaces(SmallVectorImpl<NamespaceDecl * > & Namespaces)2270 void ExternalSemaSource::ReadKnownNamespaces(
2271 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
2272 }
2273
ReadUndefinedButUsed(llvm::MapVector<NamedDecl *,SourceLocation> & Undefined)2274 void ExternalSemaSource::ReadUndefinedButUsed(
2275 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2276
ReadMismatchingDeleteExpressions(llvm::MapVector<FieldDecl *,llvm::SmallVector<std::pair<SourceLocation,bool>,4>> &)2277 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
2278 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2279
2280 /// Figure out if an expression could be turned into a call.
2281 ///
2282 /// Use this when trying to recover from an error where the programmer may have
2283 /// written just the name of a function instead of actually calling it.
2284 ///
2285 /// \param E - The expression to examine.
2286 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
2287 /// with no arguments, this parameter is set to the type returned by such a
2288 /// call; otherwise, it is set to an empty QualType.
2289 /// \param OverloadSet - If the expression is an overloaded function
2290 /// name, this parameter is populated with the decls of the various overloads.
tryExprAsCall(Expr & E,QualType & ZeroArgCallReturnTy,UnresolvedSetImpl & OverloadSet)2291 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2292 UnresolvedSetImpl &OverloadSet) {
2293 ZeroArgCallReturnTy = QualType();
2294 OverloadSet.clear();
2295
2296 const OverloadExpr *Overloads = nullptr;
2297 bool IsMemExpr = false;
2298 if (E.getType() == Context.OverloadTy) {
2299 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
2300
2301 // Ignore overloads that are pointer-to-member constants.
2302 if (FR.HasFormOfMemberPointer)
2303 return false;
2304
2305 Overloads = FR.Expression;
2306 } else if (E.getType() == Context.BoundMemberTy) {
2307 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2308 IsMemExpr = true;
2309 }
2310
2311 bool Ambiguous = false;
2312 bool IsMV = false;
2313
2314 if (Overloads) {
2315 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2316 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
2317 OverloadSet.addDecl(*it);
2318
2319 // Check whether the function is a non-template, non-member which takes no
2320 // arguments.
2321 if (IsMemExpr)
2322 continue;
2323 if (const FunctionDecl *OverloadDecl
2324 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2325 if (OverloadDecl->getMinRequiredArguments() == 0) {
2326 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
2327 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2328 OverloadDecl->isCPUSpecificMultiVersion()))) {
2329 ZeroArgCallReturnTy = QualType();
2330 Ambiguous = true;
2331 } else {
2332 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2333 IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2334 OverloadDecl->isCPUSpecificMultiVersion();
2335 }
2336 }
2337 }
2338 }
2339
2340 // If it's not a member, use better machinery to try to resolve the call
2341 if (!IsMemExpr)
2342 return !ZeroArgCallReturnTy.isNull();
2343 }
2344
2345 // Attempt to call the member with no arguments - this will correctly handle
2346 // member templates with defaults/deduction of template arguments, overloads
2347 // with default arguments, etc.
2348 if (IsMemExpr && !E.isTypeDependent()) {
2349 Sema::TentativeAnalysisScope Trap(*this);
2350 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
2351 None, SourceLocation());
2352 if (R.isUsable()) {
2353 ZeroArgCallReturnTy = R.get()->getType();
2354 return true;
2355 }
2356 return false;
2357 }
2358
2359 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2360 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2361 if (Fun->getMinRequiredArguments() == 0)
2362 ZeroArgCallReturnTy = Fun->getReturnType();
2363 return true;
2364 }
2365 }
2366
2367 // We don't have an expression that's convenient to get a FunctionDecl from,
2368 // but we can at least check if the type is "function of 0 arguments".
2369 QualType ExprTy = E.getType();
2370 const FunctionType *FunTy = nullptr;
2371 QualType PointeeTy = ExprTy->getPointeeType();
2372 if (!PointeeTy.isNull())
2373 FunTy = PointeeTy->getAs<FunctionType>();
2374 if (!FunTy)
2375 FunTy = ExprTy->getAs<FunctionType>();
2376
2377 if (const FunctionProtoType *FPT =
2378 dyn_cast_or_null<FunctionProtoType>(FunTy)) {
2379 if (FPT->getNumParams() == 0)
2380 ZeroArgCallReturnTy = FunTy->getReturnType();
2381 return true;
2382 }
2383 return false;
2384 }
2385
2386 /// Give notes for a set of overloads.
2387 ///
2388 /// A companion to tryExprAsCall. In cases when the name that the programmer
2389 /// wrote was an overloaded function, we may be able to make some guesses about
2390 /// plausible overloads based on their return types; such guesses can be handed
2391 /// off to this method to be emitted as notes.
2392 ///
2393 /// \param Overloads - The overloads to note.
2394 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2395 /// -fshow-overloads=best, this is the location to attach to the note about too
2396 /// many candidates. Typically this will be the location of the original
2397 /// ill-formed expression.
noteOverloads(Sema & S,const UnresolvedSetImpl & Overloads,const SourceLocation FinalNoteLoc)2398 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2399 const SourceLocation FinalNoteLoc) {
2400 int ShownOverloads = 0;
2401 int SuppressedOverloads = 0;
2402 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2403 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2404 // FIXME: Magic number for max shown overloads stolen from
2405 // OverloadCandidateSet::NoteCandidates.
2406 if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
2407 ++SuppressedOverloads;
2408 continue;
2409 }
2410
2411 NamedDecl *Fn = (*It)->getUnderlyingDecl();
2412 // Don't print overloads for non-default multiversioned functions.
2413 if (const auto *FD = Fn->getAsFunction()) {
2414 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
2415 !FD->getAttr<TargetAttr>()->isDefaultVersion())
2416 continue;
2417 }
2418 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2419 ++ShownOverloads;
2420 }
2421
2422 if (SuppressedOverloads)
2423 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2424 << SuppressedOverloads;
2425 }
2426
notePlausibleOverloads(Sema & S,SourceLocation Loc,const UnresolvedSetImpl & Overloads,bool (* IsPlausibleResult)(QualType))2427 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
2428 const UnresolvedSetImpl &Overloads,
2429 bool (*IsPlausibleResult)(QualType)) {
2430 if (!IsPlausibleResult)
2431 return noteOverloads(S, Overloads, Loc);
2432
2433 UnresolvedSet<2> PlausibleOverloads;
2434 for (OverloadExpr::decls_iterator It = Overloads.begin(),
2435 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2436 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
2437 QualType OverloadResultTy = OverloadDecl->getReturnType();
2438 if (IsPlausibleResult(OverloadResultTy))
2439 PlausibleOverloads.addDecl(It.getDecl());
2440 }
2441 noteOverloads(S, PlausibleOverloads, Loc);
2442 }
2443
2444 /// Determine whether the given expression can be called by just
2445 /// putting parentheses after it. Notably, expressions with unary
2446 /// operators can't be because the unary operator will start parsing
2447 /// outside the call.
IsCallableWithAppend(Expr * E)2448 static bool IsCallableWithAppend(Expr *E) {
2449 E = E->IgnoreImplicit();
2450 return (!isa<CStyleCastExpr>(E) &&
2451 !isa<UnaryOperator>(E) &&
2452 !isa<BinaryOperator>(E) &&
2453 !isa<CXXOperatorCallExpr>(E));
2454 }
2455
IsCPUDispatchCPUSpecificMultiVersion(const Expr * E)2456 static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
2457 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2458 E = UO->getSubExpr();
2459
2460 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2461 if (ULE->getNumDecls() == 0)
2462 return false;
2463
2464 const NamedDecl *ND = *ULE->decls_begin();
2465 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2466 return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
2467 }
2468 return false;
2469 }
2470
tryToRecoverWithCall(ExprResult & E,const PartialDiagnostic & PD,bool ForceComplain,bool (* IsPlausibleResult)(QualType))2471 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2472 bool ForceComplain,
2473 bool (*IsPlausibleResult)(QualType)) {
2474 SourceLocation Loc = E.get()->getExprLoc();
2475 SourceRange Range = E.get()->getSourceRange();
2476
2477 QualType ZeroArgCallTy;
2478 UnresolvedSet<4> Overloads;
2479 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2480 !ZeroArgCallTy.isNull() &&
2481 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
2482 // At this point, we know E is potentially callable with 0
2483 // arguments and that it returns something of a reasonable type,
2484 // so we can emit a fixit and carry on pretending that E was
2485 // actually a CallExpr.
2486 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2487 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2488 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2489 << (IsCallableWithAppend(E.get())
2490 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
2491 : FixItHint());
2492 if (!IsMV)
2493 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2494
2495 // FIXME: Try this before emitting the fixit, and suppress diagnostics
2496 // while doing so.
2497 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None,
2498 Range.getEnd().getLocWithOffset(1));
2499 return true;
2500 }
2501
2502 if (!ForceComplain) return false;
2503
2504 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2505 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2506 if (!IsMV)
2507 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2508 E = ExprError();
2509 return true;
2510 }
2511
getSuperIdentifier() const2512 IdentifierInfo *Sema::getSuperIdentifier() const {
2513 if (!Ident_super)
2514 Ident_super = &Context.Idents.get("super");
2515 return Ident_super;
2516 }
2517
getFloat128Identifier() const2518 IdentifierInfo *Sema::getFloat128Identifier() const {
2519 if (!Ident___float128)
2520 Ident___float128 = &Context.Idents.get("__float128");
2521 return Ident___float128;
2522 }
2523
PushCapturedRegionScope(Scope * S,CapturedDecl * CD,RecordDecl * RD,CapturedRegionKind K,unsigned OpenMPCaptureLevel)2524 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
2525 CapturedRegionKind K,
2526 unsigned OpenMPCaptureLevel) {
2527 auto *CSI = new CapturedRegionScopeInfo(
2528 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2529 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
2530 OpenMPCaptureLevel);
2531 CSI->ReturnType = Context.VoidTy;
2532 FunctionScopes.push_back(CSI);
2533 }
2534
getCurCapturedRegion()2535 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
2536 if (FunctionScopes.empty())
2537 return nullptr;
2538
2539 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2540 }
2541
2542 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
getMismatchingDeleteExpressions() const2543 Sema::getMismatchingDeleteExpressions() const {
2544 return DeleteExprs;
2545 }
2546
setOpenCLExtensionForType(QualType T,llvm::StringRef ExtStr)2547 void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
2548 if (ExtStr.empty())
2549 return;
2550 llvm::SmallVector<StringRef, 1> Exts;
2551 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
2552 auto CanT = T.getCanonicalType().getTypePtr();
2553 for (auto &I : Exts)
2554 OpenCLTypeExtMap[CanT].insert(I.str());
2555 }
2556
setOpenCLExtensionForDecl(Decl * FD,StringRef ExtStr)2557 void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
2558 llvm::SmallVector<StringRef, 1> Exts;
2559 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
2560 if (Exts.empty())
2561 return;
2562 for (auto &I : Exts)
2563 OpenCLDeclExtMap[FD].insert(I.str());
2564 }
2565
setCurrentOpenCLExtensionForType(QualType T)2566 void Sema::setCurrentOpenCLExtensionForType(QualType T) {
2567 if (CurrOpenCLExtension.empty())
2568 return;
2569 setOpenCLExtensionForType(T, CurrOpenCLExtension);
2570 }
2571
setCurrentOpenCLExtensionForDecl(Decl * D)2572 void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
2573 if (CurrOpenCLExtension.empty())
2574 return;
2575 setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
2576 }
2577
getOpenCLExtensionsFromDeclExtMap(FunctionDecl * FD)2578 std::string Sema::getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD) {
2579 if (!OpenCLDeclExtMap.empty())
2580 return getOpenCLExtensionsFromExtMap(FD, OpenCLDeclExtMap);
2581
2582 return "";
2583 }
2584
getOpenCLExtensionsFromTypeExtMap(FunctionType * FT)2585 std::string Sema::getOpenCLExtensionsFromTypeExtMap(FunctionType *FT) {
2586 if (!OpenCLTypeExtMap.empty())
2587 return getOpenCLExtensionsFromExtMap(FT, OpenCLTypeExtMap);
2588
2589 return "";
2590 }
2591
2592 template <typename T, typename MapT>
getOpenCLExtensionsFromExtMap(T * FDT,MapT & Map)2593 std::string Sema::getOpenCLExtensionsFromExtMap(T *FDT, MapT &Map) {
2594 auto Loc = Map.find(FDT);
2595 return llvm::join(Loc->second, " ");
2596 }
2597
isOpenCLDisabledDecl(Decl * FD)2598 bool Sema::isOpenCLDisabledDecl(Decl *FD) {
2599 auto Loc = OpenCLDeclExtMap.find(FD);
2600 if (Loc == OpenCLDeclExtMap.end())
2601 return false;
2602 for (auto &I : Loc->second) {
2603 if (!getOpenCLOptions().isEnabled(I))
2604 return true;
2605 }
2606 return false;
2607 }
2608
2609 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
checkOpenCLDisabledTypeOrDecl(T D,DiagLocT DiagLoc,DiagInfoT DiagInfo,MapT & Map,unsigned Selector,SourceRange SrcRange)2610 bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
2611 DiagInfoT DiagInfo, MapT &Map,
2612 unsigned Selector,
2613 SourceRange SrcRange) {
2614 auto Loc = Map.find(D);
2615 if (Loc == Map.end())
2616 return false;
2617 bool Disabled = false;
2618 for (auto &I : Loc->second) {
2619 if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
2620 Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
2621 << I << SrcRange;
2622 Disabled = true;
2623 }
2624 }
2625 return Disabled;
2626 }
2627
checkOpenCLDisabledTypeDeclSpec(const DeclSpec & DS,QualType QT)2628 bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
2629 // Check extensions for declared types.
2630 Decl *Decl = nullptr;
2631 if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
2632 Decl = TypedefT->getDecl();
2633 if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
2634 Decl = TagT->getDecl();
2635 auto Loc = DS.getTypeSpecTypeLoc();
2636
2637 // Check extensions for vector types.
2638 // e.g. double4 is not allowed when cl_khr_fp64 is absent.
2639 if (QT->isExtVectorType()) {
2640 auto TypePtr = QT->castAs<ExtVectorType>()->getElementType().getTypePtr();
2641 return checkOpenCLDisabledTypeOrDecl(TypePtr, Loc, QT, OpenCLTypeExtMap);
2642 }
2643
2644 if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
2645 return true;
2646
2647 // Check extensions for builtin types.
2648 return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
2649 QT, OpenCLTypeExtMap);
2650 }
2651
checkOpenCLDisabledDecl(const NamedDecl & D,const Expr & E)2652 bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) {
2653 IdentifierInfo *FnName = D.getIdentifier();
2654 return checkOpenCLDisabledTypeOrDecl(&D, E.getBeginLoc(), FnName,
2655 OpenCLDeclExtMap, 1, D.getSourceRange());
2656 }
2657