1 //===- Decl.cpp - Declaration AST Node 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 Decl subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/AST/Decl.h"
14 #include "Linkage.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/CanonicalType.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/DeclarationName.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/ExternalASTSource.h"
30 #include "clang/AST/ODRHash.h"
31 #include "clang/AST/PrettyDeclStackTrace.h"
32 #include "clang/AST/PrettyPrinter.h"
33 #include "clang/AST/Redeclarable.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/Basic/Builtins.h"
39 #include "clang/Basic/IdentifierTable.h"
40 #include "clang/Basic/LLVM.h"
41 #include "clang/Basic/LangOptions.h"
42 #include "clang/Basic/Linkage.h"
43 #include "clang/Basic/Module.h"
44 #include "clang/Basic/NoSanitizeList.h"
45 #include "clang/Basic/PartialDiagnostic.h"
46 #include "clang/Basic/Sanitizers.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/TargetCXXABI.h"
51 #include "clang/Basic/TargetInfo.h"
52 #include "clang/Basic/Visibility.h"
53 #include "llvm/ADT/APSInt.h"
54 #include "llvm/ADT/ArrayRef.h"
55 #include "llvm/ADT/None.h"
56 #include "llvm/ADT/Optional.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/StringSwitch.h"
61 #include "llvm/ADT/Triple.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cstddef>
68 #include <cstring>
69 #include <memory>
70 #include <string>
71 #include <tuple>
72 #include <type_traits>
73
74 using namespace clang;
75
getPrimaryMergedDecl(Decl * D)76 Decl *clang::getPrimaryMergedDecl(Decl *D) {
77 return D->getASTContext().getPrimaryMergedDecl(D);
78 }
79
print(raw_ostream & OS) const80 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
81 SourceLocation Loc = this->Loc;
82 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
83 if (Loc.isValid()) {
84 Loc.print(OS, Context.getSourceManager());
85 OS << ": ";
86 }
87 OS << Message;
88
89 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
90 OS << " '";
91 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
92 OS << "'";
93 }
94
95 OS << '\n';
96 }
97
98 // Defined here so that it can be inlined into its direct callers.
isOutOfLine() const99 bool Decl::isOutOfLine() const {
100 return !getLexicalDeclContext()->Equals(getDeclContext());
101 }
102
TranslationUnitDecl(ASTContext & ctx)103 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
104 : Decl(TranslationUnit, nullptr, SourceLocation()),
105 DeclContext(TranslationUnit), Ctx(ctx) {}
106
107 //===----------------------------------------------------------------------===//
108 // NamedDecl Implementation
109 //===----------------------------------------------------------------------===//
110
111 // Visibility rules aren't rigorously externally specified, but here
112 // are the basic principles behind what we implement:
113 //
114 // 1. An explicit visibility attribute is generally a direct expression
115 // of the user's intent and should be honored. Only the innermost
116 // visibility attribute applies. If no visibility attribute applies,
117 // global visibility settings are considered.
118 //
119 // 2. There is one caveat to the above: on or in a template pattern,
120 // an explicit visibility attribute is just a default rule, and
121 // visibility can be decreased by the visibility of template
122 // arguments. But this, too, has an exception: an attribute on an
123 // explicit specialization or instantiation causes all the visibility
124 // restrictions of the template arguments to be ignored.
125 //
126 // 3. A variable that does not otherwise have explicit visibility can
127 // be restricted by the visibility of its type.
128 //
129 // 4. A visibility restriction is explicit if it comes from an
130 // attribute (or something like it), not a global visibility setting.
131 // When emitting a reference to an external symbol, visibility
132 // restrictions are ignored unless they are explicit.
133 //
134 // 5. When computing the visibility of a non-type, including a
135 // non-type member of a class, only non-type visibility restrictions
136 // are considered: the 'visibility' attribute, global value-visibility
137 // settings, and a few special cases like __private_extern.
138 //
139 // 6. When computing the visibility of a type, including a type member
140 // of a class, only type visibility restrictions are considered:
141 // the 'type_visibility' attribute and global type-visibility settings.
142 // However, a 'visibility' attribute counts as a 'type_visibility'
143 // attribute on any declaration that only has the former.
144 //
145 // The visibility of a "secondary" entity, like a template argument,
146 // is computed using the kind of that entity, not the kind of the
147 // primary entity for which we are computing visibility. For example,
148 // the visibility of a specialization of either of these templates:
149 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
150 // template <class T, bool (&compare)(T, X)> class matcher;
151 // is restricted according to the type visibility of the argument 'T',
152 // the type visibility of 'bool(&)(T,X)', and the value visibility of
153 // the argument function 'compare'. That 'has_match' is a value
154 // and 'matcher' is a type only matters when looking for attributes
155 // and settings from the immediate context.
156
157 /// Does this computation kind permit us to consider additional
158 /// visibility settings from attributes and the like?
hasExplicitVisibilityAlready(LVComputationKind computation)159 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
160 return computation.IgnoreExplicitVisibility;
161 }
162
163 /// Given an LVComputationKind, return one of the same type/value sort
164 /// that records that it already has explicit visibility.
165 static LVComputationKind
withExplicitVisibilityAlready(LVComputationKind Kind)166 withExplicitVisibilityAlready(LVComputationKind Kind) {
167 Kind.IgnoreExplicitVisibility = true;
168 return Kind;
169 }
170
getExplicitVisibility(const NamedDecl * D,LVComputationKind kind)171 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
172 LVComputationKind kind) {
173 assert(!kind.IgnoreExplicitVisibility &&
174 "asking for explicit visibility when we shouldn't be");
175 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
176 }
177
178 /// Is the given declaration a "type" or a "value" for the purposes of
179 /// visibility computation?
usesTypeVisibility(const NamedDecl * D)180 static bool usesTypeVisibility(const NamedDecl *D) {
181 return isa<TypeDecl>(D) ||
182 isa<ClassTemplateDecl>(D) ||
183 isa<ObjCInterfaceDecl>(D);
184 }
185
186 /// Does the given declaration have member specialization information,
187 /// and if so, is it an explicit specialization?
188 template <class T> static typename
189 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
isExplicitMemberSpecialization(const T * D)190 isExplicitMemberSpecialization(const T *D) {
191 if (const MemberSpecializationInfo *member =
192 D->getMemberSpecializationInfo()) {
193 return member->isExplicitSpecialization();
194 }
195 return false;
196 }
197
198 /// For templates, this question is easier: a member template can't be
199 /// explicitly instantiated, so there's a single bit indicating whether
200 /// or not this is an explicit member specialization.
isExplicitMemberSpecialization(const RedeclarableTemplateDecl * D)201 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
202 return D->isMemberSpecialization();
203 }
204
205 /// Given a visibility attribute, return the explicit visibility
206 /// associated with it.
207 template <class T>
getVisibilityFromAttr(const T * attr)208 static Visibility getVisibilityFromAttr(const T *attr) {
209 switch (attr->getVisibility()) {
210 case T::Default:
211 return DefaultVisibility;
212 case T::Hidden:
213 return HiddenVisibility;
214 case T::Protected:
215 return ProtectedVisibility;
216 }
217 llvm_unreachable("bad visibility kind");
218 }
219
220 /// Return the explicit visibility of the given declaration.
getVisibilityOf(const NamedDecl * D,NamedDecl::ExplicitVisibilityKind kind)221 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
222 NamedDecl::ExplicitVisibilityKind kind) {
223 // If we're ultimately computing the visibility of a type, look for
224 // a 'type_visibility' attribute before looking for 'visibility'.
225 if (kind == NamedDecl::VisibilityForType) {
226 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
227 return getVisibilityFromAttr(A);
228 }
229 }
230
231 // If this declaration has an explicit visibility attribute, use it.
232 if (const auto *A = D->getAttr<VisibilityAttr>()) {
233 return getVisibilityFromAttr(A);
234 }
235
236 return None;
237 }
238
getLVForType(const Type & T,LVComputationKind computation)239 LinkageInfo LinkageComputer::getLVForType(const Type &T,
240 LVComputationKind computation) {
241 if (computation.IgnoreAllVisibility)
242 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
243 return getTypeLinkageAndVisibility(&T);
244 }
245
246 /// Get the most restrictive linkage for the types in the given
247 /// template parameter list. For visibility purposes, template
248 /// parameters are part of the signature of a template.
getLVForTemplateParameterList(const TemplateParameterList * Params,LVComputationKind computation)249 LinkageInfo LinkageComputer::getLVForTemplateParameterList(
250 const TemplateParameterList *Params, LVComputationKind computation) {
251 LinkageInfo LV;
252 for (const NamedDecl *P : *Params) {
253 // Template type parameters are the most common and never
254 // contribute to visibility, pack or not.
255 if (isa<TemplateTypeParmDecl>(P))
256 continue;
257
258 // Non-type template parameters can be restricted by the value type, e.g.
259 // template <enum X> class A { ... };
260 // We have to be careful here, though, because we can be dealing with
261 // dependent types.
262 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
263 // Handle the non-pack case first.
264 if (!NTTP->isExpandedParameterPack()) {
265 if (!NTTP->getType()->isDependentType()) {
266 LV.merge(getLVForType(*NTTP->getType(), computation));
267 }
268 continue;
269 }
270
271 // Look at all the types in an expanded pack.
272 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
273 QualType type = NTTP->getExpansionType(i);
274 if (!type->isDependentType())
275 LV.merge(getTypeLinkageAndVisibility(type));
276 }
277 continue;
278 }
279
280 // Template template parameters can be restricted by their
281 // template parameters, recursively.
282 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
283
284 // Handle the non-pack case first.
285 if (!TTP->isExpandedParameterPack()) {
286 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
287 computation));
288 continue;
289 }
290
291 // Look at all expansions in an expanded pack.
292 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
293 i != n; ++i) {
294 LV.merge(getLVForTemplateParameterList(
295 TTP->getExpansionTemplateParameters(i), computation));
296 }
297 }
298
299 return LV;
300 }
301
getOutermostFuncOrBlockContext(const Decl * D)302 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
303 const Decl *Ret = nullptr;
304 const DeclContext *DC = D->getDeclContext();
305 while (DC->getDeclKind() != Decl::TranslationUnit) {
306 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
307 Ret = cast<Decl>(DC);
308 DC = DC->getParent();
309 }
310 return Ret;
311 }
312
313 /// Get the most restrictive linkage for the types and
314 /// declarations in the given template argument list.
315 ///
316 /// Note that we don't take an LVComputationKind because we always
317 /// want to honor the visibility of template arguments in the same way.
318 LinkageInfo
getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,LVComputationKind computation)319 LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
320 LVComputationKind computation) {
321 LinkageInfo LV;
322
323 for (const TemplateArgument &Arg : Args) {
324 switch (Arg.getKind()) {
325 case TemplateArgument::Null:
326 case TemplateArgument::Integral:
327 case TemplateArgument::Expression:
328 continue;
329
330 case TemplateArgument::Type:
331 LV.merge(getLVForType(*Arg.getAsType(), computation));
332 continue;
333
334 case TemplateArgument::Declaration: {
335 const NamedDecl *ND = Arg.getAsDecl();
336 assert(!usesTypeVisibility(ND));
337 LV.merge(getLVForDecl(ND, computation));
338 continue;
339 }
340
341 case TemplateArgument::NullPtr:
342 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
343 continue;
344
345 case TemplateArgument::Template:
346 case TemplateArgument::TemplateExpansion:
347 if (TemplateDecl *Template =
348 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
349 LV.merge(getLVForDecl(Template, computation));
350 continue;
351
352 case TemplateArgument::Pack:
353 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
354 continue;
355 }
356 llvm_unreachable("bad template argument kind");
357 }
358
359 return LV;
360 }
361
362 LinkageInfo
getLVForTemplateArgumentList(const TemplateArgumentList & TArgs,LVComputationKind computation)363 LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
364 LVComputationKind computation) {
365 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
366 }
367
shouldConsiderTemplateVisibility(const FunctionDecl * fn,const FunctionTemplateSpecializationInfo * specInfo)368 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
369 const FunctionTemplateSpecializationInfo *specInfo) {
370 // Include visibility from the template parameters and arguments
371 // only if this is not an explicit instantiation or specialization
372 // with direct explicit visibility. (Implicit instantiations won't
373 // have a direct attribute.)
374 if (!specInfo->isExplicitInstantiationOrSpecialization())
375 return true;
376
377 return !fn->hasAttr<VisibilityAttr>();
378 }
379
380 /// Merge in template-related linkage and visibility for the given
381 /// function template specialization.
382 ///
383 /// We don't need a computation kind here because we can assume
384 /// LVForValue.
385 ///
386 /// \param[out] LV the computation to use for the parent
mergeTemplateLV(LinkageInfo & LV,const FunctionDecl * fn,const FunctionTemplateSpecializationInfo * specInfo,LVComputationKind computation)387 void LinkageComputer::mergeTemplateLV(
388 LinkageInfo &LV, const FunctionDecl *fn,
389 const FunctionTemplateSpecializationInfo *specInfo,
390 LVComputationKind computation) {
391 bool considerVisibility =
392 shouldConsiderTemplateVisibility(fn, specInfo);
393
394 // Merge information from the template parameters.
395 FunctionTemplateDecl *temp = specInfo->getTemplate();
396 LinkageInfo tempLV =
397 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
398 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
399
400 // Merge information from the template arguments.
401 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
402 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
403 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
404 }
405
406 /// Does the given declaration have a direct visibility attribute
407 /// that would match the given rules?
hasDirectVisibilityAttribute(const NamedDecl * D,LVComputationKind computation)408 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
409 LVComputationKind computation) {
410 if (computation.IgnoreAllVisibility)
411 return false;
412
413 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
414 D->hasAttr<VisibilityAttr>();
415 }
416
417 /// Should we consider visibility associated with the template
418 /// arguments and parameters of the given class template specialization?
shouldConsiderTemplateVisibility(const ClassTemplateSpecializationDecl * spec,LVComputationKind computation)419 static bool shouldConsiderTemplateVisibility(
420 const ClassTemplateSpecializationDecl *spec,
421 LVComputationKind computation) {
422 // Include visibility from the template parameters and arguments
423 // only if this is not an explicit instantiation or specialization
424 // with direct explicit visibility (and note that implicit
425 // instantiations won't have a direct attribute).
426 //
427 // Furthermore, we want to ignore template parameters and arguments
428 // for an explicit specialization when computing the visibility of a
429 // member thereof with explicit visibility.
430 //
431 // This is a bit complex; let's unpack it.
432 //
433 // An explicit class specialization is an independent, top-level
434 // declaration. As such, if it or any of its members has an
435 // explicit visibility attribute, that must directly express the
436 // user's intent, and we should honor it. The same logic applies to
437 // an explicit instantiation of a member of such a thing.
438
439 // Fast path: if this is not an explicit instantiation or
440 // specialization, we always want to consider template-related
441 // visibility restrictions.
442 if (!spec->isExplicitInstantiationOrSpecialization())
443 return true;
444
445 // This is the 'member thereof' check.
446 if (spec->isExplicitSpecialization() &&
447 hasExplicitVisibilityAlready(computation))
448 return false;
449
450 return !hasDirectVisibilityAttribute(spec, computation);
451 }
452
453 /// Merge in template-related linkage and visibility for the given
454 /// class template specialization.
mergeTemplateLV(LinkageInfo & LV,const ClassTemplateSpecializationDecl * spec,LVComputationKind computation)455 void LinkageComputer::mergeTemplateLV(
456 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
457 LVComputationKind computation) {
458 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
459
460 // Merge information from the template parameters, but ignore
461 // visibility if we're only considering template arguments.
462
463 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
464 LinkageInfo tempLV =
465 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
466 LV.mergeMaybeWithVisibility(tempLV,
467 considerVisibility && !hasExplicitVisibilityAlready(computation));
468
469 // Merge information from the template arguments. We ignore
470 // template-argument visibility if we've got an explicit
471 // instantiation with a visibility attribute.
472 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
473 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
474 if (considerVisibility)
475 LV.mergeVisibility(argsLV);
476 LV.mergeExternalVisibility(argsLV);
477 }
478
479 /// Should we consider visibility associated with the template
480 /// arguments and parameters of the given variable template
481 /// specialization? As usual, follow class template specialization
482 /// logic up to initialization.
shouldConsiderTemplateVisibility(const VarTemplateSpecializationDecl * spec,LVComputationKind computation)483 static bool shouldConsiderTemplateVisibility(
484 const VarTemplateSpecializationDecl *spec,
485 LVComputationKind computation) {
486 // Include visibility from the template parameters and arguments
487 // only if this is not an explicit instantiation or specialization
488 // with direct explicit visibility (and note that implicit
489 // instantiations won't have a direct attribute).
490 if (!spec->isExplicitInstantiationOrSpecialization())
491 return true;
492
493 // An explicit variable specialization is an independent, top-level
494 // declaration. As such, if it has an explicit visibility attribute,
495 // that must directly express the user's intent, and we should honor
496 // it.
497 if (spec->isExplicitSpecialization() &&
498 hasExplicitVisibilityAlready(computation))
499 return false;
500
501 return !hasDirectVisibilityAttribute(spec, computation);
502 }
503
504 /// Merge in template-related linkage and visibility for the given
505 /// variable template specialization. As usual, follow class template
506 /// specialization logic up to initialization.
mergeTemplateLV(LinkageInfo & LV,const VarTemplateSpecializationDecl * spec,LVComputationKind computation)507 void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
508 const VarTemplateSpecializationDecl *spec,
509 LVComputationKind computation) {
510 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
511
512 // Merge information from the template parameters, but ignore
513 // visibility if we're only considering template arguments.
514
515 VarTemplateDecl *temp = spec->getSpecializedTemplate();
516 LinkageInfo tempLV =
517 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
518 LV.mergeMaybeWithVisibility(tempLV,
519 considerVisibility && !hasExplicitVisibilityAlready(computation));
520
521 // Merge information from the template arguments. We ignore
522 // template-argument visibility if we've got an explicit
523 // instantiation with a visibility attribute.
524 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
525 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
526 if (considerVisibility)
527 LV.mergeVisibility(argsLV);
528 LV.mergeExternalVisibility(argsLV);
529 }
530
useInlineVisibilityHidden(const NamedDecl * D)531 static bool useInlineVisibilityHidden(const NamedDecl *D) {
532 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
533 const LangOptions &Opts = D->getASTContext().getLangOpts();
534 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
535 return false;
536
537 const auto *FD = dyn_cast<FunctionDecl>(D);
538 if (!FD)
539 return false;
540
541 TemplateSpecializationKind TSK = TSK_Undeclared;
542 if (FunctionTemplateSpecializationInfo *spec
543 = FD->getTemplateSpecializationInfo()) {
544 TSK = spec->getTemplateSpecializationKind();
545 } else if (MemberSpecializationInfo *MSI =
546 FD->getMemberSpecializationInfo()) {
547 TSK = MSI->getTemplateSpecializationKind();
548 }
549
550 const FunctionDecl *Def = nullptr;
551 // InlineVisibilityHidden only applies to definitions, and
552 // isInlined() only gives meaningful answers on definitions
553 // anyway.
554 return TSK != TSK_ExplicitInstantiationDeclaration &&
555 TSK != TSK_ExplicitInstantiationDefinition &&
556 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
557 }
558
isFirstInExternCContext(T * D)559 template <typename T> static bool isFirstInExternCContext(T *D) {
560 const T *First = D->getFirstDecl();
561 return First->isInExternCContext();
562 }
563
isSingleLineLanguageLinkage(const Decl & D)564 static bool isSingleLineLanguageLinkage(const Decl &D) {
565 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
566 if (!SD->hasBraces())
567 return true;
568 return false;
569 }
570
571 /// Determine whether D is declared in the purview of a named module.
isInModulePurview(const NamedDecl * D)572 static bool isInModulePurview(const NamedDecl *D) {
573 if (auto *M = D->getOwningModule())
574 return M->isModulePurview();
575 return false;
576 }
577
isExportedFromModuleInterfaceUnit(const NamedDecl * D)578 static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
579 // FIXME: Handle isModulePrivate.
580 switch (D->getModuleOwnershipKind()) {
581 case Decl::ModuleOwnershipKind::Unowned:
582 case Decl::ModuleOwnershipKind::ModulePrivate:
583 return false;
584 case Decl::ModuleOwnershipKind::Visible:
585 case Decl::ModuleOwnershipKind::VisibleWhenImported:
586 return isInModulePurview(D);
587 }
588 llvm_unreachable("unexpected module ownership kind");
589 }
590
getInternalLinkageFor(const NamedDecl * D)591 static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
592 // Internal linkage declarations within a module interface unit are modeled
593 // as "module-internal linkage", which means that they have internal linkage
594 // formally but can be indirectly accessed from outside the module via inline
595 // functions and templates defined within the module.
596 if (isInModulePurview(D))
597 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
598
599 return LinkageInfo::internal();
600 }
601
getExternalLinkageFor(const NamedDecl * D)602 static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
603 // C++ Modules TS [basic.link]/6.8:
604 // - A name declared at namespace scope that does not have internal linkage
605 // by the previous rules and that is introduced by a non-exported
606 // declaration has module linkage.
607 if (isInModulePurview(D) && !isExportedFromModuleInterfaceUnit(
608 cast<NamedDecl>(D->getCanonicalDecl())))
609 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
610
611 return LinkageInfo::external();
612 }
613
getStorageClass(const Decl * D)614 static StorageClass getStorageClass(const Decl *D) {
615 if (auto *TD = dyn_cast<TemplateDecl>(D))
616 D = TD->getTemplatedDecl();
617 if (D) {
618 if (auto *VD = dyn_cast<VarDecl>(D))
619 return VD->getStorageClass();
620 if (auto *FD = dyn_cast<FunctionDecl>(D))
621 return FD->getStorageClass();
622 }
623 return SC_None;
624 }
625
626 LinkageInfo
getLVForNamespaceScopeDecl(const NamedDecl * D,LVComputationKind computation,bool IgnoreVarTypeLinkage)627 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
628 LVComputationKind computation,
629 bool IgnoreVarTypeLinkage) {
630 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
631 "Not a name having namespace scope");
632 ASTContext &Context = D->getASTContext();
633
634 // C++ [basic.link]p3:
635 // A name having namespace scope (3.3.6) has internal linkage if it
636 // is the name of
637
638 if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
639 // - a variable, variable template, function, or function template
640 // that is explicitly declared static; or
641 // (This bullet corresponds to C99 6.2.2p3.)
642 return getInternalLinkageFor(D);
643 }
644
645 if (const auto *Var = dyn_cast<VarDecl>(D)) {
646 // - a non-template variable of non-volatile const-qualified type, unless
647 // - it is explicitly declared extern, or
648 // - it is inline or exported, or
649 // - it was previously declared and the prior declaration did not have
650 // internal linkage
651 // (There is no equivalent in C99.)
652 if (Context.getLangOpts().CPlusPlus &&
653 Var->getType().isConstQualified() &&
654 !Var->getType().isVolatileQualified() &&
655 !Var->isInline() &&
656 !isExportedFromModuleInterfaceUnit(Var) &&
657 !isa<VarTemplateSpecializationDecl>(Var) &&
658 !Var->getDescribedVarTemplate()) {
659 const VarDecl *PrevVar = Var->getPreviousDecl();
660 if (PrevVar)
661 return getLVForDecl(PrevVar, computation);
662
663 if (Var->getStorageClass() != SC_Extern &&
664 Var->getStorageClass() != SC_PrivateExtern &&
665 !isSingleLineLanguageLinkage(*Var))
666 return getInternalLinkageFor(Var);
667 }
668
669 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
670 PrevVar = PrevVar->getPreviousDecl()) {
671 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
672 Var->getStorageClass() == SC_None)
673 return getDeclLinkageAndVisibility(PrevVar);
674 // Explicitly declared static.
675 if (PrevVar->getStorageClass() == SC_Static)
676 return getInternalLinkageFor(Var);
677 }
678 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
679 // - a data member of an anonymous union.
680 const VarDecl *VD = IFD->getVarDecl();
681 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
682 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
683 }
684 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
685
686 // FIXME: This gives internal linkage to names that should have no linkage
687 // (those not covered by [basic.link]p6).
688 if (D->isInAnonymousNamespace()) {
689 const auto *Var = dyn_cast<VarDecl>(D);
690 const auto *Func = dyn_cast<FunctionDecl>(D);
691 // FIXME: The check for extern "C" here is not justified by the standard
692 // wording, but we retain it from the pre-DR1113 model to avoid breaking
693 // code.
694 //
695 // C++11 [basic.link]p4:
696 // An unnamed namespace or a namespace declared directly or indirectly
697 // within an unnamed namespace has internal linkage.
698 if ((!Var || !isFirstInExternCContext(Var)) &&
699 (!Func || !isFirstInExternCContext(Func)))
700 return getInternalLinkageFor(D);
701 }
702
703 // Set up the defaults.
704
705 // C99 6.2.2p5:
706 // If the declaration of an identifier for an object has file
707 // scope and no storage-class specifier, its linkage is
708 // external.
709 LinkageInfo LV = getExternalLinkageFor(D);
710
711 if (!hasExplicitVisibilityAlready(computation)) {
712 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
713 LV.mergeVisibility(*Vis, true);
714 } else {
715 // If we're declared in a namespace with a visibility attribute,
716 // use that namespace's visibility, and it still counts as explicit.
717 for (const DeclContext *DC = D->getDeclContext();
718 !isa<TranslationUnitDecl>(DC);
719 DC = DC->getParent()) {
720 const auto *ND = dyn_cast<NamespaceDecl>(DC);
721 if (!ND) continue;
722 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
723 LV.mergeVisibility(*Vis, true);
724 break;
725 }
726 }
727 }
728
729 // Add in global settings if the above didn't give us direct visibility.
730 if (!LV.isVisibilityExplicit()) {
731 // Use global type/value visibility as appropriate.
732 Visibility globalVisibility =
733 computation.isValueVisibility()
734 ? Context.getLangOpts().getValueVisibilityMode()
735 : Context.getLangOpts().getTypeVisibilityMode();
736 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
737
738 // If we're paying attention to global visibility, apply
739 // -finline-visibility-hidden if this is an inline method.
740 if (useInlineVisibilityHidden(D))
741 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
742 }
743 }
744
745 // C++ [basic.link]p4:
746
747 // A name having namespace scope that has not been given internal linkage
748 // above and that is the name of
749 // [...bullets...]
750 // has its linkage determined as follows:
751 // - if the enclosing namespace has internal linkage, the name has
752 // internal linkage; [handled above]
753 // - otherwise, if the declaration of the name is attached to a named
754 // module and is not exported, the name has module linkage;
755 // - otherwise, the name has external linkage.
756 // LV is currently set up to handle the last two bullets.
757 //
758 // The bullets are:
759
760 // - a variable; or
761 if (const auto *Var = dyn_cast<VarDecl>(D)) {
762 // GCC applies the following optimization to variables and static
763 // data members, but not to functions:
764 //
765 // Modify the variable's LV by the LV of its type unless this is
766 // C or extern "C". This follows from [basic.link]p9:
767 // A type without linkage shall not be used as the type of a
768 // variable or function with external linkage unless
769 // - the entity has C language linkage, or
770 // - the entity is declared within an unnamed namespace, or
771 // - the entity is not used or is defined in the same
772 // translation unit.
773 // and [basic.link]p10:
774 // ...the types specified by all declarations referring to a
775 // given variable or function shall be identical...
776 // C does not have an equivalent rule.
777 //
778 // Ignore this if we've got an explicit attribute; the user
779 // probably knows what they're doing.
780 //
781 // Note that we don't want to make the variable non-external
782 // because of this, but unique-external linkage suits us.
783 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
784 !IgnoreVarTypeLinkage) {
785 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
786 if (!isExternallyVisible(TypeLV.getLinkage()))
787 return LinkageInfo::uniqueExternal();
788 if (!LV.isVisibilityExplicit())
789 LV.mergeVisibility(TypeLV);
790 }
791
792 if (Var->getStorageClass() == SC_PrivateExtern)
793 LV.mergeVisibility(HiddenVisibility, true);
794
795 // Note that Sema::MergeVarDecl already takes care of implementing
796 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
797 // to do it here.
798
799 // As per function and class template specializations (below),
800 // consider LV for the template and template arguments. We're at file
801 // scope, so we do not need to worry about nested specializations.
802 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
803 mergeTemplateLV(LV, spec, computation);
804 }
805
806 // - a function; or
807 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
808 // In theory, we can modify the function's LV by the LV of its
809 // type unless it has C linkage (see comment above about variables
810 // for justification). In practice, GCC doesn't do this, so it's
811 // just too painful to make work.
812
813 if (Function->getStorageClass() == SC_PrivateExtern)
814 LV.mergeVisibility(HiddenVisibility, true);
815
816 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
817 // merging storage classes and visibility attributes, so we don't have to
818 // look at previous decls in here.
819
820 // In C++, then if the type of the function uses a type with
821 // unique-external linkage, it's not legally usable from outside
822 // this translation unit. However, we should use the C linkage
823 // rules instead for extern "C" declarations.
824 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
825 // Only look at the type-as-written. Otherwise, deducing the return type
826 // of a function could change its linkage.
827 QualType TypeAsWritten = Function->getType();
828 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
829 TypeAsWritten = TSI->getType();
830 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
831 return LinkageInfo::uniqueExternal();
832 }
833
834 // Consider LV from the template and the template arguments.
835 // We're at file scope, so we do not need to worry about nested
836 // specializations.
837 if (FunctionTemplateSpecializationInfo *specInfo
838 = Function->getTemplateSpecializationInfo()) {
839 mergeTemplateLV(LV, Function, specInfo, computation);
840 }
841
842 // - a named class (Clause 9), or an unnamed class defined in a
843 // typedef declaration in which the class has the typedef name
844 // for linkage purposes (7.1.3); or
845 // - a named enumeration (7.2), or an unnamed enumeration
846 // defined in a typedef declaration in which the enumeration
847 // has the typedef name for linkage purposes (7.1.3); or
848 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
849 // Unnamed tags have no linkage.
850 if (!Tag->hasNameForLinkage())
851 return LinkageInfo::none();
852
853 // If this is a class template specialization, consider the
854 // linkage of the template and template arguments. We're at file
855 // scope, so we do not need to worry about nested specializations.
856 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
857 mergeTemplateLV(LV, spec, computation);
858 }
859
860 // FIXME: This is not part of the C++ standard any more.
861 // - an enumerator belonging to an enumeration with external linkage; or
862 } else if (isa<EnumConstantDecl>(D)) {
863 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
864 computation);
865 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
866 return LinkageInfo::none();
867 LV.merge(EnumLV);
868
869 // - a template
870 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
871 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
872 LinkageInfo tempLV =
873 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
874 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
875
876 // An unnamed namespace or a namespace declared directly or indirectly
877 // within an unnamed namespace has internal linkage. All other namespaces
878 // have external linkage.
879 //
880 // We handled names in anonymous namespaces above.
881 } else if (isa<NamespaceDecl>(D)) {
882 return LV;
883
884 // By extension, we assign external linkage to Objective-C
885 // interfaces.
886 } else if (isa<ObjCInterfaceDecl>(D)) {
887 // fallout
888
889 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
890 // A typedef declaration has linkage if it gives a type a name for
891 // linkage purposes.
892 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
893 return LinkageInfo::none();
894
895 } else if (isa<MSGuidDecl>(D)) {
896 // A GUID behaves like an inline variable with external linkage. Fall
897 // through.
898
899 // Everything not covered here has no linkage.
900 } else {
901 return LinkageInfo::none();
902 }
903
904 // If we ended up with non-externally-visible linkage, visibility should
905 // always be default.
906 if (!isExternallyVisible(LV.getLinkage()))
907 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
908
909 // Mark the symbols as hidden when compiling for the device.
910 if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice)
911 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
912
913 return LV;
914 }
915
916 LinkageInfo
getLVForClassMember(const NamedDecl * D,LVComputationKind computation,bool IgnoreVarTypeLinkage)917 LinkageComputer::getLVForClassMember(const NamedDecl *D,
918 LVComputationKind computation,
919 bool IgnoreVarTypeLinkage) {
920 // Only certain class members have linkage. Note that fields don't
921 // really have linkage, but it's convenient to say they do for the
922 // purposes of calculating linkage of pointer-to-data-member
923 // template arguments.
924 //
925 // Templates also don't officially have linkage, but since we ignore
926 // the C++ standard and look at template arguments when determining
927 // linkage and visibility of a template specialization, we might hit
928 // a template template argument that way. If we do, we need to
929 // consider its linkage.
930 if (!(isa<CXXMethodDecl>(D) ||
931 isa<VarDecl>(D) ||
932 isa<FieldDecl>(D) ||
933 isa<IndirectFieldDecl>(D) ||
934 isa<TagDecl>(D) ||
935 isa<TemplateDecl>(D)))
936 return LinkageInfo::none();
937
938 LinkageInfo LV;
939
940 // If we have an explicit visibility attribute, merge that in.
941 if (!hasExplicitVisibilityAlready(computation)) {
942 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
943 LV.mergeVisibility(*Vis, true);
944 // If we're paying attention to global visibility, apply
945 // -finline-visibility-hidden if this is an inline method.
946 //
947 // Note that we do this before merging information about
948 // the class visibility.
949 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
950 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
951 }
952
953 // If this class member has an explicit visibility attribute, the only
954 // thing that can change its visibility is the template arguments, so
955 // only look for them when processing the class.
956 LVComputationKind classComputation = computation;
957 if (LV.isVisibilityExplicit())
958 classComputation = withExplicitVisibilityAlready(computation);
959
960 LinkageInfo classLV =
961 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
962 // The member has the same linkage as the class. If that's not externally
963 // visible, we don't need to compute anything about the linkage.
964 // FIXME: If we're only computing linkage, can we bail out here?
965 if (!isExternallyVisible(classLV.getLinkage()))
966 return classLV;
967
968
969 // Otherwise, don't merge in classLV yet, because in certain cases
970 // we need to completely ignore the visibility from it.
971
972 // Specifically, if this decl exists and has an explicit attribute.
973 const NamedDecl *explicitSpecSuppressor = nullptr;
974
975 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
976 // Only look at the type-as-written. Otherwise, deducing the return type
977 // of a function could change its linkage.
978 QualType TypeAsWritten = MD->getType();
979 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
980 TypeAsWritten = TSI->getType();
981 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
982 return LinkageInfo::uniqueExternal();
983
984 // If this is a method template specialization, use the linkage for
985 // the template parameters and arguments.
986 if (FunctionTemplateSpecializationInfo *spec
987 = MD->getTemplateSpecializationInfo()) {
988 mergeTemplateLV(LV, MD, spec, computation);
989 if (spec->isExplicitSpecialization()) {
990 explicitSpecSuppressor = MD;
991 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
992 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
993 }
994 } else if (isExplicitMemberSpecialization(MD)) {
995 explicitSpecSuppressor = MD;
996 }
997
998 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
999 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1000 mergeTemplateLV(LV, spec, computation);
1001 if (spec->isExplicitSpecialization()) {
1002 explicitSpecSuppressor = spec;
1003 } else {
1004 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1005 if (isExplicitMemberSpecialization(temp)) {
1006 explicitSpecSuppressor = temp->getTemplatedDecl();
1007 }
1008 }
1009 } else if (isExplicitMemberSpecialization(RD)) {
1010 explicitSpecSuppressor = RD;
1011 }
1012
1013 // Static data members.
1014 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1015 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1016 mergeTemplateLV(LV, spec, computation);
1017
1018 // Modify the variable's linkage by its type, but ignore the
1019 // type's visibility unless it's a definition.
1020 if (!IgnoreVarTypeLinkage) {
1021 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1022 // FIXME: If the type's linkage is not externally visible, we can
1023 // give this static data member UniqueExternalLinkage.
1024 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1025 LV.mergeVisibility(typeLV);
1026 LV.mergeExternalVisibility(typeLV);
1027 }
1028
1029 if (isExplicitMemberSpecialization(VD)) {
1030 explicitSpecSuppressor = VD;
1031 }
1032
1033 // Template members.
1034 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1035 bool considerVisibility =
1036 (!LV.isVisibilityExplicit() &&
1037 !classLV.isVisibilityExplicit() &&
1038 !hasExplicitVisibilityAlready(computation));
1039 LinkageInfo tempLV =
1040 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1041 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1042
1043 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1044 if (isExplicitMemberSpecialization(redeclTemp)) {
1045 explicitSpecSuppressor = temp->getTemplatedDecl();
1046 }
1047 }
1048 }
1049
1050 // We should never be looking for an attribute directly on a template.
1051 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1052
1053 // If this member is an explicit member specialization, and it has
1054 // an explicit attribute, ignore visibility from the parent.
1055 bool considerClassVisibility = true;
1056 if (explicitSpecSuppressor &&
1057 // optimization: hasDVA() is true only with explicit visibility.
1058 LV.isVisibilityExplicit() &&
1059 classLV.getVisibility() != DefaultVisibility &&
1060 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1061 considerClassVisibility = false;
1062 }
1063
1064 // Finally, merge in information from the class.
1065 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1066 return LV;
1067 }
1068
anchor()1069 void NamedDecl::anchor() {}
1070
isLinkageValid() const1071 bool NamedDecl::isLinkageValid() const {
1072 if (!hasCachedLinkage())
1073 return true;
1074
1075 Linkage L = LinkageComputer{}
1076 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1077 .getLinkage();
1078 return L == getCachedLinkage();
1079 }
1080
1081 ReservedIdentifierStatus
isReserved(const LangOptions & LangOpts) const1082 NamedDecl::isReserved(const LangOptions &LangOpts) const {
1083 const IdentifierInfo *II = getIdentifier();
1084 if (!II)
1085 if (const auto *FD = dyn_cast<FunctionDecl>(this))
1086 II = FD->getLiteralIdentifier();
1087
1088 if (!II)
1089 return ReservedIdentifierStatus::NotReserved;
1090
1091 ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1092 if (Status == ReservedIdentifierStatus::StartsWithUnderscoreAtGlobalScope) {
1093 // Check if we're at TU level or not.
1094 if (isa<ParmVarDecl>(this) || isTemplateParameter())
1095 return ReservedIdentifierStatus::NotReserved;
1096 const DeclContext *DC = getDeclContext()->getRedeclContext();
1097 if (!DC->isTranslationUnit())
1098 return ReservedIdentifierStatus::NotReserved;
1099 }
1100
1101 return Status;
1102 }
1103
getObjCFStringFormattingFamily() const1104 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1105 StringRef name = getName();
1106 if (name.empty()) return SFF_None;
1107
1108 if (name.front() == 'C')
1109 if (name == "CFStringCreateWithFormat" ||
1110 name == "CFStringCreateWithFormatAndArguments" ||
1111 name == "CFStringAppendFormat" ||
1112 name == "CFStringAppendFormatAndArguments")
1113 return SFF_CFString;
1114 return SFF_None;
1115 }
1116
getLinkageInternal() const1117 Linkage NamedDecl::getLinkageInternal() const {
1118 // We don't care about visibility here, so ask for the cheapest
1119 // possible visibility analysis.
1120 return LinkageComputer{}
1121 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1122 .getLinkage();
1123 }
1124
getLinkageAndVisibility() const1125 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1126 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
1127 }
1128
1129 static Optional<Visibility>
getExplicitVisibilityAux(const NamedDecl * ND,NamedDecl::ExplicitVisibilityKind kind,bool IsMostRecent)1130 getExplicitVisibilityAux(const NamedDecl *ND,
1131 NamedDecl::ExplicitVisibilityKind kind,
1132 bool IsMostRecent) {
1133 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1134
1135 // Check the declaration itself first.
1136 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1137 return V;
1138
1139 // If this is a member class of a specialization of a class template
1140 // and the corresponding decl has explicit visibility, use that.
1141 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1142 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1143 if (InstantiatedFrom)
1144 return getVisibilityOf(InstantiatedFrom, kind);
1145 }
1146
1147 // If there wasn't explicit visibility there, and this is a
1148 // specialization of a class template, check for visibility
1149 // on the pattern.
1150 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1151 // Walk all the template decl till this point to see if there are
1152 // explicit visibility attributes.
1153 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1154 while (TD != nullptr) {
1155 auto Vis = getVisibilityOf(TD, kind);
1156 if (Vis != None)
1157 return Vis;
1158 TD = TD->getPreviousDecl();
1159 }
1160 return None;
1161 }
1162
1163 // Use the most recent declaration.
1164 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1165 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1166 if (MostRecent != ND)
1167 return getExplicitVisibilityAux(MostRecent, kind, true);
1168 }
1169
1170 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1171 if (Var->isStaticDataMember()) {
1172 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1173 if (InstantiatedFrom)
1174 return getVisibilityOf(InstantiatedFrom, kind);
1175 }
1176
1177 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1178 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1179 kind);
1180
1181 return None;
1182 }
1183 // Also handle function template specializations.
1184 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1185 // If the function is a specialization of a template with an
1186 // explicit visibility attribute, use that.
1187 if (FunctionTemplateSpecializationInfo *templateInfo
1188 = fn->getTemplateSpecializationInfo())
1189 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1190 kind);
1191
1192 // If the function is a member of a specialization of a class template
1193 // and the corresponding decl has explicit visibility, use that.
1194 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1195 if (InstantiatedFrom)
1196 return getVisibilityOf(InstantiatedFrom, kind);
1197
1198 return None;
1199 }
1200
1201 // The visibility of a template is stored in the templated decl.
1202 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1203 return getVisibilityOf(TD->getTemplatedDecl(), kind);
1204
1205 return None;
1206 }
1207
1208 Optional<Visibility>
getExplicitVisibility(ExplicitVisibilityKind kind) const1209 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1210 return getExplicitVisibilityAux(this, kind, false);
1211 }
1212
getLVForClosure(const DeclContext * DC,Decl * ContextDecl,LVComputationKind computation)1213 LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1214 Decl *ContextDecl,
1215 LVComputationKind computation) {
1216 // This lambda has its linkage/visibility determined by its owner.
1217 const NamedDecl *Owner;
1218 if (!ContextDecl)
1219 Owner = dyn_cast<NamedDecl>(DC);
1220 else if (isa<ParmVarDecl>(ContextDecl))
1221 Owner =
1222 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1223 else
1224 Owner = cast<NamedDecl>(ContextDecl);
1225
1226 if (!Owner)
1227 return LinkageInfo::none();
1228
1229 // If the owner has a deduced type, we need to skip querying the linkage and
1230 // visibility of that type, because it might involve this closure type. The
1231 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1232 // than NoLinkage when we don't strictly need to, which is benign.
1233 auto *VD = dyn_cast<VarDecl>(Owner);
1234 LinkageInfo OwnerLV =
1235 VD && VD->getType()->getContainedDeducedType()
1236 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1237 : getLVForDecl(Owner, computation);
1238
1239 // A lambda never formally has linkage. But if the owner is externally
1240 // visible, then the lambda is too. We apply the same rules to blocks.
1241 if (!isExternallyVisible(OwnerLV.getLinkage()))
1242 return LinkageInfo::none();
1243 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1244 OwnerLV.isVisibilityExplicit());
1245 }
1246
getLVForLocalDecl(const NamedDecl * D,LVComputationKind computation)1247 LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1248 LVComputationKind computation) {
1249 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1250 if (Function->isInAnonymousNamespace() &&
1251 !isFirstInExternCContext(Function))
1252 return getInternalLinkageFor(Function);
1253
1254 // This is a "void f();" which got merged with a file static.
1255 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1256 return getInternalLinkageFor(Function);
1257
1258 LinkageInfo LV;
1259 if (!hasExplicitVisibilityAlready(computation)) {
1260 if (Optional<Visibility> Vis =
1261 getExplicitVisibility(Function, computation))
1262 LV.mergeVisibility(*Vis, true);
1263 }
1264
1265 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1266 // merging storage classes and visibility attributes, so we don't have to
1267 // look at previous decls in here.
1268
1269 return LV;
1270 }
1271
1272 if (const auto *Var = dyn_cast<VarDecl>(D)) {
1273 if (Var->hasExternalStorage()) {
1274 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1275 return getInternalLinkageFor(Var);
1276
1277 LinkageInfo LV;
1278 if (Var->getStorageClass() == SC_PrivateExtern)
1279 LV.mergeVisibility(HiddenVisibility, true);
1280 else if (!hasExplicitVisibilityAlready(computation)) {
1281 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1282 LV.mergeVisibility(*Vis, true);
1283 }
1284
1285 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1286 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1287 if (PrevLV.getLinkage())
1288 LV.setLinkage(PrevLV.getLinkage());
1289 LV.mergeVisibility(PrevLV);
1290 }
1291
1292 return LV;
1293 }
1294
1295 if (!Var->isStaticLocal())
1296 return LinkageInfo::none();
1297 }
1298
1299 ASTContext &Context = D->getASTContext();
1300 if (!Context.getLangOpts().CPlusPlus)
1301 return LinkageInfo::none();
1302
1303 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1304 if (!OuterD || OuterD->isInvalidDecl())
1305 return LinkageInfo::none();
1306
1307 LinkageInfo LV;
1308 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1309 if (!BD->getBlockManglingNumber())
1310 return LinkageInfo::none();
1311
1312 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1313 BD->getBlockManglingContextDecl(), computation);
1314 } else {
1315 const auto *FD = cast<FunctionDecl>(OuterD);
1316 if (!FD->isInlined() &&
1317 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1318 return LinkageInfo::none();
1319
1320 // If a function is hidden by -fvisibility-inlines-hidden option and
1321 // is not explicitly attributed as a hidden function,
1322 // we should not make static local variables in the function hidden.
1323 LV = getLVForDecl(FD, computation);
1324 if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1325 !LV.isVisibilityExplicit() &&
1326 !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
1327 assert(cast<VarDecl>(D)->isStaticLocal());
1328 // If this was an implicitly hidden inline method, check again for
1329 // explicit visibility on the parent class, and use that for static locals
1330 // if present.
1331 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1332 LV = getLVForDecl(MD->getParent(), computation);
1333 if (!LV.isVisibilityExplicit()) {
1334 Visibility globalVisibility =
1335 computation.isValueVisibility()
1336 ? Context.getLangOpts().getValueVisibilityMode()
1337 : Context.getLangOpts().getTypeVisibilityMode();
1338 return LinkageInfo(VisibleNoLinkage, globalVisibility,
1339 /*visibilityExplicit=*/false);
1340 }
1341 }
1342 }
1343 if (!isExternallyVisible(LV.getLinkage()))
1344 return LinkageInfo::none();
1345 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1346 LV.isVisibilityExplicit());
1347 }
1348
computeLVForDecl(const NamedDecl * D,LVComputationKind computation,bool IgnoreVarTypeLinkage)1349 LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1350 LVComputationKind computation,
1351 bool IgnoreVarTypeLinkage) {
1352 // Internal_linkage attribute overrides other considerations.
1353 if (D->hasAttr<InternalLinkageAttr>())
1354 return getInternalLinkageFor(D);
1355
1356 // Objective-C: treat all Objective-C declarations as having external
1357 // linkage.
1358 switch (D->getKind()) {
1359 default:
1360 break;
1361
1362 // Per C++ [basic.link]p2, only the names of objects, references,
1363 // functions, types, templates, namespaces, and values ever have linkage.
1364 //
1365 // Note that the name of a typedef, namespace alias, using declaration,
1366 // and so on are not the name of the corresponding type, namespace, or
1367 // declaration, so they do *not* have linkage.
1368 case Decl::ImplicitParam:
1369 case Decl::Label:
1370 case Decl::NamespaceAlias:
1371 case Decl::ParmVar:
1372 case Decl::Using:
1373 case Decl::UsingShadow:
1374 case Decl::UsingDirective:
1375 return LinkageInfo::none();
1376
1377 case Decl::EnumConstant:
1378 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1379 if (D->getASTContext().getLangOpts().CPlusPlus)
1380 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1381 return LinkageInfo::visible_none();
1382
1383 case Decl::Typedef:
1384 case Decl::TypeAlias:
1385 // A typedef declaration has linkage if it gives a type a name for
1386 // linkage purposes.
1387 if (!cast<TypedefNameDecl>(D)
1388 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1389 return LinkageInfo::none();
1390 break;
1391
1392 case Decl::TemplateTemplateParm: // count these as external
1393 case Decl::NonTypeTemplateParm:
1394 case Decl::ObjCAtDefsField:
1395 case Decl::ObjCCategory:
1396 case Decl::ObjCCategoryImpl:
1397 case Decl::ObjCCompatibleAlias:
1398 case Decl::ObjCImplementation:
1399 case Decl::ObjCMethod:
1400 case Decl::ObjCProperty:
1401 case Decl::ObjCPropertyImpl:
1402 case Decl::ObjCProtocol:
1403 return getExternalLinkageFor(D);
1404
1405 case Decl::CXXRecord: {
1406 const auto *Record = cast<CXXRecordDecl>(D);
1407 if (Record->isLambda()) {
1408 if (Record->hasKnownLambdaInternalLinkage() ||
1409 !Record->getLambdaManglingNumber()) {
1410 // This lambda has no mangling number, so it's internal.
1411 return getInternalLinkageFor(D);
1412 }
1413
1414 return getLVForClosure(
1415 Record->getDeclContext()->getRedeclContext(),
1416 Record->getLambdaContextDecl(), computation);
1417 }
1418
1419 break;
1420 }
1421
1422 case Decl::TemplateParamObject: {
1423 // The template parameter object can be referenced from anywhere its type
1424 // and value can be referenced.
1425 auto *TPO = cast<TemplateParamObjectDecl>(D);
1426 LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1427 LV.merge(getLVForValue(TPO->getValue(), computation));
1428 return LV;
1429 }
1430 }
1431
1432 // Handle linkage for namespace-scope names.
1433 if (D->getDeclContext()->getRedeclContext()->isFileContext())
1434 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1435
1436 // C++ [basic.link]p5:
1437 // In addition, a member function, static data member, a named
1438 // class or enumeration of class scope, or an unnamed class or
1439 // enumeration defined in a class-scope typedef declaration such
1440 // that the class or enumeration has the typedef name for linkage
1441 // purposes (7.1.3), has external linkage if the name of the class
1442 // has external linkage.
1443 if (D->getDeclContext()->isRecord())
1444 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1445
1446 // C++ [basic.link]p6:
1447 // The name of a function declared in block scope and the name of
1448 // an object declared by a block scope extern declaration have
1449 // linkage. If there is a visible declaration of an entity with
1450 // linkage having the same name and type, ignoring entities
1451 // declared outside the innermost enclosing namespace scope, the
1452 // block scope declaration declares that same entity and receives
1453 // the linkage of the previous declaration. If there is more than
1454 // one such matching entity, the program is ill-formed. Otherwise,
1455 // if no matching entity is found, the block scope entity receives
1456 // external linkage.
1457 if (D->getDeclContext()->isFunctionOrMethod())
1458 return getLVForLocalDecl(D, computation);
1459
1460 // C++ [basic.link]p6:
1461 // Names not covered by these rules have no linkage.
1462 return LinkageInfo::none();
1463 }
1464
1465 /// getLVForDecl - Get the linkage and visibility for the given declaration.
getLVForDecl(const NamedDecl * D,LVComputationKind computation)1466 LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1467 LVComputationKind computation) {
1468 // Internal_linkage attribute overrides other considerations.
1469 if (D->hasAttr<InternalLinkageAttr>())
1470 return getInternalLinkageFor(D);
1471
1472 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1473 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1474
1475 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1476 return *LI;
1477
1478 LinkageInfo LV = computeLVForDecl(D, computation);
1479 if (D->hasCachedLinkage())
1480 assert(D->getCachedLinkage() == LV.getLinkage());
1481
1482 D->setCachedLinkage(LV.getLinkage());
1483 cache(D, computation, LV);
1484
1485 #ifndef NDEBUG
1486 // In C (because of gnu inline) and in c++ with microsoft extensions an
1487 // static can follow an extern, so we can have two decls with different
1488 // linkages.
1489 const LangOptions &Opts = D->getASTContext().getLangOpts();
1490 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1491 return LV;
1492
1493 // We have just computed the linkage for this decl. By induction we know
1494 // that all other computed linkages match, check that the one we just
1495 // computed also does.
1496 NamedDecl *Old = nullptr;
1497 for (auto I : D->redecls()) {
1498 auto *T = cast<NamedDecl>(I);
1499 if (T == D)
1500 continue;
1501 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1502 Old = T;
1503 break;
1504 }
1505 }
1506 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1507 #endif
1508
1509 return LV;
1510 }
1511
getDeclLinkageAndVisibility(const NamedDecl * D)1512 LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1513 NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D)
1514 ? NamedDecl::VisibilityForType
1515 : NamedDecl::VisibilityForValue;
1516 LVComputationKind CK(EK);
1517 return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1518 ? CK.forLinkageOnly()
1519 : CK);
1520 }
1521
getOwningModuleForLinkage(bool IgnoreLinkage) const1522 Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
1523 Module *M = getOwningModule();
1524 if (!M)
1525 return nullptr;
1526
1527 switch (M->Kind) {
1528 case Module::ModuleMapModule:
1529 // Module map modules have no special linkage semantics.
1530 return nullptr;
1531
1532 case Module::ModuleInterfaceUnit:
1533 return M;
1534
1535 case Module::GlobalModuleFragment: {
1536 // External linkage declarations in the global module have no owning module
1537 // for linkage purposes. But internal linkage declarations in the global
1538 // module fragment of a particular module are owned by that module for
1539 // linkage purposes.
1540 if (IgnoreLinkage)
1541 return nullptr;
1542 bool InternalLinkage;
1543 if (auto *ND = dyn_cast<NamedDecl>(this))
1544 InternalLinkage = !ND->hasExternalFormalLinkage();
1545 else {
1546 auto *NSD = dyn_cast<NamespaceDecl>(this);
1547 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1548 isInAnonymousNamespace();
1549 }
1550 return InternalLinkage ? M->Parent : nullptr;
1551 }
1552
1553 case Module::PrivateModuleFragment:
1554 // The private module fragment is part of its containing module for linkage
1555 // purposes.
1556 return M->Parent;
1557 }
1558
1559 llvm_unreachable("unknown module kind");
1560 }
1561
printName(raw_ostream & os) const1562 void NamedDecl::printName(raw_ostream &os) const {
1563 os << Name;
1564 }
1565
getQualifiedNameAsString() const1566 std::string NamedDecl::getQualifiedNameAsString() const {
1567 std::string QualName;
1568 llvm::raw_string_ostream OS(QualName);
1569 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1570 return OS.str();
1571 }
1572
printQualifiedName(raw_ostream & OS) const1573 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1574 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1575 }
1576
printQualifiedName(raw_ostream & OS,const PrintingPolicy & P) const1577 void NamedDecl::printQualifiedName(raw_ostream &OS,
1578 const PrintingPolicy &P) const {
1579 if (getDeclContext()->isFunctionOrMethod()) {
1580 // We do not print '(anonymous)' for function parameters without name.
1581 printName(OS);
1582 return;
1583 }
1584 printNestedNameSpecifier(OS, P);
1585 if (getDeclName())
1586 OS << *this;
1587 else {
1588 // Give the printName override a chance to pick a different name before we
1589 // fall back to "(anonymous)".
1590 SmallString<64> NameBuffer;
1591 llvm::raw_svector_ostream NameOS(NameBuffer);
1592 printName(NameOS);
1593 if (NameBuffer.empty())
1594 OS << "(anonymous)";
1595 else
1596 OS << NameBuffer;
1597 }
1598 }
1599
printNestedNameSpecifier(raw_ostream & OS) const1600 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1601 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1602 }
1603
printNestedNameSpecifier(raw_ostream & OS,const PrintingPolicy & P) const1604 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1605 const PrintingPolicy &P) const {
1606 const DeclContext *Ctx = getDeclContext();
1607
1608 // For ObjC methods and properties, look through categories and use the
1609 // interface as context.
1610 if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1611 if (auto *ID = MD->getClassInterface())
1612 Ctx = ID;
1613 } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1614 if (auto *MD = PD->getGetterMethodDecl())
1615 if (auto *ID = MD->getClassInterface())
1616 Ctx = ID;
1617 } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1618 if (auto *CI = ID->getContainingInterface())
1619 Ctx = CI;
1620 }
1621
1622 if (Ctx->isFunctionOrMethod())
1623 return;
1624
1625 using ContextsTy = SmallVector<const DeclContext *, 8>;
1626 ContextsTy Contexts;
1627
1628 // Collect named contexts.
1629 DeclarationName NameInScope = getDeclName();
1630 for (; Ctx; Ctx = Ctx->getParent()) {
1631 // Suppress anonymous namespace if requested.
1632 if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1633 cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1634 continue;
1635
1636 // Suppress inline namespace if it doesn't make the result ambiguous.
1637 if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&
1638 cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope))
1639 continue;
1640
1641 // Skip non-named contexts such as linkage specifications and ExportDecls.
1642 const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1643 if (!ND)
1644 continue;
1645
1646 Contexts.push_back(Ctx);
1647 NameInScope = ND->getDeclName();
1648 }
1649
1650 for (unsigned I = Contexts.size(); I != 0; --I) {
1651 const DeclContext *DC = Contexts[I - 1];
1652 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1653 OS << Spec->getName();
1654 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1655 printTemplateArgumentList(
1656 OS, TemplateArgs.asArray(), P,
1657 Spec->getSpecializedTemplate()->getTemplateParameters());
1658 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1659 if (ND->isAnonymousNamespace()) {
1660 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1661 : "(anonymous namespace)");
1662 }
1663 else
1664 OS << *ND;
1665 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1666 if (!RD->getIdentifier())
1667 OS << "(anonymous " << RD->getKindName() << ')';
1668 else
1669 OS << *RD;
1670 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1671 const FunctionProtoType *FT = nullptr;
1672 if (FD->hasWrittenPrototype())
1673 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1674
1675 OS << *FD << '(';
1676 if (FT) {
1677 unsigned NumParams = FD->getNumParams();
1678 for (unsigned i = 0; i < NumParams; ++i) {
1679 if (i)
1680 OS << ", ";
1681 OS << FD->getParamDecl(i)->getType().stream(P);
1682 }
1683
1684 if (FT->isVariadic()) {
1685 if (NumParams > 0)
1686 OS << ", ";
1687 OS << "...";
1688 }
1689 }
1690 OS << ')';
1691 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1692 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1693 // enumerator is declared in the scope that immediately contains
1694 // the enum-specifier. Each scoped enumerator is declared in the
1695 // scope of the enumeration.
1696 // For the case of unscoped enumerator, do not include in the qualified
1697 // name any information about its enum enclosing scope, as its visibility
1698 // is global.
1699 if (ED->isScoped())
1700 OS << *ED;
1701 else
1702 continue;
1703 } else {
1704 OS << *cast<NamedDecl>(DC);
1705 }
1706 OS << "::";
1707 }
1708 }
1709
getNameForDiagnostic(raw_ostream & OS,const PrintingPolicy & Policy,bool Qualified) const1710 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1711 const PrintingPolicy &Policy,
1712 bool Qualified) const {
1713 if (Qualified)
1714 printQualifiedName(OS, Policy);
1715 else
1716 printName(OS);
1717 }
1718
isRedeclarableImpl(Redeclarable<T> *)1719 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1720 return true;
1721 }
isRedeclarableImpl(...)1722 static bool isRedeclarableImpl(...) { return false; }
isRedeclarable(Decl::Kind K)1723 static bool isRedeclarable(Decl::Kind K) {
1724 switch (K) {
1725 #define DECL(Type, Base) \
1726 case Decl::Type: \
1727 return isRedeclarableImpl((Type##Decl *)nullptr);
1728 #define ABSTRACT_DECL(DECL)
1729 #include "clang/AST/DeclNodes.inc"
1730 }
1731 llvm_unreachable("unknown decl kind");
1732 }
1733
declarationReplaces(NamedDecl * OldD,bool IsKnownNewer) const1734 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1735 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1736
1737 // Never replace one imported declaration with another; we need both results
1738 // when re-exporting.
1739 if (OldD->isFromASTFile() && isFromASTFile())
1740 return false;
1741
1742 // A kind mismatch implies that the declaration is not replaced.
1743 if (OldD->getKind() != getKind())
1744 return false;
1745
1746 // For method declarations, we never replace. (Why?)
1747 if (isa<ObjCMethodDecl>(this))
1748 return false;
1749
1750 // For parameters, pick the newer one. This is either an error or (in
1751 // Objective-C) permitted as an extension.
1752 if (isa<ParmVarDecl>(this))
1753 return true;
1754
1755 // Inline namespaces can give us two declarations with the same
1756 // name and kind in the same scope but different contexts; we should
1757 // keep both declarations in this case.
1758 if (!this->getDeclContext()->getRedeclContext()->Equals(
1759 OldD->getDeclContext()->getRedeclContext()))
1760 return false;
1761
1762 // Using declarations can be replaced if they import the same name from the
1763 // same context.
1764 if (auto *UD = dyn_cast<UsingDecl>(this)) {
1765 ASTContext &Context = getASTContext();
1766 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1767 Context.getCanonicalNestedNameSpecifier(
1768 cast<UsingDecl>(OldD)->getQualifier());
1769 }
1770 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1771 ASTContext &Context = getASTContext();
1772 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1773 Context.getCanonicalNestedNameSpecifier(
1774 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1775 }
1776
1777 if (isRedeclarable(getKind())) {
1778 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1779 return false;
1780
1781 if (IsKnownNewer)
1782 return true;
1783
1784 // Check whether this is actually newer than OldD. We want to keep the
1785 // newer declaration. This loop will usually only iterate once, because
1786 // OldD is usually the previous declaration.
1787 for (auto D : redecls()) {
1788 if (D == OldD)
1789 break;
1790
1791 // If we reach the canonical declaration, then OldD is not actually older
1792 // than this one.
1793 //
1794 // FIXME: In this case, we should not add this decl to the lookup table.
1795 if (D->isCanonicalDecl())
1796 return false;
1797 }
1798
1799 // It's a newer declaration of the same kind of declaration in the same
1800 // scope: we want this decl instead of the existing one.
1801 return true;
1802 }
1803
1804 // In all other cases, we need to keep both declarations in case they have
1805 // different visibility. Any attempt to use the name will result in an
1806 // ambiguity if more than one is visible.
1807 return false;
1808 }
1809
hasLinkage() const1810 bool NamedDecl::hasLinkage() const {
1811 return getFormalLinkage() != NoLinkage;
1812 }
1813
getUnderlyingDeclImpl()1814 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1815 NamedDecl *ND = this;
1816 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1817 ND = UD->getTargetDecl();
1818
1819 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1820 return AD->getClassInterface();
1821
1822 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1823 return AD->getNamespace();
1824
1825 return ND;
1826 }
1827
isCXXInstanceMember() const1828 bool NamedDecl::isCXXInstanceMember() const {
1829 if (!isCXXClassMember())
1830 return false;
1831
1832 const NamedDecl *D = this;
1833 if (isa<UsingShadowDecl>(D))
1834 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1835
1836 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1837 return true;
1838 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1839 return MD->isInstance();
1840 return false;
1841 }
1842
1843 //===----------------------------------------------------------------------===//
1844 // DeclaratorDecl Implementation
1845 //===----------------------------------------------------------------------===//
1846
1847 template <typename DeclT>
getTemplateOrInnerLocStart(const DeclT * decl)1848 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1849 if (decl->getNumTemplateParameterLists() > 0)
1850 return decl->getTemplateParameterList(0)->getTemplateLoc();
1851 return decl->getInnerLocStart();
1852 }
1853
getTypeSpecStartLoc() const1854 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1855 TypeSourceInfo *TSI = getTypeSourceInfo();
1856 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1857 return SourceLocation();
1858 }
1859
getTypeSpecEndLoc() const1860 SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1861 TypeSourceInfo *TSI = getTypeSourceInfo();
1862 if (TSI) return TSI->getTypeLoc().getEndLoc();
1863 return SourceLocation();
1864 }
1865
setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)1866 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1867 if (QualifierLoc) {
1868 // Make sure the extended decl info is allocated.
1869 if (!hasExtInfo()) {
1870 // Save (non-extended) type source info pointer.
1871 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1872 // Allocate external info struct.
1873 DeclInfo = new (getASTContext()) ExtInfo;
1874 // Restore savedTInfo into (extended) decl info.
1875 getExtInfo()->TInfo = savedTInfo;
1876 }
1877 // Set qualifier info.
1878 getExtInfo()->QualifierLoc = QualifierLoc;
1879 } else if (hasExtInfo()) {
1880 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1881 getExtInfo()->QualifierLoc = QualifierLoc;
1882 }
1883 }
1884
setTrailingRequiresClause(Expr * TrailingRequiresClause)1885 void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1886 assert(TrailingRequiresClause);
1887 // Make sure the extended decl info is allocated.
1888 if (!hasExtInfo()) {
1889 // Save (non-extended) type source info pointer.
1890 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1891 // Allocate external info struct.
1892 DeclInfo = new (getASTContext()) ExtInfo;
1893 // Restore savedTInfo into (extended) decl info.
1894 getExtInfo()->TInfo = savedTInfo;
1895 }
1896 // Set requires clause info.
1897 getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
1898 }
1899
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)1900 void DeclaratorDecl::setTemplateParameterListsInfo(
1901 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1902 assert(!TPLists.empty());
1903 // Make sure the extended decl info is allocated.
1904 if (!hasExtInfo()) {
1905 // Save (non-extended) type source info pointer.
1906 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1907 // Allocate external info struct.
1908 DeclInfo = new (getASTContext()) ExtInfo;
1909 // Restore savedTInfo into (extended) decl info.
1910 getExtInfo()->TInfo = savedTInfo;
1911 }
1912 // Set the template parameter lists info.
1913 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1914 }
1915
getOuterLocStart() const1916 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1917 return getTemplateOrInnerLocStart(this);
1918 }
1919
1920 // Helper function: returns true if QT is or contains a type
1921 // having a postfix component.
typeIsPostfix(QualType QT)1922 static bool typeIsPostfix(QualType QT) {
1923 while (true) {
1924 const Type* T = QT.getTypePtr();
1925 switch (T->getTypeClass()) {
1926 default:
1927 return false;
1928 case Type::Pointer:
1929 QT = cast<PointerType>(T)->getPointeeType();
1930 break;
1931 case Type::BlockPointer:
1932 QT = cast<BlockPointerType>(T)->getPointeeType();
1933 break;
1934 case Type::MemberPointer:
1935 QT = cast<MemberPointerType>(T)->getPointeeType();
1936 break;
1937 case Type::LValueReference:
1938 case Type::RValueReference:
1939 QT = cast<ReferenceType>(T)->getPointeeType();
1940 break;
1941 case Type::PackExpansion:
1942 QT = cast<PackExpansionType>(T)->getPattern();
1943 break;
1944 case Type::Paren:
1945 case Type::ConstantArray:
1946 case Type::DependentSizedArray:
1947 case Type::IncompleteArray:
1948 case Type::VariableArray:
1949 case Type::FunctionProto:
1950 case Type::FunctionNoProto:
1951 return true;
1952 }
1953 }
1954 }
1955
getSourceRange() const1956 SourceRange DeclaratorDecl::getSourceRange() const {
1957 SourceLocation RangeEnd = getLocation();
1958 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1959 // If the declaration has no name or the type extends past the name take the
1960 // end location of the type.
1961 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1962 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1963 }
1964 return SourceRange(getOuterLocStart(), RangeEnd);
1965 }
1966
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)1967 void QualifierInfo::setTemplateParameterListsInfo(
1968 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1969 // Free previous template parameters (if any).
1970 if (NumTemplParamLists > 0) {
1971 Context.Deallocate(TemplParamLists);
1972 TemplParamLists = nullptr;
1973 NumTemplParamLists = 0;
1974 }
1975 // Set info on matched template parameter lists (if any).
1976 if (!TPLists.empty()) {
1977 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1978 NumTemplParamLists = TPLists.size();
1979 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
1980 }
1981 }
1982
1983 //===----------------------------------------------------------------------===//
1984 // VarDecl Implementation
1985 //===----------------------------------------------------------------------===//
1986
getStorageClassSpecifierString(StorageClass SC)1987 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1988 switch (SC) {
1989 case SC_None: break;
1990 case SC_Auto: return "auto";
1991 case SC_Extern: return "extern";
1992 case SC_PrivateExtern: return "__private_extern__";
1993 case SC_Register: return "register";
1994 case SC_Static: return "static";
1995 }
1996
1997 llvm_unreachable("Invalid storage class");
1998 }
1999
VarDecl(Kind DK,ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass SC)2000 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
2001 SourceLocation StartLoc, SourceLocation IdLoc,
2002 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2003 StorageClass SC)
2004 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2005 redeclarable_base(C) {
2006 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
2007 "VarDeclBitfields too large!");
2008 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
2009 "ParmVarDeclBitfields too large!");
2010 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
2011 "NonParmVarDeclBitfields too large!");
2012 AllBits = 0;
2013 VarDeclBits.SClass = SC;
2014 // Everything else is implicitly initialized to false.
2015 }
2016
Create(ASTContext & C,DeclContext * DC,SourceLocation StartL,SourceLocation IdL,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass S)2017 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
2018 SourceLocation StartL, SourceLocation IdL,
2019 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2020 StorageClass S) {
2021 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
2022 }
2023
CreateDeserialized(ASTContext & C,unsigned ID)2024 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2025 return new (C, ID)
2026 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2027 QualType(), nullptr, SC_None);
2028 }
2029
setStorageClass(StorageClass SC)2030 void VarDecl::setStorageClass(StorageClass SC) {
2031 assert(isLegalForVariable(SC));
2032 VarDeclBits.SClass = SC;
2033 }
2034
getTLSKind() const2035 VarDecl::TLSKind VarDecl::getTLSKind() const {
2036 switch (VarDeclBits.TSCSpec) {
2037 case TSCS_unspecified:
2038 if (!hasAttr<ThreadAttr>() &&
2039 !(getASTContext().getLangOpts().OpenMPUseTLS &&
2040 getASTContext().getTargetInfo().isTLSSupported() &&
2041 hasAttr<OMPThreadPrivateDeclAttr>()))
2042 return TLS_None;
2043 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2044 LangOptions::MSVC2015)) ||
2045 hasAttr<OMPThreadPrivateDeclAttr>())
2046 ? TLS_Dynamic
2047 : TLS_Static;
2048 case TSCS___thread: // Fall through.
2049 case TSCS__Thread_local:
2050 return TLS_Static;
2051 case TSCS_thread_local:
2052 return TLS_Dynamic;
2053 }
2054 llvm_unreachable("Unknown thread storage class specifier!");
2055 }
2056
getSourceRange() const2057 SourceRange VarDecl::getSourceRange() const {
2058 if (const Expr *Init = getInit()) {
2059 SourceLocation InitEnd = Init->getEndLoc();
2060 // If Init is implicit, ignore its source range and fallback on
2061 // DeclaratorDecl::getSourceRange() to handle postfix elements.
2062 if (InitEnd.isValid() && InitEnd != getLocation())
2063 return SourceRange(getOuterLocStart(), InitEnd);
2064 }
2065 return DeclaratorDecl::getSourceRange();
2066 }
2067
2068 template<typename T>
getDeclLanguageLinkage(const T & D)2069 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2070 // C++ [dcl.link]p1: All function types, function names with external linkage,
2071 // and variable names with external linkage have a language linkage.
2072 if (!D.hasExternalFormalLinkage())
2073 return NoLanguageLinkage;
2074
2075 // Language linkage is a C++ concept, but saying that everything else in C has
2076 // C language linkage fits the implementation nicely.
2077 ASTContext &Context = D.getASTContext();
2078 if (!Context.getLangOpts().CPlusPlus)
2079 return CLanguageLinkage;
2080
2081 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2082 // language linkage of the names of class members and the function type of
2083 // class member functions.
2084 const DeclContext *DC = D.getDeclContext();
2085 if (DC->isRecord())
2086 return CXXLanguageLinkage;
2087
2088 // If the first decl is in an extern "C" context, any other redeclaration
2089 // will have C language linkage. If the first one is not in an extern "C"
2090 // context, we would have reported an error for any other decl being in one.
2091 if (isFirstInExternCContext(&D))
2092 return CLanguageLinkage;
2093 return CXXLanguageLinkage;
2094 }
2095
2096 template<typename T>
isDeclExternC(const T & D)2097 static bool isDeclExternC(const T &D) {
2098 // Since the context is ignored for class members, they can only have C++
2099 // language linkage or no language linkage.
2100 const DeclContext *DC = D.getDeclContext();
2101 if (DC->isRecord()) {
2102 assert(D.getASTContext().getLangOpts().CPlusPlus);
2103 return false;
2104 }
2105
2106 return D.getLanguageLinkage() == CLanguageLinkage;
2107 }
2108
getLanguageLinkage() const2109 LanguageLinkage VarDecl::getLanguageLinkage() const {
2110 return getDeclLanguageLinkage(*this);
2111 }
2112
isExternC() const2113 bool VarDecl::isExternC() const {
2114 return isDeclExternC(*this);
2115 }
2116
isInExternCContext() const2117 bool VarDecl::isInExternCContext() const {
2118 return getLexicalDeclContext()->isExternCContext();
2119 }
2120
isInExternCXXContext() const2121 bool VarDecl::isInExternCXXContext() const {
2122 return getLexicalDeclContext()->isExternCXXContext();
2123 }
2124
getCanonicalDecl()2125 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
2126
2127 VarDecl::DefinitionKind
isThisDeclarationADefinition(ASTContext & C) const2128 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
2129 if (isThisDeclarationADemotedDefinition())
2130 return DeclarationOnly;
2131
2132 // C++ [basic.def]p2:
2133 // A declaration is a definition unless [...] it contains the 'extern'
2134 // specifier or a linkage-specification and neither an initializer [...],
2135 // it declares a non-inline static data member in a class declaration [...],
2136 // it declares a static data member outside a class definition and the variable
2137 // was defined within the class with the constexpr specifier [...],
2138 // C++1y [temp.expl.spec]p15:
2139 // An explicit specialization of a static data member or an explicit
2140 // specialization of a static data member template is a definition if the
2141 // declaration includes an initializer; otherwise, it is a declaration.
2142 //
2143 // FIXME: How do you declare (but not define) a partial specialization of
2144 // a static data member template outside the containing class?
2145 if (isStaticDataMember()) {
2146 if (isOutOfLine() &&
2147 !(getCanonicalDecl()->isInline() &&
2148 getCanonicalDecl()->isConstexpr()) &&
2149 (hasInit() ||
2150 // If the first declaration is out-of-line, this may be an
2151 // instantiation of an out-of-line partial specialization of a variable
2152 // template for which we have not yet instantiated the initializer.
2153 (getFirstDecl()->isOutOfLine()
2154 ? getTemplateSpecializationKind() == TSK_Undeclared
2155 : getTemplateSpecializationKind() !=
2156 TSK_ExplicitSpecialization) ||
2157 isa<VarTemplatePartialSpecializationDecl>(this)))
2158 return Definition;
2159 if (!isOutOfLine() && isInline())
2160 return Definition;
2161 return DeclarationOnly;
2162 }
2163 // C99 6.7p5:
2164 // A definition of an identifier is a declaration for that identifier that
2165 // [...] causes storage to be reserved for that object.
2166 // Note: that applies for all non-file-scope objects.
2167 // C99 6.9.2p1:
2168 // If the declaration of an identifier for an object has file scope and an
2169 // initializer, the declaration is an external definition for the identifier
2170 if (hasInit())
2171 return Definition;
2172
2173 if (hasDefiningAttr())
2174 return Definition;
2175
2176 if (const auto *SAA = getAttr<SelectAnyAttr>())
2177 if (!SAA->isInherited())
2178 return Definition;
2179
2180 // A variable template specialization (other than a static data member
2181 // template or an explicit specialization) is a declaration until we
2182 // instantiate its initializer.
2183 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2184 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2185 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2186 !VTSD->IsCompleteDefinition)
2187 return DeclarationOnly;
2188 }
2189
2190 if (hasExternalStorage())
2191 return DeclarationOnly;
2192
2193 // [dcl.link] p7:
2194 // A declaration directly contained in a linkage-specification is treated
2195 // as if it contains the extern specifier for the purpose of determining
2196 // the linkage of the declared name and whether it is a definition.
2197 if (isSingleLineLanguageLinkage(*this))
2198 return DeclarationOnly;
2199
2200 // C99 6.9.2p2:
2201 // A declaration of an object that has file scope without an initializer,
2202 // and without a storage class specifier or the scs 'static', constitutes
2203 // a tentative definition.
2204 // No such thing in C++.
2205 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2206 return TentativeDefinition;
2207
2208 // What's left is (in C, block-scope) declarations without initializers or
2209 // external storage. These are definitions.
2210 return Definition;
2211 }
2212
getActingDefinition()2213 VarDecl *VarDecl::getActingDefinition() {
2214 DefinitionKind Kind = isThisDeclarationADefinition();
2215 if (Kind != TentativeDefinition)
2216 return nullptr;
2217
2218 VarDecl *LastTentative = nullptr;
2219 VarDecl *First = getFirstDecl();
2220 for (auto I : First->redecls()) {
2221 Kind = I->isThisDeclarationADefinition();
2222 if (Kind == Definition)
2223 return nullptr;
2224 if (Kind == TentativeDefinition)
2225 LastTentative = I;
2226 }
2227 return LastTentative;
2228 }
2229
getDefinition(ASTContext & C)2230 VarDecl *VarDecl::getDefinition(ASTContext &C) {
2231 VarDecl *First = getFirstDecl();
2232 for (auto I : First->redecls()) {
2233 if (I->isThisDeclarationADefinition(C) == Definition)
2234 return I;
2235 }
2236 return nullptr;
2237 }
2238
hasDefinition(ASTContext & C) const2239 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2240 DefinitionKind Kind = DeclarationOnly;
2241
2242 const VarDecl *First = getFirstDecl();
2243 for (auto I : First->redecls()) {
2244 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2245 if (Kind == Definition)
2246 break;
2247 }
2248
2249 return Kind;
2250 }
2251
getAnyInitializer(const VarDecl * & D) const2252 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2253 for (auto I : redecls()) {
2254 if (auto Expr = I->getInit()) {
2255 D = I;
2256 return Expr;
2257 }
2258 }
2259 return nullptr;
2260 }
2261
hasInit() const2262 bool VarDecl::hasInit() const {
2263 if (auto *P = dyn_cast<ParmVarDecl>(this))
2264 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2265 return false;
2266
2267 return !Init.isNull();
2268 }
2269
getInit()2270 Expr *VarDecl::getInit() {
2271 if (!hasInit())
2272 return nullptr;
2273
2274 if (auto *S = Init.dyn_cast<Stmt *>())
2275 return cast<Expr>(S);
2276
2277 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2278 }
2279
getInitAddress()2280 Stmt **VarDecl::getInitAddress() {
2281 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2282 return &ES->Value;
2283
2284 return Init.getAddrOfPtr1();
2285 }
2286
getInitializingDeclaration()2287 VarDecl *VarDecl::getInitializingDeclaration() {
2288 VarDecl *Def = nullptr;
2289 for (auto I : redecls()) {
2290 if (I->hasInit())
2291 return I;
2292
2293 if (I->isThisDeclarationADefinition()) {
2294 if (isStaticDataMember())
2295 return I;
2296 Def = I;
2297 }
2298 }
2299 return Def;
2300 }
2301
isOutOfLine() const2302 bool VarDecl::isOutOfLine() const {
2303 if (Decl::isOutOfLine())
2304 return true;
2305
2306 if (!isStaticDataMember())
2307 return false;
2308
2309 // If this static data member was instantiated from a static data member of
2310 // a class template, check whether that static data member was defined
2311 // out-of-line.
2312 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2313 return VD->isOutOfLine();
2314
2315 return false;
2316 }
2317
setInit(Expr * I)2318 void VarDecl::setInit(Expr *I) {
2319 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2320 Eval->~EvaluatedStmt();
2321 getASTContext().Deallocate(Eval);
2322 }
2323
2324 Init = I;
2325 }
2326
mightBeUsableInConstantExpressions(const ASTContext & C) const2327 bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
2328 const LangOptions &Lang = C.getLangOpts();
2329
2330 // OpenCL permits const integral variables to be used in constant
2331 // expressions, like in C++98.
2332 if (!Lang.CPlusPlus && !Lang.OpenCL)
2333 return false;
2334
2335 // Function parameters are never usable in constant expressions.
2336 if (isa<ParmVarDecl>(this))
2337 return false;
2338
2339 // The values of weak variables are never usable in constant expressions.
2340 if (isWeak())
2341 return false;
2342
2343 // In C++11, any variable of reference type can be used in a constant
2344 // expression if it is initialized by a constant expression.
2345 if (Lang.CPlusPlus11 && getType()->isReferenceType())
2346 return true;
2347
2348 // Only const objects can be used in constant expressions in C++. C++98 does
2349 // not require the variable to be non-volatile, but we consider this to be a
2350 // defect.
2351 if (!getType().isConstant(C) || getType().isVolatileQualified())
2352 return false;
2353
2354 // In C++, const, non-volatile variables of integral or enumeration types
2355 // can be used in constant expressions.
2356 if (getType()->isIntegralOrEnumerationType())
2357 return true;
2358
2359 // Additionally, in C++11, non-volatile constexpr variables can be used in
2360 // constant expressions.
2361 return Lang.CPlusPlus11 && isConstexpr();
2362 }
2363
isUsableInConstantExpressions(const ASTContext & Context) const2364 bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
2365 // C++2a [expr.const]p3:
2366 // A variable is usable in constant expressions after its initializing
2367 // declaration is encountered...
2368 const VarDecl *DefVD = nullptr;
2369 const Expr *Init = getAnyInitializer(DefVD);
2370 if (!Init || Init->isValueDependent() || getType()->isDependentType())
2371 return false;
2372 // ... if it is a constexpr variable, or it is of reference type or of
2373 // const-qualified integral or enumeration type, ...
2374 if (!DefVD->mightBeUsableInConstantExpressions(Context))
2375 return false;
2376 // ... and its initializer is a constant initializer.
2377 if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2378 return false;
2379 // C++98 [expr.const]p1:
2380 // An integral constant-expression can involve only [...] const variables
2381 // or static data members of integral or enumeration types initialized with
2382 // [integer] constant expressions (dcl.init)
2383 if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2384 !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2385 return false;
2386 return true;
2387 }
2388
2389 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2390 /// form, which contains extra information on the evaluated value of the
2391 /// initializer.
ensureEvaluatedStmt() const2392 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2393 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2394 if (!Eval) {
2395 // Note: EvaluatedStmt contains an APValue, which usually holds
2396 // resources not allocated from the ASTContext. We need to do some
2397 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2398 // where we can detect whether there's anything to clean up or not.
2399 Eval = new (getASTContext()) EvaluatedStmt;
2400 Eval->Value = Init.get<Stmt *>();
2401 Init = Eval;
2402 }
2403 return Eval;
2404 }
2405
getEvaluatedStmt() const2406 EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2407 return Init.dyn_cast<EvaluatedStmt *>();
2408 }
2409
evaluateValue() const2410 APValue *VarDecl::evaluateValue() const {
2411 SmallVector<PartialDiagnosticAt, 8> Notes;
2412 return evaluateValueImpl(Notes, hasConstantInitialization());
2413 }
2414
evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const2415 APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2416 bool IsConstantInitialization) const {
2417 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2418
2419 const auto *Init = cast<Expr>(Eval->Value);
2420 assert(!Init->isValueDependent());
2421
2422 // We only produce notes indicating why an initializer is non-constant the
2423 // first time it is evaluated. FIXME: The notes won't always be emitted the
2424 // first time we try evaluation, so might not be produced at all.
2425 if (Eval->WasEvaluated)
2426 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2427
2428 if (Eval->IsEvaluating) {
2429 // FIXME: Produce a diagnostic for self-initialization.
2430 return nullptr;
2431 }
2432
2433 Eval->IsEvaluating = true;
2434
2435 ASTContext &Ctx = getASTContext();
2436 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2437 IsConstantInitialization);
2438
2439 // In C++11, this isn't a constant initializer if we produced notes. In that
2440 // case, we can't keep the result, because it may only be correct under the
2441 // assumption that the initializer is a constant context.
2442 if (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11 &&
2443 !Notes.empty())
2444 Result = false;
2445
2446 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2447 // or that it's empty (so that there's nothing to clean up) if evaluation
2448 // failed.
2449 if (!Result)
2450 Eval->Evaluated = APValue();
2451 else if (Eval->Evaluated.needsCleanup())
2452 Ctx.addDestruction(&Eval->Evaluated);
2453
2454 Eval->IsEvaluating = false;
2455 Eval->WasEvaluated = true;
2456
2457 return Result ? &Eval->Evaluated : nullptr;
2458 }
2459
getEvaluatedValue() const2460 APValue *VarDecl::getEvaluatedValue() const {
2461 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2462 if (Eval->WasEvaluated)
2463 return &Eval->Evaluated;
2464
2465 return nullptr;
2466 }
2467
hasICEInitializer(const ASTContext & Context) const2468 bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2469 const Expr *Init = getInit();
2470 assert(Init && "no initializer");
2471
2472 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2473 if (!Eval->CheckedForICEInit) {
2474 Eval->CheckedForICEInit = true;
2475 Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2476 }
2477 return Eval->HasICEInit;
2478 }
2479
hasConstantInitialization() const2480 bool VarDecl::hasConstantInitialization() const {
2481 // In C, all globals (and only globals) have constant initialization.
2482 if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus)
2483 return true;
2484
2485 // In C++, it depends on whether the evaluation at the point of definition
2486 // was evaluatable as a constant initializer.
2487 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2488 return Eval->HasConstantInitialization;
2489
2490 return false;
2491 }
2492
checkForConstantInitialization(SmallVectorImpl<PartialDiagnosticAt> & Notes) const2493 bool VarDecl::checkForConstantInitialization(
2494 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2495 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2496 // If we ask for the value before we know whether we have a constant
2497 // initializer, we can compute the wrong value (for example, due to
2498 // std::is_constant_evaluated()).
2499 assert(!Eval->WasEvaluated &&
2500 "already evaluated var value before checking for constant init");
2501 assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++");
2502
2503 assert(!cast<Expr>(Eval->Value)->isValueDependent());
2504
2505 // Evaluate the initializer to check whether it's a constant expression.
2506 Eval->HasConstantInitialization =
2507 evaluateValueImpl(Notes, true) && Notes.empty();
2508
2509 // If evaluation as a constant initializer failed, allow re-evaluation as a
2510 // non-constant initializer if we later find we want the value.
2511 if (!Eval->HasConstantInitialization)
2512 Eval->WasEvaluated = false;
2513
2514 return Eval->HasConstantInitialization;
2515 }
2516
isParameterPack() const2517 bool VarDecl::isParameterPack() const {
2518 return isa<PackExpansionType>(getType());
2519 }
2520
2521 template<typename DeclT>
getDefinitionOrSelf(DeclT * D)2522 static DeclT *getDefinitionOrSelf(DeclT *D) {
2523 assert(D);
2524 if (auto *Def = D->getDefinition())
2525 return Def;
2526 return D;
2527 }
2528
isEscapingByref() const2529 bool VarDecl::isEscapingByref() const {
2530 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2531 }
2532
isNonEscapingByref() const2533 bool VarDecl::isNonEscapingByref() const {
2534 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2535 }
2536
getTemplateInstantiationPattern() const2537 VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2538 const VarDecl *VD = this;
2539
2540 // If this is an instantiated member, walk back to the template from which
2541 // it was instantiated.
2542 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
2543 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2544 VD = VD->getInstantiatedFromStaticDataMember();
2545 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2546 VD = NewVD;
2547 }
2548 }
2549
2550 // If it's an instantiated variable template specialization, find the
2551 // template or partial specialization from which it was instantiated.
2552 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2553 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2554 auto From = VDTemplSpec->getInstantiatedFrom();
2555 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2556 while (!VTD->isMemberSpecialization()) {
2557 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2558 if (!NewVTD)
2559 break;
2560 VTD = NewVTD;
2561 }
2562 return getDefinitionOrSelf(VTD->getTemplatedDecl());
2563 }
2564 if (auto *VTPSD =
2565 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2566 while (!VTPSD->isMemberSpecialization()) {
2567 auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2568 if (!NewVTPSD)
2569 break;
2570 VTPSD = NewVTPSD;
2571 }
2572 return getDefinitionOrSelf<VarDecl>(VTPSD);
2573 }
2574 }
2575 }
2576
2577 // If this is the pattern of a variable template, find where it was
2578 // instantiated from. FIXME: Is this necessary?
2579 if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2580 while (!VarTemplate->isMemberSpecialization()) {
2581 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2582 if (!NewVT)
2583 break;
2584 VarTemplate = NewVT;
2585 }
2586
2587 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2588 }
2589
2590 if (VD == this)
2591 return nullptr;
2592 return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2593 }
2594
getInstantiatedFromStaticDataMember() const2595 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2596 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2597 return cast<VarDecl>(MSI->getInstantiatedFrom());
2598
2599 return nullptr;
2600 }
2601
getTemplateSpecializationKind() const2602 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2603 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2604 return Spec->getSpecializationKind();
2605
2606 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2607 return MSI->getTemplateSpecializationKind();
2608
2609 return TSK_Undeclared;
2610 }
2611
2612 TemplateSpecializationKind
getTemplateSpecializationKindForInstantiation() const2613 VarDecl::getTemplateSpecializationKindForInstantiation() const {
2614 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2615 return MSI->getTemplateSpecializationKind();
2616
2617 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2618 return Spec->getSpecializationKind();
2619
2620 return TSK_Undeclared;
2621 }
2622
getPointOfInstantiation() const2623 SourceLocation VarDecl::getPointOfInstantiation() const {
2624 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2625 return Spec->getPointOfInstantiation();
2626
2627 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2628 return MSI->getPointOfInstantiation();
2629
2630 return SourceLocation();
2631 }
2632
getDescribedVarTemplate() const2633 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2634 return getASTContext().getTemplateOrSpecializationInfo(this)
2635 .dyn_cast<VarTemplateDecl *>();
2636 }
2637
setDescribedVarTemplate(VarTemplateDecl * Template)2638 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2639 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2640 }
2641
isKnownToBeDefined() const2642 bool VarDecl::isKnownToBeDefined() const {
2643 const auto &LangOpts = getASTContext().getLangOpts();
2644 // In CUDA mode without relocatable device code, variables of form 'extern
2645 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2646 // memory pool. These are never undefined variables, even if they appear
2647 // inside of an anon namespace or static function.
2648 //
2649 // With CUDA relocatable device code enabled, these variables don't get
2650 // special handling; they're treated like regular extern variables.
2651 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2652 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2653 isa<IncompleteArrayType>(getType()))
2654 return true;
2655
2656 return hasDefinition();
2657 }
2658
isNoDestroy(const ASTContext & Ctx) const2659 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2660 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2661 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2662 !hasAttr<AlwaysDestroyAttr>()));
2663 }
2664
2665 QualType::DestructionKind
needsDestruction(const ASTContext & Ctx) const2666 VarDecl::needsDestruction(const ASTContext &Ctx) const {
2667 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2668 if (Eval->HasConstantDestruction)
2669 return QualType::DK_none;
2670
2671 if (isNoDestroy(Ctx))
2672 return QualType::DK_none;
2673
2674 return getType().isDestructedType();
2675 }
2676
getMemberSpecializationInfo() const2677 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2678 if (isStaticDataMember())
2679 // FIXME: Remove ?
2680 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2681 return getASTContext().getTemplateOrSpecializationInfo(this)
2682 .dyn_cast<MemberSpecializationInfo *>();
2683 return nullptr;
2684 }
2685
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)2686 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2687 SourceLocation PointOfInstantiation) {
2688 assert((isa<VarTemplateSpecializationDecl>(this) ||
2689 getMemberSpecializationInfo()) &&
2690 "not a variable or static data member template specialization");
2691
2692 if (VarTemplateSpecializationDecl *Spec =
2693 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2694 Spec->setSpecializationKind(TSK);
2695 if (TSK != TSK_ExplicitSpecialization &&
2696 PointOfInstantiation.isValid() &&
2697 Spec->getPointOfInstantiation().isInvalid()) {
2698 Spec->setPointOfInstantiation(PointOfInstantiation);
2699 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2700 L->InstantiationRequested(this);
2701 }
2702 } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2703 MSI->setTemplateSpecializationKind(TSK);
2704 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2705 MSI->getPointOfInstantiation().isInvalid()) {
2706 MSI->setPointOfInstantiation(PointOfInstantiation);
2707 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2708 L->InstantiationRequested(this);
2709 }
2710 }
2711 }
2712
2713 void
setInstantiationOfStaticDataMember(VarDecl * VD,TemplateSpecializationKind TSK)2714 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2715 TemplateSpecializationKind TSK) {
2716 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2717 "Previous template or instantiation?");
2718 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2719 }
2720
2721 //===----------------------------------------------------------------------===//
2722 // ParmVarDecl Implementation
2723 //===----------------------------------------------------------------------===//
2724
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass S,Expr * DefArg)2725 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2726 SourceLocation StartLoc,
2727 SourceLocation IdLoc, IdentifierInfo *Id,
2728 QualType T, TypeSourceInfo *TInfo,
2729 StorageClass S, Expr *DefArg) {
2730 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2731 S, DefArg);
2732 }
2733
getOriginalType() const2734 QualType ParmVarDecl::getOriginalType() const {
2735 TypeSourceInfo *TSI = getTypeSourceInfo();
2736 QualType T = TSI ? TSI->getType() : getType();
2737 if (const auto *DT = dyn_cast<DecayedType>(T))
2738 return DT->getOriginalType();
2739 return T;
2740 }
2741
CreateDeserialized(ASTContext & C,unsigned ID)2742 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2743 return new (C, ID)
2744 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2745 nullptr, QualType(), nullptr, SC_None, nullptr);
2746 }
2747
getSourceRange() const2748 SourceRange ParmVarDecl::getSourceRange() const {
2749 if (!hasInheritedDefaultArg()) {
2750 SourceRange ArgRange = getDefaultArgRange();
2751 if (ArgRange.isValid())
2752 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2753 }
2754
2755 // DeclaratorDecl considers the range of postfix types as overlapping with the
2756 // declaration name, but this is not the case with parameters in ObjC methods.
2757 if (isa<ObjCMethodDecl>(getDeclContext()))
2758 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2759
2760 return DeclaratorDecl::getSourceRange();
2761 }
2762
isDestroyedInCallee() const2763 bool ParmVarDecl::isDestroyedInCallee() const {
2764 if (hasAttr<NSConsumedAttr>())
2765 return true;
2766
2767 auto *RT = getType()->getAs<RecordType>();
2768 if (RT && RT->getDecl()->isParamDestroyedInCallee())
2769 return true;
2770
2771 return false;
2772 }
2773
getDefaultArg()2774 Expr *ParmVarDecl::getDefaultArg() {
2775 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2776 assert(!hasUninstantiatedDefaultArg() &&
2777 "Default argument is not yet instantiated!");
2778
2779 Expr *Arg = getInit();
2780 if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
2781 return E->getSubExpr();
2782
2783 return Arg;
2784 }
2785
setDefaultArg(Expr * defarg)2786 void ParmVarDecl::setDefaultArg(Expr *defarg) {
2787 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2788 Init = defarg;
2789 }
2790
getDefaultArgRange() const2791 SourceRange ParmVarDecl::getDefaultArgRange() const {
2792 switch (ParmVarDeclBits.DefaultArgKind) {
2793 case DAK_None:
2794 case DAK_Unparsed:
2795 // Nothing we can do here.
2796 return SourceRange();
2797
2798 case DAK_Uninstantiated:
2799 return getUninstantiatedDefaultArg()->getSourceRange();
2800
2801 case DAK_Normal:
2802 if (const Expr *E = getInit())
2803 return E->getSourceRange();
2804
2805 // Missing an actual expression, may be invalid.
2806 return SourceRange();
2807 }
2808 llvm_unreachable("Invalid default argument kind.");
2809 }
2810
setUninstantiatedDefaultArg(Expr * arg)2811 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2812 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2813 Init = arg;
2814 }
2815
getUninstantiatedDefaultArg()2816 Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2817 assert(hasUninstantiatedDefaultArg() &&
2818 "Wrong kind of initialization expression!");
2819 return cast_or_null<Expr>(Init.get<Stmt *>());
2820 }
2821
hasDefaultArg() const2822 bool ParmVarDecl::hasDefaultArg() const {
2823 // FIXME: We should just return false for DAK_None here once callers are
2824 // prepared for the case that we encountered an invalid default argument and
2825 // were unable to even build an invalid expression.
2826 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2827 !Init.isNull();
2828 }
2829
setParameterIndexLarge(unsigned parameterIndex)2830 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2831 getASTContext().setParameterIndex(this, parameterIndex);
2832 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2833 }
2834
getParameterIndexLarge() const2835 unsigned ParmVarDecl::getParameterIndexLarge() const {
2836 return getASTContext().getParameterIndex(this);
2837 }
2838
2839 //===----------------------------------------------------------------------===//
2840 // FunctionDecl Implementation
2841 //===----------------------------------------------------------------------===//
2842
FunctionDecl(Kind DK,ASTContext & C,DeclContext * DC,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,StorageClass S,bool isInlineSpecified,ConstexprSpecKind ConstexprKind,Expr * TrailingRequiresClause)2843 FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2844 SourceLocation StartLoc,
2845 const DeclarationNameInfo &NameInfo, QualType T,
2846 TypeSourceInfo *TInfo, StorageClass S,
2847 bool isInlineSpecified,
2848 ConstexprSpecKind ConstexprKind,
2849 Expr *TrailingRequiresClause)
2850 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2851 StartLoc),
2852 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
2853 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
2854 assert(T.isNull() || T->isFunctionType());
2855 FunctionDeclBits.SClass = S;
2856 FunctionDeclBits.IsInline = isInlineSpecified;
2857 FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
2858 FunctionDeclBits.IsVirtualAsWritten = false;
2859 FunctionDeclBits.IsPure = false;
2860 FunctionDeclBits.HasInheritedPrototype = false;
2861 FunctionDeclBits.HasWrittenPrototype = true;
2862 FunctionDeclBits.IsDeleted = false;
2863 FunctionDeclBits.IsTrivial = false;
2864 FunctionDeclBits.IsTrivialForCall = false;
2865 FunctionDeclBits.IsDefaulted = false;
2866 FunctionDeclBits.IsExplicitlyDefaulted = false;
2867 FunctionDeclBits.HasDefaultedFunctionInfo = false;
2868 FunctionDeclBits.HasImplicitReturnZero = false;
2869 FunctionDeclBits.IsLateTemplateParsed = false;
2870 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
2871 FunctionDeclBits.InstantiationIsPending = false;
2872 FunctionDeclBits.UsesSEHTry = false;
2873 FunctionDeclBits.UsesFPIntrin = false;
2874 FunctionDeclBits.HasSkippedBody = false;
2875 FunctionDeclBits.WillHaveBody = false;
2876 FunctionDeclBits.IsMultiVersion = false;
2877 FunctionDeclBits.IsCopyDeductionCandidate = false;
2878 FunctionDeclBits.HasODRHash = false;
2879 if (TrailingRequiresClause)
2880 setTrailingRequiresClause(TrailingRequiresClause);
2881 }
2882
getNameForDiagnostic(raw_ostream & OS,const PrintingPolicy & Policy,bool Qualified) const2883 void FunctionDecl::getNameForDiagnostic(
2884 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2885 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2886 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2887 if (TemplateArgs)
2888 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
2889 }
2890
isVariadic() const2891 bool FunctionDecl::isVariadic() const {
2892 if (const auto *FT = getType()->getAs<FunctionProtoType>())
2893 return FT->isVariadic();
2894 return false;
2895 }
2896
2897 FunctionDecl::DefaultedFunctionInfo *
Create(ASTContext & Context,ArrayRef<DeclAccessPair> Lookups)2898 FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
2899 ArrayRef<DeclAccessPair> Lookups) {
2900 DefaultedFunctionInfo *Info = new (Context.Allocate(
2901 totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
2902 std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
2903 DefaultedFunctionInfo;
2904 Info->NumLookups = Lookups.size();
2905 std::uninitialized_copy(Lookups.begin(), Lookups.end(),
2906 Info->getTrailingObjects<DeclAccessPair>());
2907 return Info;
2908 }
2909
setDefaultedFunctionInfo(DefaultedFunctionInfo * Info)2910 void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
2911 assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
2912 assert(!Body && "can't replace function body with defaulted function info");
2913
2914 FunctionDeclBits.HasDefaultedFunctionInfo = true;
2915 DefaultedInfo = Info;
2916 }
2917
2918 FunctionDecl::DefaultedFunctionInfo *
getDefaultedFunctionInfo() const2919 FunctionDecl::getDefaultedFunctionInfo() const {
2920 return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
2921 }
2922
hasBody(const FunctionDecl * & Definition) const2923 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2924 for (auto I : redecls()) {
2925 if (I->doesThisDeclarationHaveABody()) {
2926 Definition = I;
2927 return true;
2928 }
2929 }
2930
2931 return false;
2932 }
2933
hasTrivialBody() const2934 bool FunctionDecl::hasTrivialBody() const {
2935 Stmt *S = getBody();
2936 if (!S) {
2937 // Since we don't have a body for this function, we don't know if it's
2938 // trivial or not.
2939 return false;
2940 }
2941
2942 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2943 return true;
2944 return false;
2945 }
2946
isThisDeclarationInstantiatedFromAFriendDefinition() const2947 bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {
2948 if (!getFriendObjectKind())
2949 return false;
2950
2951 // Check for a friend function instantiated from a friend function
2952 // definition in a templated class.
2953 if (const FunctionDecl *InstantiatedFrom =
2954 getInstantiatedFromMemberFunction())
2955 return InstantiatedFrom->getFriendObjectKind() &&
2956 InstantiatedFrom->isThisDeclarationADefinition();
2957
2958 // Check for a friend function template instantiated from a friend
2959 // function template definition in a templated class.
2960 if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
2961 if (const FunctionTemplateDecl *InstantiatedFrom =
2962 Template->getInstantiatedFromMemberTemplate())
2963 return InstantiatedFrom->getFriendObjectKind() &&
2964 InstantiatedFrom->isThisDeclarationADefinition();
2965 }
2966
2967 return false;
2968 }
2969
isDefined(const FunctionDecl * & Definition,bool CheckForPendingFriendDefinition) const2970 bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
2971 bool CheckForPendingFriendDefinition) const {
2972 for (const FunctionDecl *FD : redecls()) {
2973 if (FD->isThisDeclarationADefinition()) {
2974 Definition = FD;
2975 return true;
2976 }
2977
2978 // If this is a friend function defined in a class template, it does not
2979 // have a body until it is used, nevertheless it is a definition, see
2980 // [temp.inst]p2:
2981 //
2982 // ... for the purpose of determining whether an instantiated redeclaration
2983 // is valid according to [basic.def.odr] and [class.mem], a declaration that
2984 // corresponds to a definition in the template is considered to be a
2985 // definition.
2986 //
2987 // The following code must produce redefinition error:
2988 //
2989 // template<typename T> struct C20 { friend void func_20() {} };
2990 // C20<int> c20i;
2991 // void func_20() {}
2992 //
2993 if (CheckForPendingFriendDefinition &&
2994 FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
2995 Definition = FD;
2996 return true;
2997 }
2998 }
2999
3000 return false;
3001 }
3002
getBody(const FunctionDecl * & Definition) const3003 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
3004 if (!hasBody(Definition))
3005 return nullptr;
3006
3007 assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
3008 "definition should not have a body");
3009 if (Definition->Body)
3010 return Definition->Body.get(getASTContext().getExternalSource());
3011
3012 return nullptr;
3013 }
3014
setBody(Stmt * B)3015 void FunctionDecl::setBody(Stmt *B) {
3016 FunctionDeclBits.HasDefaultedFunctionInfo = false;
3017 Body = LazyDeclStmtPtr(B);
3018 if (B)
3019 EndRangeLoc = B->getEndLoc();
3020 }
3021
setPure(bool P)3022 void FunctionDecl::setPure(bool P) {
3023 FunctionDeclBits.IsPure = P;
3024 if (P)
3025 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
3026 Parent->markedVirtualFunctionPure();
3027 }
3028
3029 template<std::size_t Len>
isNamed(const NamedDecl * ND,const char (& Str)[Len])3030 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3031 IdentifierInfo *II = ND->getIdentifier();
3032 return II && II->isStr(Str);
3033 }
3034
isMain() const3035 bool FunctionDecl::isMain() const {
3036 const TranslationUnitDecl *tunit =
3037 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3038 return tunit &&
3039 !tunit->getASTContext().getLangOpts().Freestanding &&
3040 isNamed(this, "main");
3041 }
3042
isMSVCRTEntryPoint() const3043 bool FunctionDecl::isMSVCRTEntryPoint() const {
3044 const TranslationUnitDecl *TUnit =
3045 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3046 if (!TUnit)
3047 return false;
3048
3049 // Even though we aren't really targeting MSVCRT if we are freestanding,
3050 // semantic analysis for these functions remains the same.
3051
3052 // MSVCRT entry points only exist on MSVCRT targets.
3053 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
3054 return false;
3055
3056 // Nameless functions like constructors cannot be entry points.
3057 if (!getIdentifier())
3058 return false;
3059
3060 return llvm::StringSwitch<bool>(getName())
3061 .Cases("main", // an ANSI console app
3062 "wmain", // a Unicode console App
3063 "WinMain", // an ANSI GUI app
3064 "wWinMain", // a Unicode GUI app
3065 "DllMain", // a DLL
3066 true)
3067 .Default(false);
3068 }
3069
isReservedGlobalPlacementOperator() const3070 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
3071 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
3072 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
3073 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3074 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
3075 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
3076
3077 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3078 return false;
3079
3080 const auto *proto = getType()->castAs<FunctionProtoType>();
3081 if (proto->getNumParams() != 2 || proto->isVariadic())
3082 return false;
3083
3084 ASTContext &Context =
3085 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3086 ->getASTContext();
3087
3088 // The result type and first argument type are constant across all
3089 // these operators. The second argument must be exactly void*.
3090 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3091 }
3092
isReplaceableGlobalAllocationFunction(Optional<unsigned> * AlignmentParam,bool * IsNothrow) const3093 bool FunctionDecl::isReplaceableGlobalAllocationFunction(
3094 Optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
3095 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3096 return false;
3097 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3098 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3099 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3100 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3101 return false;
3102
3103 if (isa<CXXRecordDecl>(getDeclContext()))
3104 return false;
3105
3106 // This can only fail for an invalid 'operator new' declaration.
3107 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3108 return false;
3109
3110 const auto *FPT = getType()->castAs<FunctionProtoType>();
3111 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
3112 return false;
3113
3114 // If this is a single-parameter function, it must be a replaceable global
3115 // allocation or deallocation function.
3116 if (FPT->getNumParams() == 1)
3117 return true;
3118
3119 unsigned Params = 1;
3120 QualType Ty = FPT->getParamType(Params);
3121 ASTContext &Ctx = getASTContext();
3122
3123 auto Consume = [&] {
3124 ++Params;
3125 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3126 };
3127
3128 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3129 bool IsSizedDelete = false;
3130 if (Ctx.getLangOpts().SizedDeallocation &&
3131 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3132 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3133 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3134 IsSizedDelete = true;
3135 Consume();
3136 }
3137
3138 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3139 // new/delete.
3140 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3141 Consume();
3142 if (AlignmentParam)
3143 *AlignmentParam = Params;
3144 }
3145
3146 // Finally, if this is not a sized delete, the final parameter can
3147 // be a 'const std::nothrow_t&'.
3148 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3149 Ty = Ty->getPointeeType();
3150 if (Ty.getCVRQualifiers() != Qualifiers::Const)
3151 return false;
3152 if (Ty->isNothrowT()) {
3153 if (IsNothrow)
3154 *IsNothrow = true;
3155 Consume();
3156 }
3157 }
3158
3159 return Params == FPT->getNumParams();
3160 }
3161
isInlineBuiltinDeclaration() const3162 bool FunctionDecl::isInlineBuiltinDeclaration() const {
3163 if (!getBuiltinID())
3164 return false;
3165
3166 const FunctionDecl *Definition;
3167 return hasBody(Definition) && Definition->isInlineSpecified();
3168 }
3169
isDestroyingOperatorDelete() const3170 bool FunctionDecl::isDestroyingOperatorDelete() const {
3171 // C++ P0722:
3172 // Within a class C, a single object deallocation function with signature
3173 // (T, std::destroying_delete_t, <more params>)
3174 // is a destroying operator delete.
3175 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3176 getNumParams() < 2)
3177 return false;
3178
3179 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3180 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3181 RD->getIdentifier()->isStr("destroying_delete_t");
3182 }
3183
getLanguageLinkage() const3184 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
3185 return getDeclLanguageLinkage(*this);
3186 }
3187
isExternC() const3188 bool FunctionDecl::isExternC() const {
3189 return isDeclExternC(*this);
3190 }
3191
isInExternCContext() const3192 bool FunctionDecl::isInExternCContext() const {
3193 if (hasAttr<OpenCLKernelAttr>())
3194 return true;
3195 return getLexicalDeclContext()->isExternCContext();
3196 }
3197
isInExternCXXContext() const3198 bool FunctionDecl::isInExternCXXContext() const {
3199 return getLexicalDeclContext()->isExternCXXContext();
3200 }
3201
isGlobal() const3202 bool FunctionDecl::isGlobal() const {
3203 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3204 return Method->isStatic();
3205
3206 if (getCanonicalDecl()->getStorageClass() == SC_Static)
3207 return false;
3208
3209 for (const DeclContext *DC = getDeclContext();
3210 DC->isNamespace();
3211 DC = DC->getParent()) {
3212 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3213 if (!Namespace->getDeclName())
3214 return false;
3215 break;
3216 }
3217 }
3218
3219 return true;
3220 }
3221
isNoReturn() const3222 bool FunctionDecl::isNoReturn() const {
3223 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3224 hasAttr<C11NoReturnAttr>())
3225 return true;
3226
3227 if (auto *FnTy = getType()->getAs<FunctionType>())
3228 return FnTy->getNoReturnAttr();
3229
3230 return false;
3231 }
3232
3233
getMultiVersionKind() const3234 MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3235 if (hasAttr<TargetAttr>())
3236 return MultiVersionKind::Target;
3237 if (hasAttr<CPUDispatchAttr>())
3238 return MultiVersionKind::CPUDispatch;
3239 if (hasAttr<CPUSpecificAttr>())
3240 return MultiVersionKind::CPUSpecific;
3241 return MultiVersionKind::None;
3242 }
3243
isCPUDispatchMultiVersion() const3244 bool FunctionDecl::isCPUDispatchMultiVersion() const {
3245 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3246 }
3247
isCPUSpecificMultiVersion() const3248 bool FunctionDecl::isCPUSpecificMultiVersion() const {
3249 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3250 }
3251
isTargetMultiVersion() const3252 bool FunctionDecl::isTargetMultiVersion() const {
3253 return isMultiVersion() && hasAttr<TargetAttr>();
3254 }
3255
3256 void
setPreviousDeclaration(FunctionDecl * PrevDecl)3257 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
3258 redeclarable_base::setPreviousDecl(PrevDecl);
3259
3260 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3261 FunctionTemplateDecl *PrevFunTmpl
3262 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3263 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3264 FunTmpl->setPreviousDecl(PrevFunTmpl);
3265 }
3266
3267 if (PrevDecl && PrevDecl->isInlined())
3268 setImplicitlyInline(true);
3269 }
3270
getCanonicalDecl()3271 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
3272
3273 /// Returns a value indicating whether this function corresponds to a builtin
3274 /// function.
3275 ///
3276 /// The function corresponds to a built-in function if it is declared at
3277 /// translation scope or within an extern "C" block and its name matches with
3278 /// the name of a builtin. The returned value will be 0 for functions that do
3279 /// not correspond to a builtin, a value of type \c Builtin::ID if in the
3280 /// target-independent range \c [1,Builtin::First), or a target-specific builtin
3281 /// value.
3282 ///
3283 /// \param ConsiderWrapperFunctions If true, we should consider wrapper
3284 /// functions as their wrapped builtins. This shouldn't be done in general, but
3285 /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
getBuiltinID(bool ConsiderWrapperFunctions) const3286 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3287 unsigned BuiltinID = 0;
3288
3289 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3290 BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3291 } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3292 BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3293 } else if (const auto *A = getAttr<BuiltinAttr>()) {
3294 BuiltinID = A->getID();
3295 }
3296
3297 if (!BuiltinID)
3298 return 0;
3299
3300 // If the function is marked "overloadable", it has a different mangled name
3301 // and is not the C library function.
3302 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3303 (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
3304 return 0;
3305
3306 ASTContext &Context = getASTContext();
3307 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3308 return BuiltinID;
3309
3310 // This function has the name of a known C library
3311 // function. Determine whether it actually refers to the C library
3312 // function or whether it just has the same name.
3313
3314 // If this is a static function, it's not a builtin.
3315 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3316 return 0;
3317
3318 // OpenCL v1.2 s6.9.f - The library functions defined in
3319 // the C99 standard headers are not available.
3320 if (Context.getLangOpts().OpenCL &&
3321 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3322 return 0;
3323
3324 // CUDA does not have device-side standard library. printf and malloc are the
3325 // only special cases that are supported by device-side runtime.
3326 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3327 !hasAttr<CUDAHostAttr>() &&
3328 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3329 return 0;
3330
3331 // As AMDGCN implementation of OpenMP does not have a device-side standard
3332 // library, none of the predefined library functions except printf and malloc
3333 // should be treated as a builtin i.e. 0 should be returned for them.
3334 if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3335 Context.getLangOpts().OpenMPIsDevice &&
3336 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3337 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3338 return 0;
3339
3340 return BuiltinID;
3341 }
3342
3343 /// getNumParams - Return the number of parameters this function must have
3344 /// based on its FunctionType. This is the length of the ParamInfo array
3345 /// after it has been created.
getNumParams() const3346 unsigned FunctionDecl::getNumParams() const {
3347 const auto *FPT = getType()->getAs<FunctionProtoType>();
3348 return FPT ? FPT->getNumParams() : 0;
3349 }
3350
setParams(ASTContext & C,ArrayRef<ParmVarDecl * > NewParamInfo)3351 void FunctionDecl::setParams(ASTContext &C,
3352 ArrayRef<ParmVarDecl *> NewParamInfo) {
3353 assert(!ParamInfo && "Already has param info!");
3354 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3355
3356 // Zero params -> null pointer.
3357 if (!NewParamInfo.empty()) {
3358 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3359 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3360 }
3361 }
3362
3363 /// getMinRequiredArguments - Returns the minimum number of arguments
3364 /// needed to call this function. This may be fewer than the number of
3365 /// function parameters, if some of the parameters have default
3366 /// arguments (in C++) or are parameter packs (C++11).
getMinRequiredArguments() const3367 unsigned FunctionDecl::getMinRequiredArguments() const {
3368 if (!getASTContext().getLangOpts().CPlusPlus)
3369 return getNumParams();
3370
3371 // Note that it is possible for a parameter with no default argument to
3372 // follow a parameter with a default argument.
3373 unsigned NumRequiredArgs = 0;
3374 unsigned MinParamsSoFar = 0;
3375 for (auto *Param : parameters()) {
3376 if (!Param->isParameterPack()) {
3377 ++MinParamsSoFar;
3378 if (!Param->hasDefaultArg())
3379 NumRequiredArgs = MinParamsSoFar;
3380 }
3381 }
3382 return NumRequiredArgs;
3383 }
3384
hasOneParamOrDefaultArgs() const3385 bool FunctionDecl::hasOneParamOrDefaultArgs() const {
3386 return getNumParams() == 1 ||
3387 (getNumParams() > 1 &&
3388 std::all_of(param_begin() + 1, param_end(),
3389 [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3390 }
3391
3392 /// The combination of the extern and inline keywords under MSVC forces
3393 /// the function to be required.
3394 ///
3395 /// Note: This function assumes that we will only get called when isInlined()
3396 /// would return true for this FunctionDecl.
isMSExternInline() const3397 bool FunctionDecl::isMSExternInline() const {
3398 assert(isInlined() && "expected to get called on an inlined function!");
3399
3400 const ASTContext &Context = getASTContext();
3401 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3402 !hasAttr<DLLExportAttr>())
3403 return false;
3404
3405 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3406 FD = FD->getPreviousDecl())
3407 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3408 return true;
3409
3410 return false;
3411 }
3412
redeclForcesDefMSVC(const FunctionDecl * Redecl)3413 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3414 if (Redecl->getStorageClass() != SC_Extern)
3415 return false;
3416
3417 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3418 FD = FD->getPreviousDecl())
3419 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3420 return false;
3421
3422 return true;
3423 }
3424
RedeclForcesDefC99(const FunctionDecl * Redecl)3425 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3426 // Only consider file-scope declarations in this test.
3427 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3428 return false;
3429
3430 // Only consider explicit declarations; the presence of a builtin for a
3431 // libcall shouldn't affect whether a definition is externally visible.
3432 if (Redecl->isImplicit())
3433 return false;
3434
3435 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3436 return true; // Not an inline definition
3437
3438 return false;
3439 }
3440
3441 /// For a function declaration in C or C++, determine whether this
3442 /// declaration causes the definition to be externally visible.
3443 ///
3444 /// For instance, this determines if adding the current declaration to the set
3445 /// of redeclarations of the given functions causes
3446 /// isInlineDefinitionExternallyVisible to change from false to true.
doesDeclarationForceExternallyVisibleDefinition() const3447 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3448 assert(!doesThisDeclarationHaveABody() &&
3449 "Must have a declaration without a body.");
3450
3451 ASTContext &Context = getASTContext();
3452
3453 if (Context.getLangOpts().MSVCCompat) {
3454 const FunctionDecl *Definition;
3455 if (hasBody(Definition) && Definition->isInlined() &&
3456 redeclForcesDefMSVC(this))
3457 return true;
3458 }
3459
3460 if (Context.getLangOpts().CPlusPlus)
3461 return false;
3462
3463 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3464 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3465 // an externally visible definition.
3466 //
3467 // FIXME: What happens if gnu_inline gets added on after the first
3468 // declaration?
3469 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
3470 return false;
3471
3472 const FunctionDecl *Prev = this;
3473 bool FoundBody = false;
3474 while ((Prev = Prev->getPreviousDecl())) {
3475 FoundBody |= Prev->doesThisDeclarationHaveABody();
3476
3477 if (Prev->doesThisDeclarationHaveABody()) {
3478 // If it's not the case that both 'inline' and 'extern' are
3479 // specified on the definition, then it is always externally visible.
3480 if (!Prev->isInlineSpecified() ||
3481 Prev->getStorageClass() != SC_Extern)
3482 return false;
3483 } else if (Prev->isInlineSpecified() &&
3484 Prev->getStorageClass() != SC_Extern) {
3485 return false;
3486 }
3487 }
3488 return FoundBody;
3489 }
3490
3491 // C99 6.7.4p6:
3492 // [...] If all of the file scope declarations for a function in a
3493 // translation unit include the inline function specifier without extern,
3494 // then the definition in that translation unit is an inline definition.
3495 if (isInlineSpecified() && getStorageClass() != SC_Extern)
3496 return false;
3497 const FunctionDecl *Prev = this;
3498 bool FoundBody = false;
3499 while ((Prev = Prev->getPreviousDecl())) {
3500 FoundBody |= Prev->doesThisDeclarationHaveABody();
3501 if (RedeclForcesDefC99(Prev))
3502 return false;
3503 }
3504 return FoundBody;
3505 }
3506
getFunctionTypeLoc() const3507 FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
3508 const TypeSourceInfo *TSI = getTypeSourceInfo();
3509 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3510 : FunctionTypeLoc();
3511 }
3512
getReturnTypeSourceRange() const3513 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3514 FunctionTypeLoc FTL = getFunctionTypeLoc();
3515 if (!FTL)
3516 return SourceRange();
3517
3518 // Skip self-referential return types.
3519 const SourceManager &SM = getASTContext().getSourceManager();
3520 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3521 SourceLocation Boundary = getNameInfo().getBeginLoc();
3522 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3523 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3524 return SourceRange();
3525
3526 return RTRange;
3527 }
3528
getParametersSourceRange() const3529 SourceRange FunctionDecl::getParametersSourceRange() const {
3530 unsigned NP = getNumParams();
3531 SourceLocation EllipsisLoc = getEllipsisLoc();
3532
3533 if (NP == 0 && EllipsisLoc.isInvalid())
3534 return SourceRange();
3535
3536 SourceLocation Begin =
3537 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3538 SourceLocation End = EllipsisLoc.isValid()
3539 ? EllipsisLoc
3540 : ParamInfo[NP - 1]->getSourceRange().getEnd();
3541
3542 return SourceRange(Begin, End);
3543 }
3544
getExceptionSpecSourceRange() const3545 SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3546 FunctionTypeLoc FTL = getFunctionTypeLoc();
3547 return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3548 }
3549
3550 /// For an inline function definition in C, or for a gnu_inline function
3551 /// in C++, determine whether the definition will be externally visible.
3552 ///
3553 /// Inline function definitions are always available for inlining optimizations.
3554 /// However, depending on the language dialect, declaration specifiers, and
3555 /// attributes, the definition of an inline function may or may not be
3556 /// "externally" visible to other translation units in the program.
3557 ///
3558 /// In C99, inline definitions are not externally visible by default. However,
3559 /// if even one of the global-scope declarations is marked "extern inline", the
3560 /// inline definition becomes externally visible (C99 6.7.4p6).
3561 ///
3562 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3563 /// definition, we use the GNU semantics for inline, which are nearly the
3564 /// opposite of C99 semantics. In particular, "inline" by itself will create
3565 /// an externally visible symbol, but "extern inline" will not create an
3566 /// externally visible symbol.
isInlineDefinitionExternallyVisible() const3567 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3568 assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3569 hasAttr<AliasAttr>()) &&
3570 "Must be a function definition");
3571 assert(isInlined() && "Function must be inline");
3572 ASTContext &Context = getASTContext();
3573
3574 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3575 // Note: If you change the logic here, please change
3576 // doesDeclarationForceExternallyVisibleDefinition as well.
3577 //
3578 // If it's not the case that both 'inline' and 'extern' are
3579 // specified on the definition, then this inline definition is
3580 // externally visible.
3581 if (Context.getLangOpts().CPlusPlus)
3582 return false;
3583 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3584 return true;
3585
3586 // If any declaration is 'inline' but not 'extern', then this definition
3587 // is externally visible.
3588 for (auto Redecl : redecls()) {
3589 if (Redecl->isInlineSpecified() &&
3590 Redecl->getStorageClass() != SC_Extern)
3591 return true;
3592 }
3593
3594 return false;
3595 }
3596
3597 // The rest of this function is C-only.
3598 assert(!Context.getLangOpts().CPlusPlus &&
3599 "should not use C inline rules in C++");
3600
3601 // C99 6.7.4p6:
3602 // [...] If all of the file scope declarations for a function in a
3603 // translation unit include the inline function specifier without extern,
3604 // then the definition in that translation unit is an inline definition.
3605 for (auto Redecl : redecls()) {
3606 if (RedeclForcesDefC99(Redecl))
3607 return true;
3608 }
3609
3610 // C99 6.7.4p6:
3611 // An inline definition does not provide an external definition for the
3612 // function, and does not forbid an external definition in another
3613 // translation unit.
3614 return false;
3615 }
3616
3617 /// getOverloadedOperator - Which C++ overloaded operator this
3618 /// function represents, if any.
getOverloadedOperator() const3619 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3620 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3621 return getDeclName().getCXXOverloadedOperator();
3622 return OO_None;
3623 }
3624
3625 /// getLiteralIdentifier - The literal suffix identifier this function
3626 /// represents, if any.
getLiteralIdentifier() const3627 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3628 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3629 return getDeclName().getCXXLiteralIdentifier();
3630 return nullptr;
3631 }
3632
getTemplatedKind() const3633 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3634 if (TemplateOrSpecialization.isNull())
3635 return TK_NonTemplate;
3636 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3637 return TK_FunctionTemplate;
3638 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3639 return TK_MemberSpecialization;
3640 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3641 return TK_FunctionTemplateSpecialization;
3642 if (TemplateOrSpecialization.is
3643 <DependentFunctionTemplateSpecializationInfo*>())
3644 return TK_DependentFunctionTemplateSpecialization;
3645
3646 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3647 }
3648
getInstantiatedFromMemberFunction() const3649 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3650 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3651 return cast<FunctionDecl>(Info->getInstantiatedFrom());
3652
3653 return nullptr;
3654 }
3655
getMemberSpecializationInfo() const3656 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3657 if (auto *MSI =
3658 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3659 return MSI;
3660 if (auto *FTSI = TemplateOrSpecialization
3661 .dyn_cast<FunctionTemplateSpecializationInfo *>())
3662 return FTSI->getMemberSpecializationInfo();
3663 return nullptr;
3664 }
3665
3666 void
setInstantiationOfMemberFunction(ASTContext & C,FunctionDecl * FD,TemplateSpecializationKind TSK)3667 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3668 FunctionDecl *FD,
3669 TemplateSpecializationKind TSK) {
3670 assert(TemplateOrSpecialization.isNull() &&
3671 "Member function is already a specialization");
3672 MemberSpecializationInfo *Info
3673 = new (C) MemberSpecializationInfo(FD, TSK);
3674 TemplateOrSpecialization = Info;
3675 }
3676
getDescribedFunctionTemplate() const3677 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3678 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3679 }
3680
setDescribedFunctionTemplate(FunctionTemplateDecl * Template)3681 void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3682 assert(TemplateOrSpecialization.isNull() &&
3683 "Member function is already a specialization");
3684 TemplateOrSpecialization = Template;
3685 }
3686
isImplicitlyInstantiable() const3687 bool FunctionDecl::isImplicitlyInstantiable() const {
3688 // If the function is invalid, it can't be implicitly instantiated.
3689 if (isInvalidDecl())
3690 return false;
3691
3692 switch (getTemplateSpecializationKindForInstantiation()) {
3693 case TSK_Undeclared:
3694 case TSK_ExplicitInstantiationDefinition:
3695 case TSK_ExplicitSpecialization:
3696 return false;
3697
3698 case TSK_ImplicitInstantiation:
3699 return true;
3700
3701 case TSK_ExplicitInstantiationDeclaration:
3702 // Handled below.
3703 break;
3704 }
3705
3706 // Find the actual template from which we will instantiate.
3707 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3708 bool HasPattern = false;
3709 if (PatternDecl)
3710 HasPattern = PatternDecl->hasBody(PatternDecl);
3711
3712 // C++0x [temp.explicit]p9:
3713 // Except for inline functions, other explicit instantiation declarations
3714 // have the effect of suppressing the implicit instantiation of the entity
3715 // to which they refer.
3716 if (!HasPattern || !PatternDecl)
3717 return true;
3718
3719 return PatternDecl->isInlined();
3720 }
3721
isTemplateInstantiation() const3722 bool FunctionDecl::isTemplateInstantiation() const {
3723 // FIXME: Remove this, it's not clear what it means. (Which template
3724 // specialization kind?)
3725 return clang::isTemplateInstantiation(getTemplateSpecializationKind());
3726 }
3727
3728 FunctionDecl *
getTemplateInstantiationPattern(bool ForDefinition) const3729 FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
3730 // If this is a generic lambda call operator specialization, its
3731 // instantiation pattern is always its primary template's pattern
3732 // even if its primary template was instantiated from another
3733 // member template (which happens with nested generic lambdas).
3734 // Since a lambda's call operator's body is transformed eagerly,
3735 // we don't have to go hunting for a prototype definition template
3736 // (i.e. instantiated-from-member-template) to use as an instantiation
3737 // pattern.
3738
3739 if (isGenericLambdaCallOperatorSpecialization(
3740 dyn_cast<CXXMethodDecl>(this))) {
3741 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3742 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
3743 }
3744
3745 // Check for a declaration of this function that was instantiated from a
3746 // friend definition.
3747 const FunctionDecl *FD = nullptr;
3748 if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
3749 FD = this;
3750
3751 if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {
3752 if (ForDefinition &&
3753 !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
3754 return nullptr;
3755 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
3756 }
3757
3758 if (ForDefinition &&
3759 !clang::isTemplateInstantiation(getTemplateSpecializationKind()))
3760 return nullptr;
3761
3762 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3763 // If we hit a point where the user provided a specialization of this
3764 // template, we're done looking.
3765 while (!ForDefinition || !Primary->isMemberSpecialization()) {
3766 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
3767 if (!NewPrimary)
3768 break;
3769 Primary = NewPrimary;
3770 }
3771
3772 return getDefinitionOrSelf(Primary->getTemplatedDecl());
3773 }
3774
3775 return nullptr;
3776 }
3777
getPrimaryTemplate() const3778 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3779 if (FunctionTemplateSpecializationInfo *Info
3780 = TemplateOrSpecialization
3781 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3782 return Info->getTemplate();
3783 }
3784 return nullptr;
3785 }
3786
3787 FunctionTemplateSpecializationInfo *
getTemplateSpecializationInfo() const3788 FunctionDecl::getTemplateSpecializationInfo() const {
3789 return TemplateOrSpecialization
3790 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3791 }
3792
3793 const TemplateArgumentList *
getTemplateSpecializationArgs() const3794 FunctionDecl::getTemplateSpecializationArgs() const {
3795 if (FunctionTemplateSpecializationInfo *Info
3796 = TemplateOrSpecialization
3797 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3798 return Info->TemplateArguments;
3799 }
3800 return nullptr;
3801 }
3802
3803 const ASTTemplateArgumentListInfo *
getTemplateSpecializationArgsAsWritten() const3804 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3805 if (FunctionTemplateSpecializationInfo *Info
3806 = TemplateOrSpecialization
3807 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3808 return Info->TemplateArgumentsAsWritten;
3809 }
3810 return nullptr;
3811 }
3812
3813 void
setFunctionTemplateSpecialization(ASTContext & C,FunctionTemplateDecl * Template,const TemplateArgumentList * TemplateArgs,void * InsertPos,TemplateSpecializationKind TSK,const TemplateArgumentListInfo * TemplateArgsAsWritten,SourceLocation PointOfInstantiation)3814 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3815 FunctionTemplateDecl *Template,
3816 const TemplateArgumentList *TemplateArgs,
3817 void *InsertPos,
3818 TemplateSpecializationKind TSK,
3819 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3820 SourceLocation PointOfInstantiation) {
3821 assert((TemplateOrSpecialization.isNull() ||
3822 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
3823 "Member function is already a specialization");
3824 assert(TSK != TSK_Undeclared &&
3825 "Must specify the type of function template specialization");
3826 assert((TemplateOrSpecialization.isNull() ||
3827 TSK == TSK_ExplicitSpecialization) &&
3828 "Member specialization must be an explicit specialization");
3829 FunctionTemplateSpecializationInfo *Info =
3830 FunctionTemplateSpecializationInfo::Create(
3831 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
3832 PointOfInstantiation,
3833 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
3834 TemplateOrSpecialization = Info;
3835 Template->addSpecialization(Info, InsertPos);
3836 }
3837
3838 void
setDependentTemplateSpecialization(ASTContext & Context,const UnresolvedSetImpl & Templates,const TemplateArgumentListInfo & TemplateArgs)3839 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3840 const UnresolvedSetImpl &Templates,
3841 const TemplateArgumentListInfo &TemplateArgs) {
3842 assert(TemplateOrSpecialization.isNull());
3843 DependentFunctionTemplateSpecializationInfo *Info =
3844 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3845 TemplateArgs);
3846 TemplateOrSpecialization = Info;
3847 }
3848
3849 DependentFunctionTemplateSpecializationInfo *
getDependentSpecializationInfo() const3850 FunctionDecl::getDependentSpecializationInfo() const {
3851 return TemplateOrSpecialization
3852 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3853 }
3854
3855 DependentFunctionTemplateSpecializationInfo *
Create(ASTContext & Context,const UnresolvedSetImpl & Ts,const TemplateArgumentListInfo & TArgs)3856 DependentFunctionTemplateSpecializationInfo::Create(
3857 ASTContext &Context, const UnresolvedSetImpl &Ts,
3858 const TemplateArgumentListInfo &TArgs) {
3859 void *Buffer = Context.Allocate(
3860 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3861 TArgs.size(), Ts.size()));
3862 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3863 }
3864
3865 DependentFunctionTemplateSpecializationInfo::
DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl & Ts,const TemplateArgumentListInfo & TArgs)3866 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3867 const TemplateArgumentListInfo &TArgs)
3868 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3869 NumTemplates = Ts.size();
3870 NumArgs = TArgs.size();
3871
3872 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
3873 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3874 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3875
3876 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
3877 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3878 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3879 }
3880
getTemplateSpecializationKind() const3881 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3882 // For a function template specialization, query the specialization
3883 // information object.
3884 if (FunctionTemplateSpecializationInfo *FTSInfo =
3885 TemplateOrSpecialization
3886 .dyn_cast<FunctionTemplateSpecializationInfo *>())
3887 return FTSInfo->getTemplateSpecializationKind();
3888
3889 if (MemberSpecializationInfo *MSInfo =
3890 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3891 return MSInfo->getTemplateSpecializationKind();
3892
3893 return TSK_Undeclared;
3894 }
3895
3896 TemplateSpecializationKind
getTemplateSpecializationKindForInstantiation() const3897 FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
3898 // This is the same as getTemplateSpecializationKind(), except that for a
3899 // function that is both a function template specialization and a member
3900 // specialization, we prefer the member specialization information. Eg:
3901 //
3902 // template<typename T> struct A {
3903 // template<typename U> void f() {}
3904 // template<> void f<int>() {}
3905 // };
3906 //
3907 // For A<int>::f<int>():
3908 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
3909 // * getTemplateSpecializationKindForInstantiation() will return
3910 // TSK_ImplicitInstantiation
3911 //
3912 // This reflects the facts that A<int>::f<int> is an explicit specialization
3913 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
3914 // from A::f<int> if a definition is needed.
3915 if (FunctionTemplateSpecializationInfo *FTSInfo =
3916 TemplateOrSpecialization
3917 .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
3918 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
3919 return MSInfo->getTemplateSpecializationKind();
3920 return FTSInfo->getTemplateSpecializationKind();
3921 }
3922
3923 if (MemberSpecializationInfo *MSInfo =
3924 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3925 return MSInfo->getTemplateSpecializationKind();
3926
3927 return TSK_Undeclared;
3928 }
3929
3930 void
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)3931 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3932 SourceLocation PointOfInstantiation) {
3933 if (FunctionTemplateSpecializationInfo *FTSInfo
3934 = TemplateOrSpecialization.dyn_cast<
3935 FunctionTemplateSpecializationInfo*>()) {
3936 FTSInfo->setTemplateSpecializationKind(TSK);
3937 if (TSK != TSK_ExplicitSpecialization &&
3938 PointOfInstantiation.isValid() &&
3939 FTSInfo->getPointOfInstantiation().isInvalid()) {
3940 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3941 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3942 L->InstantiationRequested(this);
3943 }
3944 } else if (MemberSpecializationInfo *MSInfo
3945 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3946 MSInfo->setTemplateSpecializationKind(TSK);
3947 if (TSK != TSK_ExplicitSpecialization &&
3948 PointOfInstantiation.isValid() &&
3949 MSInfo->getPointOfInstantiation().isInvalid()) {
3950 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3951 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3952 L->InstantiationRequested(this);
3953 }
3954 } else
3955 llvm_unreachable("Function cannot have a template specialization kind");
3956 }
3957
getPointOfInstantiation() const3958 SourceLocation FunctionDecl::getPointOfInstantiation() const {
3959 if (FunctionTemplateSpecializationInfo *FTSInfo
3960 = TemplateOrSpecialization.dyn_cast<
3961 FunctionTemplateSpecializationInfo*>())
3962 return FTSInfo->getPointOfInstantiation();
3963 if (MemberSpecializationInfo *MSInfo =
3964 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3965 return MSInfo->getPointOfInstantiation();
3966
3967 return SourceLocation();
3968 }
3969
isOutOfLine() const3970 bool FunctionDecl::isOutOfLine() const {
3971 if (Decl::isOutOfLine())
3972 return true;
3973
3974 // If this function was instantiated from a member function of a
3975 // class template, check whether that member function was defined out-of-line.
3976 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3977 const FunctionDecl *Definition;
3978 if (FD->hasBody(Definition))
3979 return Definition->isOutOfLine();
3980 }
3981
3982 // If this function was instantiated from a function template,
3983 // check whether that function template was defined out-of-line.
3984 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3985 const FunctionDecl *Definition;
3986 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3987 return Definition->isOutOfLine();
3988 }
3989
3990 return false;
3991 }
3992
getSourceRange() const3993 SourceRange FunctionDecl::getSourceRange() const {
3994 return SourceRange(getOuterLocStart(), EndRangeLoc);
3995 }
3996
getMemoryFunctionKind() const3997 unsigned FunctionDecl::getMemoryFunctionKind() const {
3998 IdentifierInfo *FnInfo = getIdentifier();
3999
4000 if (!FnInfo)
4001 return 0;
4002
4003 // Builtin handling.
4004 switch (getBuiltinID()) {
4005 case Builtin::BI__builtin_memset:
4006 case Builtin::BI__builtin___memset_chk:
4007 case Builtin::BImemset:
4008 return Builtin::BImemset;
4009
4010 case Builtin::BI__builtin_memcpy:
4011 case Builtin::BI__builtin___memcpy_chk:
4012 case Builtin::BImemcpy:
4013 return Builtin::BImemcpy;
4014
4015 case Builtin::BI__builtin_mempcpy:
4016 case Builtin::BI__builtin___mempcpy_chk:
4017 case Builtin::BImempcpy:
4018 return Builtin::BImempcpy;
4019
4020 case Builtin::BI__builtin_memmove:
4021 case Builtin::BI__builtin___memmove_chk:
4022 case Builtin::BImemmove:
4023 return Builtin::BImemmove;
4024
4025 case Builtin::BIstrlcpy:
4026 case Builtin::BI__builtin___strlcpy_chk:
4027 return Builtin::BIstrlcpy;
4028
4029 case Builtin::BIstrlcat:
4030 case Builtin::BI__builtin___strlcat_chk:
4031 return Builtin::BIstrlcat;
4032
4033 case Builtin::BI__builtin_memcmp:
4034 case Builtin::BImemcmp:
4035 return Builtin::BImemcmp;
4036
4037 case Builtin::BI__builtin_bcmp:
4038 case Builtin::BIbcmp:
4039 return Builtin::BIbcmp;
4040
4041 case Builtin::BI__builtin_strncpy:
4042 case Builtin::BI__builtin___strncpy_chk:
4043 case Builtin::BIstrncpy:
4044 return Builtin::BIstrncpy;
4045
4046 case Builtin::BI__builtin_strncmp:
4047 case Builtin::BIstrncmp:
4048 return Builtin::BIstrncmp;
4049
4050 case Builtin::BI__builtin_strncasecmp:
4051 case Builtin::BIstrncasecmp:
4052 return Builtin::BIstrncasecmp;
4053
4054 case Builtin::BI__builtin_strncat:
4055 case Builtin::BI__builtin___strncat_chk:
4056 case Builtin::BIstrncat:
4057 return Builtin::BIstrncat;
4058
4059 case Builtin::BI__builtin_strndup:
4060 case Builtin::BIstrndup:
4061 return Builtin::BIstrndup;
4062
4063 case Builtin::BI__builtin_strlen:
4064 case Builtin::BIstrlen:
4065 return Builtin::BIstrlen;
4066
4067 case Builtin::BI__builtin_bzero:
4068 case Builtin::BIbzero:
4069 return Builtin::BIbzero;
4070
4071 case Builtin::BIfree:
4072 return Builtin::BIfree;
4073
4074 default:
4075 if (isExternC()) {
4076 if (FnInfo->isStr("memset"))
4077 return Builtin::BImemset;
4078 if (FnInfo->isStr("memcpy"))
4079 return Builtin::BImemcpy;
4080 if (FnInfo->isStr("mempcpy"))
4081 return Builtin::BImempcpy;
4082 if (FnInfo->isStr("memmove"))
4083 return Builtin::BImemmove;
4084 if (FnInfo->isStr("memcmp"))
4085 return Builtin::BImemcmp;
4086 if (FnInfo->isStr("bcmp"))
4087 return Builtin::BIbcmp;
4088 if (FnInfo->isStr("strncpy"))
4089 return Builtin::BIstrncpy;
4090 if (FnInfo->isStr("strncmp"))
4091 return Builtin::BIstrncmp;
4092 if (FnInfo->isStr("strncasecmp"))
4093 return Builtin::BIstrncasecmp;
4094 if (FnInfo->isStr("strncat"))
4095 return Builtin::BIstrncat;
4096 if (FnInfo->isStr("strndup"))
4097 return Builtin::BIstrndup;
4098 if (FnInfo->isStr("strlen"))
4099 return Builtin::BIstrlen;
4100 if (FnInfo->isStr("bzero"))
4101 return Builtin::BIbzero;
4102 } else if (isInStdNamespace()) {
4103 if (FnInfo->isStr("free"))
4104 return Builtin::BIfree;
4105 }
4106 break;
4107 }
4108 return 0;
4109 }
4110
getODRHash() const4111 unsigned FunctionDecl::getODRHash() const {
4112 assert(hasODRHash());
4113 return ODRHash;
4114 }
4115
getODRHash()4116 unsigned FunctionDecl::getODRHash() {
4117 if (hasODRHash())
4118 return ODRHash;
4119
4120 if (auto *FT = getInstantiatedFromMemberFunction()) {
4121 setHasODRHash(true);
4122 ODRHash = FT->getODRHash();
4123 return ODRHash;
4124 }
4125
4126 class ODRHash Hash;
4127 Hash.AddFunctionDecl(this);
4128 setHasODRHash(true);
4129 ODRHash = Hash.CalculateHash();
4130 return ODRHash;
4131 }
4132
4133 //===----------------------------------------------------------------------===//
4134 // FieldDecl Implementation
4135 //===----------------------------------------------------------------------===//
4136
Create(const ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,Expr * BW,bool Mutable,InClassInitStyle InitStyle)4137 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
4138 SourceLocation StartLoc, SourceLocation IdLoc,
4139 IdentifierInfo *Id, QualType T,
4140 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4141 InClassInitStyle InitStyle) {
4142 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4143 BW, Mutable, InitStyle);
4144 }
4145
CreateDeserialized(ASTContext & C,unsigned ID)4146 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4147 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4148 SourceLocation(), nullptr, QualType(), nullptr,
4149 nullptr, false, ICIS_NoInit);
4150 }
4151
isAnonymousStructOrUnion() const4152 bool FieldDecl::isAnonymousStructOrUnion() const {
4153 if (!isImplicit() || getDeclName())
4154 return false;
4155
4156 if (const auto *Record = getType()->getAs<RecordType>())
4157 return Record->getDecl()->isAnonymousStructOrUnion();
4158
4159 return false;
4160 }
4161
getBitWidthValue(const ASTContext & Ctx) const4162 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4163 assert(isBitField() && "not a bitfield");
4164 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4165 }
4166
isZeroLengthBitField(const ASTContext & Ctx) const4167 bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
4168 return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
4169 getBitWidthValue(Ctx) == 0;
4170 }
4171
isZeroSize(const ASTContext & Ctx) const4172 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4173 if (isZeroLengthBitField(Ctx))
4174 return true;
4175
4176 // C++2a [intro.object]p7:
4177 // An object has nonzero size if it
4178 // -- is not a potentially-overlapping subobject, or
4179 if (!hasAttr<NoUniqueAddressAttr>())
4180 return false;
4181
4182 // -- is not of class type, or
4183 const auto *RT = getType()->getAs<RecordType>();
4184 if (!RT)
4185 return false;
4186 const RecordDecl *RD = RT->getDecl()->getDefinition();
4187 if (!RD) {
4188 assert(isInvalidDecl() && "valid field has incomplete type");
4189 return false;
4190 }
4191
4192 // -- [has] virtual member functions or virtual base classes, or
4193 // -- has subobjects of nonzero size or bit-fields of nonzero length
4194 const auto *CXXRD = cast<CXXRecordDecl>(RD);
4195 if (!CXXRD->isEmpty())
4196 return false;
4197
4198 // Otherwise, [...] the circumstances under which the object has zero size
4199 // are implementation-defined.
4200 // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
4201 // ABI will do.
4202 return true;
4203 }
4204
getFieldIndex() const4205 unsigned FieldDecl::getFieldIndex() const {
4206 const FieldDecl *Canonical = getCanonicalDecl();
4207 if (Canonical != this)
4208 return Canonical->getFieldIndex();
4209
4210 if (CachedFieldIndex) return CachedFieldIndex - 1;
4211
4212 unsigned Index = 0;
4213 const RecordDecl *RD = getParent()->getDefinition();
4214 assert(RD && "requested index for field of struct with no definition");
4215
4216 for (auto *Field : RD->fields()) {
4217 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4218 ++Index;
4219 }
4220
4221 assert(CachedFieldIndex && "failed to find field in parent");
4222 return CachedFieldIndex - 1;
4223 }
4224
getSourceRange() const4225 SourceRange FieldDecl::getSourceRange() const {
4226 const Expr *FinalExpr = getInClassInitializer();
4227 if (!FinalExpr)
4228 FinalExpr = getBitWidth();
4229 if (FinalExpr)
4230 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4231 return DeclaratorDecl::getSourceRange();
4232 }
4233
setCapturedVLAType(const VariableArrayType * VLAType)4234 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
4235 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4236 "capturing type in non-lambda or captured record.");
4237 assert(InitStorage.getInt() == ISK_NoInit &&
4238 InitStorage.getPointer() == nullptr &&
4239 "bit width, initializer or captured type already set");
4240 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
4241 ISK_CapturedVLAType);
4242 }
4243
4244 //===----------------------------------------------------------------------===//
4245 // TagDecl Implementation
4246 //===----------------------------------------------------------------------===//
4247
TagDecl(Kind DK,TagKind TK,const ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,TagDecl * PrevDecl,SourceLocation StartL)4248 TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4249 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4250 SourceLocation StartL)
4251 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4252 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4253 assert((DK != Enum || TK == TTK_Enum) &&
4254 "EnumDecl not matched with TTK_Enum");
4255 setPreviousDecl(PrevDecl);
4256 setTagKind(TK);
4257 setCompleteDefinition(false);
4258 setBeingDefined(false);
4259 setEmbeddedInDeclarator(false);
4260 setFreeStanding(false);
4261 setCompleteDefinitionRequired(false);
4262 }
4263
getOuterLocStart() const4264 SourceLocation TagDecl::getOuterLocStart() const {
4265 return getTemplateOrInnerLocStart(this);
4266 }
4267
getSourceRange() const4268 SourceRange TagDecl::getSourceRange() const {
4269 SourceLocation RBraceLoc = BraceRange.getEnd();
4270 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4271 return SourceRange(getOuterLocStart(), E);
4272 }
4273
getCanonicalDecl()4274 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
4275
setTypedefNameForAnonDecl(TypedefNameDecl * TDD)4276 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
4277 TypedefNameDeclOrQualifier = TDD;
4278 if (const Type *T = getTypeForDecl()) {
4279 (void)T;
4280 assert(T->isLinkageValid());
4281 }
4282 assert(isLinkageValid());
4283 }
4284
startDefinition()4285 void TagDecl::startDefinition() {
4286 setBeingDefined(true);
4287
4288 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4289 struct CXXRecordDecl::DefinitionData *Data =
4290 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4291 for (auto I : redecls())
4292 cast<CXXRecordDecl>(I)->DefinitionData = Data;
4293 }
4294 }
4295
completeDefinition()4296 void TagDecl::completeDefinition() {
4297 assert((!isa<CXXRecordDecl>(this) ||
4298 cast<CXXRecordDecl>(this)->hasDefinition()) &&
4299 "definition completed but not started");
4300
4301 setCompleteDefinition(true);
4302 setBeingDefined(false);
4303
4304 if (ASTMutationListener *L = getASTMutationListener())
4305 L->CompletedTagDefinition(this);
4306 }
4307
getDefinition() const4308 TagDecl *TagDecl::getDefinition() const {
4309 if (isCompleteDefinition())
4310 return const_cast<TagDecl *>(this);
4311
4312 // If it's possible for us to have an out-of-date definition, check now.
4313 if (mayHaveOutOfDateDef()) {
4314 if (IdentifierInfo *II = getIdentifier()) {
4315 if (II->isOutOfDate()) {
4316 updateOutOfDate(*II);
4317 }
4318 }
4319 }
4320
4321 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4322 return CXXRD->getDefinition();
4323
4324 for (auto R : redecls())
4325 if (R->isCompleteDefinition())
4326 return R;
4327
4328 return nullptr;
4329 }
4330
setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)4331 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4332 if (QualifierLoc) {
4333 // Make sure the extended qualifier info is allocated.
4334 if (!hasExtInfo())
4335 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4336 // Set qualifier info.
4337 getExtInfo()->QualifierLoc = QualifierLoc;
4338 } else {
4339 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4340 if (hasExtInfo()) {
4341 if (getExtInfo()->NumTemplParamLists == 0) {
4342 getASTContext().Deallocate(getExtInfo());
4343 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4344 }
4345 else
4346 getExtInfo()->QualifierLoc = QualifierLoc;
4347 }
4348 }
4349 }
4350
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)4351 void TagDecl::setTemplateParameterListsInfo(
4352 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4353 assert(!TPLists.empty());
4354 // Make sure the extended decl info is allocated.
4355 if (!hasExtInfo())
4356 // Allocate external info struct.
4357 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4358 // Set the template parameter lists info.
4359 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4360 }
4361
4362 //===----------------------------------------------------------------------===//
4363 // EnumDecl Implementation
4364 //===----------------------------------------------------------------------===//
4365
EnumDecl(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,EnumDecl * PrevDecl,bool Scoped,bool ScopedUsingClassTag,bool Fixed)4366 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4367 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4368 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4369 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4370 assert(Scoped || !ScopedUsingClassTag);
4371 IntegerType = nullptr;
4372 setNumPositiveBits(0);
4373 setNumNegativeBits(0);
4374 setScoped(Scoped);
4375 setScopedUsingClassTag(ScopedUsingClassTag);
4376 setFixed(Fixed);
4377 setHasODRHash(false);
4378 ODRHash = 0;
4379 }
4380
anchor()4381 void EnumDecl::anchor() {}
4382
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,EnumDecl * PrevDecl,bool IsScoped,bool IsScopedUsingClassTag,bool IsFixed)4383 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4384 SourceLocation StartLoc, SourceLocation IdLoc,
4385 IdentifierInfo *Id,
4386 EnumDecl *PrevDecl, bool IsScoped,
4387 bool IsScopedUsingClassTag, bool IsFixed) {
4388 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4389 IsScoped, IsScopedUsingClassTag, IsFixed);
4390 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4391 C.getTypeDeclType(Enum, PrevDecl);
4392 return Enum;
4393 }
4394
CreateDeserialized(ASTContext & C,unsigned ID)4395 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4396 EnumDecl *Enum =
4397 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4398 nullptr, nullptr, false, false, false);
4399 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4400 return Enum;
4401 }
4402
getIntegerTypeRange() const4403 SourceRange EnumDecl::getIntegerTypeRange() const {
4404 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4405 return TI->getTypeLoc().getSourceRange();
4406 return SourceRange();
4407 }
4408
completeDefinition(QualType NewType,QualType NewPromotionType,unsigned NumPositiveBits,unsigned NumNegativeBits)4409 void EnumDecl::completeDefinition(QualType NewType,
4410 QualType NewPromotionType,
4411 unsigned NumPositiveBits,
4412 unsigned NumNegativeBits) {
4413 assert(!isCompleteDefinition() && "Cannot redefine enums!");
4414 if (!IntegerType)
4415 IntegerType = NewType.getTypePtr();
4416 PromotionType = NewPromotionType;
4417 setNumPositiveBits(NumPositiveBits);
4418 setNumNegativeBits(NumNegativeBits);
4419 TagDecl::completeDefinition();
4420 }
4421
isClosed() const4422 bool EnumDecl::isClosed() const {
4423 if (const auto *A = getAttr<EnumExtensibilityAttr>())
4424 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4425 return true;
4426 }
4427
isClosedFlag() const4428 bool EnumDecl::isClosedFlag() const {
4429 return isClosed() && hasAttr<FlagEnumAttr>();
4430 }
4431
isClosedNonFlag() const4432 bool EnumDecl::isClosedNonFlag() const {
4433 return isClosed() && !hasAttr<FlagEnumAttr>();
4434 }
4435
getTemplateSpecializationKind() const4436 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4437 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4438 return MSI->getTemplateSpecializationKind();
4439
4440 return TSK_Undeclared;
4441 }
4442
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)4443 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4444 SourceLocation PointOfInstantiation) {
4445 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4446 assert(MSI && "Not an instantiated member enumeration?");
4447 MSI->setTemplateSpecializationKind(TSK);
4448 if (TSK != TSK_ExplicitSpecialization &&
4449 PointOfInstantiation.isValid() &&
4450 MSI->getPointOfInstantiation().isInvalid())
4451 MSI->setPointOfInstantiation(PointOfInstantiation);
4452 }
4453
getTemplateInstantiationPattern() const4454 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4455 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4456 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4457 EnumDecl *ED = getInstantiatedFromMemberEnum();
4458 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4459 ED = NewED;
4460 return getDefinitionOrSelf(ED);
4461 }
4462 }
4463
4464 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4465 "couldn't find pattern for enum instantiation");
4466 return nullptr;
4467 }
4468
getInstantiatedFromMemberEnum() const4469 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4470 if (SpecializationInfo)
4471 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4472
4473 return nullptr;
4474 }
4475
setInstantiationOfMemberEnum(ASTContext & C,EnumDecl * ED,TemplateSpecializationKind TSK)4476 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4477 TemplateSpecializationKind TSK) {
4478 assert(!SpecializationInfo && "Member enum is already a specialization");
4479 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4480 }
4481
getODRHash()4482 unsigned EnumDecl::getODRHash() {
4483 if (hasODRHash())
4484 return ODRHash;
4485
4486 class ODRHash Hash;
4487 Hash.AddEnumDecl(this);
4488 setHasODRHash(true);
4489 ODRHash = Hash.CalculateHash();
4490 return ODRHash;
4491 }
4492
4493 //===----------------------------------------------------------------------===//
4494 // RecordDecl Implementation
4495 //===----------------------------------------------------------------------===//
4496
RecordDecl(Kind DK,TagKind TK,const ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,RecordDecl * PrevDecl)4497 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4498 DeclContext *DC, SourceLocation StartLoc,
4499 SourceLocation IdLoc, IdentifierInfo *Id,
4500 RecordDecl *PrevDecl)
4501 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4502 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4503 setHasFlexibleArrayMember(false);
4504 setAnonymousStructOrUnion(false);
4505 setHasObjectMember(false);
4506 setHasVolatileMember(false);
4507 setHasLoadedFieldsFromExternalStorage(false);
4508 setNonTrivialToPrimitiveDefaultInitialize(false);
4509 setNonTrivialToPrimitiveCopy(false);
4510 setNonTrivialToPrimitiveDestroy(false);
4511 setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
4512 setHasNonTrivialToPrimitiveDestructCUnion(false);
4513 setHasNonTrivialToPrimitiveCopyCUnion(false);
4514 setParamDestroyedInCallee(false);
4515 setArgPassingRestrictions(APK_CanPassInRegs);
4516 }
4517
Create(const ASTContext & C,TagKind TK,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,RecordDecl * PrevDecl)4518 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
4519 SourceLocation StartLoc, SourceLocation IdLoc,
4520 IdentifierInfo *Id, RecordDecl* PrevDecl) {
4521 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4522 StartLoc, IdLoc, Id, PrevDecl);
4523 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4524
4525 C.getTypeDeclType(R, PrevDecl);
4526 return R;
4527 }
4528
CreateDeserialized(const ASTContext & C,unsigned ID)4529 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
4530 RecordDecl *R =
4531 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4532 SourceLocation(), nullptr, nullptr);
4533 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4534 return R;
4535 }
4536
isInjectedClassName() const4537 bool RecordDecl::isInjectedClassName() const {
4538 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
4539 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4540 }
4541
isLambda() const4542 bool RecordDecl::isLambda() const {
4543 if (auto RD = dyn_cast<CXXRecordDecl>(this))
4544 return RD->isLambda();
4545 return false;
4546 }
4547
isCapturedRecord() const4548 bool RecordDecl::isCapturedRecord() const {
4549 return hasAttr<CapturedRecordAttr>();
4550 }
4551
setCapturedRecord()4552 void RecordDecl::setCapturedRecord() {
4553 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4554 }
4555
isOrContainsUnion() const4556 bool RecordDecl::isOrContainsUnion() const {
4557 if (isUnion())
4558 return true;
4559
4560 if (const RecordDecl *Def = getDefinition()) {
4561 for (const FieldDecl *FD : Def->fields()) {
4562 const RecordType *RT = FD->getType()->getAs<RecordType>();
4563 if (RT && RT->getDecl()->isOrContainsUnion())
4564 return true;
4565 }
4566 }
4567
4568 return false;
4569 }
4570
field_begin() const4571 RecordDecl::field_iterator RecordDecl::field_begin() const {
4572 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
4573 LoadFieldsFromExternalStorage();
4574
4575 return field_iterator(decl_iterator(FirstDecl));
4576 }
4577
4578 /// completeDefinition - Notes that the definition of this type is now
4579 /// complete.
completeDefinition()4580 void RecordDecl::completeDefinition() {
4581 assert(!isCompleteDefinition() && "Cannot redefine record!");
4582 TagDecl::completeDefinition();
4583 }
4584
4585 /// isMsStruct - Get whether or not this record uses ms_struct layout.
4586 /// This which can be turned on with an attribute, pragma, or the
4587 /// -mms-bitfields command-line option.
isMsStruct(const ASTContext & C) const4588 bool RecordDecl::isMsStruct(const ASTContext &C) const {
4589 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
4590 }
4591
LoadFieldsFromExternalStorage() const4592 void RecordDecl::LoadFieldsFromExternalStorage() const {
4593 ExternalASTSource *Source = getASTContext().getExternalSource();
4594 assert(hasExternalLexicalStorage() && Source && "No external storage?");
4595
4596 // Notify that we have a RecordDecl doing some initialization.
4597 ExternalASTSource::Deserializing TheFields(Source);
4598
4599 SmallVector<Decl*, 64> Decls;
4600 setHasLoadedFieldsFromExternalStorage(true);
4601 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4602 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4603 }, Decls);
4604
4605 #ifndef NDEBUG
4606 // Check that all decls we got were FieldDecls.
4607 for (unsigned i=0, e=Decls.size(); i != e; ++i)
4608 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
4609 #endif
4610
4611 if (Decls.empty())
4612 return;
4613
4614 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
4615 /*FieldsAlreadyLoaded=*/false);
4616 }
4617
mayInsertExtraPadding(bool EmitRemark) const4618 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4619 ASTContext &Context = getASTContext();
4620 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4621 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4622 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
4623 return false;
4624 const auto &NoSanitizeList = Context.getNoSanitizeList();
4625 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
4626 // We may be able to relax some of these requirements.
4627 int ReasonToReject = -1;
4628 if (!CXXRD || CXXRD->isExternCContext())
4629 ReasonToReject = 0; // is not C++.
4630 else if (CXXRD->hasAttr<PackedAttr>())
4631 ReasonToReject = 1; // is packed.
4632 else if (CXXRD->isUnion())
4633 ReasonToReject = 2; // is a union.
4634 else if (CXXRD->isTriviallyCopyable())
4635 ReasonToReject = 3; // is trivially copyable.
4636 else if (CXXRD->hasTrivialDestructor())
4637 ReasonToReject = 4; // has trivial destructor.
4638 else if (CXXRD->isStandardLayout())
4639 ReasonToReject = 5; // is standard layout.
4640 else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
4641 "field-padding"))
4642 ReasonToReject = 6; // is in an excluded file.
4643 else if (NoSanitizeList.containsType(
4644 EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
4645 ReasonToReject = 7; // The type is excluded.
4646
4647 if (EmitRemark) {
4648 if (ReasonToReject >= 0)
4649 Context.getDiagnostics().Report(
4650 getLocation(),
4651 diag::remark_sanitize_address_insert_extra_padding_rejected)
4652 << getQualifiedNameAsString() << ReasonToReject;
4653 else
4654 Context.getDiagnostics().Report(
4655 getLocation(),
4656 diag::remark_sanitize_address_insert_extra_padding_accepted)
4657 << getQualifiedNameAsString();
4658 }
4659 return ReasonToReject < 0;
4660 }
4661
findFirstNamedDataMember() const4662 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4663 for (const auto *I : fields()) {
4664 if (I->getIdentifier())
4665 return I;
4666
4667 if (const auto *RT = I->getType()->getAs<RecordType>())
4668 if (const FieldDecl *NamedDataMember =
4669 RT->getDecl()->findFirstNamedDataMember())
4670 return NamedDataMember;
4671 }
4672
4673 // We didn't find a named data member.
4674 return nullptr;
4675 }
4676
4677 //===----------------------------------------------------------------------===//
4678 // BlockDecl Implementation
4679 //===----------------------------------------------------------------------===//
4680
BlockDecl(DeclContext * DC,SourceLocation CaretLoc)4681 BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4682 : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4683 setIsVariadic(false);
4684 setCapturesCXXThis(false);
4685 setBlockMissingReturnType(true);
4686 setIsConversionFromLambda(false);
4687 setDoesNotEscape(false);
4688 setCanAvoidCopyToHeap(false);
4689 }
4690
setParams(ArrayRef<ParmVarDecl * > NewParamInfo)4691 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
4692 assert(!ParamInfo && "Already has param info!");
4693
4694 // Zero params -> null pointer.
4695 if (!NewParamInfo.empty()) {
4696 NumParams = NewParamInfo.size();
4697 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4698 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
4699 }
4700 }
4701
setCaptures(ASTContext & Context,ArrayRef<Capture> Captures,bool CapturesCXXThis)4702 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4703 bool CapturesCXXThis) {
4704 this->setCapturesCXXThis(CapturesCXXThis);
4705 this->NumCaptures = Captures.size();
4706
4707 if (Captures.empty()) {
4708 this->Captures = nullptr;
4709 return;
4710 }
4711
4712 this->Captures = Captures.copy(Context).data();
4713 }
4714
capturesVariable(const VarDecl * variable) const4715 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
4716 for (const auto &I : captures())
4717 // Only auto vars can be captured, so no redeclaration worries.
4718 if (I.getVariable() == variable)
4719 return true;
4720
4721 return false;
4722 }
4723
getSourceRange() const4724 SourceRange BlockDecl::getSourceRange() const {
4725 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
4726 }
4727
4728 //===----------------------------------------------------------------------===//
4729 // Other Decl Allocation/Deallocation Method Implementations
4730 //===----------------------------------------------------------------------===//
4731
anchor()4732 void TranslationUnitDecl::anchor() {}
4733
Create(ASTContext & C)4734 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
4735 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
4736 }
4737
anchor()4738 void PragmaCommentDecl::anchor() {}
4739
Create(const ASTContext & C,TranslationUnitDecl * DC,SourceLocation CommentLoc,PragmaMSCommentKind CommentKind,StringRef Arg)4740 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4741 TranslationUnitDecl *DC,
4742 SourceLocation CommentLoc,
4743 PragmaMSCommentKind CommentKind,
4744 StringRef Arg) {
4745 PragmaCommentDecl *PCD =
4746 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4747 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4748 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4749 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4750 return PCD;
4751 }
4752
CreateDeserialized(ASTContext & C,unsigned ID,unsigned ArgSize)4753 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4754 unsigned ID,
4755 unsigned ArgSize) {
4756 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4757 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4758 }
4759
anchor()4760 void PragmaDetectMismatchDecl::anchor() {}
4761
4762 PragmaDetectMismatchDecl *
Create(const ASTContext & C,TranslationUnitDecl * DC,SourceLocation Loc,StringRef Name,StringRef Value)4763 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4764 SourceLocation Loc, StringRef Name,
4765 StringRef Value) {
4766 size_t ValueStart = Name.size() + 1;
4767 PragmaDetectMismatchDecl *PDMD =
4768 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4769 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4770 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4771 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4772 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4773 Value.size());
4774 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4775 return PDMD;
4776 }
4777
4778 PragmaDetectMismatchDecl *
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NameValueSize)4779 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4780 unsigned NameValueSize) {
4781 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4782 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4783 }
4784
anchor()4785 void ExternCContextDecl::anchor() {}
4786
Create(const ASTContext & C,TranslationUnitDecl * DC)4787 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4788 TranslationUnitDecl *DC) {
4789 return new (C, DC) ExternCContextDecl(DC);
4790 }
4791
anchor()4792 void LabelDecl::anchor() {}
4793
Create(ASTContext & C,DeclContext * DC,SourceLocation IdentL,IdentifierInfo * II)4794 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4795 SourceLocation IdentL, IdentifierInfo *II) {
4796 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
4797 }
4798
Create(ASTContext & C,DeclContext * DC,SourceLocation IdentL,IdentifierInfo * II,SourceLocation GnuLabelL)4799 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4800 SourceLocation IdentL, IdentifierInfo *II,
4801 SourceLocation GnuLabelL) {
4802 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
4803 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
4804 }
4805
CreateDeserialized(ASTContext & C,unsigned ID)4806 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4807 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4808 SourceLocation());
4809 }
4810
setMSAsmLabel(StringRef Name)4811 void LabelDecl::setMSAsmLabel(StringRef Name) {
4812 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4813 memcpy(Buffer, Name.data(), Name.size());
4814 Buffer[Name.size()] = '\0';
4815 MSAsmName = Buffer;
4816 }
4817
anchor()4818 void ValueDecl::anchor() {}
4819
isWeak() const4820 bool ValueDecl::isWeak() const {
4821 auto *MostRecent = getMostRecentDecl();
4822 return MostRecent->hasAttr<WeakAttr>() ||
4823 MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
4824 }
4825
anchor()4826 void ImplicitParamDecl::anchor() {}
4827
Create(ASTContext & C,DeclContext * DC,SourceLocation IdLoc,IdentifierInfo * Id,QualType Type,ImplicitParamKind ParamKind)4828 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
4829 SourceLocation IdLoc,
4830 IdentifierInfo *Id, QualType Type,
4831 ImplicitParamKind ParamKind) {
4832 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4833 }
4834
Create(ASTContext & C,QualType Type,ImplicitParamKind ParamKind)4835 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4836 ImplicitParamKind ParamKind) {
4837 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
4838 }
4839
CreateDeserialized(ASTContext & C,unsigned ID)4840 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
4841 unsigned ID) {
4842 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
4843 }
4844
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,StorageClass SC,bool isInlineSpecified,bool hasWrittenPrototype,ConstexprSpecKind ConstexprKind,Expr * TrailingRequiresClause)4845 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
4846 SourceLocation StartLoc,
4847 const DeclarationNameInfo &NameInfo,
4848 QualType T, TypeSourceInfo *TInfo,
4849 StorageClass SC, bool isInlineSpecified,
4850 bool hasWrittenPrototype,
4851 ConstexprSpecKind ConstexprKind,
4852 Expr *TrailingRequiresClause) {
4853 FunctionDecl *New =
4854 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4855 SC, isInlineSpecified, ConstexprKind,
4856 TrailingRequiresClause);
4857 New->setHasWrittenPrototype(hasWrittenPrototype);
4858 return New;
4859 }
4860
CreateDeserialized(ASTContext & C,unsigned ID)4861 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4862 return new (C, ID) FunctionDecl(
4863 Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),
4864 nullptr, SC_None, false, ConstexprSpecKind::Unspecified, nullptr);
4865 }
4866
Create(ASTContext & C,DeclContext * DC,SourceLocation L)4867 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4868 return new (C, DC) BlockDecl(DC, L);
4869 }
4870
CreateDeserialized(ASTContext & C,unsigned ID)4871 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4872 return new (C, ID) BlockDecl(nullptr, SourceLocation());
4873 }
4874
CapturedDecl(DeclContext * DC,unsigned NumParams)4875 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4876 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4877 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4878
Create(ASTContext & C,DeclContext * DC,unsigned NumParams)4879 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4880 unsigned NumParams) {
4881 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4882 CapturedDecl(DC, NumParams);
4883 }
4884
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NumParams)4885 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4886 unsigned NumParams) {
4887 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4888 CapturedDecl(nullptr, NumParams);
4889 }
4890
getBody() const4891 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
setBody(Stmt * B)4892 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4893
isNothrow() const4894 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
setNothrow(bool Nothrow)4895 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4896
Create(ASTContext & C,EnumDecl * CD,SourceLocation L,IdentifierInfo * Id,QualType T,Expr * E,const llvm::APSInt & V)4897 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4898 SourceLocation L,
4899 IdentifierInfo *Id, QualType T,
4900 Expr *E, const llvm::APSInt &V) {
4901 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
4902 }
4903
4904 EnumConstantDecl *
CreateDeserialized(ASTContext & C,unsigned ID)4905 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4906 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4907 QualType(), nullptr, llvm::APSInt());
4908 }
4909
anchor()4910 void IndirectFieldDecl::anchor() {}
4911
IndirectFieldDecl(ASTContext & C,DeclContext * DC,SourceLocation L,DeclarationName N,QualType T,MutableArrayRef<NamedDecl * > CH)4912 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4913 SourceLocation L, DeclarationName N,
4914 QualType T,
4915 MutableArrayRef<NamedDecl *> CH)
4916 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4917 ChainingSize(CH.size()) {
4918 // In C++, indirect field declarations conflict with tag declarations in the
4919 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4920 if (C.getLangOpts().CPlusPlus)
4921 IdentifierNamespace |= IDNS_Tag;
4922 }
4923
4924 IndirectFieldDecl *
Create(ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,QualType T,llvm::MutableArrayRef<NamedDecl * > CH)4925 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
4926 IdentifierInfo *Id, QualType T,
4927 llvm::MutableArrayRef<NamedDecl *> CH) {
4928 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
4929 }
4930
CreateDeserialized(ASTContext & C,unsigned ID)4931 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4932 unsigned ID) {
4933 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
4934 DeclarationName(), QualType(), None);
4935 }
4936
getSourceRange() const4937 SourceRange EnumConstantDecl::getSourceRange() const {
4938 SourceLocation End = getLocation();
4939 if (Init)
4940 End = Init->getEndLoc();
4941 return SourceRange(getLocation(), End);
4942 }
4943
anchor()4944 void TypeDecl::anchor() {}
4945
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)4946 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
4947 SourceLocation StartLoc, SourceLocation IdLoc,
4948 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
4949 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4950 }
4951
anchor()4952 void TypedefNameDecl::anchor() {}
4953
getAnonDeclWithTypedefName(bool AnyRedecl) const4954 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4955 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4956 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4957 auto *ThisTypedef = this;
4958 if (AnyRedecl && OwningTypedef) {
4959 OwningTypedef = OwningTypedef->getCanonicalDecl();
4960 ThisTypedef = ThisTypedef->getCanonicalDecl();
4961 }
4962 if (OwningTypedef == ThisTypedef)
4963 return TT->getDecl();
4964 }
4965
4966 return nullptr;
4967 }
4968
isTransparentTagSlow() const4969 bool TypedefNameDecl::isTransparentTagSlow() const {
4970 auto determineIsTransparent = [&]() {
4971 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4972 if (auto *TD = TT->getDecl()) {
4973 if (TD->getName() != getName())
4974 return false;
4975 SourceLocation TTLoc = getLocation();
4976 SourceLocation TDLoc = TD->getLocation();
4977 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4978 return false;
4979 SourceManager &SM = getASTContext().getSourceManager();
4980 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4981 }
4982 }
4983 return false;
4984 };
4985
4986 bool isTransparent = determineIsTransparent();
4987 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
4988 return isTransparent;
4989 }
4990
CreateDeserialized(ASTContext & C,unsigned ID)4991 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4992 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
4993 nullptr, nullptr);
4994 }
4995
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)4996 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4997 SourceLocation StartLoc,
4998 SourceLocation IdLoc, IdentifierInfo *Id,
4999 TypeSourceInfo *TInfo) {
5000 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5001 }
5002
CreateDeserialized(ASTContext & C,unsigned ID)5003 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5004 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
5005 SourceLocation(), nullptr, nullptr);
5006 }
5007
getSourceRange() const5008 SourceRange TypedefDecl::getSourceRange() const {
5009 SourceLocation RangeEnd = getLocation();
5010 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
5011 if (typeIsPostfix(TInfo->getType()))
5012 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5013 }
5014 return SourceRange(getBeginLoc(), RangeEnd);
5015 }
5016
getSourceRange() const5017 SourceRange TypeAliasDecl::getSourceRange() const {
5018 SourceLocation RangeEnd = getBeginLoc();
5019 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
5020 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5021 return SourceRange(getBeginLoc(), RangeEnd);
5022 }
5023
anchor()5024 void FileScopeAsmDecl::anchor() {}
5025
Create(ASTContext & C,DeclContext * DC,StringLiteral * Str,SourceLocation AsmLoc,SourceLocation RParenLoc)5026 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
5027 StringLiteral *Str,
5028 SourceLocation AsmLoc,
5029 SourceLocation RParenLoc) {
5030 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
5031 }
5032
CreateDeserialized(ASTContext & C,unsigned ID)5033 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
5034 unsigned ID) {
5035 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
5036 SourceLocation());
5037 }
5038
anchor()5039 void EmptyDecl::anchor() {}
5040
Create(ASTContext & C,DeclContext * DC,SourceLocation L)5041 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5042 return new (C, DC) EmptyDecl(DC, L);
5043 }
5044
CreateDeserialized(ASTContext & C,unsigned ID)5045 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5046 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
5047 }
5048
5049 //===----------------------------------------------------------------------===//
5050 // ImportDecl Implementation
5051 //===----------------------------------------------------------------------===//
5052
5053 /// Retrieve the number of module identifiers needed to name the given
5054 /// module.
getNumModuleIdentifiers(Module * Mod)5055 static unsigned getNumModuleIdentifiers(Module *Mod) {
5056 unsigned Result = 1;
5057 while (Mod->Parent) {
5058 Mod = Mod->Parent;
5059 ++Result;
5060 }
5061 return Result;
5062 }
5063
ImportDecl(DeclContext * DC,SourceLocation StartLoc,Module * Imported,ArrayRef<SourceLocation> IdentifierLocs)5064 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5065 Module *Imported,
5066 ArrayRef<SourceLocation> IdentifierLocs)
5067 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5068 NextLocalImportAndComplete(nullptr, true) {
5069 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
5070 auto *StoredLocs = getTrailingObjects<SourceLocation>();
5071 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
5072 StoredLocs);
5073 }
5074
ImportDecl(DeclContext * DC,SourceLocation StartLoc,Module * Imported,SourceLocation EndLoc)5075 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5076 Module *Imported, SourceLocation EndLoc)
5077 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5078 NextLocalImportAndComplete(nullptr, false) {
5079 *getTrailingObjects<SourceLocation>() = EndLoc;
5080 }
5081
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,Module * Imported,ArrayRef<SourceLocation> IdentifierLocs)5082 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
5083 SourceLocation StartLoc, Module *Imported,
5084 ArrayRef<SourceLocation> IdentifierLocs) {
5085 return new (C, DC,
5086 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
5087 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
5088 }
5089
CreateImplicit(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,Module * Imported,SourceLocation EndLoc)5090 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
5091 SourceLocation StartLoc,
5092 Module *Imported,
5093 SourceLocation EndLoc) {
5094 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
5095 ImportDecl(DC, StartLoc, Imported, EndLoc);
5096 Import->setImplicit();
5097 return Import;
5098 }
5099
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NumLocations)5100 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
5101 unsigned NumLocations) {
5102 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
5103 ImportDecl(EmptyShell());
5104 }
5105
getIdentifierLocs() const5106 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
5107 if (!isImportComplete())
5108 return None;
5109
5110 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
5111 return llvm::makeArrayRef(StoredLocs,
5112 getNumModuleIdentifiers(getImportedModule()));
5113 }
5114
getSourceRange() const5115 SourceRange ImportDecl::getSourceRange() const {
5116 if (!isImportComplete())
5117 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
5118
5119 return SourceRange(getLocation(), getIdentifierLocs().back());
5120 }
5121
5122 //===----------------------------------------------------------------------===//
5123 // ExportDecl Implementation
5124 //===----------------------------------------------------------------------===//
5125
anchor()5126 void ExportDecl::anchor() {}
5127
Create(ASTContext & C,DeclContext * DC,SourceLocation ExportLoc)5128 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
5129 SourceLocation ExportLoc) {
5130 return new (C, DC) ExportDecl(DC, ExportLoc);
5131 }
5132
CreateDeserialized(ASTContext & C,unsigned ID)5133 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5134 return new (C, ID) ExportDecl(nullptr, SourceLocation());
5135 }
5136