Deleted Added
full compact
Decl.cpp (280031) Decl.cpp (283526)
1//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/PrettyPrinter.h"
25#include "clang/AST/Stmt.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/IdentifierTable.h"
29#include "clang/Basic/Module.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Frontend/FrontendDiagnostic.h"
33#include "llvm/Support/ErrorHandling.h"
34#include <algorithm>
35
36using namespace clang;
37
38Decl *clang::getPrimaryMergedDecl(Decl *D) {
39 return D->getASTContext().getPrimaryMergedDecl(D);
40}
41
42// Defined here so that it can be inlined into its direct callers.
43bool Decl::isOutOfLine() const {
44 return !getLexicalDeclContext()->Equals(getDeclContext());
45}
46
47//===----------------------------------------------------------------------===//
48// NamedDecl Implementation
49//===----------------------------------------------------------------------===//
50
51// Visibility rules aren't rigorously externally specified, but here
52// are the basic principles behind what we implement:
53//
54// 1. An explicit visibility attribute is generally a direct expression
55// of the user's intent and should be honored. Only the innermost
56// visibility attribute applies. If no visibility attribute applies,
57// global visibility settings are considered.
58//
59// 2. There is one caveat to the above: on or in a template pattern,
60// an explicit visibility attribute is just a default rule, and
61// visibility can be decreased by the visibility of template
62// arguments. But this, too, has an exception: an attribute on an
63// explicit specialization or instantiation causes all the visibility
64// restrictions of the template arguments to be ignored.
65//
66// 3. A variable that does not otherwise have explicit visibility can
67// be restricted by the visibility of its type.
68//
69// 4. A visibility restriction is explicit if it comes from an
70// attribute (or something like it), not a global visibility setting.
71// When emitting a reference to an external symbol, visibility
72// restrictions are ignored unless they are explicit.
73//
74// 5. When computing the visibility of a non-type, including a
75// non-type member of a class, only non-type visibility restrictions
76// are considered: the 'visibility' attribute, global value-visibility
77// settings, and a few special cases like __private_extern.
78//
79// 6. When computing the visibility of a type, including a type member
80// of a class, only type visibility restrictions are considered:
81// the 'type_visibility' attribute and global type-visibility settings.
82// However, a 'visibility' attribute counts as a 'type_visibility'
83// attribute on any declaration that only has the former.
84//
85// The visibility of a "secondary" entity, like a template argument,
86// is computed using the kind of that entity, not the kind of the
87// primary entity for which we are computing visibility. For example,
88// the visibility of a specialization of either of these templates:
89// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
90// template <class T, bool (&compare)(T, X)> class matcher;
91// is restricted according to the type visibility of the argument 'T',
92// the type visibility of 'bool(&)(T,X)', and the value visibility of
93// the argument function 'compare'. That 'has_match' is a value
94// and 'matcher' is a type only matters when looking for attributes
95// and settings from the immediate context.
96
97const unsigned IgnoreExplicitVisibilityBit = 2;
98const unsigned IgnoreAllVisibilityBit = 4;
99
100/// Kinds of LV computation. The linkage side of the computation is
101/// always the same, but different things can change how visibility is
102/// computed.
103enum LVComputationKind {
104 /// Do an LV computation for, ultimately, a type.
105 /// Visibility may be restricted by type visibility settings and
106 /// the visibility of template arguments.
107 LVForType = NamedDecl::VisibilityForType,
108
109 /// Do an LV computation for, ultimately, a non-type declaration.
110 /// Visibility may be restricted by value visibility settings and
111 /// the visibility of template arguments.
112 LVForValue = NamedDecl::VisibilityForValue,
113
114 /// Do an LV computation for, ultimately, a type that already has
115 /// some sort of explicit visibility. Visibility may only be
116 /// restricted by the visibility of template arguments.
117 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
118
119 /// Do an LV computation for, ultimately, a non-type declaration
120 /// that already has some sort of explicit visibility. Visibility
121 /// may only be restricted by the visibility of template arguments.
122 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
123
124 /// Do an LV computation when we only care about the linkage.
125 LVForLinkageOnly =
126 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
127};
128
129/// Does this computation kind permit us to consider additional
130/// visibility settings from attributes and the like?
131static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
132 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
133}
134
135/// Given an LVComputationKind, return one of the same type/value sort
136/// that records that it already has explicit visibility.
137static LVComputationKind
138withExplicitVisibilityAlready(LVComputationKind oldKind) {
139 LVComputationKind newKind =
140 static_cast<LVComputationKind>(unsigned(oldKind) |
141 IgnoreExplicitVisibilityBit);
142 assert(oldKind != LVForType || newKind == LVForExplicitType);
143 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
144 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
145 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
146 return newKind;
147}
148
149static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
150 LVComputationKind kind) {
151 assert(!hasExplicitVisibilityAlready(kind) &&
152 "asking for explicit visibility when we shouldn't be");
153 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
154}
155
156/// Is the given declaration a "type" or a "value" for the purposes of
157/// visibility computation?
158static bool usesTypeVisibility(const NamedDecl *D) {
159 return isa<TypeDecl>(D) ||
160 isa<ClassTemplateDecl>(D) ||
161 isa<ObjCInterfaceDecl>(D);
162}
163
164/// Does the given declaration have member specialization information,
165/// and if so, is it an explicit specialization?
166template <class T> static typename
167std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
168isExplicitMemberSpecialization(const T *D) {
169 if (const MemberSpecializationInfo *member =
170 D->getMemberSpecializationInfo()) {
171 return member->isExplicitSpecialization();
172 }
173 return false;
174}
175
176/// For templates, this question is easier: a member template can't be
177/// explicitly instantiated, so there's a single bit indicating whether
178/// or not this is an explicit member specialization.
179static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
180 return D->isMemberSpecialization();
181}
182
183/// Given a visibility attribute, return the explicit visibility
184/// associated with it.
185template <class T>
186static Visibility getVisibilityFromAttr(const T *attr) {
187 switch (attr->getVisibility()) {
188 case T::Default:
189 return DefaultVisibility;
190 case T::Hidden:
191 return HiddenVisibility;
192 case T::Protected:
193 return ProtectedVisibility;
194 }
195 llvm_unreachable("bad visibility kind");
196}
197
198/// Return the explicit visibility of the given declaration.
199static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
200 NamedDecl::ExplicitVisibilityKind kind) {
201 // If we're ultimately computing the visibility of a type, look for
202 // a 'type_visibility' attribute before looking for 'visibility'.
203 if (kind == NamedDecl::VisibilityForType) {
204 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
205 return getVisibilityFromAttr(A);
206 }
207 }
208
209 // If this declaration has an explicit visibility attribute, use it.
210 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
211 return getVisibilityFromAttr(A);
212 }
213
214 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
215 // implies visibility(default).
216 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
217 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
218 if (A->getPlatform()->getName().equals("macosx"))
219 return DefaultVisibility;
220 }
221
222 return None;
223}
224
225static LinkageInfo
226getLVForType(const Type &T, LVComputationKind computation) {
227 if (computation == LVForLinkageOnly)
228 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
229 return T.getLinkageAndVisibility();
230}
231
232/// \brief Get the most restrictive linkage for the types in the given
233/// template parameter list. For visibility purposes, template
234/// parameters are part of the signature of a template.
235static LinkageInfo
236getLVForTemplateParameterList(const TemplateParameterList *Params,
237 LVComputationKind computation) {
238 LinkageInfo LV;
239 for (const NamedDecl *P : *Params) {
240 // Template type parameters are the most common and never
241 // contribute to visibility, pack or not.
242 if (isa<TemplateTypeParmDecl>(P))
243 continue;
244
245 // Non-type template parameters can be restricted by the value type, e.g.
246 // template <enum X> class A { ... };
247 // We have to be careful here, though, because we can be dealing with
248 // dependent types.
249 if (const NonTypeTemplateParmDecl *NTTP =
250 dyn_cast<NonTypeTemplateParmDecl>(P)) {
251 // Handle the non-pack case first.
252 if (!NTTP->isExpandedParameterPack()) {
253 if (!NTTP->getType()->isDependentType()) {
254 LV.merge(getLVForType(*NTTP->getType(), computation));
255 }
256 continue;
257 }
258
259 // Look at all the types in an expanded pack.
260 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
261 QualType type = NTTP->getExpansionType(i);
262 if (!type->isDependentType())
263 LV.merge(type->getLinkageAndVisibility());
264 }
265 continue;
266 }
267
268 // Template template parameters can be restricted by their
269 // template parameters, recursively.
270 const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P);
271
272 // Handle the non-pack case first.
273 if (!TTP->isExpandedParameterPack()) {
274 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
275 computation));
276 continue;
277 }
278
279 // Look at all expansions in an expanded pack.
280 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
281 i != n; ++i) {
282 LV.merge(getLVForTemplateParameterList(
283 TTP->getExpansionTemplateParameters(i), computation));
284 }
285 }
286
287 return LV;
288}
289
290/// getLVForDecl - Get the linkage and visibility for the given declaration.
291static LinkageInfo getLVForDecl(const NamedDecl *D,
292 LVComputationKind computation);
293
294static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
295 const Decl *Ret = nullptr;
296 const DeclContext *DC = D->getDeclContext();
297 while (DC->getDeclKind() != Decl::TranslationUnit) {
298 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
299 Ret = cast<Decl>(DC);
300 DC = DC->getParent();
301 }
302 return Ret;
303}
304
305/// \brief Get the most restrictive linkage for the types and
306/// declarations in the given template argument list.
307///
308/// Note that we don't take an LVComputationKind because we always
309/// want to honor the visibility of template arguments in the same way.
310static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
311 LVComputationKind computation) {
312 LinkageInfo LV;
313
314 for (const TemplateArgument &Arg : Args) {
315 switch (Arg.getKind()) {
316 case TemplateArgument::Null:
317 case TemplateArgument::Integral:
318 case TemplateArgument::Expression:
319 continue;
320
321 case TemplateArgument::Type:
322 LV.merge(getLVForType(*Arg.getAsType(), computation));
323 continue;
324
325 case TemplateArgument::Declaration:
326 if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
327 assert(!usesTypeVisibility(ND));
328 LV.merge(getLVForDecl(ND, computation));
329 }
330 continue;
331
332 case TemplateArgument::NullPtr:
333 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
334 continue;
335
336 case TemplateArgument::Template:
337 case TemplateArgument::TemplateExpansion:
338 if (TemplateDecl *Template =
339 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
340 LV.merge(getLVForDecl(Template, computation));
341 continue;
342
343 case TemplateArgument::Pack:
344 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
345 continue;
346 }
347 llvm_unreachable("bad template argument kind");
348 }
349
350 return LV;
351}
352
353static LinkageInfo
354getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
355 LVComputationKind computation) {
356 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
357}
358
359static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
360 const FunctionTemplateSpecializationInfo *specInfo) {
361 // Include visibility from the template parameters and arguments
362 // only if this is not an explicit instantiation or specialization
363 // with direct explicit visibility. (Implicit instantiations won't
364 // have a direct attribute.)
365 if (!specInfo->isExplicitInstantiationOrSpecialization())
366 return true;
367
368 return !fn->hasAttr<VisibilityAttr>();
369}
370
371/// Merge in template-related linkage and visibility for the given
372/// function template specialization.
373///
374/// We don't need a computation kind here because we can assume
375/// LVForValue.
376///
377/// \param[out] LV the computation to use for the parent
378static void
379mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
380 const FunctionTemplateSpecializationInfo *specInfo,
381 LVComputationKind computation) {
382 bool considerVisibility =
383 shouldConsiderTemplateVisibility(fn, specInfo);
384
385 // Merge information from the template parameters.
386 FunctionTemplateDecl *temp = specInfo->getTemplate();
387 LinkageInfo tempLV =
388 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
389 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
390
391 // Merge information from the template arguments.
392 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
393 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
394 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
395}
396
397/// Does the given declaration have a direct visibility attribute
398/// that would match the given rules?
399static bool hasDirectVisibilityAttribute(const NamedDecl *D,
400 LVComputationKind computation) {
401 switch (computation) {
402 case LVForType:
403 case LVForExplicitType:
404 if (D->hasAttr<TypeVisibilityAttr>())
405 return true;
406 // fallthrough
407 case LVForValue:
408 case LVForExplicitValue:
409 if (D->hasAttr<VisibilityAttr>())
410 return true;
411 return false;
412 case LVForLinkageOnly:
413 return false;
414 }
415 llvm_unreachable("bad visibility computation kind");
416}
417
418/// Should we consider visibility associated with the template
419/// arguments and parameters of the given class template specialization?
420static bool shouldConsiderTemplateVisibility(
421 const ClassTemplateSpecializationDecl *spec,
422 LVComputationKind computation) {
423 // Include visibility from the template parameters and arguments
424 // only if this is not an explicit instantiation or specialization
425 // with direct explicit visibility (and note that implicit
426 // instantiations won't have a direct attribute).
427 //
428 // Furthermore, we want to ignore template parameters and arguments
429 // for an explicit specialization when computing the visibility of a
430 // member thereof with explicit visibility.
431 //
432 // This is a bit complex; let's unpack it.
433 //
434 // An explicit class specialization is an independent, top-level
435 // declaration. As such, if it or any of its members has an
436 // explicit visibility attribute, that must directly express the
437 // user's intent, and we should honor it. The same logic applies to
438 // an explicit instantiation of a member of such a thing.
439
440 // Fast path: if this is not an explicit instantiation or
441 // specialization, we always want to consider template-related
442 // visibility restrictions.
443 if (!spec->isExplicitInstantiationOrSpecialization())
444 return true;
445
446 // This is the 'member thereof' check.
447 if (spec->isExplicitSpecialization() &&
448 hasExplicitVisibilityAlready(computation))
449 return false;
450
451 return !hasDirectVisibilityAttribute(spec, computation);
452}
453
454/// Merge in template-related linkage and visibility for the given
455/// class template specialization.
456static void mergeTemplateLV(LinkageInfo &LV,
457 const ClassTemplateSpecializationDecl *spec,
458 LVComputationKind computation) {
459 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
460
461 // Merge information from the template parameters, but ignore
462 // visibility if we're only considering template arguments.
463
464 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
465 LinkageInfo tempLV =
466 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
467 LV.mergeMaybeWithVisibility(tempLV,
468 considerVisibility && !hasExplicitVisibilityAlready(computation));
469
470 // Merge information from the template arguments. We ignore
471 // template-argument visibility if we've got an explicit
472 // instantiation with a visibility attribute.
473 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
474 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
475 if (considerVisibility)
476 LV.mergeVisibility(argsLV);
477 LV.mergeExternalVisibility(argsLV);
478}
479
480/// Should we consider visibility associated with the template
481/// arguments and parameters of the given variable template
482/// specialization? As usual, follow class template specialization
483/// logic up to initialization.
484static bool shouldConsiderTemplateVisibility(
485 const VarTemplateSpecializationDecl *spec,
486 LVComputationKind computation) {
487 // Include visibility from the template parameters and arguments
488 // only if this is not an explicit instantiation or specialization
489 // with direct explicit visibility (and note that implicit
490 // instantiations won't have a direct attribute).
491 if (!spec->isExplicitInstantiationOrSpecialization())
492 return true;
493
494 // An explicit variable specialization is an independent, top-level
495 // declaration. As such, if it has an explicit visibility attribute,
496 // that must directly express the user's intent, and we should honor
497 // it.
498 if (spec->isExplicitSpecialization() &&
499 hasExplicitVisibilityAlready(computation))
500 return false;
501
502 return !hasDirectVisibilityAttribute(spec, computation);
503}
504
505/// Merge in template-related linkage and visibility for the given
506/// variable template specialization. As usual, follow class template
507/// specialization logic up to initialization.
508static void mergeTemplateLV(LinkageInfo &LV,
509 const VarTemplateSpecializationDecl *spec,
510 LVComputationKind computation) {
511 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
512
513 // Merge information from the template parameters, but ignore
514 // visibility if we're only considering template arguments.
515
516 VarTemplateDecl *temp = spec->getSpecializedTemplate();
517 LinkageInfo tempLV =
518 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
519 LV.mergeMaybeWithVisibility(tempLV,
520 considerVisibility && !hasExplicitVisibilityAlready(computation));
521
522 // Merge information from the template arguments. We ignore
523 // template-argument visibility if we've got an explicit
524 // instantiation with a visibility attribute.
525 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
526 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
527 if (considerVisibility)
528 LV.mergeVisibility(argsLV);
529 LV.mergeExternalVisibility(argsLV);
530}
531
532static bool useInlineVisibilityHidden(const NamedDecl *D) {
533 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
534 const LangOptions &Opts = D->getASTContext().getLangOpts();
535 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
536 return false;
537
538 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
539 if (!FD)
540 return false;
541
542 TemplateSpecializationKind TSK = TSK_Undeclared;
543 if (FunctionTemplateSpecializationInfo *spec
544 = FD->getTemplateSpecializationInfo()) {
545 TSK = spec->getTemplateSpecializationKind();
546 } else if (MemberSpecializationInfo *MSI =
547 FD->getMemberSpecializationInfo()) {
548 TSK = MSI->getTemplateSpecializationKind();
549 }
550
551 const FunctionDecl *Def = nullptr;
552 // InlineVisibilityHidden only applies to definitions, and
553 // isInlined() only gives meaningful answers on definitions
554 // anyway.
555 return TSK != TSK_ExplicitInstantiationDeclaration &&
556 TSK != TSK_ExplicitInstantiationDefinition &&
557 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
558}
559
560template <typename T> static bool isFirstInExternCContext(T *D) {
561 const T *First = D->getFirstDecl();
562 return First->isInExternCContext();
563}
564
565static bool isSingleLineLanguageLinkage(const Decl &D) {
566 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
567 if (!SD->hasBraces())
568 return true;
569 return false;
570}
571
572static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
573 LVComputationKind computation) {
574 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
575 "Not a name having namespace scope");
576 ASTContext &Context = D->getASTContext();
577
578 // C++ [basic.link]p3:
579 // A name having namespace scope (3.3.6) has internal linkage if it
580 // is the name of
581 // - an object, reference, function or function template that is
582 // explicitly declared static; or,
583 // (This bullet corresponds to C99 6.2.2p3.)
584 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
585 // Explicitly declared static.
586 if (Var->getStorageClass() == SC_Static)
587 return LinkageInfo::internal();
588
589 // - a non-volatile object or reference that is explicitly declared const
590 // or constexpr and neither explicitly declared extern nor previously
591 // declared to have external linkage; or (there is no equivalent in C99)
592 if (Context.getLangOpts().CPlusPlus &&
593 Var->getType().isConstQualified() &&
594 !Var->getType().isVolatileQualified()) {
595 const VarDecl *PrevVar = Var->getPreviousDecl();
596 if (PrevVar)
597 return getLVForDecl(PrevVar, computation);
598
599 if (Var->getStorageClass() != SC_Extern &&
600 Var->getStorageClass() != SC_PrivateExtern &&
601 !isSingleLineLanguageLinkage(*Var))
602 return LinkageInfo::internal();
603 }
604
605 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
606 PrevVar = PrevVar->getPreviousDecl()) {
607 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
608 Var->getStorageClass() == SC_None)
609 return PrevVar->getLinkageAndVisibility();
610 // Explicitly declared static.
611 if (PrevVar->getStorageClass() == SC_Static)
612 return LinkageInfo::internal();
613 }
614 } else if (const FunctionDecl *Function = D->getAsFunction()) {
615 // C++ [temp]p4:
616 // A non-member function template can have internal linkage; any
617 // other template name shall have external linkage.
618
619 // Explicitly declared static.
620 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
621 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
622 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
623 // - a data member of an anonymous union.
624 const VarDecl *VD = IFD->getVarDecl();
625 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
626 return getLVForNamespaceScopeDecl(VD, computation);
627 }
628 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
629
630 if (D->isInAnonymousNamespace()) {
631 const VarDecl *Var = dyn_cast<VarDecl>(D);
632 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
633 if ((!Var || !isFirstInExternCContext(Var)) &&
634 (!Func || !isFirstInExternCContext(Func)))
635 return LinkageInfo::uniqueExternal();
636 }
637
638 // Set up the defaults.
639
640 // C99 6.2.2p5:
641 // If the declaration of an identifier for an object has file
642 // scope and no storage-class specifier, its linkage is
643 // external.
644 LinkageInfo LV;
645
646 if (!hasExplicitVisibilityAlready(computation)) {
647 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
648 LV.mergeVisibility(*Vis, true);
649 } else {
650 // If we're declared in a namespace with a visibility attribute,
651 // use that namespace's visibility, and it still counts as explicit.
652 for (const DeclContext *DC = D->getDeclContext();
653 !isa<TranslationUnitDecl>(DC);
654 DC = DC->getParent()) {
655 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
656 if (!ND) continue;
657 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
658 LV.mergeVisibility(*Vis, true);
659 break;
660 }
661 }
662 }
663
664 // Add in global settings if the above didn't give us direct visibility.
665 if (!LV.isVisibilityExplicit()) {
666 // Use global type/value visibility as appropriate.
667 Visibility globalVisibility;
668 if (computation == LVForValue) {
669 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
670 } else {
671 assert(computation == LVForType);
672 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
673 }
674 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
675
676 // If we're paying attention to global visibility, apply
677 // -finline-visibility-hidden if this is an inline method.
678 if (useInlineVisibilityHidden(D))
679 LV.mergeVisibility(HiddenVisibility, true);
680 }
681 }
682
683 // C++ [basic.link]p4:
684
685 // A name having namespace scope has external linkage if it is the
686 // name of
687 //
688 // - an object or reference, unless it has internal linkage; or
689 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
690 // GCC applies the following optimization to variables and static
691 // data members, but not to functions:
692 //
693 // Modify the variable's LV by the LV of its type unless this is
694 // C or extern "C". This follows from [basic.link]p9:
695 // A type without linkage shall not be used as the type of a
696 // variable or function with external linkage unless
697 // - the entity has C language linkage, or
698 // - the entity is declared within an unnamed namespace, or
699 // - the entity is not used or is defined in the same
700 // translation unit.
701 // and [basic.link]p10:
702 // ...the types specified by all declarations referring to a
703 // given variable or function shall be identical...
704 // C does not have an equivalent rule.
705 //
706 // Ignore this if we've got an explicit attribute; the user
707 // probably knows what they're doing.
708 //
709 // Note that we don't want to make the variable non-external
710 // because of this, but unique-external linkage suits us.
711 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
712 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
713 if (TypeLV.getLinkage() != ExternalLinkage)
714 return LinkageInfo::uniqueExternal();
715 if (!LV.isVisibilityExplicit())
716 LV.mergeVisibility(TypeLV);
717 }
718
719 if (Var->getStorageClass() == SC_PrivateExtern)
720 LV.mergeVisibility(HiddenVisibility, true);
721
722 // Note that Sema::MergeVarDecl already takes care of implementing
723 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
724 // to do it here.
725
726 // As per function and class template specializations (below),
727 // consider LV for the template and template arguments. We're at file
728 // scope, so we do not need to worry about nested specializations.
729 if (const VarTemplateSpecializationDecl *spec
730 = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
731 mergeTemplateLV(LV, spec, computation);
732 }
733
734 // - a function, unless it has internal linkage; or
735 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
736 // In theory, we can modify the function's LV by the LV of its
737 // type unless it has C linkage (see comment above about variables
738 // for justification). In practice, GCC doesn't do this, so it's
739 // just too painful to make work.
740
741 if (Function->getStorageClass() == SC_PrivateExtern)
742 LV.mergeVisibility(HiddenVisibility, true);
743
744 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
745 // merging storage classes and visibility attributes, so we don't have to
746 // look at previous decls in here.
747
748 // In C++, then if the type of the function uses a type with
749 // unique-external linkage, it's not legally usable from outside
750 // this translation unit. However, we should use the C linkage
751 // rules instead for extern "C" declarations.
752 if (Context.getLangOpts().CPlusPlus &&
753 !Function->isInExternCContext()) {
754 // Only look at the type-as-written. If this function has an auto-deduced
755 // return type, we can't compute the linkage of that type because it could
756 // require looking at the linkage of this function, and we don't need this
757 // for correctness because the type is not part of the function's
758 // signature.
759 // FIXME: This is a hack. We should be able to solve this circularity and
760 // the one in getLVForClassMember for Functions some other way.
761 QualType TypeAsWritten = Function->getType();
762 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
763 TypeAsWritten = TSI->getType();
764 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
765 return LinkageInfo::uniqueExternal();
766 }
767
768 // Consider LV from the template and the template arguments.
769 // We're at file scope, so we do not need to worry about nested
770 // specializations.
771 if (FunctionTemplateSpecializationInfo *specInfo
772 = Function->getTemplateSpecializationInfo()) {
773 mergeTemplateLV(LV, Function, specInfo, computation);
774 }
775
776 // - a named class (Clause 9), or an unnamed class defined in a
777 // typedef declaration in which the class has the typedef name
778 // for linkage purposes (7.1.3); or
779 // - a named enumeration (7.2), or an unnamed enumeration
780 // defined in a typedef declaration in which the enumeration
781 // has the typedef name for linkage purposes (7.1.3); or
782 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
783 // Unnamed tags have no linkage.
784 if (!Tag->hasNameForLinkage())
785 return LinkageInfo::none();
786
787 // If this is a class template specialization, consider the
788 // linkage of the template and template arguments. We're at file
789 // scope, so we do not need to worry about nested specializations.
790 if (const ClassTemplateSpecializationDecl *spec
791 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
792 mergeTemplateLV(LV, spec, computation);
793 }
794
795 // - an enumerator belonging to an enumeration with external linkage;
796 } else if (isa<EnumConstantDecl>(D)) {
797 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
798 computation);
799 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
800 return LinkageInfo::none();
801 LV.merge(EnumLV);
802
803 // - a template, unless it is a function template that has
804 // internal linkage (Clause 14);
805 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
806 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
807 LinkageInfo tempLV =
808 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
809 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
810
811 // - a namespace (7.3), unless it is declared within an unnamed
812 // namespace.
813 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
814 return LV;
815
816 // By extension, we assign external linkage to Objective-C
817 // interfaces.
818 } else if (isa<ObjCInterfaceDecl>(D)) {
819 // fallout
820
821 // Everything not covered here has no linkage.
822 } else {
823 // FIXME: A typedef declaration has linkage if it gives a type a name for
824 // linkage purposes.
825 return LinkageInfo::none();
826 }
827
828 // If we ended up with non-external linkage, visibility should
829 // always be default.
830 if (LV.getLinkage() != ExternalLinkage)
831 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
832
833 return LV;
834}
835
836static LinkageInfo getLVForClassMember(const NamedDecl *D,
837 LVComputationKind computation) {
838 // Only certain class members have linkage. Note that fields don't
839 // really have linkage, but it's convenient to say they do for the
840 // purposes of calculating linkage of pointer-to-data-member
841 // template arguments.
842 //
843 // Templates also don't officially have linkage, but since we ignore
844 // the C++ standard and look at template arguments when determining
845 // linkage and visibility of a template specialization, we might hit
846 // a template template argument that way. If we do, we need to
847 // consider its linkage.
848 if (!(isa<CXXMethodDecl>(D) ||
849 isa<VarDecl>(D) ||
850 isa<FieldDecl>(D) ||
851 isa<IndirectFieldDecl>(D) ||
852 isa<TagDecl>(D) ||
853 isa<TemplateDecl>(D)))
854 return LinkageInfo::none();
855
856 LinkageInfo LV;
857
858 // If we have an explicit visibility attribute, merge that in.
859 if (!hasExplicitVisibilityAlready(computation)) {
860 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
861 LV.mergeVisibility(*Vis, true);
862 // If we're paying attention to global visibility, apply
863 // -finline-visibility-hidden if this is an inline method.
864 //
865 // Note that we do this before merging information about
866 // the class visibility.
867 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
868 LV.mergeVisibility(HiddenVisibility, true);
869 }
870
871 // If this class member has an explicit visibility attribute, the only
872 // thing that can change its visibility is the template arguments, so
873 // only look for them when processing the class.
874 LVComputationKind classComputation = computation;
875 if (LV.isVisibilityExplicit())
876 classComputation = withExplicitVisibilityAlready(computation);
877
878 LinkageInfo classLV =
879 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
880 // If the class already has unique-external linkage, we can't improve.
881 if (classLV.getLinkage() == UniqueExternalLinkage)
882 return LinkageInfo::uniqueExternal();
883
884 if (!isExternallyVisible(classLV.getLinkage()))
885 return LinkageInfo::none();
886
887
888 // Otherwise, don't merge in classLV yet, because in certain cases
889 // we need to completely ignore the visibility from it.
890
891 // Specifically, if this decl exists and has an explicit attribute.
892 const NamedDecl *explicitSpecSuppressor = nullptr;
893
894 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
895 // If the type of the function uses a type with unique-external
896 // linkage, it's not legally usable from outside this translation unit.
897 // But only look at the type-as-written. If this function has an auto-deduced
898 // return type, we can't compute the linkage of that type because it could
899 // require looking at the linkage of this function, and we don't need this
900 // for correctness because the type is not part of the function's
901 // signature.
902 // FIXME: This is a hack. We should be able to solve this circularity and the
903 // one in getLVForNamespaceScopeDecl for Functions some other way.
904 {
905 QualType TypeAsWritten = MD->getType();
906 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
907 TypeAsWritten = TSI->getType();
908 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
909 return LinkageInfo::uniqueExternal();
910 }
911 // If this is a method template specialization, use the linkage for
912 // the template parameters and arguments.
913 if (FunctionTemplateSpecializationInfo *spec
914 = MD->getTemplateSpecializationInfo()) {
915 mergeTemplateLV(LV, MD, spec, computation);
916 if (spec->isExplicitSpecialization()) {
917 explicitSpecSuppressor = MD;
918 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
919 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
920 }
921 } else if (isExplicitMemberSpecialization(MD)) {
922 explicitSpecSuppressor = MD;
923 }
924
925 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
926 if (const ClassTemplateSpecializationDecl *spec
927 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
928 mergeTemplateLV(LV, spec, computation);
929 if (spec->isExplicitSpecialization()) {
930 explicitSpecSuppressor = spec;
931 } else {
932 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
933 if (isExplicitMemberSpecialization(temp)) {
934 explicitSpecSuppressor = temp->getTemplatedDecl();
935 }
936 }
937 } else if (isExplicitMemberSpecialization(RD)) {
938 explicitSpecSuppressor = RD;
939 }
940
941 // Static data members.
942 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
943 if (const VarTemplateSpecializationDecl *spec
944 = dyn_cast<VarTemplateSpecializationDecl>(VD))
945 mergeTemplateLV(LV, spec, computation);
946
947 // Modify the variable's linkage by its type, but ignore the
948 // type's visibility unless it's a definition.
949 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
950 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
951 LV.mergeVisibility(typeLV);
952 LV.mergeExternalVisibility(typeLV);
953
954 if (isExplicitMemberSpecialization(VD)) {
955 explicitSpecSuppressor = VD;
956 }
957
958 // Template members.
959 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
960 bool considerVisibility =
961 (!LV.isVisibilityExplicit() &&
962 !classLV.isVisibilityExplicit() &&
963 !hasExplicitVisibilityAlready(computation));
964 LinkageInfo tempLV =
965 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
966 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
967
968 if (const RedeclarableTemplateDecl *redeclTemp =
969 dyn_cast<RedeclarableTemplateDecl>(temp)) {
970 if (isExplicitMemberSpecialization(redeclTemp)) {
971 explicitSpecSuppressor = temp->getTemplatedDecl();
972 }
973 }
974 }
975
976 // We should never be looking for an attribute directly on a template.
977 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
978
979 // If this member is an explicit member specialization, and it has
980 // an explicit attribute, ignore visibility from the parent.
981 bool considerClassVisibility = true;
982 if (explicitSpecSuppressor &&
983 // optimization: hasDVA() is true only with explicit visibility.
984 LV.isVisibilityExplicit() &&
985 classLV.getVisibility() != DefaultVisibility &&
986 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
987 considerClassVisibility = false;
988 }
989
990 // Finally, merge in information from the class.
991 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
992 return LV;
993}
994
995void NamedDecl::anchor() { }
996
997static LinkageInfo computeLVForDecl(const NamedDecl *D,
998 LVComputationKind computation);
999
1000bool NamedDecl::isLinkageValid() const {
1001 if (!hasCachedLinkage())
1002 return true;
1003
1004 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
1005 getCachedLinkage();
1006}
1007
1008ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1009 StringRef name = getName();
1010 if (name.empty()) return SFF_None;
1011
1012 if (name.front() == 'C')
1013 if (name == "CFStringCreateWithFormat" ||
1014 name == "CFStringCreateWithFormatAndArguments" ||
1015 name == "CFStringAppendFormat" ||
1016 name == "CFStringAppendFormatAndArguments")
1017 return SFF_CFString;
1018 return SFF_None;
1019}
1020
1021Linkage NamedDecl::getLinkageInternal() const {
1022 // We don't care about visibility here, so ask for the cheapest
1023 // possible visibility analysis.
1024 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
1025}
1026
1027LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1028 LVComputationKind computation =
1029 (usesTypeVisibility(this) ? LVForType : LVForValue);
1030 return getLVForDecl(this, computation);
1031}
1032
1033static Optional<Visibility>
1034getExplicitVisibilityAux(const NamedDecl *ND,
1035 NamedDecl::ExplicitVisibilityKind kind,
1036 bool IsMostRecent) {
1037 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1038
1039 // Check the declaration itself first.
1040 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1041 return V;
1042
1043 // If this is a member class of a specialization of a class template
1044 // and the corresponding decl has explicit visibility, use that.
1045 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
1046 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1047 if (InstantiatedFrom)
1048 return getVisibilityOf(InstantiatedFrom, kind);
1049 }
1050
1051 // If there wasn't explicit visibility there, and this is a
1052 // specialization of a class template, check for visibility
1053 // on the pattern.
1054 if (const ClassTemplateSpecializationDecl *spec
1055 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
1056 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1057 kind);
1058
1059 // Use the most recent declaration.
1060 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1061 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1062 if (MostRecent != ND)
1063 return getExplicitVisibilityAux(MostRecent, kind, true);
1064 }
1065
1066 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
1067 if (Var->isStaticDataMember()) {
1068 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1069 if (InstantiatedFrom)
1070 return getVisibilityOf(InstantiatedFrom, kind);
1071 }
1072
1073 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1074 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1075 kind);
1076
1077 return None;
1078 }
1079 // Also handle function template specializations.
1080 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
1081 // If the function is a specialization of a template with an
1082 // explicit visibility attribute, use that.
1083 if (FunctionTemplateSpecializationInfo *templateInfo
1084 = fn->getTemplateSpecializationInfo())
1085 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1086 kind);
1087
1088 // If the function is a member of a specialization of a class template
1089 // and the corresponding decl has explicit visibility, use that.
1090 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1091 if (InstantiatedFrom)
1092 return getVisibilityOf(InstantiatedFrom, kind);
1093
1094 return None;
1095 }
1096
1097 // The visibility of a template is stored in the templated decl.
1098 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
1099 return getVisibilityOf(TD->getTemplatedDecl(), kind);
1100
1101 return None;
1102}
1103
1104Optional<Visibility>
1105NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1106 return getExplicitVisibilityAux(this, kind, false);
1107}
1108
1109static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1110 LVComputationKind computation) {
1111 // This lambda has its linkage/visibility determined by its owner.
1112 if (ContextDecl) {
1113 if (isa<ParmVarDecl>(ContextDecl))
1114 DC = ContextDecl->getDeclContext()->getRedeclContext();
1115 else
1116 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1117 }
1118
1119 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1120 return getLVForDecl(ND, computation);
1121
1122 return LinkageInfo::external();
1123}
1124
1125static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1126 LVComputationKind computation) {
1127 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1128 if (Function->isInAnonymousNamespace() &&
1129 !Function->isInExternCContext())
1130 return LinkageInfo::uniqueExternal();
1131
1132 // This is a "void f();" which got merged with a file static.
1133 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1134 return LinkageInfo::internal();
1135
1136 LinkageInfo LV;
1137 if (!hasExplicitVisibilityAlready(computation)) {
1138 if (Optional<Visibility> Vis =
1139 getExplicitVisibility(Function, computation))
1140 LV.mergeVisibility(*Vis, true);
1141 }
1142
1143 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1144 // merging storage classes and visibility attributes, so we don't have to
1145 // look at previous decls in here.
1146
1147 return LV;
1148 }
1149
1150 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1151 if (Var->hasExternalStorage()) {
1152 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
1153 return LinkageInfo::uniqueExternal();
1154
1155 LinkageInfo LV;
1156 if (Var->getStorageClass() == SC_PrivateExtern)
1157 LV.mergeVisibility(HiddenVisibility, true);
1158 else if (!hasExplicitVisibilityAlready(computation)) {
1159 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1160 LV.mergeVisibility(*Vis, true);
1161 }
1162
1163 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1164 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1165 if (PrevLV.getLinkage())
1166 LV.setLinkage(PrevLV.getLinkage());
1167 LV.mergeVisibility(PrevLV);
1168 }
1169
1170 return LV;
1171 }
1172
1173 if (!Var->isStaticLocal())
1174 return LinkageInfo::none();
1175 }
1176
1177 ASTContext &Context = D->getASTContext();
1178 if (!Context.getLangOpts().CPlusPlus)
1179 return LinkageInfo::none();
1180
1181 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1182 if (!OuterD)
1183 return LinkageInfo::none();
1184
1185 LinkageInfo LV;
1186 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1187 if (!BD->getBlockManglingNumber())
1188 return LinkageInfo::none();
1189
1190 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1191 BD->getBlockManglingContextDecl(), computation);
1192 } else {
1193 const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1194 if (!FD->isInlined() &&
1195 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1196 return LinkageInfo::none();
1197
1198 LV = getLVForDecl(FD, computation);
1199 }
1200 if (!isExternallyVisible(LV.getLinkage()))
1201 return LinkageInfo::none();
1202 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1203 LV.isVisibilityExplicit());
1204}
1205
1206static inline const CXXRecordDecl*
1207getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1208 const CXXRecordDecl *Ret = Record;
1209 while (Record && Record->isLambda()) {
1210 Ret = Record;
1211 if (!Record->getParent()) break;
1212 // Get the Containing Class of this Lambda Class
1213 Record = dyn_cast_or_null<CXXRecordDecl>(
1214 Record->getParent()->getParent());
1215 }
1216 return Ret;
1217}
1218
1219static LinkageInfo computeLVForDecl(const NamedDecl *D,
1220 LVComputationKind computation) {
1221 // Objective-C: treat all Objective-C declarations as having external
1222 // linkage.
1223 switch (D->getKind()) {
1224 default:
1225 break;
1226 case Decl::ParmVar:
1227 return LinkageInfo::none();
1228 case Decl::TemplateTemplateParm: // count these as external
1229 case Decl::NonTypeTemplateParm:
1230 case Decl::ObjCAtDefsField:
1231 case Decl::ObjCCategory:
1232 case Decl::ObjCCategoryImpl:
1233 case Decl::ObjCCompatibleAlias:
1234 case Decl::ObjCImplementation:
1235 case Decl::ObjCMethod:
1236 case Decl::ObjCProperty:
1237 case Decl::ObjCPropertyImpl:
1238 case Decl::ObjCProtocol:
1239 return LinkageInfo::external();
1240
1241 case Decl::CXXRecord: {
1242 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1243 if (Record->isLambda()) {
1244 if (!Record->getLambdaManglingNumber()) {
1245 // This lambda has no mangling number, so it's internal.
1246 return LinkageInfo::internal();
1247 }
1248
1249 // This lambda has its linkage/visibility determined:
1250 // - either by the outermost lambda if that lambda has no mangling
1251 // number.
1252 // - or by the parent of the outer most lambda
1253 // This prevents infinite recursion in settings such as nested lambdas
1254 // used in NSDMI's, for e.g.
1255 // struct L {
1256 // int t{};
1257 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1258 // };
1259 const CXXRecordDecl *OuterMostLambda =
1260 getOutermostEnclosingLambda(Record);
1261 if (!OuterMostLambda->getLambdaManglingNumber())
1262 return LinkageInfo::internal();
1263
1264 return getLVForClosure(
1265 OuterMostLambda->getDeclContext()->getRedeclContext(),
1266 OuterMostLambda->getLambdaContextDecl(), computation);
1267 }
1268
1269 break;
1270 }
1271 }
1272
1273 // Handle linkage for namespace-scope names.
1274 if (D->getDeclContext()->getRedeclContext()->isFileContext())
1275 return getLVForNamespaceScopeDecl(D, computation);
1276
1277 // C++ [basic.link]p5:
1278 // In addition, a member function, static data member, a named
1279 // class or enumeration of class scope, or an unnamed class or
1280 // enumeration defined in a class-scope typedef declaration such
1281 // that the class or enumeration has the typedef name for linkage
1282 // purposes (7.1.3), has external linkage if the name of the class
1283 // has external linkage.
1284 if (D->getDeclContext()->isRecord())
1285 return getLVForClassMember(D, computation);
1286
1287 // C++ [basic.link]p6:
1288 // The name of a function declared in block scope and the name of
1289 // an object declared by a block scope extern declaration have
1290 // linkage. If there is a visible declaration of an entity with
1291 // linkage having the same name and type, ignoring entities
1292 // declared outside the innermost enclosing namespace scope, the
1293 // block scope declaration declares that same entity and receives
1294 // the linkage of the previous declaration. If there is more than
1295 // one such matching entity, the program is ill-formed. Otherwise,
1296 // if no matching entity is found, the block scope entity receives
1297 // external linkage.
1298 if (D->getDeclContext()->isFunctionOrMethod())
1299 return getLVForLocalDecl(D, computation);
1300
1301 // C++ [basic.link]p6:
1302 // Names not covered by these rules have no linkage.
1303 return LinkageInfo::none();
1304}
1305
1306namespace clang {
1307class LinkageComputer {
1308public:
1309 static LinkageInfo getLVForDecl(const NamedDecl *D,
1310 LVComputationKind computation) {
1311 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1312 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1313
1314 LinkageInfo LV = computeLVForDecl(D, computation);
1315 if (D->hasCachedLinkage())
1316 assert(D->getCachedLinkage() == LV.getLinkage());
1317
1318 D->setCachedLinkage(LV.getLinkage());
1319
1320#ifndef NDEBUG
1321 // In C (because of gnu inline) and in c++ with microsoft extensions an
1322 // static can follow an extern, so we can have two decls with different
1323 // linkages.
1324 const LangOptions &Opts = D->getASTContext().getLangOpts();
1325 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1326 return LV;
1327
1328 // We have just computed the linkage for this decl. By induction we know
1329 // that all other computed linkages match, check that the one we just
1330 // computed also does.
1331 NamedDecl *Old = nullptr;
1332 for (auto I : D->redecls()) {
1333 NamedDecl *T = cast<NamedDecl>(I);
1334 if (T == D)
1335 continue;
1336 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1337 Old = T;
1338 break;
1339 }
1340 }
1341 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1342#endif
1343
1344 return LV;
1345 }
1346};
1347}
1348
1349static LinkageInfo getLVForDecl(const NamedDecl *D,
1350 LVComputationKind computation) {
1351 return clang::LinkageComputer::getLVForDecl(D, computation);
1352}
1353
1354std::string NamedDecl::getQualifiedNameAsString() const {
1355 std::string QualName;
1356 llvm::raw_string_ostream OS(QualName);
1357 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1358 return OS.str();
1359}
1360
1361void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1362 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1363}
1364
1365void NamedDecl::printQualifiedName(raw_ostream &OS,
1366 const PrintingPolicy &P) const {
1367 const DeclContext *Ctx = getDeclContext();
1368
1369 if (Ctx->isFunctionOrMethod()) {
1370 printName(OS);
1371 return;
1372 }
1373
1374 typedef SmallVector<const DeclContext *, 8> ContextsTy;
1375 ContextsTy Contexts;
1376
1377 // Collect contexts.
1378 while (Ctx && isa<NamedDecl>(Ctx)) {
1379 Contexts.push_back(Ctx);
1380 Ctx = Ctx->getParent();
1381 }
1382
1383 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1384 I != E; ++I) {
1385 if (const ClassTemplateSpecializationDecl *Spec
1386 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
1387 OS << Spec->getName();
1388 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1389 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1390 TemplateArgs.data(),
1391 TemplateArgs.size(),
1392 P);
1393 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
1394 if (P.SuppressUnwrittenScope &&
1395 (ND->isAnonymousNamespace() || ND->isInline()))
1396 continue;
1397 if (ND->isAnonymousNamespace())
1398 OS << "(anonymous namespace)";
1399 else
1400 OS << *ND;
1401 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1402 if (!RD->getIdentifier())
1403 OS << "(anonymous " << RD->getKindName() << ')';
1404 else
1405 OS << *RD;
1406 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1407 const FunctionProtoType *FT = nullptr;
1408 if (FD->hasWrittenPrototype())
1409 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1410
1411 OS << *FD << '(';
1412 if (FT) {
1413 unsigned NumParams = FD->getNumParams();
1414 for (unsigned i = 0; i < NumParams; ++i) {
1415 if (i)
1416 OS << ", ";
1417 OS << FD->getParamDecl(i)->getType().stream(P);
1418 }
1419
1420 if (FT->isVariadic()) {
1421 if (NumParams > 0)
1422 OS << ", ";
1423 OS << "...";
1424 }
1425 }
1426 OS << ')';
1427 } else {
1428 OS << *cast<NamedDecl>(*I);
1429 }
1430 OS << "::";
1431 }
1432
1433 if (getDeclName())
1434 OS << *this;
1435 else
1436 OS << "(anonymous)";
1437}
1438
1439void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1440 const PrintingPolicy &Policy,
1441 bool Qualified) const {
1442 if (Qualified)
1443 printQualifiedName(OS, Policy);
1444 else
1445 printName(OS);
1446}
1447
1448bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
1449 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1450
1451 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1452 // We want to keep it, unless it nominates same namespace.
1453 if (getKind() == Decl::UsingDirective) {
1454 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1455 ->getOriginalNamespace() ==
1456 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1457 ->getOriginalNamespace();
1458 }
1459
1460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1461 // For function declarations, we keep track of redeclarations.
1462 return FD->getPreviousDecl() == OldD;
1463
1464 // For function templates, the underlying function declarations are linked.
1465 if (const FunctionTemplateDecl *FunctionTemplate
1466 = dyn_cast<FunctionTemplateDecl>(this))
1467 if (const FunctionTemplateDecl *OldFunctionTemplate
1468 = dyn_cast<FunctionTemplateDecl>(OldD))
1469 return FunctionTemplate->getTemplatedDecl()
1470 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
1471
1472 // For method declarations, we keep track of redeclarations.
1473 if (isa<ObjCMethodDecl>(this))
1474 return false;
1475
1476 // FIXME: Is this correct if one of the decls comes from an inline namespace?
1477 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1478 return true;
1479
1480 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1481 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1482 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1483
1484 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1485 ASTContext &Context = getASTContext();
1486 return Context.getCanonicalNestedNameSpecifier(
1487 cast<UsingDecl>(this)->getQualifier()) ==
1488 Context.getCanonicalNestedNameSpecifier(
1489 cast<UsingDecl>(OldD)->getQualifier());
1490 }
1491
1492 if (isa<UnresolvedUsingValueDecl>(this) &&
1493 isa<UnresolvedUsingValueDecl>(OldD)) {
1494 ASTContext &Context = getASTContext();
1495 return Context.getCanonicalNestedNameSpecifier(
1496 cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1497 Context.getCanonicalNestedNameSpecifier(
1498 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1499 }
1500
1501 // A typedef of an Objective-C class type can replace an Objective-C class
1502 // declaration or definition, and vice versa.
1503 // FIXME: Is this correct if one of the decls comes from an inline namespace?
1504 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1505 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1506 return true;
1507
1508 // For non-function declarations, if the declarations are of the
1509 // same kind and have the same parent then this must be a redeclaration,
1510 // or semantic analysis would not have given us the new declaration.
1511 // Note that inline namespaces can give us two declarations with the same
1512 // name and kind in the same scope but different contexts.
1513 return this->getKind() == OldD->getKind() &&
1514 this->getDeclContext()->getRedeclContext()->Equals(
1515 OldD->getDeclContext()->getRedeclContext());
1516}
1517
1518bool NamedDecl::hasLinkage() const {
1519 return getFormalLinkage() != NoLinkage;
1520}
1521
1522NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1523 NamedDecl *ND = this;
1524 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1525 ND = UD->getTargetDecl();
1526
1527 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1528 return AD->getClassInterface();
1529
1530 return ND;
1531}
1532
1533bool NamedDecl::isCXXInstanceMember() const {
1534 if (!isCXXClassMember())
1535 return false;
1536
1537 const NamedDecl *D = this;
1538 if (isa<UsingShadowDecl>(D))
1539 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1540
1541 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1542 return true;
1543 if (const CXXMethodDecl *MD =
1544 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1545 return MD->isInstance();
1546 return false;
1547}
1548
1549//===----------------------------------------------------------------------===//
1550// DeclaratorDecl Implementation
1551//===----------------------------------------------------------------------===//
1552
1553template <typename DeclT>
1554static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1555 if (decl->getNumTemplateParameterLists() > 0)
1556 return decl->getTemplateParameterList(0)->getTemplateLoc();
1557 else
1558 return decl->getInnerLocStart();
1559}
1560
1561SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1562 TypeSourceInfo *TSI = getTypeSourceInfo();
1563 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1564 return SourceLocation();
1565}
1566
1567void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1568 if (QualifierLoc) {
1569 // Make sure the extended decl info is allocated.
1570 if (!hasExtInfo()) {
1571 // Save (non-extended) type source info pointer.
1572 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1573 // Allocate external info struct.
1574 DeclInfo = new (getASTContext()) ExtInfo;
1575 // Restore savedTInfo into (extended) decl info.
1576 getExtInfo()->TInfo = savedTInfo;
1577 }
1578 // Set qualifier info.
1579 getExtInfo()->QualifierLoc = QualifierLoc;
1580 } else {
1581 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1582 if (hasExtInfo()) {
1583 if (getExtInfo()->NumTemplParamLists == 0) {
1584 // Save type source info pointer.
1585 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1586 // Deallocate the extended decl info.
1587 getASTContext().Deallocate(getExtInfo());
1588 // Restore savedTInfo into (non-extended) decl info.
1589 DeclInfo = savedTInfo;
1590 }
1591 else
1592 getExtInfo()->QualifierLoc = QualifierLoc;
1593 }
1594 }
1595}
1596
1597void
1598DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1599 unsigned NumTPLists,
1600 TemplateParameterList **TPLists) {
1601 assert(NumTPLists > 0);
1602 // Make sure the extended decl info is allocated.
1603 if (!hasExtInfo()) {
1604 // Save (non-extended) type source info pointer.
1605 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1606 // Allocate external info struct.
1607 DeclInfo = new (getASTContext()) ExtInfo;
1608 // Restore savedTInfo into (extended) decl info.
1609 getExtInfo()->TInfo = savedTInfo;
1610 }
1611 // Set the template parameter lists info.
1612 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1613}
1614
1615SourceLocation DeclaratorDecl::getOuterLocStart() const {
1616 return getTemplateOrInnerLocStart(this);
1617}
1618
1619namespace {
1620
1621// Helper function: returns true if QT is or contains a type
1622// having a postfix component.
1623bool typeIsPostfix(clang::QualType QT) {
1624 while (true) {
1625 const Type* T = QT.getTypePtr();
1626 switch (T->getTypeClass()) {
1627 default:
1628 return false;
1629 case Type::Pointer:
1630 QT = cast<PointerType>(T)->getPointeeType();
1631 break;
1632 case Type::BlockPointer:
1633 QT = cast<BlockPointerType>(T)->getPointeeType();
1634 break;
1635 case Type::MemberPointer:
1636 QT = cast<MemberPointerType>(T)->getPointeeType();
1637 break;
1638 case Type::LValueReference:
1639 case Type::RValueReference:
1640 QT = cast<ReferenceType>(T)->getPointeeType();
1641 break;
1642 case Type::PackExpansion:
1643 QT = cast<PackExpansionType>(T)->getPattern();
1644 break;
1645 case Type::Paren:
1646 case Type::ConstantArray:
1647 case Type::DependentSizedArray:
1648 case Type::IncompleteArray:
1649 case Type::VariableArray:
1650 case Type::FunctionProto:
1651 case Type::FunctionNoProto:
1652 return true;
1653 }
1654 }
1655}
1656
1657} // namespace
1658
1659SourceRange DeclaratorDecl::getSourceRange() const {
1660 SourceLocation RangeEnd = getLocation();
1661 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1662 // If the declaration has no name or the type extends past the name take the
1663 // end location of the type.
1664 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1665 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1666 }
1667 return SourceRange(getOuterLocStart(), RangeEnd);
1668}
1669
1670void
1671QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1672 unsigned NumTPLists,
1673 TemplateParameterList **TPLists) {
1674 assert((NumTPLists == 0 || TPLists != nullptr) &&
1675 "Empty array of template parameters with positive size!");
1676
1677 // Free previous template parameters (if any).
1678 if (NumTemplParamLists > 0) {
1679 Context.Deallocate(TemplParamLists);
1680 TemplParamLists = nullptr;
1681 NumTemplParamLists = 0;
1682 }
1683 // Set info on matched template parameter lists (if any).
1684 if (NumTPLists > 0) {
1685 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1686 NumTemplParamLists = NumTPLists;
1687 for (unsigned i = NumTPLists; i-- > 0; )
1688 TemplParamLists[i] = TPLists[i];
1689 }
1690}
1691
1692//===----------------------------------------------------------------------===//
1693// VarDecl Implementation
1694//===----------------------------------------------------------------------===//
1695
1696const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1697 switch (SC) {
1698 case SC_None: break;
1699 case SC_Auto: return "auto";
1700 case SC_Extern: return "extern";
1701 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1702 case SC_PrivateExtern: return "__private_extern__";
1703 case SC_Register: return "register";
1704 case SC_Static: return "static";
1705 }
1706
1707 llvm_unreachable("Invalid storage class");
1708}
1709
1710VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1711 SourceLocation StartLoc, SourceLocation IdLoc,
1712 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1713 StorageClass SC)
1714 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1715 redeclarable_base(C), Init() {
1716 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1717 "VarDeclBitfields too large!");
1718 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1719 "ParmVarDeclBitfields too large!");
1720 AllBits = 0;
1721 VarDeclBits.SClass = SC;
1722 // Everything else is implicitly initialized to false.
1723}
1724
1725VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1726 SourceLocation StartL, SourceLocation IdL,
1727 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1728 StorageClass S) {
1729 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
1730}
1731
1732VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1733 return new (C, ID)
1734 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1735 QualType(), nullptr, SC_None);
1736}
1737
1738void VarDecl::setStorageClass(StorageClass SC) {
1739 assert(isLegalForVariable(SC));
1740 VarDeclBits.SClass = SC;
1741}
1742
1743VarDecl::TLSKind VarDecl::getTLSKind() const {
1744 switch (VarDeclBits.TSCSpec) {
1745 case TSCS_unspecified:
1746 if (hasAttr<ThreadAttr>())
1747 return TLS_Static;
1748 return TLS_None;
1749 case TSCS___thread: // Fall through.
1750 case TSCS__Thread_local:
1751 return TLS_Static;
1752 case TSCS_thread_local:
1753 return TLS_Dynamic;
1754 }
1755 llvm_unreachable("Unknown thread storage class specifier!");
1756}
1757
1758SourceRange VarDecl::getSourceRange() const {
1759 if (const Expr *Init = getInit()) {
1760 SourceLocation InitEnd = Init->getLocEnd();
1761 // If Init is implicit, ignore its source range and fallback on
1762 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1763 if (InitEnd.isValid() && InitEnd != getLocation())
1764 return SourceRange(getOuterLocStart(), InitEnd);
1765 }
1766 return DeclaratorDecl::getSourceRange();
1767}
1768
1769template<typename T>
1770static LanguageLinkage getDeclLanguageLinkage(const T &D) {
1771 // C++ [dcl.link]p1: All function types, function names with external linkage,
1772 // and variable names with external linkage have a language linkage.
1773 if (!D.hasExternalFormalLinkage())
1774 return NoLanguageLinkage;
1775
1776 // Language linkage is a C++ concept, but saying that everything else in C has
1777 // C language linkage fits the implementation nicely.
1778 ASTContext &Context = D.getASTContext();
1779 if (!Context.getLangOpts().CPlusPlus)
1780 return CLanguageLinkage;
1781
1782 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1783 // language linkage of the names of class members and the function type of
1784 // class member functions.
1785 const DeclContext *DC = D.getDeclContext();
1786 if (DC->isRecord())
1787 return CXXLanguageLinkage;
1788
1789 // If the first decl is in an extern "C" context, any other redeclaration
1790 // will have C language linkage. If the first one is not in an extern "C"
1791 // context, we would have reported an error for any other decl being in one.
1792 if (isFirstInExternCContext(&D))
1793 return CLanguageLinkage;
1794 return CXXLanguageLinkage;
1795}
1796
1797template<typename T>
1798static bool isDeclExternC(const T &D) {
1799 // Since the context is ignored for class members, they can only have C++
1800 // language linkage or no language linkage.
1801 const DeclContext *DC = D.getDeclContext();
1802 if (DC->isRecord()) {
1803 assert(D.getASTContext().getLangOpts().CPlusPlus);
1804 return false;
1805 }
1806
1807 return D.getLanguageLinkage() == CLanguageLinkage;
1808}
1809
1810LanguageLinkage VarDecl::getLanguageLinkage() const {
1811 return getDeclLanguageLinkage(*this);
1812}
1813
1814bool VarDecl::isExternC() const {
1815 return isDeclExternC(*this);
1816}
1817
1818bool VarDecl::isInExternCContext() const {
1819 return getLexicalDeclContext()->isExternCContext();
1820}
1821
1822bool VarDecl::isInExternCXXContext() const {
1823 return getLexicalDeclContext()->isExternCXXContext();
1824}
1825
1826VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
1827
1828VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1829 ASTContext &C) const
1830{
1831 // C++ [basic.def]p2:
1832 // A declaration is a definition unless [...] it contains the 'extern'
1833 // specifier or a linkage-specification and neither an initializer [...],
1834 // it declares a static data member in a class declaration [...].
1835 // C++1y [temp.expl.spec]p15:
1836 // An explicit specialization of a static data member or an explicit
1837 // specialization of a static data member template is a definition if the
1838 // declaration includes an initializer; otherwise, it is a declaration.
1839 //
1840 // FIXME: How do you declare (but not define) a partial specialization of
1841 // a static data member template outside the containing class?
1842 if (isStaticDataMember()) {
1843 if (isOutOfLine() &&
1844 (hasInit() ||
1845 // If the first declaration is out-of-line, this may be an
1846 // instantiation of an out-of-line partial specialization of a variable
1847 // template for which we have not yet instantiated the initializer.
1848 (getFirstDecl()->isOutOfLine()
1849 ? getTemplateSpecializationKind() == TSK_Undeclared
1850 : getTemplateSpecializationKind() !=
1851 TSK_ExplicitSpecialization) ||
1852 isa<VarTemplatePartialSpecializationDecl>(this)))
1853 return Definition;
1854 else
1855 return DeclarationOnly;
1856 }
1857 // C99 6.7p5:
1858 // A definition of an identifier is a declaration for that identifier that
1859 // [...] causes storage to be reserved for that object.
1860 // Note: that applies for all non-file-scope objects.
1861 // C99 6.9.2p1:
1862 // If the declaration of an identifier for an object has file scope and an
1863 // initializer, the declaration is an external definition for the identifier
1864 if (hasInit())
1865 return Definition;
1866
1867 if (hasAttr<AliasAttr>())
1868 return Definition;
1869
1870 // A variable template specialization (other than a static data member
1871 // template or an explicit specialization) is a declaration until we
1872 // instantiate its initializer.
1873 if (isa<VarTemplateSpecializationDecl>(this) &&
1874 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1875 return DeclarationOnly;
1876
1877 if (hasExternalStorage())
1878 return DeclarationOnly;
1879
1880 // [dcl.link] p7:
1881 // A declaration directly contained in a linkage-specification is treated
1882 // as if it contains the extern specifier for the purpose of determining
1883 // the linkage of the declared name and whether it is a definition.
1884 if (isSingleLineLanguageLinkage(*this))
1885 return DeclarationOnly;
1886
1887 // C99 6.9.2p2:
1888 // A declaration of an object that has file scope without an initializer,
1889 // and without a storage class specifier or the scs 'static', constitutes
1890 // a tentative definition.
1891 // No such thing in C++.
1892 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1893 return TentativeDefinition;
1894
1895 // What's left is (in C, block-scope) declarations without initializers or
1896 // external storage. These are definitions.
1897 return Definition;
1898}
1899
1900VarDecl *VarDecl::getActingDefinition() {
1901 DefinitionKind Kind = isThisDeclarationADefinition();
1902 if (Kind != TentativeDefinition)
1903 return nullptr;
1904
1905 VarDecl *LastTentative = nullptr;
1906 VarDecl *First = getFirstDecl();
1907 for (auto I : First->redecls()) {
1908 Kind = I->isThisDeclarationADefinition();
1909 if (Kind == Definition)
1910 return nullptr;
1911 else if (Kind == TentativeDefinition)
1912 LastTentative = I;
1913 }
1914 return LastTentative;
1915}
1916
1917VarDecl *VarDecl::getDefinition(ASTContext &C) {
1918 VarDecl *First = getFirstDecl();
1919 for (auto I : First->redecls()) {
1920 if (I->isThisDeclarationADefinition(C) == Definition)
1921 return I;
1922 }
1923 return nullptr;
1924}
1925
1926VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1927 DefinitionKind Kind = DeclarationOnly;
1928
1929 const VarDecl *First = getFirstDecl();
1930 for (auto I : First->redecls()) {
1931 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
1932 if (Kind == Definition)
1933 break;
1934 }
1935
1936 return Kind;
1937}
1938
1939const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1940 for (auto I : redecls()) {
1941 if (auto Expr = I->getInit()) {
1942 D = I;
1943 return Expr;
1944 }
1945 }
1946 return nullptr;
1947}
1948
1949bool VarDecl::isOutOfLine() const {
1950 if (Decl::isOutOfLine())
1951 return true;
1952
1953 if (!isStaticDataMember())
1954 return false;
1955
1956 // If this static data member was instantiated from a static data member of
1957 // a class template, check whether that static data member was defined
1958 // out-of-line.
1959 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1960 return VD->isOutOfLine();
1961
1962 return false;
1963}
1964
1965VarDecl *VarDecl::getOutOfLineDefinition() {
1966 if (!isStaticDataMember())
1967 return nullptr;
1968
1969 for (auto RD : redecls()) {
1970 if (RD->getLexicalDeclContext()->isFileContext())
1971 return RD;
1972 }
1973
1974 return nullptr;
1975}
1976
1977void VarDecl::setInit(Expr *I) {
1978 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1979 Eval->~EvaluatedStmt();
1980 getASTContext().Deallocate(Eval);
1981 }
1982
1983 Init = I;
1984}
1985
1986bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1987 const LangOptions &Lang = C.getLangOpts();
1988
1989 if (!Lang.CPlusPlus)
1990 return false;
1991
1992 // In C++11, any variable of reference type can be used in a constant
1993 // expression if it is initialized by a constant expression.
1994 if (Lang.CPlusPlus11 && getType()->isReferenceType())
1995 return true;
1996
1997 // Only const objects can be used in constant expressions in C++. C++98 does
1998 // not require the variable to be non-volatile, but we consider this to be a
1999 // defect.
2000 if (!getType().isConstQualified() || getType().isVolatileQualified())
2001 return false;
2002
2003 // In C++, const, non-volatile variables of integral or enumeration types
2004 // can be used in constant expressions.
2005 if (getType()->isIntegralOrEnumerationType())
2006 return true;
2007
2008 // Additionally, in C++11, non-volatile constexpr variables can be used in
2009 // constant expressions.
2010 return Lang.CPlusPlus11 && isConstexpr();
2011}
2012
2013/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2014/// form, which contains extra information on the evaluated value of the
2015/// initializer.
2016EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2017 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
2018 if (!Eval) {
2019 Stmt *S = Init.get<Stmt *>();
2020 // Note: EvaluatedStmt contains an APValue, which usually holds
2021 // resources not allocated from the ASTContext. We need to do some
2022 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2023 // where we can detect whether there's anything to clean up or not.
2024 Eval = new (getASTContext()) EvaluatedStmt;
2025 Eval->Value = S;
2026 Init = Eval;
2027 }
2028 return Eval;
2029}
2030
2031APValue *VarDecl::evaluateValue() const {
2032 SmallVector<PartialDiagnosticAt, 8> Notes;
2033 return evaluateValue(Notes);
2034}
2035
2036namespace {
2037// Destroy an APValue that was allocated in an ASTContext.
2038void DestroyAPValue(void* UntypedValue) {
2039 static_cast<APValue*>(UntypedValue)->~APValue();
2040}
2041} // namespace
2042
2043APValue *VarDecl::evaluateValue(
2044 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2045 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2046
2047 // We only produce notes indicating why an initializer is non-constant the
2048 // first time it is evaluated. FIXME: The notes won't always be emitted the
2049 // first time we try evaluation, so might not be produced at all.
2050 if (Eval->WasEvaluated)
2051 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
2052
2053 const Expr *Init = cast<Expr>(Eval->Value);
2054 assert(!Init->isValueDependent());
2055
2056 if (Eval->IsEvaluating) {
2057 // FIXME: Produce a diagnostic for self-initialization.
2058 Eval->CheckedICE = true;
2059 Eval->IsICE = false;
2060 return nullptr;
2061 }
2062
2063 Eval->IsEvaluating = true;
2064
2065 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2066 this, Notes);
2067
2068 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2069 // or that it's empty (so that there's nothing to clean up) if evaluation
2070 // failed.
2071 if (!Result)
2072 Eval->Evaluated = APValue();
2073 else if (Eval->Evaluated.needsCleanup())
2074 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
2075
2076 Eval->IsEvaluating = false;
2077 Eval->WasEvaluated = true;
2078
2079 // In C++11, we have determined whether the initializer was a constant
2080 // expression as a side-effect.
2081 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
2082 Eval->CheckedICE = true;
2083 Eval->IsICE = Result && Notes.empty();
2084 }
2085
2086 return Result ? &Eval->Evaluated : nullptr;
2087}
2088
2089bool VarDecl::checkInitIsICE() const {
2090 // Initializers of weak variables are never ICEs.
2091 if (isWeak())
2092 return false;
2093
2094 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2095 if (Eval->CheckedICE)
2096 // We have already checked whether this subexpression is an
2097 // integral constant expression.
2098 return Eval->IsICE;
2099
2100 const Expr *Init = cast<Expr>(Eval->Value);
2101 assert(!Init->isValueDependent());
2102
2103 // In C++11, evaluate the initializer to check whether it's a constant
2104 // expression.
2105 if (getASTContext().getLangOpts().CPlusPlus11) {
2106 SmallVector<PartialDiagnosticAt, 8> Notes;
2107 evaluateValue(Notes);
2108 return Eval->IsICE;
2109 }
2110
2111 // It's an ICE whether or not the definition we found is
2112 // out-of-line. See DR 721 and the discussion in Clang PR
2113 // 6206 for details.
2114
2115 if (Eval->CheckingICE)
2116 return false;
2117 Eval->CheckingICE = true;
2118
2119 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2120 Eval->CheckingICE = false;
2121 Eval->CheckedICE = true;
2122 return Eval->IsICE;
2123}
2124
2125VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2126 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2127 return cast<VarDecl>(MSI->getInstantiatedFrom());
2128
2129 return nullptr;
2130}
2131
2132TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2133 if (const VarTemplateSpecializationDecl *Spec =
2134 dyn_cast<VarTemplateSpecializationDecl>(this))
2135 return Spec->getSpecializationKind();
2136
2137 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2138 return MSI->getTemplateSpecializationKind();
2139
2140 return TSK_Undeclared;
2141}
2142
2143SourceLocation VarDecl::getPointOfInstantiation() const {
2144 if (const VarTemplateSpecializationDecl *Spec =
2145 dyn_cast<VarTemplateSpecializationDecl>(this))
2146 return Spec->getPointOfInstantiation();
2147
2148 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2149 return MSI->getPointOfInstantiation();
2150
2151 return SourceLocation();
2152}
2153
2154VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2155 return getASTContext().getTemplateOrSpecializationInfo(this)
2156 .dyn_cast<VarTemplateDecl *>();
2157}
2158
2159void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2160 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2161}
2162
2163MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2164 if (isStaticDataMember())
2165 // FIXME: Remove ?
2166 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2167 return getASTContext().getTemplateOrSpecializationInfo(this)
2168 .dyn_cast<MemberSpecializationInfo *>();
2169 return nullptr;
2170}
2171
2172void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2173 SourceLocation PointOfInstantiation) {
2174 assert((isa<VarTemplateSpecializationDecl>(this) ||
2175 getMemberSpecializationInfo()) &&
2176 "not a variable or static data member template specialization");
2177
2178 if (VarTemplateSpecializationDecl *Spec =
2179 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2180 Spec->setSpecializationKind(TSK);
2181 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2182 Spec->getPointOfInstantiation().isInvalid())
2183 Spec->setPointOfInstantiation(PointOfInstantiation);
2184 }
2185
2186 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2187 MSI->setTemplateSpecializationKind(TSK);
2188 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2189 MSI->getPointOfInstantiation().isInvalid())
2190 MSI->setPointOfInstantiation(PointOfInstantiation);
2191 }
2192}
2193
2194void
2195VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2196 TemplateSpecializationKind TSK) {
2197 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2198 "Previous template or instantiation?");
2199 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2200}
2201
2202//===----------------------------------------------------------------------===//
2203// ParmVarDecl Implementation
2204//===----------------------------------------------------------------------===//
2205
2206ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2207 SourceLocation StartLoc,
2208 SourceLocation IdLoc, IdentifierInfo *Id,
2209 QualType T, TypeSourceInfo *TInfo,
2210 StorageClass S, Expr *DefArg) {
2211 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2212 S, DefArg);
2213}
2214
2215QualType ParmVarDecl::getOriginalType() const {
2216 TypeSourceInfo *TSI = getTypeSourceInfo();
2217 QualType T = TSI ? TSI->getType() : getType();
2218 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2219 return DT->getOriginalType();
2220 return T;
2221}
2222
2223ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2224 return new (C, ID)
2225 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2226 nullptr, QualType(), nullptr, SC_None, nullptr);
2227}
2228
2229SourceRange ParmVarDecl::getSourceRange() const {
2230 if (!hasInheritedDefaultArg()) {
2231 SourceRange ArgRange = getDefaultArgRange();
2232 if (ArgRange.isValid())
2233 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2234 }
2235
2236 // DeclaratorDecl considers the range of postfix types as overlapping with the
2237 // declaration name, but this is not the case with parameters in ObjC methods.
2238 if (isa<ObjCMethodDecl>(getDeclContext()))
2239 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2240
2241 return DeclaratorDecl::getSourceRange();
2242}
2243
2244Expr *ParmVarDecl::getDefaultArg() {
2245 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2246 assert(!hasUninstantiatedDefaultArg() &&
2247 "Default argument is not yet instantiated!");
2248
2249 Expr *Arg = getInit();
2250 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
2251 return E->getSubExpr();
2252
2253 return Arg;
2254}
2255
2256SourceRange ParmVarDecl::getDefaultArgRange() const {
2257 if (const Expr *E = getInit())
2258 return E->getSourceRange();
2259
2260 if (hasUninstantiatedDefaultArg())
2261 return getUninstantiatedDefaultArg()->getSourceRange();
2262
2263 return SourceRange();
2264}
2265
2266bool ParmVarDecl::isParameterPack() const {
2267 return isa<PackExpansionType>(getType());
2268}
2269
2270void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2271 getASTContext().setParameterIndex(this, parameterIndex);
2272 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2273}
2274
2275unsigned ParmVarDecl::getParameterIndexLarge() const {
2276 return getASTContext().getParameterIndex(this);
2277}
2278
2279//===----------------------------------------------------------------------===//
2280// FunctionDecl Implementation
2281//===----------------------------------------------------------------------===//
2282
2283void FunctionDecl::getNameForDiagnostic(
2284 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2285 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2286 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2287 if (TemplateArgs)
2288 TemplateSpecializationType::PrintTemplateArgumentList(
2289 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
2290}
2291
2292bool FunctionDecl::isVariadic() const {
2293 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2294 return FT->isVariadic();
2295 return false;
2296}
2297
2298bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2299 for (auto I : redecls()) {
2300 if (I->Body || I->IsLateTemplateParsed) {
2301 Definition = I;
2302 return true;
2303 }
2304 }
2305
2306 return false;
2307}
2308
2309bool FunctionDecl::hasTrivialBody() const
2310{
2311 Stmt *S = getBody();
2312 if (!S) {
2313 // Since we don't have a body for this function, we don't know if it's
2314 // trivial or not.
2315 return false;
2316 }
2317
2318 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2319 return true;
2320 return false;
2321}
2322
2323bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2324 for (auto I : redecls()) {
2325 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2326 I->hasAttr<AliasAttr>()) {
2327 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
2328 return true;
2329 }
2330 }
2331
2332 return false;
2333}
2334
2335Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2336 if (!hasBody(Definition))
2337 return nullptr;
2338
2339 if (Definition->Body)
2340 return Definition->Body.get(getASTContext().getExternalSource());
2341
2342 return nullptr;
2343}
2344
2345void FunctionDecl::setBody(Stmt *B) {
2346 Body = B;
2347 if (B)
2348 EndRangeLoc = B->getLocEnd();
2349}
2350
2351void FunctionDecl::setPure(bool P) {
2352 IsPure = P;
2353 if (P)
2354 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2355 Parent->markedVirtualFunctionPure();
2356}
2357
2358template<std::size_t Len>
2359static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2360 IdentifierInfo *II = ND->getIdentifier();
2361 return II && II->isStr(Str);
2362}
2363
2364bool FunctionDecl::isMain() const {
2365 const TranslationUnitDecl *tunit =
2366 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2367 return tunit &&
2368 !tunit->getASTContext().getLangOpts().Freestanding &&
2369 isNamed(this, "main");
2370}
2371
2372bool FunctionDecl::isMSVCRTEntryPoint() const {
2373 const TranslationUnitDecl *TUnit =
2374 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2375 if (!TUnit)
2376 return false;
2377
2378 // Even though we aren't really targeting MSVCRT if we are freestanding,
2379 // semantic analysis for these functions remains the same.
2380
2381 // MSVCRT entry points only exist on MSVCRT targets.
2382 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2383 return false;
2384
2385 // Nameless functions like constructors cannot be entry points.
2386 if (!getIdentifier())
2387 return false;
2388
2389 return llvm::StringSwitch<bool>(getName())
2390 .Cases("main", // an ANSI console app
2391 "wmain", // a Unicode console App
2392 "WinMain", // an ANSI GUI app
2393 "wWinMain", // a Unicode GUI app
2394 "DllMain", // a DLL
2395 true)
2396 .Default(false);
2397}
2398
2399bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2400 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2401 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2402 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2403 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2404 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2405
2406 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2407 return false;
2408
2409 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2410 if (proto->getNumParams() != 2 || proto->isVariadic())
2411 return false;
2412
2413 ASTContext &Context =
2414 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2415 ->getASTContext();
2416
2417 // The result type and first argument type are constant across all
2418 // these operators. The second argument must be exactly void*.
2419 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2420}
2421
2422bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2423 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2424 return false;
2425 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2426 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2427 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2428 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2429 return false;
2430
2431 if (isa<CXXRecordDecl>(getDeclContext()))
2432 return false;
2433
2434 // This can only fail for an invalid 'operator new' declaration.
2435 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2436 return false;
2437
2438 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
2439 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
2440 return false;
2441
2442 // If this is a single-parameter function, it must be a replaceable global
2443 // allocation or deallocation function.
2444 if (FPT->getNumParams() == 1)
2445 return true;
2446
2447 // Otherwise, we're looking for a second parameter whose type is
2448 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
2449 QualType Ty = FPT->getParamType(1);
2450 ASTContext &Ctx = getASTContext();
2451 if (Ctx.getLangOpts().SizedDeallocation &&
2452 Ctx.hasSameType(Ty, Ctx.getSizeType()))
2453 return true;
2454 if (!Ty->isReferenceType())
2455 return false;
2456 Ty = Ty->getPointeeType();
2457 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2458 return false;
2459 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2460 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
2461}
2462
2463FunctionDecl *
2464FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2465 ASTContext &Ctx = getASTContext();
2466 if (!Ctx.getLangOpts().SizedDeallocation)
2467 return nullptr;
2468
2469 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2470 return nullptr;
2471 if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2472 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2473 return nullptr;
2474 if (isa<CXXRecordDecl>(getDeclContext()))
2475 return nullptr;
2476
2477 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2478 return nullptr;
2479
2480 if (getNumParams() != 2 || isVariadic() ||
2481 !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
2482 Ctx.getSizeType()))
2483 return nullptr;
2484
2485 // This is a sized deallocation function. Find the corresponding unsized
2486 // deallocation function.
2487 lookup_const_result R = getDeclContext()->lookup(getDeclName());
2488 for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2489 ++RI)
2490 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2491 if (FD->getNumParams() == 1 && !FD->isVariadic())
2492 return FD;
2493 return nullptr;
2494}
2495
2496LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2497 return getDeclLanguageLinkage(*this);
2498}
2499
2500bool FunctionDecl::isExternC() const {
2501 return isDeclExternC(*this);
2502}
2503
2504bool FunctionDecl::isInExternCContext() const {
2505 return getLexicalDeclContext()->isExternCContext();
2506}
2507
2508bool FunctionDecl::isInExternCXXContext() const {
2509 return getLexicalDeclContext()->isExternCXXContext();
2510}
2511
2512bool FunctionDecl::isGlobal() const {
2513 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2514 return Method->isStatic();
2515
2516 if (getCanonicalDecl()->getStorageClass() == SC_Static)
2517 return false;
2518
2519 for (const DeclContext *DC = getDeclContext();
2520 DC->isNamespace();
2521 DC = DC->getParent()) {
2522 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2523 if (!Namespace->getDeclName())
2524 return false;
2525 break;
2526 }
2527 }
2528
2529 return true;
2530}
2531
2532bool FunctionDecl::isNoReturn() const {
2533 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2534 hasAttr<C11NoReturnAttr>() ||
2535 getType()->getAs<FunctionType>()->getNoReturnAttr();
2536}
2537
2538void
2539FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2540 redeclarable_base::setPreviousDecl(PrevDecl);
2541
2542 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2543 FunctionTemplateDecl *PrevFunTmpl
2544 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
2545 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2546 FunTmpl->setPreviousDecl(PrevFunTmpl);
2547 }
2548
2549 if (PrevDecl && PrevDecl->IsInline)
2550 IsInline = true;
2551}
2552
2553const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2554 return getFirstDecl();
2555}
2556
2557FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2558
2559/// \brief Returns a value indicating whether this function
2560/// corresponds to a builtin function.
2561///
2562/// The function corresponds to a built-in function if it is
2563/// declared at translation scope or within an extern "C" block and
2564/// its name matches with the name of a builtin. The returned value
2565/// will be 0 for functions that do not correspond to a builtin, a
2566/// value of type \c Builtin::ID if in the target-independent range
2567/// \c [1,Builtin::First), or a target-specific builtin value.
2568unsigned FunctionDecl::getBuiltinID() const {
2569 if (!getIdentifier())
2570 return 0;
2571
2572 unsigned BuiltinID = getIdentifier()->getBuiltinID();
2573 if (!BuiltinID)
2574 return 0;
2575
2576 ASTContext &Context = getASTContext();
2577 if (Context.getLangOpts().CPlusPlus) {
2578 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2579 getFirstDecl()->getDeclContext());
2580 // In C++, the first declaration of a builtin is always inside an implicit
2581 // extern "C".
2582 // FIXME: A recognised library function may not be directly in an extern "C"
2583 // declaration, for instance "extern "C" { namespace std { decl } }".
2584 if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2585 return 0;
2586 }
2587
2588 // If the function is marked "overloadable", it has a different mangled name
2589 // and is not the C library function.
2590 if (hasAttr<OverloadableAttr>())
2591 return 0;
2592
2593 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2594 return BuiltinID;
2595
2596 // This function has the name of a known C library
2597 // function. Determine whether it actually refers to the C library
2598 // function or whether it just has the same name.
2599
2600 // If this is a static function, it's not a builtin.
2601 if (getStorageClass() == SC_Static)
2602 return 0;
2603
2604 return BuiltinID;
2605}
2606
2607
2608/// getNumParams - Return the number of parameters this function must have
2609/// based on its FunctionType. This is the length of the ParamInfo array
2610/// after it has been created.
2611unsigned FunctionDecl::getNumParams() const {
2612 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
2613 return FPT ? FPT->getNumParams() : 0;
2614}
2615
2616void FunctionDecl::setParams(ASTContext &C,
2617 ArrayRef<ParmVarDecl *> NewParamInfo) {
2618 assert(!ParamInfo && "Already has param info!");
2619 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2620
2621 // Zero params -> null pointer.
2622 if (!NewParamInfo.empty()) {
2623 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2624 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2625 }
2626}
2627
2628void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2629 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2630
2631 if (!NewDecls.empty()) {
2632 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2633 std::copy(NewDecls.begin(), NewDecls.end(), A);
2634 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
2635 // Move declarations introduced in prototype to the function context.
2636 for (auto I : NewDecls) {
2637 DeclContext *DC = I->getDeclContext();
2638 // Forward-declared reference to an enumeration is not added to
2639 // declaration scope, so skip declaration that is absent from its
2640 // declaration contexts.
2641 if (DC->containsDecl(I)) {
2642 DC->removeDecl(I);
2643 I->setDeclContext(this);
2644 addDecl(I);
2645 }
2646 }
2647 }
2648}
2649
2650/// getMinRequiredArguments - Returns the minimum number of arguments
2651/// needed to call this function. This may be fewer than the number of
2652/// function parameters, if some of the parameters have default
2653/// arguments (in C++) or are parameter packs (C++11).
2654unsigned FunctionDecl::getMinRequiredArguments() const {
2655 if (!getASTContext().getLangOpts().CPlusPlus)
2656 return getNumParams();
2657
2658 unsigned NumRequiredArgs = 0;
2659 for (auto *Param : params())
2660 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2661 ++NumRequiredArgs;
2662 return NumRequiredArgs;
2663}
2664
2665/// \brief The combination of the extern and inline keywords under MSVC forces
2666/// the function to be required.
2667///
2668/// Note: This function assumes that we will only get called when isInlined()
2669/// would return true for this FunctionDecl.
2670bool FunctionDecl::isMSExternInline() const {
2671 assert(isInlined() && "expected to get called on an inlined function!");
2672
2673 const ASTContext &Context = getASTContext();
2674 if (!Context.getLangOpts().MSVCCompat && !hasAttr<DLLExportAttr>())
2675 return false;
2676
1//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/PrettyPrinter.h"
25#include "clang/AST/Stmt.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/IdentifierTable.h"
29#include "clang/Basic/Module.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Frontend/FrontendDiagnostic.h"
33#include "llvm/Support/ErrorHandling.h"
34#include <algorithm>
35
36using namespace clang;
37
38Decl *clang::getPrimaryMergedDecl(Decl *D) {
39 return D->getASTContext().getPrimaryMergedDecl(D);
40}
41
42// Defined here so that it can be inlined into its direct callers.
43bool Decl::isOutOfLine() const {
44 return !getLexicalDeclContext()->Equals(getDeclContext());
45}
46
47//===----------------------------------------------------------------------===//
48// NamedDecl Implementation
49//===----------------------------------------------------------------------===//
50
51// Visibility rules aren't rigorously externally specified, but here
52// are the basic principles behind what we implement:
53//
54// 1. An explicit visibility attribute is generally a direct expression
55// of the user's intent and should be honored. Only the innermost
56// visibility attribute applies. If no visibility attribute applies,
57// global visibility settings are considered.
58//
59// 2. There is one caveat to the above: on or in a template pattern,
60// an explicit visibility attribute is just a default rule, and
61// visibility can be decreased by the visibility of template
62// arguments. But this, too, has an exception: an attribute on an
63// explicit specialization or instantiation causes all the visibility
64// restrictions of the template arguments to be ignored.
65//
66// 3. A variable that does not otherwise have explicit visibility can
67// be restricted by the visibility of its type.
68//
69// 4. A visibility restriction is explicit if it comes from an
70// attribute (or something like it), not a global visibility setting.
71// When emitting a reference to an external symbol, visibility
72// restrictions are ignored unless they are explicit.
73//
74// 5. When computing the visibility of a non-type, including a
75// non-type member of a class, only non-type visibility restrictions
76// are considered: the 'visibility' attribute, global value-visibility
77// settings, and a few special cases like __private_extern.
78//
79// 6. When computing the visibility of a type, including a type member
80// of a class, only type visibility restrictions are considered:
81// the 'type_visibility' attribute and global type-visibility settings.
82// However, a 'visibility' attribute counts as a 'type_visibility'
83// attribute on any declaration that only has the former.
84//
85// The visibility of a "secondary" entity, like a template argument,
86// is computed using the kind of that entity, not the kind of the
87// primary entity for which we are computing visibility. For example,
88// the visibility of a specialization of either of these templates:
89// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
90// template <class T, bool (&compare)(T, X)> class matcher;
91// is restricted according to the type visibility of the argument 'T',
92// the type visibility of 'bool(&)(T,X)', and the value visibility of
93// the argument function 'compare'. That 'has_match' is a value
94// and 'matcher' is a type only matters when looking for attributes
95// and settings from the immediate context.
96
97const unsigned IgnoreExplicitVisibilityBit = 2;
98const unsigned IgnoreAllVisibilityBit = 4;
99
100/// Kinds of LV computation. The linkage side of the computation is
101/// always the same, but different things can change how visibility is
102/// computed.
103enum LVComputationKind {
104 /// Do an LV computation for, ultimately, a type.
105 /// Visibility may be restricted by type visibility settings and
106 /// the visibility of template arguments.
107 LVForType = NamedDecl::VisibilityForType,
108
109 /// Do an LV computation for, ultimately, a non-type declaration.
110 /// Visibility may be restricted by value visibility settings and
111 /// the visibility of template arguments.
112 LVForValue = NamedDecl::VisibilityForValue,
113
114 /// Do an LV computation for, ultimately, a type that already has
115 /// some sort of explicit visibility. Visibility may only be
116 /// restricted by the visibility of template arguments.
117 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
118
119 /// Do an LV computation for, ultimately, a non-type declaration
120 /// that already has some sort of explicit visibility. Visibility
121 /// may only be restricted by the visibility of template arguments.
122 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
123
124 /// Do an LV computation when we only care about the linkage.
125 LVForLinkageOnly =
126 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
127};
128
129/// Does this computation kind permit us to consider additional
130/// visibility settings from attributes and the like?
131static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
132 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
133}
134
135/// Given an LVComputationKind, return one of the same type/value sort
136/// that records that it already has explicit visibility.
137static LVComputationKind
138withExplicitVisibilityAlready(LVComputationKind oldKind) {
139 LVComputationKind newKind =
140 static_cast<LVComputationKind>(unsigned(oldKind) |
141 IgnoreExplicitVisibilityBit);
142 assert(oldKind != LVForType || newKind == LVForExplicitType);
143 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
144 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
145 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
146 return newKind;
147}
148
149static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
150 LVComputationKind kind) {
151 assert(!hasExplicitVisibilityAlready(kind) &&
152 "asking for explicit visibility when we shouldn't be");
153 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
154}
155
156/// Is the given declaration a "type" or a "value" for the purposes of
157/// visibility computation?
158static bool usesTypeVisibility(const NamedDecl *D) {
159 return isa<TypeDecl>(D) ||
160 isa<ClassTemplateDecl>(D) ||
161 isa<ObjCInterfaceDecl>(D);
162}
163
164/// Does the given declaration have member specialization information,
165/// and if so, is it an explicit specialization?
166template <class T> static typename
167std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
168isExplicitMemberSpecialization(const T *D) {
169 if (const MemberSpecializationInfo *member =
170 D->getMemberSpecializationInfo()) {
171 return member->isExplicitSpecialization();
172 }
173 return false;
174}
175
176/// For templates, this question is easier: a member template can't be
177/// explicitly instantiated, so there's a single bit indicating whether
178/// or not this is an explicit member specialization.
179static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
180 return D->isMemberSpecialization();
181}
182
183/// Given a visibility attribute, return the explicit visibility
184/// associated with it.
185template <class T>
186static Visibility getVisibilityFromAttr(const T *attr) {
187 switch (attr->getVisibility()) {
188 case T::Default:
189 return DefaultVisibility;
190 case T::Hidden:
191 return HiddenVisibility;
192 case T::Protected:
193 return ProtectedVisibility;
194 }
195 llvm_unreachable("bad visibility kind");
196}
197
198/// Return the explicit visibility of the given declaration.
199static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
200 NamedDecl::ExplicitVisibilityKind kind) {
201 // If we're ultimately computing the visibility of a type, look for
202 // a 'type_visibility' attribute before looking for 'visibility'.
203 if (kind == NamedDecl::VisibilityForType) {
204 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
205 return getVisibilityFromAttr(A);
206 }
207 }
208
209 // If this declaration has an explicit visibility attribute, use it.
210 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
211 return getVisibilityFromAttr(A);
212 }
213
214 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
215 // implies visibility(default).
216 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
217 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
218 if (A->getPlatform()->getName().equals("macosx"))
219 return DefaultVisibility;
220 }
221
222 return None;
223}
224
225static LinkageInfo
226getLVForType(const Type &T, LVComputationKind computation) {
227 if (computation == LVForLinkageOnly)
228 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
229 return T.getLinkageAndVisibility();
230}
231
232/// \brief Get the most restrictive linkage for the types in the given
233/// template parameter list. For visibility purposes, template
234/// parameters are part of the signature of a template.
235static LinkageInfo
236getLVForTemplateParameterList(const TemplateParameterList *Params,
237 LVComputationKind computation) {
238 LinkageInfo LV;
239 for (const NamedDecl *P : *Params) {
240 // Template type parameters are the most common and never
241 // contribute to visibility, pack or not.
242 if (isa<TemplateTypeParmDecl>(P))
243 continue;
244
245 // Non-type template parameters can be restricted by the value type, e.g.
246 // template <enum X> class A { ... };
247 // We have to be careful here, though, because we can be dealing with
248 // dependent types.
249 if (const NonTypeTemplateParmDecl *NTTP =
250 dyn_cast<NonTypeTemplateParmDecl>(P)) {
251 // Handle the non-pack case first.
252 if (!NTTP->isExpandedParameterPack()) {
253 if (!NTTP->getType()->isDependentType()) {
254 LV.merge(getLVForType(*NTTP->getType(), computation));
255 }
256 continue;
257 }
258
259 // Look at all the types in an expanded pack.
260 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
261 QualType type = NTTP->getExpansionType(i);
262 if (!type->isDependentType())
263 LV.merge(type->getLinkageAndVisibility());
264 }
265 continue;
266 }
267
268 // Template template parameters can be restricted by their
269 // template parameters, recursively.
270 const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P);
271
272 // Handle the non-pack case first.
273 if (!TTP->isExpandedParameterPack()) {
274 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
275 computation));
276 continue;
277 }
278
279 // Look at all expansions in an expanded pack.
280 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
281 i != n; ++i) {
282 LV.merge(getLVForTemplateParameterList(
283 TTP->getExpansionTemplateParameters(i), computation));
284 }
285 }
286
287 return LV;
288}
289
290/// getLVForDecl - Get the linkage and visibility for the given declaration.
291static LinkageInfo getLVForDecl(const NamedDecl *D,
292 LVComputationKind computation);
293
294static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
295 const Decl *Ret = nullptr;
296 const DeclContext *DC = D->getDeclContext();
297 while (DC->getDeclKind() != Decl::TranslationUnit) {
298 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
299 Ret = cast<Decl>(DC);
300 DC = DC->getParent();
301 }
302 return Ret;
303}
304
305/// \brief Get the most restrictive linkage for the types and
306/// declarations in the given template argument list.
307///
308/// Note that we don't take an LVComputationKind because we always
309/// want to honor the visibility of template arguments in the same way.
310static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
311 LVComputationKind computation) {
312 LinkageInfo LV;
313
314 for (const TemplateArgument &Arg : Args) {
315 switch (Arg.getKind()) {
316 case TemplateArgument::Null:
317 case TemplateArgument::Integral:
318 case TemplateArgument::Expression:
319 continue;
320
321 case TemplateArgument::Type:
322 LV.merge(getLVForType(*Arg.getAsType(), computation));
323 continue;
324
325 case TemplateArgument::Declaration:
326 if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
327 assert(!usesTypeVisibility(ND));
328 LV.merge(getLVForDecl(ND, computation));
329 }
330 continue;
331
332 case TemplateArgument::NullPtr:
333 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
334 continue;
335
336 case TemplateArgument::Template:
337 case TemplateArgument::TemplateExpansion:
338 if (TemplateDecl *Template =
339 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
340 LV.merge(getLVForDecl(Template, computation));
341 continue;
342
343 case TemplateArgument::Pack:
344 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
345 continue;
346 }
347 llvm_unreachable("bad template argument kind");
348 }
349
350 return LV;
351}
352
353static LinkageInfo
354getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
355 LVComputationKind computation) {
356 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
357}
358
359static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
360 const FunctionTemplateSpecializationInfo *specInfo) {
361 // Include visibility from the template parameters and arguments
362 // only if this is not an explicit instantiation or specialization
363 // with direct explicit visibility. (Implicit instantiations won't
364 // have a direct attribute.)
365 if (!specInfo->isExplicitInstantiationOrSpecialization())
366 return true;
367
368 return !fn->hasAttr<VisibilityAttr>();
369}
370
371/// Merge in template-related linkage and visibility for the given
372/// function template specialization.
373///
374/// We don't need a computation kind here because we can assume
375/// LVForValue.
376///
377/// \param[out] LV the computation to use for the parent
378static void
379mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
380 const FunctionTemplateSpecializationInfo *specInfo,
381 LVComputationKind computation) {
382 bool considerVisibility =
383 shouldConsiderTemplateVisibility(fn, specInfo);
384
385 // Merge information from the template parameters.
386 FunctionTemplateDecl *temp = specInfo->getTemplate();
387 LinkageInfo tempLV =
388 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
389 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
390
391 // Merge information from the template arguments.
392 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
393 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
394 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
395}
396
397/// Does the given declaration have a direct visibility attribute
398/// that would match the given rules?
399static bool hasDirectVisibilityAttribute(const NamedDecl *D,
400 LVComputationKind computation) {
401 switch (computation) {
402 case LVForType:
403 case LVForExplicitType:
404 if (D->hasAttr<TypeVisibilityAttr>())
405 return true;
406 // fallthrough
407 case LVForValue:
408 case LVForExplicitValue:
409 if (D->hasAttr<VisibilityAttr>())
410 return true;
411 return false;
412 case LVForLinkageOnly:
413 return false;
414 }
415 llvm_unreachable("bad visibility computation kind");
416}
417
418/// Should we consider visibility associated with the template
419/// arguments and parameters of the given class template specialization?
420static bool shouldConsiderTemplateVisibility(
421 const ClassTemplateSpecializationDecl *spec,
422 LVComputationKind computation) {
423 // Include visibility from the template parameters and arguments
424 // only if this is not an explicit instantiation or specialization
425 // with direct explicit visibility (and note that implicit
426 // instantiations won't have a direct attribute).
427 //
428 // Furthermore, we want to ignore template parameters and arguments
429 // for an explicit specialization when computing the visibility of a
430 // member thereof with explicit visibility.
431 //
432 // This is a bit complex; let's unpack it.
433 //
434 // An explicit class specialization is an independent, top-level
435 // declaration. As such, if it or any of its members has an
436 // explicit visibility attribute, that must directly express the
437 // user's intent, and we should honor it. The same logic applies to
438 // an explicit instantiation of a member of such a thing.
439
440 // Fast path: if this is not an explicit instantiation or
441 // specialization, we always want to consider template-related
442 // visibility restrictions.
443 if (!spec->isExplicitInstantiationOrSpecialization())
444 return true;
445
446 // This is the 'member thereof' check.
447 if (spec->isExplicitSpecialization() &&
448 hasExplicitVisibilityAlready(computation))
449 return false;
450
451 return !hasDirectVisibilityAttribute(spec, computation);
452}
453
454/// Merge in template-related linkage and visibility for the given
455/// class template specialization.
456static void mergeTemplateLV(LinkageInfo &LV,
457 const ClassTemplateSpecializationDecl *spec,
458 LVComputationKind computation) {
459 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
460
461 // Merge information from the template parameters, but ignore
462 // visibility if we're only considering template arguments.
463
464 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
465 LinkageInfo tempLV =
466 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
467 LV.mergeMaybeWithVisibility(tempLV,
468 considerVisibility && !hasExplicitVisibilityAlready(computation));
469
470 // Merge information from the template arguments. We ignore
471 // template-argument visibility if we've got an explicit
472 // instantiation with a visibility attribute.
473 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
474 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
475 if (considerVisibility)
476 LV.mergeVisibility(argsLV);
477 LV.mergeExternalVisibility(argsLV);
478}
479
480/// Should we consider visibility associated with the template
481/// arguments and parameters of the given variable template
482/// specialization? As usual, follow class template specialization
483/// logic up to initialization.
484static bool shouldConsiderTemplateVisibility(
485 const VarTemplateSpecializationDecl *spec,
486 LVComputationKind computation) {
487 // Include visibility from the template parameters and arguments
488 // only if this is not an explicit instantiation or specialization
489 // with direct explicit visibility (and note that implicit
490 // instantiations won't have a direct attribute).
491 if (!spec->isExplicitInstantiationOrSpecialization())
492 return true;
493
494 // An explicit variable specialization is an independent, top-level
495 // declaration. As such, if it has an explicit visibility attribute,
496 // that must directly express the user's intent, and we should honor
497 // it.
498 if (spec->isExplicitSpecialization() &&
499 hasExplicitVisibilityAlready(computation))
500 return false;
501
502 return !hasDirectVisibilityAttribute(spec, computation);
503}
504
505/// Merge in template-related linkage and visibility for the given
506/// variable template specialization. As usual, follow class template
507/// specialization logic up to initialization.
508static void mergeTemplateLV(LinkageInfo &LV,
509 const VarTemplateSpecializationDecl *spec,
510 LVComputationKind computation) {
511 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
512
513 // Merge information from the template parameters, but ignore
514 // visibility if we're only considering template arguments.
515
516 VarTemplateDecl *temp = spec->getSpecializedTemplate();
517 LinkageInfo tempLV =
518 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
519 LV.mergeMaybeWithVisibility(tempLV,
520 considerVisibility && !hasExplicitVisibilityAlready(computation));
521
522 // Merge information from the template arguments. We ignore
523 // template-argument visibility if we've got an explicit
524 // instantiation with a visibility attribute.
525 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
526 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
527 if (considerVisibility)
528 LV.mergeVisibility(argsLV);
529 LV.mergeExternalVisibility(argsLV);
530}
531
532static bool useInlineVisibilityHidden(const NamedDecl *D) {
533 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
534 const LangOptions &Opts = D->getASTContext().getLangOpts();
535 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
536 return false;
537
538 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
539 if (!FD)
540 return false;
541
542 TemplateSpecializationKind TSK = TSK_Undeclared;
543 if (FunctionTemplateSpecializationInfo *spec
544 = FD->getTemplateSpecializationInfo()) {
545 TSK = spec->getTemplateSpecializationKind();
546 } else if (MemberSpecializationInfo *MSI =
547 FD->getMemberSpecializationInfo()) {
548 TSK = MSI->getTemplateSpecializationKind();
549 }
550
551 const FunctionDecl *Def = nullptr;
552 // InlineVisibilityHidden only applies to definitions, and
553 // isInlined() only gives meaningful answers on definitions
554 // anyway.
555 return TSK != TSK_ExplicitInstantiationDeclaration &&
556 TSK != TSK_ExplicitInstantiationDefinition &&
557 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
558}
559
560template <typename T> static bool isFirstInExternCContext(T *D) {
561 const T *First = D->getFirstDecl();
562 return First->isInExternCContext();
563}
564
565static bool isSingleLineLanguageLinkage(const Decl &D) {
566 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
567 if (!SD->hasBraces())
568 return true;
569 return false;
570}
571
572static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
573 LVComputationKind computation) {
574 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
575 "Not a name having namespace scope");
576 ASTContext &Context = D->getASTContext();
577
578 // C++ [basic.link]p3:
579 // A name having namespace scope (3.3.6) has internal linkage if it
580 // is the name of
581 // - an object, reference, function or function template that is
582 // explicitly declared static; or,
583 // (This bullet corresponds to C99 6.2.2p3.)
584 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
585 // Explicitly declared static.
586 if (Var->getStorageClass() == SC_Static)
587 return LinkageInfo::internal();
588
589 // - a non-volatile object or reference that is explicitly declared const
590 // or constexpr and neither explicitly declared extern nor previously
591 // declared to have external linkage; or (there is no equivalent in C99)
592 if (Context.getLangOpts().CPlusPlus &&
593 Var->getType().isConstQualified() &&
594 !Var->getType().isVolatileQualified()) {
595 const VarDecl *PrevVar = Var->getPreviousDecl();
596 if (PrevVar)
597 return getLVForDecl(PrevVar, computation);
598
599 if (Var->getStorageClass() != SC_Extern &&
600 Var->getStorageClass() != SC_PrivateExtern &&
601 !isSingleLineLanguageLinkage(*Var))
602 return LinkageInfo::internal();
603 }
604
605 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
606 PrevVar = PrevVar->getPreviousDecl()) {
607 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
608 Var->getStorageClass() == SC_None)
609 return PrevVar->getLinkageAndVisibility();
610 // Explicitly declared static.
611 if (PrevVar->getStorageClass() == SC_Static)
612 return LinkageInfo::internal();
613 }
614 } else if (const FunctionDecl *Function = D->getAsFunction()) {
615 // C++ [temp]p4:
616 // A non-member function template can have internal linkage; any
617 // other template name shall have external linkage.
618
619 // Explicitly declared static.
620 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
621 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
622 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
623 // - a data member of an anonymous union.
624 const VarDecl *VD = IFD->getVarDecl();
625 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
626 return getLVForNamespaceScopeDecl(VD, computation);
627 }
628 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
629
630 if (D->isInAnonymousNamespace()) {
631 const VarDecl *Var = dyn_cast<VarDecl>(D);
632 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
633 if ((!Var || !isFirstInExternCContext(Var)) &&
634 (!Func || !isFirstInExternCContext(Func)))
635 return LinkageInfo::uniqueExternal();
636 }
637
638 // Set up the defaults.
639
640 // C99 6.2.2p5:
641 // If the declaration of an identifier for an object has file
642 // scope and no storage-class specifier, its linkage is
643 // external.
644 LinkageInfo LV;
645
646 if (!hasExplicitVisibilityAlready(computation)) {
647 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
648 LV.mergeVisibility(*Vis, true);
649 } else {
650 // If we're declared in a namespace with a visibility attribute,
651 // use that namespace's visibility, and it still counts as explicit.
652 for (const DeclContext *DC = D->getDeclContext();
653 !isa<TranslationUnitDecl>(DC);
654 DC = DC->getParent()) {
655 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
656 if (!ND) continue;
657 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
658 LV.mergeVisibility(*Vis, true);
659 break;
660 }
661 }
662 }
663
664 // Add in global settings if the above didn't give us direct visibility.
665 if (!LV.isVisibilityExplicit()) {
666 // Use global type/value visibility as appropriate.
667 Visibility globalVisibility;
668 if (computation == LVForValue) {
669 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
670 } else {
671 assert(computation == LVForType);
672 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
673 }
674 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
675
676 // If we're paying attention to global visibility, apply
677 // -finline-visibility-hidden if this is an inline method.
678 if (useInlineVisibilityHidden(D))
679 LV.mergeVisibility(HiddenVisibility, true);
680 }
681 }
682
683 // C++ [basic.link]p4:
684
685 // A name having namespace scope has external linkage if it is the
686 // name of
687 //
688 // - an object or reference, unless it has internal linkage; or
689 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
690 // GCC applies the following optimization to variables and static
691 // data members, but not to functions:
692 //
693 // Modify the variable's LV by the LV of its type unless this is
694 // C or extern "C". This follows from [basic.link]p9:
695 // A type without linkage shall not be used as the type of a
696 // variable or function with external linkage unless
697 // - the entity has C language linkage, or
698 // - the entity is declared within an unnamed namespace, or
699 // - the entity is not used or is defined in the same
700 // translation unit.
701 // and [basic.link]p10:
702 // ...the types specified by all declarations referring to a
703 // given variable or function shall be identical...
704 // C does not have an equivalent rule.
705 //
706 // Ignore this if we've got an explicit attribute; the user
707 // probably knows what they're doing.
708 //
709 // Note that we don't want to make the variable non-external
710 // because of this, but unique-external linkage suits us.
711 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
712 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
713 if (TypeLV.getLinkage() != ExternalLinkage)
714 return LinkageInfo::uniqueExternal();
715 if (!LV.isVisibilityExplicit())
716 LV.mergeVisibility(TypeLV);
717 }
718
719 if (Var->getStorageClass() == SC_PrivateExtern)
720 LV.mergeVisibility(HiddenVisibility, true);
721
722 // Note that Sema::MergeVarDecl already takes care of implementing
723 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
724 // to do it here.
725
726 // As per function and class template specializations (below),
727 // consider LV for the template and template arguments. We're at file
728 // scope, so we do not need to worry about nested specializations.
729 if (const VarTemplateSpecializationDecl *spec
730 = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
731 mergeTemplateLV(LV, spec, computation);
732 }
733
734 // - a function, unless it has internal linkage; or
735 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
736 // In theory, we can modify the function's LV by the LV of its
737 // type unless it has C linkage (see comment above about variables
738 // for justification). In practice, GCC doesn't do this, so it's
739 // just too painful to make work.
740
741 if (Function->getStorageClass() == SC_PrivateExtern)
742 LV.mergeVisibility(HiddenVisibility, true);
743
744 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
745 // merging storage classes and visibility attributes, so we don't have to
746 // look at previous decls in here.
747
748 // In C++, then if the type of the function uses a type with
749 // unique-external linkage, it's not legally usable from outside
750 // this translation unit. However, we should use the C linkage
751 // rules instead for extern "C" declarations.
752 if (Context.getLangOpts().CPlusPlus &&
753 !Function->isInExternCContext()) {
754 // Only look at the type-as-written. If this function has an auto-deduced
755 // return type, we can't compute the linkage of that type because it could
756 // require looking at the linkage of this function, and we don't need this
757 // for correctness because the type is not part of the function's
758 // signature.
759 // FIXME: This is a hack. We should be able to solve this circularity and
760 // the one in getLVForClassMember for Functions some other way.
761 QualType TypeAsWritten = Function->getType();
762 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
763 TypeAsWritten = TSI->getType();
764 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
765 return LinkageInfo::uniqueExternal();
766 }
767
768 // Consider LV from the template and the template arguments.
769 // We're at file scope, so we do not need to worry about nested
770 // specializations.
771 if (FunctionTemplateSpecializationInfo *specInfo
772 = Function->getTemplateSpecializationInfo()) {
773 mergeTemplateLV(LV, Function, specInfo, computation);
774 }
775
776 // - a named class (Clause 9), or an unnamed class defined in a
777 // typedef declaration in which the class has the typedef name
778 // for linkage purposes (7.1.3); or
779 // - a named enumeration (7.2), or an unnamed enumeration
780 // defined in a typedef declaration in which the enumeration
781 // has the typedef name for linkage purposes (7.1.3); or
782 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
783 // Unnamed tags have no linkage.
784 if (!Tag->hasNameForLinkage())
785 return LinkageInfo::none();
786
787 // If this is a class template specialization, consider the
788 // linkage of the template and template arguments. We're at file
789 // scope, so we do not need to worry about nested specializations.
790 if (const ClassTemplateSpecializationDecl *spec
791 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
792 mergeTemplateLV(LV, spec, computation);
793 }
794
795 // - an enumerator belonging to an enumeration with external linkage;
796 } else if (isa<EnumConstantDecl>(D)) {
797 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
798 computation);
799 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
800 return LinkageInfo::none();
801 LV.merge(EnumLV);
802
803 // - a template, unless it is a function template that has
804 // internal linkage (Clause 14);
805 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
806 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
807 LinkageInfo tempLV =
808 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
809 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
810
811 // - a namespace (7.3), unless it is declared within an unnamed
812 // namespace.
813 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
814 return LV;
815
816 // By extension, we assign external linkage to Objective-C
817 // interfaces.
818 } else if (isa<ObjCInterfaceDecl>(D)) {
819 // fallout
820
821 // Everything not covered here has no linkage.
822 } else {
823 // FIXME: A typedef declaration has linkage if it gives a type a name for
824 // linkage purposes.
825 return LinkageInfo::none();
826 }
827
828 // If we ended up with non-external linkage, visibility should
829 // always be default.
830 if (LV.getLinkage() != ExternalLinkage)
831 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
832
833 return LV;
834}
835
836static LinkageInfo getLVForClassMember(const NamedDecl *D,
837 LVComputationKind computation) {
838 // Only certain class members have linkage. Note that fields don't
839 // really have linkage, but it's convenient to say they do for the
840 // purposes of calculating linkage of pointer-to-data-member
841 // template arguments.
842 //
843 // Templates also don't officially have linkage, but since we ignore
844 // the C++ standard and look at template arguments when determining
845 // linkage and visibility of a template specialization, we might hit
846 // a template template argument that way. If we do, we need to
847 // consider its linkage.
848 if (!(isa<CXXMethodDecl>(D) ||
849 isa<VarDecl>(D) ||
850 isa<FieldDecl>(D) ||
851 isa<IndirectFieldDecl>(D) ||
852 isa<TagDecl>(D) ||
853 isa<TemplateDecl>(D)))
854 return LinkageInfo::none();
855
856 LinkageInfo LV;
857
858 // If we have an explicit visibility attribute, merge that in.
859 if (!hasExplicitVisibilityAlready(computation)) {
860 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
861 LV.mergeVisibility(*Vis, true);
862 // If we're paying attention to global visibility, apply
863 // -finline-visibility-hidden if this is an inline method.
864 //
865 // Note that we do this before merging information about
866 // the class visibility.
867 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
868 LV.mergeVisibility(HiddenVisibility, true);
869 }
870
871 // If this class member has an explicit visibility attribute, the only
872 // thing that can change its visibility is the template arguments, so
873 // only look for them when processing the class.
874 LVComputationKind classComputation = computation;
875 if (LV.isVisibilityExplicit())
876 classComputation = withExplicitVisibilityAlready(computation);
877
878 LinkageInfo classLV =
879 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
880 // If the class already has unique-external linkage, we can't improve.
881 if (classLV.getLinkage() == UniqueExternalLinkage)
882 return LinkageInfo::uniqueExternal();
883
884 if (!isExternallyVisible(classLV.getLinkage()))
885 return LinkageInfo::none();
886
887
888 // Otherwise, don't merge in classLV yet, because in certain cases
889 // we need to completely ignore the visibility from it.
890
891 // Specifically, if this decl exists and has an explicit attribute.
892 const NamedDecl *explicitSpecSuppressor = nullptr;
893
894 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
895 // If the type of the function uses a type with unique-external
896 // linkage, it's not legally usable from outside this translation unit.
897 // But only look at the type-as-written. If this function has an auto-deduced
898 // return type, we can't compute the linkage of that type because it could
899 // require looking at the linkage of this function, and we don't need this
900 // for correctness because the type is not part of the function's
901 // signature.
902 // FIXME: This is a hack. We should be able to solve this circularity and the
903 // one in getLVForNamespaceScopeDecl for Functions some other way.
904 {
905 QualType TypeAsWritten = MD->getType();
906 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
907 TypeAsWritten = TSI->getType();
908 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
909 return LinkageInfo::uniqueExternal();
910 }
911 // If this is a method template specialization, use the linkage for
912 // the template parameters and arguments.
913 if (FunctionTemplateSpecializationInfo *spec
914 = MD->getTemplateSpecializationInfo()) {
915 mergeTemplateLV(LV, MD, spec, computation);
916 if (spec->isExplicitSpecialization()) {
917 explicitSpecSuppressor = MD;
918 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
919 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
920 }
921 } else if (isExplicitMemberSpecialization(MD)) {
922 explicitSpecSuppressor = MD;
923 }
924
925 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
926 if (const ClassTemplateSpecializationDecl *spec
927 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
928 mergeTemplateLV(LV, spec, computation);
929 if (spec->isExplicitSpecialization()) {
930 explicitSpecSuppressor = spec;
931 } else {
932 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
933 if (isExplicitMemberSpecialization(temp)) {
934 explicitSpecSuppressor = temp->getTemplatedDecl();
935 }
936 }
937 } else if (isExplicitMemberSpecialization(RD)) {
938 explicitSpecSuppressor = RD;
939 }
940
941 // Static data members.
942 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
943 if (const VarTemplateSpecializationDecl *spec
944 = dyn_cast<VarTemplateSpecializationDecl>(VD))
945 mergeTemplateLV(LV, spec, computation);
946
947 // Modify the variable's linkage by its type, but ignore the
948 // type's visibility unless it's a definition.
949 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
950 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
951 LV.mergeVisibility(typeLV);
952 LV.mergeExternalVisibility(typeLV);
953
954 if (isExplicitMemberSpecialization(VD)) {
955 explicitSpecSuppressor = VD;
956 }
957
958 // Template members.
959 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
960 bool considerVisibility =
961 (!LV.isVisibilityExplicit() &&
962 !classLV.isVisibilityExplicit() &&
963 !hasExplicitVisibilityAlready(computation));
964 LinkageInfo tempLV =
965 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
966 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
967
968 if (const RedeclarableTemplateDecl *redeclTemp =
969 dyn_cast<RedeclarableTemplateDecl>(temp)) {
970 if (isExplicitMemberSpecialization(redeclTemp)) {
971 explicitSpecSuppressor = temp->getTemplatedDecl();
972 }
973 }
974 }
975
976 // We should never be looking for an attribute directly on a template.
977 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
978
979 // If this member is an explicit member specialization, and it has
980 // an explicit attribute, ignore visibility from the parent.
981 bool considerClassVisibility = true;
982 if (explicitSpecSuppressor &&
983 // optimization: hasDVA() is true only with explicit visibility.
984 LV.isVisibilityExplicit() &&
985 classLV.getVisibility() != DefaultVisibility &&
986 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
987 considerClassVisibility = false;
988 }
989
990 // Finally, merge in information from the class.
991 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
992 return LV;
993}
994
995void NamedDecl::anchor() { }
996
997static LinkageInfo computeLVForDecl(const NamedDecl *D,
998 LVComputationKind computation);
999
1000bool NamedDecl::isLinkageValid() const {
1001 if (!hasCachedLinkage())
1002 return true;
1003
1004 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
1005 getCachedLinkage();
1006}
1007
1008ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1009 StringRef name = getName();
1010 if (name.empty()) return SFF_None;
1011
1012 if (name.front() == 'C')
1013 if (name == "CFStringCreateWithFormat" ||
1014 name == "CFStringCreateWithFormatAndArguments" ||
1015 name == "CFStringAppendFormat" ||
1016 name == "CFStringAppendFormatAndArguments")
1017 return SFF_CFString;
1018 return SFF_None;
1019}
1020
1021Linkage NamedDecl::getLinkageInternal() const {
1022 // We don't care about visibility here, so ask for the cheapest
1023 // possible visibility analysis.
1024 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
1025}
1026
1027LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1028 LVComputationKind computation =
1029 (usesTypeVisibility(this) ? LVForType : LVForValue);
1030 return getLVForDecl(this, computation);
1031}
1032
1033static Optional<Visibility>
1034getExplicitVisibilityAux(const NamedDecl *ND,
1035 NamedDecl::ExplicitVisibilityKind kind,
1036 bool IsMostRecent) {
1037 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1038
1039 // Check the declaration itself first.
1040 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1041 return V;
1042
1043 // If this is a member class of a specialization of a class template
1044 // and the corresponding decl has explicit visibility, use that.
1045 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
1046 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1047 if (InstantiatedFrom)
1048 return getVisibilityOf(InstantiatedFrom, kind);
1049 }
1050
1051 // If there wasn't explicit visibility there, and this is a
1052 // specialization of a class template, check for visibility
1053 // on the pattern.
1054 if (const ClassTemplateSpecializationDecl *spec
1055 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
1056 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1057 kind);
1058
1059 // Use the most recent declaration.
1060 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1061 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1062 if (MostRecent != ND)
1063 return getExplicitVisibilityAux(MostRecent, kind, true);
1064 }
1065
1066 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
1067 if (Var->isStaticDataMember()) {
1068 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1069 if (InstantiatedFrom)
1070 return getVisibilityOf(InstantiatedFrom, kind);
1071 }
1072
1073 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1074 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1075 kind);
1076
1077 return None;
1078 }
1079 // Also handle function template specializations.
1080 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
1081 // If the function is a specialization of a template with an
1082 // explicit visibility attribute, use that.
1083 if (FunctionTemplateSpecializationInfo *templateInfo
1084 = fn->getTemplateSpecializationInfo())
1085 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1086 kind);
1087
1088 // If the function is a member of a specialization of a class template
1089 // and the corresponding decl has explicit visibility, use that.
1090 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1091 if (InstantiatedFrom)
1092 return getVisibilityOf(InstantiatedFrom, kind);
1093
1094 return None;
1095 }
1096
1097 // The visibility of a template is stored in the templated decl.
1098 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
1099 return getVisibilityOf(TD->getTemplatedDecl(), kind);
1100
1101 return None;
1102}
1103
1104Optional<Visibility>
1105NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1106 return getExplicitVisibilityAux(this, kind, false);
1107}
1108
1109static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1110 LVComputationKind computation) {
1111 // This lambda has its linkage/visibility determined by its owner.
1112 if (ContextDecl) {
1113 if (isa<ParmVarDecl>(ContextDecl))
1114 DC = ContextDecl->getDeclContext()->getRedeclContext();
1115 else
1116 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1117 }
1118
1119 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1120 return getLVForDecl(ND, computation);
1121
1122 return LinkageInfo::external();
1123}
1124
1125static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1126 LVComputationKind computation) {
1127 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1128 if (Function->isInAnonymousNamespace() &&
1129 !Function->isInExternCContext())
1130 return LinkageInfo::uniqueExternal();
1131
1132 // This is a "void f();" which got merged with a file static.
1133 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1134 return LinkageInfo::internal();
1135
1136 LinkageInfo LV;
1137 if (!hasExplicitVisibilityAlready(computation)) {
1138 if (Optional<Visibility> Vis =
1139 getExplicitVisibility(Function, computation))
1140 LV.mergeVisibility(*Vis, true);
1141 }
1142
1143 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1144 // merging storage classes and visibility attributes, so we don't have to
1145 // look at previous decls in here.
1146
1147 return LV;
1148 }
1149
1150 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1151 if (Var->hasExternalStorage()) {
1152 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
1153 return LinkageInfo::uniqueExternal();
1154
1155 LinkageInfo LV;
1156 if (Var->getStorageClass() == SC_PrivateExtern)
1157 LV.mergeVisibility(HiddenVisibility, true);
1158 else if (!hasExplicitVisibilityAlready(computation)) {
1159 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1160 LV.mergeVisibility(*Vis, true);
1161 }
1162
1163 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1164 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1165 if (PrevLV.getLinkage())
1166 LV.setLinkage(PrevLV.getLinkage());
1167 LV.mergeVisibility(PrevLV);
1168 }
1169
1170 return LV;
1171 }
1172
1173 if (!Var->isStaticLocal())
1174 return LinkageInfo::none();
1175 }
1176
1177 ASTContext &Context = D->getASTContext();
1178 if (!Context.getLangOpts().CPlusPlus)
1179 return LinkageInfo::none();
1180
1181 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1182 if (!OuterD)
1183 return LinkageInfo::none();
1184
1185 LinkageInfo LV;
1186 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1187 if (!BD->getBlockManglingNumber())
1188 return LinkageInfo::none();
1189
1190 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1191 BD->getBlockManglingContextDecl(), computation);
1192 } else {
1193 const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1194 if (!FD->isInlined() &&
1195 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1196 return LinkageInfo::none();
1197
1198 LV = getLVForDecl(FD, computation);
1199 }
1200 if (!isExternallyVisible(LV.getLinkage()))
1201 return LinkageInfo::none();
1202 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1203 LV.isVisibilityExplicit());
1204}
1205
1206static inline const CXXRecordDecl*
1207getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1208 const CXXRecordDecl *Ret = Record;
1209 while (Record && Record->isLambda()) {
1210 Ret = Record;
1211 if (!Record->getParent()) break;
1212 // Get the Containing Class of this Lambda Class
1213 Record = dyn_cast_or_null<CXXRecordDecl>(
1214 Record->getParent()->getParent());
1215 }
1216 return Ret;
1217}
1218
1219static LinkageInfo computeLVForDecl(const NamedDecl *D,
1220 LVComputationKind computation) {
1221 // Objective-C: treat all Objective-C declarations as having external
1222 // linkage.
1223 switch (D->getKind()) {
1224 default:
1225 break;
1226 case Decl::ParmVar:
1227 return LinkageInfo::none();
1228 case Decl::TemplateTemplateParm: // count these as external
1229 case Decl::NonTypeTemplateParm:
1230 case Decl::ObjCAtDefsField:
1231 case Decl::ObjCCategory:
1232 case Decl::ObjCCategoryImpl:
1233 case Decl::ObjCCompatibleAlias:
1234 case Decl::ObjCImplementation:
1235 case Decl::ObjCMethod:
1236 case Decl::ObjCProperty:
1237 case Decl::ObjCPropertyImpl:
1238 case Decl::ObjCProtocol:
1239 return LinkageInfo::external();
1240
1241 case Decl::CXXRecord: {
1242 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1243 if (Record->isLambda()) {
1244 if (!Record->getLambdaManglingNumber()) {
1245 // This lambda has no mangling number, so it's internal.
1246 return LinkageInfo::internal();
1247 }
1248
1249 // This lambda has its linkage/visibility determined:
1250 // - either by the outermost lambda if that lambda has no mangling
1251 // number.
1252 // - or by the parent of the outer most lambda
1253 // This prevents infinite recursion in settings such as nested lambdas
1254 // used in NSDMI's, for e.g.
1255 // struct L {
1256 // int t{};
1257 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1258 // };
1259 const CXXRecordDecl *OuterMostLambda =
1260 getOutermostEnclosingLambda(Record);
1261 if (!OuterMostLambda->getLambdaManglingNumber())
1262 return LinkageInfo::internal();
1263
1264 return getLVForClosure(
1265 OuterMostLambda->getDeclContext()->getRedeclContext(),
1266 OuterMostLambda->getLambdaContextDecl(), computation);
1267 }
1268
1269 break;
1270 }
1271 }
1272
1273 // Handle linkage for namespace-scope names.
1274 if (D->getDeclContext()->getRedeclContext()->isFileContext())
1275 return getLVForNamespaceScopeDecl(D, computation);
1276
1277 // C++ [basic.link]p5:
1278 // In addition, a member function, static data member, a named
1279 // class or enumeration of class scope, or an unnamed class or
1280 // enumeration defined in a class-scope typedef declaration such
1281 // that the class or enumeration has the typedef name for linkage
1282 // purposes (7.1.3), has external linkage if the name of the class
1283 // has external linkage.
1284 if (D->getDeclContext()->isRecord())
1285 return getLVForClassMember(D, computation);
1286
1287 // C++ [basic.link]p6:
1288 // The name of a function declared in block scope and the name of
1289 // an object declared by a block scope extern declaration have
1290 // linkage. If there is a visible declaration of an entity with
1291 // linkage having the same name and type, ignoring entities
1292 // declared outside the innermost enclosing namespace scope, the
1293 // block scope declaration declares that same entity and receives
1294 // the linkage of the previous declaration. If there is more than
1295 // one such matching entity, the program is ill-formed. Otherwise,
1296 // if no matching entity is found, the block scope entity receives
1297 // external linkage.
1298 if (D->getDeclContext()->isFunctionOrMethod())
1299 return getLVForLocalDecl(D, computation);
1300
1301 // C++ [basic.link]p6:
1302 // Names not covered by these rules have no linkage.
1303 return LinkageInfo::none();
1304}
1305
1306namespace clang {
1307class LinkageComputer {
1308public:
1309 static LinkageInfo getLVForDecl(const NamedDecl *D,
1310 LVComputationKind computation) {
1311 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1312 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1313
1314 LinkageInfo LV = computeLVForDecl(D, computation);
1315 if (D->hasCachedLinkage())
1316 assert(D->getCachedLinkage() == LV.getLinkage());
1317
1318 D->setCachedLinkage(LV.getLinkage());
1319
1320#ifndef NDEBUG
1321 // In C (because of gnu inline) and in c++ with microsoft extensions an
1322 // static can follow an extern, so we can have two decls with different
1323 // linkages.
1324 const LangOptions &Opts = D->getASTContext().getLangOpts();
1325 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1326 return LV;
1327
1328 // We have just computed the linkage for this decl. By induction we know
1329 // that all other computed linkages match, check that the one we just
1330 // computed also does.
1331 NamedDecl *Old = nullptr;
1332 for (auto I : D->redecls()) {
1333 NamedDecl *T = cast<NamedDecl>(I);
1334 if (T == D)
1335 continue;
1336 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1337 Old = T;
1338 break;
1339 }
1340 }
1341 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1342#endif
1343
1344 return LV;
1345 }
1346};
1347}
1348
1349static LinkageInfo getLVForDecl(const NamedDecl *D,
1350 LVComputationKind computation) {
1351 return clang::LinkageComputer::getLVForDecl(D, computation);
1352}
1353
1354std::string NamedDecl::getQualifiedNameAsString() const {
1355 std::string QualName;
1356 llvm::raw_string_ostream OS(QualName);
1357 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1358 return OS.str();
1359}
1360
1361void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1362 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1363}
1364
1365void NamedDecl::printQualifiedName(raw_ostream &OS,
1366 const PrintingPolicy &P) const {
1367 const DeclContext *Ctx = getDeclContext();
1368
1369 if (Ctx->isFunctionOrMethod()) {
1370 printName(OS);
1371 return;
1372 }
1373
1374 typedef SmallVector<const DeclContext *, 8> ContextsTy;
1375 ContextsTy Contexts;
1376
1377 // Collect contexts.
1378 while (Ctx && isa<NamedDecl>(Ctx)) {
1379 Contexts.push_back(Ctx);
1380 Ctx = Ctx->getParent();
1381 }
1382
1383 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1384 I != E; ++I) {
1385 if (const ClassTemplateSpecializationDecl *Spec
1386 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
1387 OS << Spec->getName();
1388 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1389 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1390 TemplateArgs.data(),
1391 TemplateArgs.size(),
1392 P);
1393 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
1394 if (P.SuppressUnwrittenScope &&
1395 (ND->isAnonymousNamespace() || ND->isInline()))
1396 continue;
1397 if (ND->isAnonymousNamespace())
1398 OS << "(anonymous namespace)";
1399 else
1400 OS << *ND;
1401 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1402 if (!RD->getIdentifier())
1403 OS << "(anonymous " << RD->getKindName() << ')';
1404 else
1405 OS << *RD;
1406 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1407 const FunctionProtoType *FT = nullptr;
1408 if (FD->hasWrittenPrototype())
1409 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1410
1411 OS << *FD << '(';
1412 if (FT) {
1413 unsigned NumParams = FD->getNumParams();
1414 for (unsigned i = 0; i < NumParams; ++i) {
1415 if (i)
1416 OS << ", ";
1417 OS << FD->getParamDecl(i)->getType().stream(P);
1418 }
1419
1420 if (FT->isVariadic()) {
1421 if (NumParams > 0)
1422 OS << ", ";
1423 OS << "...";
1424 }
1425 }
1426 OS << ')';
1427 } else {
1428 OS << *cast<NamedDecl>(*I);
1429 }
1430 OS << "::";
1431 }
1432
1433 if (getDeclName())
1434 OS << *this;
1435 else
1436 OS << "(anonymous)";
1437}
1438
1439void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1440 const PrintingPolicy &Policy,
1441 bool Qualified) const {
1442 if (Qualified)
1443 printQualifiedName(OS, Policy);
1444 else
1445 printName(OS);
1446}
1447
1448bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
1449 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1450
1451 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1452 // We want to keep it, unless it nominates same namespace.
1453 if (getKind() == Decl::UsingDirective) {
1454 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1455 ->getOriginalNamespace() ==
1456 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1457 ->getOriginalNamespace();
1458 }
1459
1460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1461 // For function declarations, we keep track of redeclarations.
1462 return FD->getPreviousDecl() == OldD;
1463
1464 // For function templates, the underlying function declarations are linked.
1465 if (const FunctionTemplateDecl *FunctionTemplate
1466 = dyn_cast<FunctionTemplateDecl>(this))
1467 if (const FunctionTemplateDecl *OldFunctionTemplate
1468 = dyn_cast<FunctionTemplateDecl>(OldD))
1469 return FunctionTemplate->getTemplatedDecl()
1470 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
1471
1472 // For method declarations, we keep track of redeclarations.
1473 if (isa<ObjCMethodDecl>(this))
1474 return false;
1475
1476 // FIXME: Is this correct if one of the decls comes from an inline namespace?
1477 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1478 return true;
1479
1480 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1481 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1482 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1483
1484 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1485 ASTContext &Context = getASTContext();
1486 return Context.getCanonicalNestedNameSpecifier(
1487 cast<UsingDecl>(this)->getQualifier()) ==
1488 Context.getCanonicalNestedNameSpecifier(
1489 cast<UsingDecl>(OldD)->getQualifier());
1490 }
1491
1492 if (isa<UnresolvedUsingValueDecl>(this) &&
1493 isa<UnresolvedUsingValueDecl>(OldD)) {
1494 ASTContext &Context = getASTContext();
1495 return Context.getCanonicalNestedNameSpecifier(
1496 cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1497 Context.getCanonicalNestedNameSpecifier(
1498 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1499 }
1500
1501 // A typedef of an Objective-C class type can replace an Objective-C class
1502 // declaration or definition, and vice versa.
1503 // FIXME: Is this correct if one of the decls comes from an inline namespace?
1504 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1505 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1506 return true;
1507
1508 // For non-function declarations, if the declarations are of the
1509 // same kind and have the same parent then this must be a redeclaration,
1510 // or semantic analysis would not have given us the new declaration.
1511 // Note that inline namespaces can give us two declarations with the same
1512 // name and kind in the same scope but different contexts.
1513 return this->getKind() == OldD->getKind() &&
1514 this->getDeclContext()->getRedeclContext()->Equals(
1515 OldD->getDeclContext()->getRedeclContext());
1516}
1517
1518bool NamedDecl::hasLinkage() const {
1519 return getFormalLinkage() != NoLinkage;
1520}
1521
1522NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1523 NamedDecl *ND = this;
1524 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1525 ND = UD->getTargetDecl();
1526
1527 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1528 return AD->getClassInterface();
1529
1530 return ND;
1531}
1532
1533bool NamedDecl::isCXXInstanceMember() const {
1534 if (!isCXXClassMember())
1535 return false;
1536
1537 const NamedDecl *D = this;
1538 if (isa<UsingShadowDecl>(D))
1539 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1540
1541 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1542 return true;
1543 if (const CXXMethodDecl *MD =
1544 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1545 return MD->isInstance();
1546 return false;
1547}
1548
1549//===----------------------------------------------------------------------===//
1550// DeclaratorDecl Implementation
1551//===----------------------------------------------------------------------===//
1552
1553template <typename DeclT>
1554static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1555 if (decl->getNumTemplateParameterLists() > 0)
1556 return decl->getTemplateParameterList(0)->getTemplateLoc();
1557 else
1558 return decl->getInnerLocStart();
1559}
1560
1561SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1562 TypeSourceInfo *TSI = getTypeSourceInfo();
1563 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1564 return SourceLocation();
1565}
1566
1567void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1568 if (QualifierLoc) {
1569 // Make sure the extended decl info is allocated.
1570 if (!hasExtInfo()) {
1571 // Save (non-extended) type source info pointer.
1572 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1573 // Allocate external info struct.
1574 DeclInfo = new (getASTContext()) ExtInfo;
1575 // Restore savedTInfo into (extended) decl info.
1576 getExtInfo()->TInfo = savedTInfo;
1577 }
1578 // Set qualifier info.
1579 getExtInfo()->QualifierLoc = QualifierLoc;
1580 } else {
1581 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1582 if (hasExtInfo()) {
1583 if (getExtInfo()->NumTemplParamLists == 0) {
1584 // Save type source info pointer.
1585 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1586 // Deallocate the extended decl info.
1587 getASTContext().Deallocate(getExtInfo());
1588 // Restore savedTInfo into (non-extended) decl info.
1589 DeclInfo = savedTInfo;
1590 }
1591 else
1592 getExtInfo()->QualifierLoc = QualifierLoc;
1593 }
1594 }
1595}
1596
1597void
1598DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1599 unsigned NumTPLists,
1600 TemplateParameterList **TPLists) {
1601 assert(NumTPLists > 0);
1602 // Make sure the extended decl info is allocated.
1603 if (!hasExtInfo()) {
1604 // Save (non-extended) type source info pointer.
1605 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1606 // Allocate external info struct.
1607 DeclInfo = new (getASTContext()) ExtInfo;
1608 // Restore savedTInfo into (extended) decl info.
1609 getExtInfo()->TInfo = savedTInfo;
1610 }
1611 // Set the template parameter lists info.
1612 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1613}
1614
1615SourceLocation DeclaratorDecl::getOuterLocStart() const {
1616 return getTemplateOrInnerLocStart(this);
1617}
1618
1619namespace {
1620
1621// Helper function: returns true if QT is or contains a type
1622// having a postfix component.
1623bool typeIsPostfix(clang::QualType QT) {
1624 while (true) {
1625 const Type* T = QT.getTypePtr();
1626 switch (T->getTypeClass()) {
1627 default:
1628 return false;
1629 case Type::Pointer:
1630 QT = cast<PointerType>(T)->getPointeeType();
1631 break;
1632 case Type::BlockPointer:
1633 QT = cast<BlockPointerType>(T)->getPointeeType();
1634 break;
1635 case Type::MemberPointer:
1636 QT = cast<MemberPointerType>(T)->getPointeeType();
1637 break;
1638 case Type::LValueReference:
1639 case Type::RValueReference:
1640 QT = cast<ReferenceType>(T)->getPointeeType();
1641 break;
1642 case Type::PackExpansion:
1643 QT = cast<PackExpansionType>(T)->getPattern();
1644 break;
1645 case Type::Paren:
1646 case Type::ConstantArray:
1647 case Type::DependentSizedArray:
1648 case Type::IncompleteArray:
1649 case Type::VariableArray:
1650 case Type::FunctionProto:
1651 case Type::FunctionNoProto:
1652 return true;
1653 }
1654 }
1655}
1656
1657} // namespace
1658
1659SourceRange DeclaratorDecl::getSourceRange() const {
1660 SourceLocation RangeEnd = getLocation();
1661 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1662 // If the declaration has no name or the type extends past the name take the
1663 // end location of the type.
1664 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1665 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1666 }
1667 return SourceRange(getOuterLocStart(), RangeEnd);
1668}
1669
1670void
1671QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1672 unsigned NumTPLists,
1673 TemplateParameterList **TPLists) {
1674 assert((NumTPLists == 0 || TPLists != nullptr) &&
1675 "Empty array of template parameters with positive size!");
1676
1677 // Free previous template parameters (if any).
1678 if (NumTemplParamLists > 0) {
1679 Context.Deallocate(TemplParamLists);
1680 TemplParamLists = nullptr;
1681 NumTemplParamLists = 0;
1682 }
1683 // Set info on matched template parameter lists (if any).
1684 if (NumTPLists > 0) {
1685 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1686 NumTemplParamLists = NumTPLists;
1687 for (unsigned i = NumTPLists; i-- > 0; )
1688 TemplParamLists[i] = TPLists[i];
1689 }
1690}
1691
1692//===----------------------------------------------------------------------===//
1693// VarDecl Implementation
1694//===----------------------------------------------------------------------===//
1695
1696const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1697 switch (SC) {
1698 case SC_None: break;
1699 case SC_Auto: return "auto";
1700 case SC_Extern: return "extern";
1701 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1702 case SC_PrivateExtern: return "__private_extern__";
1703 case SC_Register: return "register";
1704 case SC_Static: return "static";
1705 }
1706
1707 llvm_unreachable("Invalid storage class");
1708}
1709
1710VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1711 SourceLocation StartLoc, SourceLocation IdLoc,
1712 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1713 StorageClass SC)
1714 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1715 redeclarable_base(C), Init() {
1716 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1717 "VarDeclBitfields too large!");
1718 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1719 "ParmVarDeclBitfields too large!");
1720 AllBits = 0;
1721 VarDeclBits.SClass = SC;
1722 // Everything else is implicitly initialized to false.
1723}
1724
1725VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1726 SourceLocation StartL, SourceLocation IdL,
1727 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1728 StorageClass S) {
1729 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
1730}
1731
1732VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1733 return new (C, ID)
1734 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1735 QualType(), nullptr, SC_None);
1736}
1737
1738void VarDecl::setStorageClass(StorageClass SC) {
1739 assert(isLegalForVariable(SC));
1740 VarDeclBits.SClass = SC;
1741}
1742
1743VarDecl::TLSKind VarDecl::getTLSKind() const {
1744 switch (VarDeclBits.TSCSpec) {
1745 case TSCS_unspecified:
1746 if (hasAttr<ThreadAttr>())
1747 return TLS_Static;
1748 return TLS_None;
1749 case TSCS___thread: // Fall through.
1750 case TSCS__Thread_local:
1751 return TLS_Static;
1752 case TSCS_thread_local:
1753 return TLS_Dynamic;
1754 }
1755 llvm_unreachable("Unknown thread storage class specifier!");
1756}
1757
1758SourceRange VarDecl::getSourceRange() const {
1759 if (const Expr *Init = getInit()) {
1760 SourceLocation InitEnd = Init->getLocEnd();
1761 // If Init is implicit, ignore its source range and fallback on
1762 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1763 if (InitEnd.isValid() && InitEnd != getLocation())
1764 return SourceRange(getOuterLocStart(), InitEnd);
1765 }
1766 return DeclaratorDecl::getSourceRange();
1767}
1768
1769template<typename T>
1770static LanguageLinkage getDeclLanguageLinkage(const T &D) {
1771 // C++ [dcl.link]p1: All function types, function names with external linkage,
1772 // and variable names with external linkage have a language linkage.
1773 if (!D.hasExternalFormalLinkage())
1774 return NoLanguageLinkage;
1775
1776 // Language linkage is a C++ concept, but saying that everything else in C has
1777 // C language linkage fits the implementation nicely.
1778 ASTContext &Context = D.getASTContext();
1779 if (!Context.getLangOpts().CPlusPlus)
1780 return CLanguageLinkage;
1781
1782 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1783 // language linkage of the names of class members and the function type of
1784 // class member functions.
1785 const DeclContext *DC = D.getDeclContext();
1786 if (DC->isRecord())
1787 return CXXLanguageLinkage;
1788
1789 // If the first decl is in an extern "C" context, any other redeclaration
1790 // will have C language linkage. If the first one is not in an extern "C"
1791 // context, we would have reported an error for any other decl being in one.
1792 if (isFirstInExternCContext(&D))
1793 return CLanguageLinkage;
1794 return CXXLanguageLinkage;
1795}
1796
1797template<typename T>
1798static bool isDeclExternC(const T &D) {
1799 // Since the context is ignored for class members, they can only have C++
1800 // language linkage or no language linkage.
1801 const DeclContext *DC = D.getDeclContext();
1802 if (DC->isRecord()) {
1803 assert(D.getASTContext().getLangOpts().CPlusPlus);
1804 return false;
1805 }
1806
1807 return D.getLanguageLinkage() == CLanguageLinkage;
1808}
1809
1810LanguageLinkage VarDecl::getLanguageLinkage() const {
1811 return getDeclLanguageLinkage(*this);
1812}
1813
1814bool VarDecl::isExternC() const {
1815 return isDeclExternC(*this);
1816}
1817
1818bool VarDecl::isInExternCContext() const {
1819 return getLexicalDeclContext()->isExternCContext();
1820}
1821
1822bool VarDecl::isInExternCXXContext() const {
1823 return getLexicalDeclContext()->isExternCXXContext();
1824}
1825
1826VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
1827
1828VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1829 ASTContext &C) const
1830{
1831 // C++ [basic.def]p2:
1832 // A declaration is a definition unless [...] it contains the 'extern'
1833 // specifier or a linkage-specification and neither an initializer [...],
1834 // it declares a static data member in a class declaration [...].
1835 // C++1y [temp.expl.spec]p15:
1836 // An explicit specialization of a static data member or an explicit
1837 // specialization of a static data member template is a definition if the
1838 // declaration includes an initializer; otherwise, it is a declaration.
1839 //
1840 // FIXME: How do you declare (but not define) a partial specialization of
1841 // a static data member template outside the containing class?
1842 if (isStaticDataMember()) {
1843 if (isOutOfLine() &&
1844 (hasInit() ||
1845 // If the first declaration is out-of-line, this may be an
1846 // instantiation of an out-of-line partial specialization of a variable
1847 // template for which we have not yet instantiated the initializer.
1848 (getFirstDecl()->isOutOfLine()
1849 ? getTemplateSpecializationKind() == TSK_Undeclared
1850 : getTemplateSpecializationKind() !=
1851 TSK_ExplicitSpecialization) ||
1852 isa<VarTemplatePartialSpecializationDecl>(this)))
1853 return Definition;
1854 else
1855 return DeclarationOnly;
1856 }
1857 // C99 6.7p5:
1858 // A definition of an identifier is a declaration for that identifier that
1859 // [...] causes storage to be reserved for that object.
1860 // Note: that applies for all non-file-scope objects.
1861 // C99 6.9.2p1:
1862 // If the declaration of an identifier for an object has file scope and an
1863 // initializer, the declaration is an external definition for the identifier
1864 if (hasInit())
1865 return Definition;
1866
1867 if (hasAttr<AliasAttr>())
1868 return Definition;
1869
1870 // A variable template specialization (other than a static data member
1871 // template or an explicit specialization) is a declaration until we
1872 // instantiate its initializer.
1873 if (isa<VarTemplateSpecializationDecl>(this) &&
1874 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1875 return DeclarationOnly;
1876
1877 if (hasExternalStorage())
1878 return DeclarationOnly;
1879
1880 // [dcl.link] p7:
1881 // A declaration directly contained in a linkage-specification is treated
1882 // as if it contains the extern specifier for the purpose of determining
1883 // the linkage of the declared name and whether it is a definition.
1884 if (isSingleLineLanguageLinkage(*this))
1885 return DeclarationOnly;
1886
1887 // C99 6.9.2p2:
1888 // A declaration of an object that has file scope without an initializer,
1889 // and without a storage class specifier or the scs 'static', constitutes
1890 // a tentative definition.
1891 // No such thing in C++.
1892 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1893 return TentativeDefinition;
1894
1895 // What's left is (in C, block-scope) declarations without initializers or
1896 // external storage. These are definitions.
1897 return Definition;
1898}
1899
1900VarDecl *VarDecl::getActingDefinition() {
1901 DefinitionKind Kind = isThisDeclarationADefinition();
1902 if (Kind != TentativeDefinition)
1903 return nullptr;
1904
1905 VarDecl *LastTentative = nullptr;
1906 VarDecl *First = getFirstDecl();
1907 for (auto I : First->redecls()) {
1908 Kind = I->isThisDeclarationADefinition();
1909 if (Kind == Definition)
1910 return nullptr;
1911 else if (Kind == TentativeDefinition)
1912 LastTentative = I;
1913 }
1914 return LastTentative;
1915}
1916
1917VarDecl *VarDecl::getDefinition(ASTContext &C) {
1918 VarDecl *First = getFirstDecl();
1919 for (auto I : First->redecls()) {
1920 if (I->isThisDeclarationADefinition(C) == Definition)
1921 return I;
1922 }
1923 return nullptr;
1924}
1925
1926VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1927 DefinitionKind Kind = DeclarationOnly;
1928
1929 const VarDecl *First = getFirstDecl();
1930 for (auto I : First->redecls()) {
1931 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
1932 if (Kind == Definition)
1933 break;
1934 }
1935
1936 return Kind;
1937}
1938
1939const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1940 for (auto I : redecls()) {
1941 if (auto Expr = I->getInit()) {
1942 D = I;
1943 return Expr;
1944 }
1945 }
1946 return nullptr;
1947}
1948
1949bool VarDecl::isOutOfLine() const {
1950 if (Decl::isOutOfLine())
1951 return true;
1952
1953 if (!isStaticDataMember())
1954 return false;
1955
1956 // If this static data member was instantiated from a static data member of
1957 // a class template, check whether that static data member was defined
1958 // out-of-line.
1959 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1960 return VD->isOutOfLine();
1961
1962 return false;
1963}
1964
1965VarDecl *VarDecl::getOutOfLineDefinition() {
1966 if (!isStaticDataMember())
1967 return nullptr;
1968
1969 for (auto RD : redecls()) {
1970 if (RD->getLexicalDeclContext()->isFileContext())
1971 return RD;
1972 }
1973
1974 return nullptr;
1975}
1976
1977void VarDecl::setInit(Expr *I) {
1978 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1979 Eval->~EvaluatedStmt();
1980 getASTContext().Deallocate(Eval);
1981 }
1982
1983 Init = I;
1984}
1985
1986bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1987 const LangOptions &Lang = C.getLangOpts();
1988
1989 if (!Lang.CPlusPlus)
1990 return false;
1991
1992 // In C++11, any variable of reference type can be used in a constant
1993 // expression if it is initialized by a constant expression.
1994 if (Lang.CPlusPlus11 && getType()->isReferenceType())
1995 return true;
1996
1997 // Only const objects can be used in constant expressions in C++. C++98 does
1998 // not require the variable to be non-volatile, but we consider this to be a
1999 // defect.
2000 if (!getType().isConstQualified() || getType().isVolatileQualified())
2001 return false;
2002
2003 // In C++, const, non-volatile variables of integral or enumeration types
2004 // can be used in constant expressions.
2005 if (getType()->isIntegralOrEnumerationType())
2006 return true;
2007
2008 // Additionally, in C++11, non-volatile constexpr variables can be used in
2009 // constant expressions.
2010 return Lang.CPlusPlus11 && isConstexpr();
2011}
2012
2013/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2014/// form, which contains extra information on the evaluated value of the
2015/// initializer.
2016EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2017 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
2018 if (!Eval) {
2019 Stmt *S = Init.get<Stmt *>();
2020 // Note: EvaluatedStmt contains an APValue, which usually holds
2021 // resources not allocated from the ASTContext. We need to do some
2022 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2023 // where we can detect whether there's anything to clean up or not.
2024 Eval = new (getASTContext()) EvaluatedStmt;
2025 Eval->Value = S;
2026 Init = Eval;
2027 }
2028 return Eval;
2029}
2030
2031APValue *VarDecl::evaluateValue() const {
2032 SmallVector<PartialDiagnosticAt, 8> Notes;
2033 return evaluateValue(Notes);
2034}
2035
2036namespace {
2037// Destroy an APValue that was allocated in an ASTContext.
2038void DestroyAPValue(void* UntypedValue) {
2039 static_cast<APValue*>(UntypedValue)->~APValue();
2040}
2041} // namespace
2042
2043APValue *VarDecl::evaluateValue(
2044 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2045 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2046
2047 // We only produce notes indicating why an initializer is non-constant the
2048 // first time it is evaluated. FIXME: The notes won't always be emitted the
2049 // first time we try evaluation, so might not be produced at all.
2050 if (Eval->WasEvaluated)
2051 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
2052
2053 const Expr *Init = cast<Expr>(Eval->Value);
2054 assert(!Init->isValueDependent());
2055
2056 if (Eval->IsEvaluating) {
2057 // FIXME: Produce a diagnostic for self-initialization.
2058 Eval->CheckedICE = true;
2059 Eval->IsICE = false;
2060 return nullptr;
2061 }
2062
2063 Eval->IsEvaluating = true;
2064
2065 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2066 this, Notes);
2067
2068 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2069 // or that it's empty (so that there's nothing to clean up) if evaluation
2070 // failed.
2071 if (!Result)
2072 Eval->Evaluated = APValue();
2073 else if (Eval->Evaluated.needsCleanup())
2074 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
2075
2076 Eval->IsEvaluating = false;
2077 Eval->WasEvaluated = true;
2078
2079 // In C++11, we have determined whether the initializer was a constant
2080 // expression as a side-effect.
2081 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
2082 Eval->CheckedICE = true;
2083 Eval->IsICE = Result && Notes.empty();
2084 }
2085
2086 return Result ? &Eval->Evaluated : nullptr;
2087}
2088
2089bool VarDecl::checkInitIsICE() const {
2090 // Initializers of weak variables are never ICEs.
2091 if (isWeak())
2092 return false;
2093
2094 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2095 if (Eval->CheckedICE)
2096 // We have already checked whether this subexpression is an
2097 // integral constant expression.
2098 return Eval->IsICE;
2099
2100 const Expr *Init = cast<Expr>(Eval->Value);
2101 assert(!Init->isValueDependent());
2102
2103 // In C++11, evaluate the initializer to check whether it's a constant
2104 // expression.
2105 if (getASTContext().getLangOpts().CPlusPlus11) {
2106 SmallVector<PartialDiagnosticAt, 8> Notes;
2107 evaluateValue(Notes);
2108 return Eval->IsICE;
2109 }
2110
2111 // It's an ICE whether or not the definition we found is
2112 // out-of-line. See DR 721 and the discussion in Clang PR
2113 // 6206 for details.
2114
2115 if (Eval->CheckingICE)
2116 return false;
2117 Eval->CheckingICE = true;
2118
2119 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2120 Eval->CheckingICE = false;
2121 Eval->CheckedICE = true;
2122 return Eval->IsICE;
2123}
2124
2125VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2126 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2127 return cast<VarDecl>(MSI->getInstantiatedFrom());
2128
2129 return nullptr;
2130}
2131
2132TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2133 if (const VarTemplateSpecializationDecl *Spec =
2134 dyn_cast<VarTemplateSpecializationDecl>(this))
2135 return Spec->getSpecializationKind();
2136
2137 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2138 return MSI->getTemplateSpecializationKind();
2139
2140 return TSK_Undeclared;
2141}
2142
2143SourceLocation VarDecl::getPointOfInstantiation() const {
2144 if (const VarTemplateSpecializationDecl *Spec =
2145 dyn_cast<VarTemplateSpecializationDecl>(this))
2146 return Spec->getPointOfInstantiation();
2147
2148 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2149 return MSI->getPointOfInstantiation();
2150
2151 return SourceLocation();
2152}
2153
2154VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2155 return getASTContext().getTemplateOrSpecializationInfo(this)
2156 .dyn_cast<VarTemplateDecl *>();
2157}
2158
2159void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2160 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2161}
2162
2163MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2164 if (isStaticDataMember())
2165 // FIXME: Remove ?
2166 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2167 return getASTContext().getTemplateOrSpecializationInfo(this)
2168 .dyn_cast<MemberSpecializationInfo *>();
2169 return nullptr;
2170}
2171
2172void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2173 SourceLocation PointOfInstantiation) {
2174 assert((isa<VarTemplateSpecializationDecl>(this) ||
2175 getMemberSpecializationInfo()) &&
2176 "not a variable or static data member template specialization");
2177
2178 if (VarTemplateSpecializationDecl *Spec =
2179 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2180 Spec->setSpecializationKind(TSK);
2181 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2182 Spec->getPointOfInstantiation().isInvalid())
2183 Spec->setPointOfInstantiation(PointOfInstantiation);
2184 }
2185
2186 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2187 MSI->setTemplateSpecializationKind(TSK);
2188 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2189 MSI->getPointOfInstantiation().isInvalid())
2190 MSI->setPointOfInstantiation(PointOfInstantiation);
2191 }
2192}
2193
2194void
2195VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2196 TemplateSpecializationKind TSK) {
2197 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2198 "Previous template or instantiation?");
2199 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2200}
2201
2202//===----------------------------------------------------------------------===//
2203// ParmVarDecl Implementation
2204//===----------------------------------------------------------------------===//
2205
2206ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2207 SourceLocation StartLoc,
2208 SourceLocation IdLoc, IdentifierInfo *Id,
2209 QualType T, TypeSourceInfo *TInfo,
2210 StorageClass S, Expr *DefArg) {
2211 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2212 S, DefArg);
2213}
2214
2215QualType ParmVarDecl::getOriginalType() const {
2216 TypeSourceInfo *TSI = getTypeSourceInfo();
2217 QualType T = TSI ? TSI->getType() : getType();
2218 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2219 return DT->getOriginalType();
2220 return T;
2221}
2222
2223ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2224 return new (C, ID)
2225 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2226 nullptr, QualType(), nullptr, SC_None, nullptr);
2227}
2228
2229SourceRange ParmVarDecl::getSourceRange() const {
2230 if (!hasInheritedDefaultArg()) {
2231 SourceRange ArgRange = getDefaultArgRange();
2232 if (ArgRange.isValid())
2233 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2234 }
2235
2236 // DeclaratorDecl considers the range of postfix types as overlapping with the
2237 // declaration name, but this is not the case with parameters in ObjC methods.
2238 if (isa<ObjCMethodDecl>(getDeclContext()))
2239 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2240
2241 return DeclaratorDecl::getSourceRange();
2242}
2243
2244Expr *ParmVarDecl::getDefaultArg() {
2245 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2246 assert(!hasUninstantiatedDefaultArg() &&
2247 "Default argument is not yet instantiated!");
2248
2249 Expr *Arg = getInit();
2250 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
2251 return E->getSubExpr();
2252
2253 return Arg;
2254}
2255
2256SourceRange ParmVarDecl::getDefaultArgRange() const {
2257 if (const Expr *E = getInit())
2258 return E->getSourceRange();
2259
2260 if (hasUninstantiatedDefaultArg())
2261 return getUninstantiatedDefaultArg()->getSourceRange();
2262
2263 return SourceRange();
2264}
2265
2266bool ParmVarDecl::isParameterPack() const {
2267 return isa<PackExpansionType>(getType());
2268}
2269
2270void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2271 getASTContext().setParameterIndex(this, parameterIndex);
2272 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2273}
2274
2275unsigned ParmVarDecl::getParameterIndexLarge() const {
2276 return getASTContext().getParameterIndex(this);
2277}
2278
2279//===----------------------------------------------------------------------===//
2280// FunctionDecl Implementation
2281//===----------------------------------------------------------------------===//
2282
2283void FunctionDecl::getNameForDiagnostic(
2284 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2285 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2286 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2287 if (TemplateArgs)
2288 TemplateSpecializationType::PrintTemplateArgumentList(
2289 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
2290}
2291
2292bool FunctionDecl::isVariadic() const {
2293 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2294 return FT->isVariadic();
2295 return false;
2296}
2297
2298bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2299 for (auto I : redecls()) {
2300 if (I->Body || I->IsLateTemplateParsed) {
2301 Definition = I;
2302 return true;
2303 }
2304 }
2305
2306 return false;
2307}
2308
2309bool FunctionDecl::hasTrivialBody() const
2310{
2311 Stmt *S = getBody();
2312 if (!S) {
2313 // Since we don't have a body for this function, we don't know if it's
2314 // trivial or not.
2315 return false;
2316 }
2317
2318 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2319 return true;
2320 return false;
2321}
2322
2323bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2324 for (auto I : redecls()) {
2325 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2326 I->hasAttr<AliasAttr>()) {
2327 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
2328 return true;
2329 }
2330 }
2331
2332 return false;
2333}
2334
2335Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2336 if (!hasBody(Definition))
2337 return nullptr;
2338
2339 if (Definition->Body)
2340 return Definition->Body.get(getASTContext().getExternalSource());
2341
2342 return nullptr;
2343}
2344
2345void FunctionDecl::setBody(Stmt *B) {
2346 Body = B;
2347 if (B)
2348 EndRangeLoc = B->getLocEnd();
2349}
2350
2351void FunctionDecl::setPure(bool P) {
2352 IsPure = P;
2353 if (P)
2354 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2355 Parent->markedVirtualFunctionPure();
2356}
2357
2358template<std::size_t Len>
2359static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2360 IdentifierInfo *II = ND->getIdentifier();
2361 return II && II->isStr(Str);
2362}
2363
2364bool FunctionDecl::isMain() const {
2365 const TranslationUnitDecl *tunit =
2366 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2367 return tunit &&
2368 !tunit->getASTContext().getLangOpts().Freestanding &&
2369 isNamed(this, "main");
2370}
2371
2372bool FunctionDecl::isMSVCRTEntryPoint() const {
2373 const TranslationUnitDecl *TUnit =
2374 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2375 if (!TUnit)
2376 return false;
2377
2378 // Even though we aren't really targeting MSVCRT if we are freestanding,
2379 // semantic analysis for these functions remains the same.
2380
2381 // MSVCRT entry points only exist on MSVCRT targets.
2382 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2383 return false;
2384
2385 // Nameless functions like constructors cannot be entry points.
2386 if (!getIdentifier())
2387 return false;
2388
2389 return llvm::StringSwitch<bool>(getName())
2390 .Cases("main", // an ANSI console app
2391 "wmain", // a Unicode console App
2392 "WinMain", // an ANSI GUI app
2393 "wWinMain", // a Unicode GUI app
2394 "DllMain", // a DLL
2395 true)
2396 .Default(false);
2397}
2398
2399bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2400 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2401 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2402 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2403 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2404 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2405
2406 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2407 return false;
2408
2409 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2410 if (proto->getNumParams() != 2 || proto->isVariadic())
2411 return false;
2412
2413 ASTContext &Context =
2414 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2415 ->getASTContext();
2416
2417 // The result type and first argument type are constant across all
2418 // these operators. The second argument must be exactly void*.
2419 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2420}
2421
2422bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2423 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2424 return false;
2425 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2426 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2427 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2428 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2429 return false;
2430
2431 if (isa<CXXRecordDecl>(getDeclContext()))
2432 return false;
2433
2434 // This can only fail for an invalid 'operator new' declaration.
2435 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2436 return false;
2437
2438 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
2439 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
2440 return false;
2441
2442 // If this is a single-parameter function, it must be a replaceable global
2443 // allocation or deallocation function.
2444 if (FPT->getNumParams() == 1)
2445 return true;
2446
2447 // Otherwise, we're looking for a second parameter whose type is
2448 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
2449 QualType Ty = FPT->getParamType(1);
2450 ASTContext &Ctx = getASTContext();
2451 if (Ctx.getLangOpts().SizedDeallocation &&
2452 Ctx.hasSameType(Ty, Ctx.getSizeType()))
2453 return true;
2454 if (!Ty->isReferenceType())
2455 return false;
2456 Ty = Ty->getPointeeType();
2457 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2458 return false;
2459 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2460 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
2461}
2462
2463FunctionDecl *
2464FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2465 ASTContext &Ctx = getASTContext();
2466 if (!Ctx.getLangOpts().SizedDeallocation)
2467 return nullptr;
2468
2469 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2470 return nullptr;
2471 if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2472 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2473 return nullptr;
2474 if (isa<CXXRecordDecl>(getDeclContext()))
2475 return nullptr;
2476
2477 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2478 return nullptr;
2479
2480 if (getNumParams() != 2 || isVariadic() ||
2481 !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
2482 Ctx.getSizeType()))
2483 return nullptr;
2484
2485 // This is a sized deallocation function. Find the corresponding unsized
2486 // deallocation function.
2487 lookup_const_result R = getDeclContext()->lookup(getDeclName());
2488 for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2489 ++RI)
2490 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2491 if (FD->getNumParams() == 1 && !FD->isVariadic())
2492 return FD;
2493 return nullptr;
2494}
2495
2496LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2497 return getDeclLanguageLinkage(*this);
2498}
2499
2500bool FunctionDecl::isExternC() const {
2501 return isDeclExternC(*this);
2502}
2503
2504bool FunctionDecl::isInExternCContext() const {
2505 return getLexicalDeclContext()->isExternCContext();
2506}
2507
2508bool FunctionDecl::isInExternCXXContext() const {
2509 return getLexicalDeclContext()->isExternCXXContext();
2510}
2511
2512bool FunctionDecl::isGlobal() const {
2513 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2514 return Method->isStatic();
2515
2516 if (getCanonicalDecl()->getStorageClass() == SC_Static)
2517 return false;
2518
2519 for (const DeclContext *DC = getDeclContext();
2520 DC->isNamespace();
2521 DC = DC->getParent()) {
2522 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2523 if (!Namespace->getDeclName())
2524 return false;
2525 break;
2526 }
2527 }
2528
2529 return true;
2530}
2531
2532bool FunctionDecl::isNoReturn() const {
2533 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2534 hasAttr<C11NoReturnAttr>() ||
2535 getType()->getAs<FunctionType>()->getNoReturnAttr();
2536}
2537
2538void
2539FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2540 redeclarable_base::setPreviousDecl(PrevDecl);
2541
2542 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2543 FunctionTemplateDecl *PrevFunTmpl
2544 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
2545 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2546 FunTmpl->setPreviousDecl(PrevFunTmpl);
2547 }
2548
2549 if (PrevDecl && PrevDecl->IsInline)
2550 IsInline = true;
2551}
2552
2553const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2554 return getFirstDecl();
2555}
2556
2557FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2558
2559/// \brief Returns a value indicating whether this function
2560/// corresponds to a builtin function.
2561///
2562/// The function corresponds to a built-in function if it is
2563/// declared at translation scope or within an extern "C" block and
2564/// its name matches with the name of a builtin. The returned value
2565/// will be 0 for functions that do not correspond to a builtin, a
2566/// value of type \c Builtin::ID if in the target-independent range
2567/// \c [1,Builtin::First), or a target-specific builtin value.
2568unsigned FunctionDecl::getBuiltinID() const {
2569 if (!getIdentifier())
2570 return 0;
2571
2572 unsigned BuiltinID = getIdentifier()->getBuiltinID();
2573 if (!BuiltinID)
2574 return 0;
2575
2576 ASTContext &Context = getASTContext();
2577 if (Context.getLangOpts().CPlusPlus) {
2578 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2579 getFirstDecl()->getDeclContext());
2580 // In C++, the first declaration of a builtin is always inside an implicit
2581 // extern "C".
2582 // FIXME: A recognised library function may not be directly in an extern "C"
2583 // declaration, for instance "extern "C" { namespace std { decl } }".
2584 if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2585 return 0;
2586 }
2587
2588 // If the function is marked "overloadable", it has a different mangled name
2589 // and is not the C library function.
2590 if (hasAttr<OverloadableAttr>())
2591 return 0;
2592
2593 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2594 return BuiltinID;
2595
2596 // This function has the name of a known C library
2597 // function. Determine whether it actually refers to the C library
2598 // function or whether it just has the same name.
2599
2600 // If this is a static function, it's not a builtin.
2601 if (getStorageClass() == SC_Static)
2602 return 0;
2603
2604 return BuiltinID;
2605}
2606
2607
2608/// getNumParams - Return the number of parameters this function must have
2609/// based on its FunctionType. This is the length of the ParamInfo array
2610/// after it has been created.
2611unsigned FunctionDecl::getNumParams() const {
2612 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
2613 return FPT ? FPT->getNumParams() : 0;
2614}
2615
2616void FunctionDecl::setParams(ASTContext &C,
2617 ArrayRef<ParmVarDecl *> NewParamInfo) {
2618 assert(!ParamInfo && "Already has param info!");
2619 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2620
2621 // Zero params -> null pointer.
2622 if (!NewParamInfo.empty()) {
2623 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2624 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2625 }
2626}
2627
2628void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2629 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2630
2631 if (!NewDecls.empty()) {
2632 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2633 std::copy(NewDecls.begin(), NewDecls.end(), A);
2634 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
2635 // Move declarations introduced in prototype to the function context.
2636 for (auto I : NewDecls) {
2637 DeclContext *DC = I->getDeclContext();
2638 // Forward-declared reference to an enumeration is not added to
2639 // declaration scope, so skip declaration that is absent from its
2640 // declaration contexts.
2641 if (DC->containsDecl(I)) {
2642 DC->removeDecl(I);
2643 I->setDeclContext(this);
2644 addDecl(I);
2645 }
2646 }
2647 }
2648}
2649
2650/// getMinRequiredArguments - Returns the minimum number of arguments
2651/// needed to call this function. This may be fewer than the number of
2652/// function parameters, if some of the parameters have default
2653/// arguments (in C++) or are parameter packs (C++11).
2654unsigned FunctionDecl::getMinRequiredArguments() const {
2655 if (!getASTContext().getLangOpts().CPlusPlus)
2656 return getNumParams();
2657
2658 unsigned NumRequiredArgs = 0;
2659 for (auto *Param : params())
2660 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2661 ++NumRequiredArgs;
2662 return NumRequiredArgs;
2663}
2664
2665/// \brief The combination of the extern and inline keywords under MSVC forces
2666/// the function to be required.
2667///
2668/// Note: This function assumes that we will only get called when isInlined()
2669/// would return true for this FunctionDecl.
2670bool FunctionDecl::isMSExternInline() const {
2671 assert(isInlined() && "expected to get called on an inlined function!");
2672
2673 const ASTContext &Context = getASTContext();
2674 if (!Context.getLangOpts().MSVCCompat && !hasAttr<DLLExportAttr>())
2675 return false;
2676
2677 for (const FunctionDecl *FD = this; FD; FD = FD->getPreviousDecl())
2677 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2678 FD = FD->getPreviousDecl())
2678 if (FD->getStorageClass() == SC_Extern)
2679 return true;
2680
2681 return false;
2682}
2683
2684static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2685 if (Redecl->getStorageClass() != SC_Extern)
2686 return false;
2687
2688 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2689 FD = FD->getPreviousDecl())
2690 if (FD->getStorageClass() == SC_Extern)
2691 return false;
2692
2693 return true;
2694}
2695
2696static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2697 // Only consider file-scope declarations in this test.
2698 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2699 return false;
2700
2701 // Only consider explicit declarations; the presence of a builtin for a
2702 // libcall shouldn't affect whether a definition is externally visible.
2703 if (Redecl->isImplicit())
2704 return false;
2705
2706 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2707 return true; // Not an inline definition
2708
2709 return false;
2710}
2711
2712/// \brief For a function declaration in C or C++, determine whether this
2713/// declaration causes the definition to be externally visible.
2714///
2715/// For instance, this determines if adding the current declaration to the set
2716/// of redeclarations of the given functions causes
2717/// isInlineDefinitionExternallyVisible to change from false to true.
2718bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2719 assert(!doesThisDeclarationHaveABody() &&
2720 "Must have a declaration without a body.");
2721
2722 ASTContext &Context = getASTContext();
2723
2724 if (Context.getLangOpts().MSVCCompat) {
2725 const FunctionDecl *Definition;
2726 if (hasBody(Definition) && Definition->isInlined() &&
2727 redeclForcesDefMSVC(this))
2728 return true;
2729 }
2730
2731 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2732 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2733 // an externally visible definition.
2734 //
2735 // FIXME: What happens if gnu_inline gets added on after the first
2736 // declaration?
2737 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2738 return false;
2739
2740 const FunctionDecl *Prev = this;
2741 bool FoundBody = false;
2742 while ((Prev = Prev->getPreviousDecl())) {
2743 FoundBody |= Prev->Body.isValid();
2744
2745 if (Prev->Body) {
2746 // If it's not the case that both 'inline' and 'extern' are
2747 // specified on the definition, then it is always externally visible.
2748 if (!Prev->isInlineSpecified() ||
2749 Prev->getStorageClass() != SC_Extern)
2750 return false;
2751 } else if (Prev->isInlineSpecified() &&
2752 Prev->getStorageClass() != SC_Extern) {
2753 return false;
2754 }
2755 }
2756 return FoundBody;
2757 }
2758
2759 if (Context.getLangOpts().CPlusPlus)
2760 return false;
2761
2762 // C99 6.7.4p6:
2763 // [...] If all of the file scope declarations for a function in a
2764 // translation unit include the inline function specifier without extern,
2765 // then the definition in that translation unit is an inline definition.
2766 if (isInlineSpecified() && getStorageClass() != SC_Extern)
2767 return false;
2768 const FunctionDecl *Prev = this;
2769 bool FoundBody = false;
2770 while ((Prev = Prev->getPreviousDecl())) {
2771 FoundBody |= Prev->Body.isValid();
2772 if (RedeclForcesDefC99(Prev))
2773 return false;
2774 }
2775 return FoundBody;
2776}
2777
2778SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2779 const TypeSourceInfo *TSI = getTypeSourceInfo();
2780 if (!TSI)
2781 return SourceRange();
2782 FunctionTypeLoc FTL =
2783 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2784 if (!FTL)
2785 return SourceRange();
2786
2787 // Skip self-referential return types.
2788 const SourceManager &SM = getASTContext().getSourceManager();
2789 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2790 SourceLocation Boundary = getNameInfo().getLocStart();
2791 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2792 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2793 return SourceRange();
2794
2795 return RTRange;
2796}
2797
2798/// \brief For an inline function definition in C, or for a gnu_inline function
2799/// in C++, determine whether the definition will be externally visible.
2800///
2801/// Inline function definitions are always available for inlining optimizations.
2802/// However, depending on the language dialect, declaration specifiers, and
2803/// attributes, the definition of an inline function may or may not be
2804/// "externally" visible to other translation units in the program.
2805///
2806/// In C99, inline definitions are not externally visible by default. However,
2807/// if even one of the global-scope declarations is marked "extern inline", the
2808/// inline definition becomes externally visible (C99 6.7.4p6).
2809///
2810/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2811/// definition, we use the GNU semantics for inline, which are nearly the
2812/// opposite of C99 semantics. In particular, "inline" by itself will create
2813/// an externally visible symbol, but "extern inline" will not create an
2814/// externally visible symbol.
2815bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2816 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2817 assert(isInlined() && "Function must be inline");
2818 ASTContext &Context = getASTContext();
2819
2820 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2821 // Note: If you change the logic here, please change
2822 // doesDeclarationForceExternallyVisibleDefinition as well.
2823 //
2824 // If it's not the case that both 'inline' and 'extern' are
2825 // specified on the definition, then this inline definition is
2826 // externally visible.
2827 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2828 return true;
2829
2830 // If any declaration is 'inline' but not 'extern', then this definition
2831 // is externally visible.
2832 for (auto Redecl : redecls()) {
2833 if (Redecl->isInlineSpecified() &&
2834 Redecl->getStorageClass() != SC_Extern)
2835 return true;
2836 }
2837
2838 return false;
2839 }
2840
2841 // The rest of this function is C-only.
2842 assert(!Context.getLangOpts().CPlusPlus &&
2843 "should not use C inline rules in C++");
2844
2845 // C99 6.7.4p6:
2846 // [...] If all of the file scope declarations for a function in a
2847 // translation unit include the inline function specifier without extern,
2848 // then the definition in that translation unit is an inline definition.
2849 for (auto Redecl : redecls()) {
2850 if (RedeclForcesDefC99(Redecl))
2851 return true;
2852 }
2853
2854 // C99 6.7.4p6:
2855 // An inline definition does not provide an external definition for the
2856 // function, and does not forbid an external definition in another
2857 // translation unit.
2858 return false;
2859}
2860
2861/// getOverloadedOperator - Which C++ overloaded operator this
2862/// function represents, if any.
2863OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2864 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2865 return getDeclName().getCXXOverloadedOperator();
2866 else
2867 return OO_None;
2868}
2869
2870/// getLiteralIdentifier - The literal suffix identifier this function
2871/// represents, if any.
2872const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2873 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2874 return getDeclName().getCXXLiteralIdentifier();
2875 else
2876 return nullptr;
2877}
2878
2879FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2880 if (TemplateOrSpecialization.isNull())
2881 return TK_NonTemplate;
2882 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2883 return TK_FunctionTemplate;
2884 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2885 return TK_MemberSpecialization;
2886 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2887 return TK_FunctionTemplateSpecialization;
2888 if (TemplateOrSpecialization.is
2889 <DependentFunctionTemplateSpecializationInfo*>())
2890 return TK_DependentFunctionTemplateSpecialization;
2891
2892 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2893}
2894
2895FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2896 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2897 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2898
2899 return nullptr;
2900}
2901
2902void
2903FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2904 FunctionDecl *FD,
2905 TemplateSpecializationKind TSK) {
2906 assert(TemplateOrSpecialization.isNull() &&
2907 "Member function is already a specialization");
2908 MemberSpecializationInfo *Info
2909 = new (C) MemberSpecializationInfo(FD, TSK);
2910 TemplateOrSpecialization = Info;
2911}
2912
2913bool FunctionDecl::isImplicitlyInstantiable() const {
2914 // If the function is invalid, it can't be implicitly instantiated.
2915 if (isInvalidDecl())
2916 return false;
2917
2918 switch (getTemplateSpecializationKind()) {
2919 case TSK_Undeclared:
2920 case TSK_ExplicitInstantiationDefinition:
2921 return false;
2922
2923 case TSK_ImplicitInstantiation:
2924 return true;
2925
2926 // It is possible to instantiate TSK_ExplicitSpecialization kind
2927 // if the FunctionDecl has a class scope specialization pattern.
2928 case TSK_ExplicitSpecialization:
2929 return getClassScopeSpecializationPattern() != nullptr;
2930
2931 case TSK_ExplicitInstantiationDeclaration:
2932 // Handled below.
2933 break;
2934 }
2935
2936 // Find the actual template from which we will instantiate.
2937 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2938 bool HasPattern = false;
2939 if (PatternDecl)
2940 HasPattern = PatternDecl->hasBody(PatternDecl);
2941
2942 // C++0x [temp.explicit]p9:
2943 // Except for inline functions, other explicit instantiation declarations
2944 // have the effect of suppressing the implicit instantiation of the entity
2945 // to which they refer.
2946 if (!HasPattern || !PatternDecl)
2947 return true;
2948
2949 return PatternDecl->isInlined();
2950}
2951
2952bool FunctionDecl::isTemplateInstantiation() const {
2953 switch (getTemplateSpecializationKind()) {
2954 case TSK_Undeclared:
2955 case TSK_ExplicitSpecialization:
2956 return false;
2957 case TSK_ImplicitInstantiation:
2958 case TSK_ExplicitInstantiationDeclaration:
2959 case TSK_ExplicitInstantiationDefinition:
2960 return true;
2961 }
2962 llvm_unreachable("All TSK values handled.");
2963}
2964
2965FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2966 // Handle class scope explicit specialization special case.
2967 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2968 return getClassScopeSpecializationPattern();
2969
2970 // If this is a generic lambda call operator specialization, its
2971 // instantiation pattern is always its primary template's pattern
2972 // even if its primary template was instantiated from another
2973 // member template (which happens with nested generic lambdas).
2974 // Since a lambda's call operator's body is transformed eagerly,
2975 // we don't have to go hunting for a prototype definition template
2976 // (i.e. instantiated-from-member-template) to use as an instantiation
2977 // pattern.
2978
2979 if (isGenericLambdaCallOperatorSpecialization(
2980 dyn_cast<CXXMethodDecl>(this))) {
2981 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
2982 "generated from a primary call operator "
2983 "template");
2984 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
2985 "A generic lambda call operator template must always have a body - "
2986 "even if instantiated from a prototype (i.e. as written) member "
2987 "template");
2988 return getPrimaryTemplate()->getTemplatedDecl();
2989 }
2990
2991 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2992 while (Primary->getInstantiatedFromMemberTemplate()) {
2993 // If we have hit a point where the user provided a specialization of
2994 // this template, we're done looking.
2995 if (Primary->isMemberSpecialization())
2996 break;
2997 Primary = Primary->getInstantiatedFromMemberTemplate();
2998 }
2999
3000 return Primary->getTemplatedDecl();
3001 }
3002
3003 return getInstantiatedFromMemberFunction();
3004}
3005
3006FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3007 if (FunctionTemplateSpecializationInfo *Info
3008 = TemplateOrSpecialization
3009 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3010 return Info->Template.getPointer();
3011 }
3012 return nullptr;
3013}
3014
3015FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3016 return getASTContext().getClassScopeSpecializationPattern(this);
3017}
3018
3019const TemplateArgumentList *
3020FunctionDecl::getTemplateSpecializationArgs() const {
3021 if (FunctionTemplateSpecializationInfo *Info
3022 = TemplateOrSpecialization
3023 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3024 return Info->TemplateArguments;
3025 }
3026 return nullptr;
3027}
3028
3029const ASTTemplateArgumentListInfo *
3030FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3031 if (FunctionTemplateSpecializationInfo *Info
3032 = TemplateOrSpecialization
3033 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3034 return Info->TemplateArgumentsAsWritten;
3035 }
3036 return nullptr;
3037}
3038
3039void
3040FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3041 FunctionTemplateDecl *Template,
3042 const TemplateArgumentList *TemplateArgs,
3043 void *InsertPos,
3044 TemplateSpecializationKind TSK,
3045 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3046 SourceLocation PointOfInstantiation) {
3047 assert(TSK != TSK_Undeclared &&
3048 "Must specify the type of function template specialization");
3049 FunctionTemplateSpecializationInfo *Info
3050 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3051 if (!Info)
3052 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3053 TemplateArgs,
3054 TemplateArgsAsWritten,
3055 PointOfInstantiation);
3056 TemplateOrSpecialization = Info;
3057 Template->addSpecialization(Info, InsertPos);
3058}
3059
3060void
3061FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3062 const UnresolvedSetImpl &Templates,
3063 const TemplateArgumentListInfo &TemplateArgs) {
3064 assert(TemplateOrSpecialization.isNull());
3065 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
3066 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
3067 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
3068 void *Buffer = Context.Allocate(Size);
3069 DependentFunctionTemplateSpecializationInfo *Info =
3070 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
3071 TemplateArgs);
3072 TemplateOrSpecialization = Info;
3073}
3074
3075DependentFunctionTemplateSpecializationInfo::
3076DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3077 const TemplateArgumentListInfo &TArgs)
3078 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3079
3080 d.NumTemplates = Ts.size();
3081 d.NumArgs = TArgs.size();
3082
3083 FunctionTemplateDecl **TsArray =
3084 const_cast<FunctionTemplateDecl**>(getTemplates());
3085 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3086 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3087
3088 TemplateArgumentLoc *ArgsArray =
3089 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
3090 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3091 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3092}
3093
3094TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3095 // For a function template specialization, query the specialization
3096 // information object.
3097 FunctionTemplateSpecializationInfo *FTSInfo
3098 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3099 if (FTSInfo)
3100 return FTSInfo->getTemplateSpecializationKind();
3101
3102 MemberSpecializationInfo *MSInfo
3103 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3104 if (MSInfo)
3105 return MSInfo->getTemplateSpecializationKind();
3106
3107 return TSK_Undeclared;
3108}
3109
3110void
3111FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3112 SourceLocation PointOfInstantiation) {
3113 if (FunctionTemplateSpecializationInfo *FTSInfo
3114 = TemplateOrSpecialization.dyn_cast<
3115 FunctionTemplateSpecializationInfo*>()) {
3116 FTSInfo->setTemplateSpecializationKind(TSK);
3117 if (TSK != TSK_ExplicitSpecialization &&
3118 PointOfInstantiation.isValid() &&
3119 FTSInfo->getPointOfInstantiation().isInvalid())
3120 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3121 } else if (MemberSpecializationInfo *MSInfo
3122 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3123 MSInfo->setTemplateSpecializationKind(TSK);
3124 if (TSK != TSK_ExplicitSpecialization &&
3125 PointOfInstantiation.isValid() &&
3126 MSInfo->getPointOfInstantiation().isInvalid())
3127 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3128 } else
3129 llvm_unreachable("Function cannot have a template specialization kind");
3130}
3131
3132SourceLocation FunctionDecl::getPointOfInstantiation() const {
3133 if (FunctionTemplateSpecializationInfo *FTSInfo
3134 = TemplateOrSpecialization.dyn_cast<
3135 FunctionTemplateSpecializationInfo*>())
3136 return FTSInfo->getPointOfInstantiation();
3137 else if (MemberSpecializationInfo *MSInfo
3138 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
3139 return MSInfo->getPointOfInstantiation();
3140
3141 return SourceLocation();
3142}
3143
3144bool FunctionDecl::isOutOfLine() const {
3145 if (Decl::isOutOfLine())
3146 return true;
3147
3148 // If this function was instantiated from a member function of a
3149 // class template, check whether that member function was defined out-of-line.
3150 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3151 const FunctionDecl *Definition;
3152 if (FD->hasBody(Definition))
3153 return Definition->isOutOfLine();
3154 }
3155
3156 // If this function was instantiated from a function template,
3157 // check whether that function template was defined out-of-line.
3158 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3159 const FunctionDecl *Definition;
3160 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3161 return Definition->isOutOfLine();
3162 }
3163
3164 return false;
3165}
3166
3167SourceRange FunctionDecl::getSourceRange() const {
3168 return SourceRange(getOuterLocStart(), EndRangeLoc);
3169}
3170
3171unsigned FunctionDecl::getMemoryFunctionKind() const {
3172 IdentifierInfo *FnInfo = getIdentifier();
3173
3174 if (!FnInfo)
3175 return 0;
3176
3177 // Builtin handling.
3178 switch (getBuiltinID()) {
3179 case Builtin::BI__builtin_memset:
3180 case Builtin::BI__builtin___memset_chk:
3181 case Builtin::BImemset:
3182 return Builtin::BImemset;
3183
3184 case Builtin::BI__builtin_memcpy:
3185 case Builtin::BI__builtin___memcpy_chk:
3186 case Builtin::BImemcpy:
3187 return Builtin::BImemcpy;
3188
3189 case Builtin::BI__builtin_memmove:
3190 case Builtin::BI__builtin___memmove_chk:
3191 case Builtin::BImemmove:
3192 return Builtin::BImemmove;
3193
3194 case Builtin::BIstrlcpy:
3195 case Builtin::BI__builtin___strlcpy_chk:
3196 return Builtin::BIstrlcpy;
3197
3198 case Builtin::BIstrlcat:
3199 case Builtin::BI__builtin___strlcat_chk:
3200 return Builtin::BIstrlcat;
3201
3202 case Builtin::BI__builtin_memcmp:
3203 case Builtin::BImemcmp:
3204 return Builtin::BImemcmp;
3205
3206 case Builtin::BI__builtin_strncpy:
3207 case Builtin::BI__builtin___strncpy_chk:
3208 case Builtin::BIstrncpy:
3209 return Builtin::BIstrncpy;
3210
3211 case Builtin::BI__builtin_strncmp:
3212 case Builtin::BIstrncmp:
3213 return Builtin::BIstrncmp;
3214
3215 case Builtin::BI__builtin_strncasecmp:
3216 case Builtin::BIstrncasecmp:
3217 return Builtin::BIstrncasecmp;
3218
3219 case Builtin::BI__builtin_strncat:
3220 case Builtin::BI__builtin___strncat_chk:
3221 case Builtin::BIstrncat:
3222 return Builtin::BIstrncat;
3223
3224 case Builtin::BI__builtin_strndup:
3225 case Builtin::BIstrndup:
3226 return Builtin::BIstrndup;
3227
3228 case Builtin::BI__builtin_strlen:
3229 case Builtin::BIstrlen:
3230 return Builtin::BIstrlen;
3231
3232 default:
3233 if (isExternC()) {
3234 if (FnInfo->isStr("memset"))
3235 return Builtin::BImemset;
3236 else if (FnInfo->isStr("memcpy"))
3237 return Builtin::BImemcpy;
3238 else if (FnInfo->isStr("memmove"))
3239 return Builtin::BImemmove;
3240 else if (FnInfo->isStr("memcmp"))
3241 return Builtin::BImemcmp;
3242 else if (FnInfo->isStr("strncpy"))
3243 return Builtin::BIstrncpy;
3244 else if (FnInfo->isStr("strncmp"))
3245 return Builtin::BIstrncmp;
3246 else if (FnInfo->isStr("strncasecmp"))
3247 return Builtin::BIstrncasecmp;
3248 else if (FnInfo->isStr("strncat"))
3249 return Builtin::BIstrncat;
3250 else if (FnInfo->isStr("strndup"))
3251 return Builtin::BIstrndup;
3252 else if (FnInfo->isStr("strlen"))
3253 return Builtin::BIstrlen;
3254 }
3255 break;
3256 }
3257 return 0;
3258}
3259
3260//===----------------------------------------------------------------------===//
3261// FieldDecl Implementation
3262//===----------------------------------------------------------------------===//
3263
3264FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3265 SourceLocation StartLoc, SourceLocation IdLoc,
3266 IdentifierInfo *Id, QualType T,
3267 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3268 InClassInitStyle InitStyle) {
3269 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3270 BW, Mutable, InitStyle);
3271}
3272
3273FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3274 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3275 SourceLocation(), nullptr, QualType(), nullptr,
3276 nullptr, false, ICIS_NoInit);
3277}
3278
3279bool FieldDecl::isAnonymousStructOrUnion() const {
3280 if (!isImplicit() || getDeclName())
3281 return false;
3282
3283 if (const RecordType *Record = getType()->getAs<RecordType>())
3284 return Record->getDecl()->isAnonymousStructOrUnion();
3285
3286 return false;
3287}
3288
3289unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3290 assert(isBitField() && "not a bitfield");
3291 Expr *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
3292 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3293}
3294
3295unsigned FieldDecl::getFieldIndex() const {
3296 const FieldDecl *Canonical = getCanonicalDecl();
3297 if (Canonical != this)
3298 return Canonical->getFieldIndex();
3299
3300 if (CachedFieldIndex) return CachedFieldIndex - 1;
3301
3302 unsigned Index = 0;
3303 const RecordDecl *RD = getParent();
3304
3305 for (auto *Field : RD->fields()) {
3306 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3307 ++Index;
3308 }
3309
3310 assert(CachedFieldIndex && "failed to find field in parent");
3311 return CachedFieldIndex - 1;
3312}
3313
3314SourceRange FieldDecl::getSourceRange() const {
3315 switch (InitStorage.getInt()) {
3316 // All three of these cases store an optional Expr*.
3317 case ISK_BitWidthOrNothing:
3318 case ISK_InClassCopyInit:
3319 case ISK_InClassListInit:
3320 if (const Expr *E = static_cast<const Expr *>(InitStorage.getPointer()))
3321 return SourceRange(getInnerLocStart(), E->getLocEnd());
3322 // FALLTHROUGH
3323
3324 case ISK_CapturedVLAType:
3325 return DeclaratorDecl::getSourceRange();
3326 }
3327 llvm_unreachable("bad init storage kind");
3328}
3329
3330void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
3331 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
3332 "capturing type in non-lambda or captured record.");
3333 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3334 InitStorage.getPointer() == nullptr &&
3335 "bit width, initializer or captured type already set");
3336 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3337 ISK_CapturedVLAType);
3338}
3339
3340//===----------------------------------------------------------------------===//
3341// TagDecl Implementation
3342//===----------------------------------------------------------------------===//
3343
3344SourceLocation TagDecl::getOuterLocStart() const {
3345 return getTemplateOrInnerLocStart(this);
3346}
3347
3348SourceRange TagDecl::getSourceRange() const {
3349 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3350 return SourceRange(getOuterLocStart(), E);
3351}
3352
3353TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3354
3355void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3356 NamedDeclOrQualifier = TDD;
3357 if (const Type *T = getTypeForDecl()) {
3358 (void)T;
3359 assert(T->isLinkageValid());
3360 }
3361 assert(isLinkageValid());
3362}
3363
3364void TagDecl::startDefinition() {
3365 IsBeingDefined = true;
3366
3367 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
3368 struct CXXRecordDecl::DefinitionData *Data =
3369 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3370 for (auto I : redecls())
3371 cast<CXXRecordDecl>(I)->DefinitionData = Data;
3372 }
3373}
3374
3375void TagDecl::completeDefinition() {
3376 assert((!isa<CXXRecordDecl>(this) ||
3377 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3378 "definition completed but not started");
3379
3380 IsCompleteDefinition = true;
3381 IsBeingDefined = false;
3382
3383 if (ASTMutationListener *L = getASTMutationListener())
3384 L->CompletedTagDefinition(this);
3385}
3386
3387TagDecl *TagDecl::getDefinition() const {
3388 if (isCompleteDefinition())
3389 return const_cast<TagDecl *>(this);
3390
3391 // If it's possible for us to have an out-of-date definition, check now.
3392 if (MayHaveOutOfDateDef) {
3393 if (IdentifierInfo *II = getIdentifier()) {
3394 if (II->isOutOfDate()) {
3395 updateOutOfDate(*II);
3396 }
3397 }
3398 }
3399
3400 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3401 return CXXRD->getDefinition();
3402
3403 for (auto R : redecls())
3404 if (R->isCompleteDefinition())
3405 return R;
3406
3407 return nullptr;
3408}
3409
3410void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3411 if (QualifierLoc) {
3412 // Make sure the extended qualifier info is allocated.
3413 if (!hasExtInfo())
3414 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3415 // Set qualifier info.
3416 getExtInfo()->QualifierLoc = QualifierLoc;
3417 } else {
3418 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3419 if (hasExtInfo()) {
3420 if (getExtInfo()->NumTemplParamLists == 0) {
3421 getASTContext().Deallocate(getExtInfo());
3422 NamedDeclOrQualifier = (TypedefNameDecl*)nullptr;
3423 }
3424 else
3425 getExtInfo()->QualifierLoc = QualifierLoc;
3426 }
3427 }
3428}
3429
3430void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3431 unsigned NumTPLists,
3432 TemplateParameterList **TPLists) {
3433 assert(NumTPLists > 0);
3434 // Make sure the extended decl info is allocated.
3435 if (!hasExtInfo())
3436 // Allocate external info struct.
3437 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3438 // Set the template parameter lists info.
3439 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3440}
3441
3442//===----------------------------------------------------------------------===//
3443// EnumDecl Implementation
3444//===----------------------------------------------------------------------===//
3445
3446void EnumDecl::anchor() { }
3447
3448EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3449 SourceLocation StartLoc, SourceLocation IdLoc,
3450 IdentifierInfo *Id,
3451 EnumDecl *PrevDecl, bool IsScoped,
3452 bool IsScopedUsingClassTag, bool IsFixed) {
3453 EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3454 IsScoped, IsScopedUsingClassTag,
3455 IsFixed);
3456 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3457 C.getTypeDeclType(Enum, PrevDecl);
3458 return Enum;
3459}
3460
3461EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3462 EnumDecl *Enum =
3463 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3464 nullptr, nullptr, false, false, false);
3465 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3466 return Enum;
3467}
3468
3469SourceRange EnumDecl::getIntegerTypeRange() const {
3470 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3471 return TI->getTypeLoc().getSourceRange();
3472 return SourceRange();
3473}
3474
3475void EnumDecl::completeDefinition(QualType NewType,
3476 QualType NewPromotionType,
3477 unsigned NumPositiveBits,
3478 unsigned NumNegativeBits) {
3479 assert(!isCompleteDefinition() && "Cannot redefine enums!");
3480 if (!IntegerType)
3481 IntegerType = NewType.getTypePtr();
3482 PromotionType = NewPromotionType;
3483 setNumPositiveBits(NumPositiveBits);
3484 setNumNegativeBits(NumNegativeBits);
3485 TagDecl::completeDefinition();
3486}
3487
3488TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3489 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3490 return MSI->getTemplateSpecializationKind();
3491
3492 return TSK_Undeclared;
3493}
3494
3495void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3496 SourceLocation PointOfInstantiation) {
3497 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3498 assert(MSI && "Not an instantiated member enumeration?");
3499 MSI->setTemplateSpecializationKind(TSK);
3500 if (TSK != TSK_ExplicitSpecialization &&
3501 PointOfInstantiation.isValid() &&
3502 MSI->getPointOfInstantiation().isInvalid())
3503 MSI->setPointOfInstantiation(PointOfInstantiation);
3504}
3505
3506EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3507 if (SpecializationInfo)
3508 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3509
3510 return nullptr;
3511}
3512
3513void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3514 TemplateSpecializationKind TSK) {
3515 assert(!SpecializationInfo && "Member enum is already a specialization");
3516 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3517}
3518
3519//===----------------------------------------------------------------------===//
3520// RecordDecl Implementation
3521//===----------------------------------------------------------------------===//
3522
3523RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3524 DeclContext *DC, SourceLocation StartLoc,
3525 SourceLocation IdLoc, IdentifierInfo *Id,
3526 RecordDecl *PrevDecl)
3527 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3528 HasFlexibleArrayMember = false;
3529 AnonymousStructOrUnion = false;
3530 HasObjectMember = false;
3531 HasVolatileMember = false;
3532 LoadedFieldsFromExternalStorage = false;
3533 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3534}
3535
3536RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3537 SourceLocation StartLoc, SourceLocation IdLoc,
3538 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3539 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3540 StartLoc, IdLoc, Id, PrevDecl);
3541 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3542
3543 C.getTypeDeclType(R, PrevDecl);
3544 return R;
3545}
3546
3547RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3548 RecordDecl *R =
3549 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3550 SourceLocation(), nullptr, nullptr);
3551 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3552 return R;
3553}
3554
3555bool RecordDecl::isInjectedClassName() const {
3556 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3557 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3558}
3559
3560bool RecordDecl::isLambda() const {
3561 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3562 return RD->isLambda();
3563 return false;
3564}
3565
3566bool RecordDecl::isCapturedRecord() const {
3567 return hasAttr<CapturedRecordAttr>();
3568}
3569
3570void RecordDecl::setCapturedRecord() {
3571 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3572}
3573
3574RecordDecl::field_iterator RecordDecl::field_begin() const {
3575 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3576 LoadFieldsFromExternalStorage();
3577
3578 return field_iterator(decl_iterator(FirstDecl));
3579}
3580
3581/// completeDefinition - Notes that the definition of this type is now
3582/// complete.
3583void RecordDecl::completeDefinition() {
3584 assert(!isCompleteDefinition() && "Cannot redefine record!");
3585 TagDecl::completeDefinition();
3586}
3587
3588/// isMsStruct - Get whether or not this record uses ms_struct layout.
3589/// This which can be turned on with an attribute, pragma, or the
3590/// -mms-bitfields command-line option.
3591bool RecordDecl::isMsStruct(const ASTContext &C) const {
3592 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3593}
3594
3595static bool isFieldOrIndirectField(Decl::Kind K) {
3596 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3597}
3598
3599void RecordDecl::LoadFieldsFromExternalStorage() const {
3600 ExternalASTSource *Source = getASTContext().getExternalSource();
3601 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3602
3603 // Notify that we have a RecordDecl doing some initialization.
3604 ExternalASTSource::Deserializing TheFields(Source);
3605
3606 SmallVector<Decl*, 64> Decls;
3607 LoadedFieldsFromExternalStorage = true;
3608 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3609 Decls)) {
3610 case ELR_Success:
3611 break;
3612
3613 case ELR_AlreadyLoaded:
3614 case ELR_Failure:
3615 return;
3616 }
3617
3618#ifndef NDEBUG
3619 // Check that all decls we got were FieldDecls.
3620 for (unsigned i=0, e=Decls.size(); i != e; ++i)
3621 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3622#endif
3623
3624 if (Decls.empty())
3625 return;
3626
3627 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3628 /*FieldsAlreadyLoaded=*/false);
3629}
3630
3631bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3632 ASTContext &Context = getASTContext();
3633 if (!Context.getLangOpts().Sanitize.has(SanitizerKind::Address) ||
3634 !Context.getLangOpts().SanitizeAddressFieldPadding)
3635 return false;
3636 const auto &Blacklist = Context.getSanitizerBlacklist();
3637 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this);
3638 // We may be able to relax some of these requirements.
3639 int ReasonToReject = -1;
3640 if (!CXXRD || CXXRD->isExternCContext())
3641 ReasonToReject = 0; // is not C++.
3642 else if (CXXRD->hasAttr<PackedAttr>())
3643 ReasonToReject = 1; // is packed.
3644 else if (CXXRD->isUnion())
3645 ReasonToReject = 2; // is a union.
3646 else if (CXXRD->isTriviallyCopyable())
3647 ReasonToReject = 3; // is trivially copyable.
3648 else if (CXXRD->hasTrivialDestructor())
3649 ReasonToReject = 4; // has trivial destructor.
3650 else if (CXXRD->isStandardLayout())
3651 ReasonToReject = 5; // is standard layout.
3652 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
3653 ReasonToReject = 6; // is in a blacklisted file.
3654 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3655 "field-padding"))
3656 ReasonToReject = 7; // is blacklisted.
3657
3658 if (EmitRemark) {
3659 if (ReasonToReject >= 0)
3660 Context.getDiagnostics().Report(
3661 getLocation(),
3662 diag::remark_sanitize_address_insert_extra_padding_rejected)
3663 << getQualifiedNameAsString() << ReasonToReject;
3664 else
3665 Context.getDiagnostics().Report(
3666 getLocation(),
3667 diag::remark_sanitize_address_insert_extra_padding_accepted)
3668 << getQualifiedNameAsString();
3669 }
3670 return ReasonToReject < 0;
3671}
3672
3673const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3674 for (const auto *I : fields()) {
3675 if (I->getIdentifier())
3676 return I;
3677
3678 if (const RecordType *RT = I->getType()->getAs<RecordType>())
3679 if (const FieldDecl *NamedDataMember =
3680 RT->getDecl()->findFirstNamedDataMember())
3681 return NamedDataMember;
3682 }
3683
3684 // We didn't find a named data member.
3685 return nullptr;
3686}
3687
3688
3689//===----------------------------------------------------------------------===//
3690// BlockDecl Implementation
3691//===----------------------------------------------------------------------===//
3692
3693void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3694 assert(!ParamInfo && "Already has param info!");
3695
3696 // Zero params -> null pointer.
3697 if (!NewParamInfo.empty()) {
3698 NumParams = NewParamInfo.size();
3699 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3700 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3701 }
3702}
3703
3704void BlockDecl::setCaptures(ASTContext &Context,
3705 const Capture *begin,
3706 const Capture *end,
3707 bool capturesCXXThis) {
3708 CapturesCXXThis = capturesCXXThis;
3709
3710 if (begin == end) {
3711 NumCaptures = 0;
3712 Captures = nullptr;
3713 return;
3714 }
3715
3716 NumCaptures = end - begin;
3717
3718 // Avoid new Capture[] because we don't want to provide a default
3719 // constructor.
3720 size_t allocationSize = NumCaptures * sizeof(Capture);
3721 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3722 memcpy(buffer, begin, allocationSize);
3723 Captures = static_cast<Capture*>(buffer);
3724}
3725
3726bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3727 for (const auto &I : captures())
3728 // Only auto vars can be captured, so no redeclaration worries.
3729 if (I.getVariable() == variable)
3730 return true;
3731
3732 return false;
3733}
3734
3735SourceRange BlockDecl::getSourceRange() const {
3736 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3737}
3738
3739//===----------------------------------------------------------------------===//
3740// Other Decl Allocation/Deallocation Method Implementations
3741//===----------------------------------------------------------------------===//
3742
3743void TranslationUnitDecl::anchor() { }
3744
3745TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3746 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
3747}
3748
3749void LabelDecl::anchor() { }
3750
3751LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3752 SourceLocation IdentL, IdentifierInfo *II) {
3753 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
3754}
3755
3756LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3757 SourceLocation IdentL, IdentifierInfo *II,
3758 SourceLocation GnuLabelL) {
3759 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3760 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
3761}
3762
3763LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3764 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3765 SourceLocation());
3766}
3767
3768void LabelDecl::setMSAsmLabel(StringRef Name) {
3769 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
3770 memcpy(Buffer, Name.data(), Name.size());
3771 Buffer[Name.size()] = '\0';
3772 MSAsmName = Buffer;
3773}
3774
3775void ValueDecl::anchor() { }
3776
3777bool ValueDecl::isWeak() const {
3778 for (const auto *I : attrs())
3779 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
3780 return true;
3781
3782 return isWeakImported();
3783}
3784
3785void ImplicitParamDecl::anchor() { }
3786
3787ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
3788 SourceLocation IdLoc,
3789 IdentifierInfo *Id,
3790 QualType Type) {
3791 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
3792}
3793
3794ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3795 unsigned ID) {
3796 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
3797 QualType());
3798}
3799
3800FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
3801 SourceLocation StartLoc,
3802 const DeclarationNameInfo &NameInfo,
3803 QualType T, TypeSourceInfo *TInfo,
3804 StorageClass SC,
3805 bool isInlineSpecified,
3806 bool hasWrittenPrototype,
3807 bool isConstexprSpecified) {
3808 FunctionDecl *New =
3809 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
3810 SC, isInlineSpecified, isConstexprSpecified);
3811 New->HasWrittenPrototype = hasWrittenPrototype;
3812 return New;
3813}
3814
3815FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3816 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
3817 DeclarationNameInfo(), QualType(), nullptr,
3818 SC_None, false, false);
3819}
3820
3821BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3822 return new (C, DC) BlockDecl(DC, L);
3823}
3824
3825BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3826 return new (C, ID) BlockDecl(nullptr, SourceLocation());
3827}
3828
3829CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3830 unsigned NumParams) {
3831 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3832 CapturedDecl(DC, NumParams);
3833}
3834
3835CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3836 unsigned NumParams) {
3837 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3838 CapturedDecl(nullptr, NumParams);
3839}
3840
3841EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3842 SourceLocation L,
3843 IdentifierInfo *Id, QualType T,
3844 Expr *E, const llvm::APSInt &V) {
3845 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
3846}
3847
3848EnumConstantDecl *
3849EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3850 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
3851 QualType(), nullptr, llvm::APSInt());
3852}
3853
3854void IndirectFieldDecl::anchor() { }
3855
3856IndirectFieldDecl *
3857IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3858 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3859 unsigned CHS) {
3860 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3861}
3862
3863IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3864 unsigned ID) {
3865 return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
3866 DeclarationName(), QualType(), nullptr,
3867 0);
3868}
3869
3870SourceRange EnumConstantDecl::getSourceRange() const {
3871 SourceLocation End = getLocation();
3872 if (Init)
3873 End = Init->getLocEnd();
3874 return SourceRange(getLocation(), End);
3875}
3876
3877void TypeDecl::anchor() { }
3878
3879TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
3880 SourceLocation StartLoc, SourceLocation IdLoc,
3881 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3882 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
3883}
3884
3885void TypedefNameDecl::anchor() { }
3886
3887TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3888 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
3889 nullptr, nullptr);
3890}
3891
3892TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3893 SourceLocation StartLoc,
3894 SourceLocation IdLoc, IdentifierInfo *Id,
3895 TypeSourceInfo *TInfo) {
3896 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
3897}
3898
3899TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3900 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
3901 SourceLocation(), nullptr, nullptr);
3902}
3903
3904SourceRange TypedefDecl::getSourceRange() const {
3905 SourceLocation RangeEnd = getLocation();
3906 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3907 if (typeIsPostfix(TInfo->getType()))
3908 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3909 }
3910 return SourceRange(getLocStart(), RangeEnd);
3911}
3912
3913SourceRange TypeAliasDecl::getSourceRange() const {
3914 SourceLocation RangeEnd = getLocStart();
3915 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3916 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3917 return SourceRange(getLocStart(), RangeEnd);
3918}
3919
3920void FileScopeAsmDecl::anchor() { }
3921
3922FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
3923 StringLiteral *Str,
3924 SourceLocation AsmLoc,
3925 SourceLocation RParenLoc) {
3926 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
3927}
3928
3929FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3930 unsigned ID) {
3931 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
3932 SourceLocation());
3933}
3934
3935void EmptyDecl::anchor() {}
3936
3937EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3938 return new (C, DC) EmptyDecl(DC, L);
3939}
3940
3941EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3942 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
3943}
3944
3945//===----------------------------------------------------------------------===//
3946// ImportDecl Implementation
3947//===----------------------------------------------------------------------===//
3948
3949/// \brief Retrieve the number of module identifiers needed to name the given
3950/// module.
3951static unsigned getNumModuleIdentifiers(Module *Mod) {
3952 unsigned Result = 1;
3953 while (Mod->Parent) {
3954 Mod = Mod->Parent;
3955 ++Result;
3956 }
3957 return Result;
3958}
3959
3960ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3961 Module *Imported,
3962 ArrayRef<SourceLocation> IdentifierLocs)
3963 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3964 NextLocalImport()
3965{
3966 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3967 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3968 memcpy(StoredLocs, IdentifierLocs.data(),
3969 IdentifierLocs.size() * sizeof(SourceLocation));
3970}
3971
3972ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3973 Module *Imported, SourceLocation EndLoc)
3974 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3975 NextLocalImport()
3976{
3977 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3978}
3979
3980ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3981 SourceLocation StartLoc, Module *Imported,
3982 ArrayRef<SourceLocation> IdentifierLocs) {
3983 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3984 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3985}
3986
3987ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3988 SourceLocation StartLoc,
3989 Module *Imported,
3990 SourceLocation EndLoc) {
3991 ImportDecl *Import =
3992 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3993 Imported, EndLoc);
3994 Import->setImplicit();
3995 return Import;
3996}
3997
3998ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3999 unsigned NumLocations) {
4000 return new (C, ID, NumLocations * sizeof(SourceLocation))
4001 ImportDecl(EmptyShell());
4002}
4003
4004ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4005 if (!ImportedAndComplete.getInt())
4006 return None;
4007
4008 const SourceLocation *StoredLocs
4009 = reinterpret_cast<const SourceLocation *>(this + 1);
4010 return llvm::makeArrayRef(StoredLocs,
4011 getNumModuleIdentifiers(getImportedModule()));
4012}
4013
4014SourceRange ImportDecl::getSourceRange() const {
4015 if (!ImportedAndComplete.getInt())
4016 return SourceRange(getLocation(),
4017 *reinterpret_cast<const SourceLocation *>(this + 1));
4018
4019 return SourceRange(getLocation(), getIdentifierLocs().back());
4020}
2679 if (FD->getStorageClass() == SC_Extern)
2680 return true;
2681
2682 return false;
2683}
2684
2685static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2686 if (Redecl->getStorageClass() != SC_Extern)
2687 return false;
2688
2689 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2690 FD = FD->getPreviousDecl())
2691 if (FD->getStorageClass() == SC_Extern)
2692 return false;
2693
2694 return true;
2695}
2696
2697static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2698 // Only consider file-scope declarations in this test.
2699 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2700 return false;
2701
2702 // Only consider explicit declarations; the presence of a builtin for a
2703 // libcall shouldn't affect whether a definition is externally visible.
2704 if (Redecl->isImplicit())
2705 return false;
2706
2707 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2708 return true; // Not an inline definition
2709
2710 return false;
2711}
2712
2713/// \brief For a function declaration in C or C++, determine whether this
2714/// declaration causes the definition to be externally visible.
2715///
2716/// For instance, this determines if adding the current declaration to the set
2717/// of redeclarations of the given functions causes
2718/// isInlineDefinitionExternallyVisible to change from false to true.
2719bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2720 assert(!doesThisDeclarationHaveABody() &&
2721 "Must have a declaration without a body.");
2722
2723 ASTContext &Context = getASTContext();
2724
2725 if (Context.getLangOpts().MSVCCompat) {
2726 const FunctionDecl *Definition;
2727 if (hasBody(Definition) && Definition->isInlined() &&
2728 redeclForcesDefMSVC(this))
2729 return true;
2730 }
2731
2732 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2733 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2734 // an externally visible definition.
2735 //
2736 // FIXME: What happens if gnu_inline gets added on after the first
2737 // declaration?
2738 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2739 return false;
2740
2741 const FunctionDecl *Prev = this;
2742 bool FoundBody = false;
2743 while ((Prev = Prev->getPreviousDecl())) {
2744 FoundBody |= Prev->Body.isValid();
2745
2746 if (Prev->Body) {
2747 // If it's not the case that both 'inline' and 'extern' are
2748 // specified on the definition, then it is always externally visible.
2749 if (!Prev->isInlineSpecified() ||
2750 Prev->getStorageClass() != SC_Extern)
2751 return false;
2752 } else if (Prev->isInlineSpecified() &&
2753 Prev->getStorageClass() != SC_Extern) {
2754 return false;
2755 }
2756 }
2757 return FoundBody;
2758 }
2759
2760 if (Context.getLangOpts().CPlusPlus)
2761 return false;
2762
2763 // C99 6.7.4p6:
2764 // [...] If all of the file scope declarations for a function in a
2765 // translation unit include the inline function specifier without extern,
2766 // then the definition in that translation unit is an inline definition.
2767 if (isInlineSpecified() && getStorageClass() != SC_Extern)
2768 return false;
2769 const FunctionDecl *Prev = this;
2770 bool FoundBody = false;
2771 while ((Prev = Prev->getPreviousDecl())) {
2772 FoundBody |= Prev->Body.isValid();
2773 if (RedeclForcesDefC99(Prev))
2774 return false;
2775 }
2776 return FoundBody;
2777}
2778
2779SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2780 const TypeSourceInfo *TSI = getTypeSourceInfo();
2781 if (!TSI)
2782 return SourceRange();
2783 FunctionTypeLoc FTL =
2784 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2785 if (!FTL)
2786 return SourceRange();
2787
2788 // Skip self-referential return types.
2789 const SourceManager &SM = getASTContext().getSourceManager();
2790 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2791 SourceLocation Boundary = getNameInfo().getLocStart();
2792 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2793 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2794 return SourceRange();
2795
2796 return RTRange;
2797}
2798
2799/// \brief For an inline function definition in C, or for a gnu_inline function
2800/// in C++, determine whether the definition will be externally visible.
2801///
2802/// Inline function definitions are always available for inlining optimizations.
2803/// However, depending on the language dialect, declaration specifiers, and
2804/// attributes, the definition of an inline function may or may not be
2805/// "externally" visible to other translation units in the program.
2806///
2807/// In C99, inline definitions are not externally visible by default. However,
2808/// if even one of the global-scope declarations is marked "extern inline", the
2809/// inline definition becomes externally visible (C99 6.7.4p6).
2810///
2811/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2812/// definition, we use the GNU semantics for inline, which are nearly the
2813/// opposite of C99 semantics. In particular, "inline" by itself will create
2814/// an externally visible symbol, but "extern inline" will not create an
2815/// externally visible symbol.
2816bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2817 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2818 assert(isInlined() && "Function must be inline");
2819 ASTContext &Context = getASTContext();
2820
2821 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2822 // Note: If you change the logic here, please change
2823 // doesDeclarationForceExternallyVisibleDefinition as well.
2824 //
2825 // If it's not the case that both 'inline' and 'extern' are
2826 // specified on the definition, then this inline definition is
2827 // externally visible.
2828 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2829 return true;
2830
2831 // If any declaration is 'inline' but not 'extern', then this definition
2832 // is externally visible.
2833 for (auto Redecl : redecls()) {
2834 if (Redecl->isInlineSpecified() &&
2835 Redecl->getStorageClass() != SC_Extern)
2836 return true;
2837 }
2838
2839 return false;
2840 }
2841
2842 // The rest of this function is C-only.
2843 assert(!Context.getLangOpts().CPlusPlus &&
2844 "should not use C inline rules in C++");
2845
2846 // C99 6.7.4p6:
2847 // [...] If all of the file scope declarations for a function in a
2848 // translation unit include the inline function specifier without extern,
2849 // then the definition in that translation unit is an inline definition.
2850 for (auto Redecl : redecls()) {
2851 if (RedeclForcesDefC99(Redecl))
2852 return true;
2853 }
2854
2855 // C99 6.7.4p6:
2856 // An inline definition does not provide an external definition for the
2857 // function, and does not forbid an external definition in another
2858 // translation unit.
2859 return false;
2860}
2861
2862/// getOverloadedOperator - Which C++ overloaded operator this
2863/// function represents, if any.
2864OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2865 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2866 return getDeclName().getCXXOverloadedOperator();
2867 else
2868 return OO_None;
2869}
2870
2871/// getLiteralIdentifier - The literal suffix identifier this function
2872/// represents, if any.
2873const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2874 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2875 return getDeclName().getCXXLiteralIdentifier();
2876 else
2877 return nullptr;
2878}
2879
2880FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2881 if (TemplateOrSpecialization.isNull())
2882 return TK_NonTemplate;
2883 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2884 return TK_FunctionTemplate;
2885 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2886 return TK_MemberSpecialization;
2887 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2888 return TK_FunctionTemplateSpecialization;
2889 if (TemplateOrSpecialization.is
2890 <DependentFunctionTemplateSpecializationInfo*>())
2891 return TK_DependentFunctionTemplateSpecialization;
2892
2893 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2894}
2895
2896FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2897 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2898 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2899
2900 return nullptr;
2901}
2902
2903void
2904FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2905 FunctionDecl *FD,
2906 TemplateSpecializationKind TSK) {
2907 assert(TemplateOrSpecialization.isNull() &&
2908 "Member function is already a specialization");
2909 MemberSpecializationInfo *Info
2910 = new (C) MemberSpecializationInfo(FD, TSK);
2911 TemplateOrSpecialization = Info;
2912}
2913
2914bool FunctionDecl::isImplicitlyInstantiable() const {
2915 // If the function is invalid, it can't be implicitly instantiated.
2916 if (isInvalidDecl())
2917 return false;
2918
2919 switch (getTemplateSpecializationKind()) {
2920 case TSK_Undeclared:
2921 case TSK_ExplicitInstantiationDefinition:
2922 return false;
2923
2924 case TSK_ImplicitInstantiation:
2925 return true;
2926
2927 // It is possible to instantiate TSK_ExplicitSpecialization kind
2928 // if the FunctionDecl has a class scope specialization pattern.
2929 case TSK_ExplicitSpecialization:
2930 return getClassScopeSpecializationPattern() != nullptr;
2931
2932 case TSK_ExplicitInstantiationDeclaration:
2933 // Handled below.
2934 break;
2935 }
2936
2937 // Find the actual template from which we will instantiate.
2938 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2939 bool HasPattern = false;
2940 if (PatternDecl)
2941 HasPattern = PatternDecl->hasBody(PatternDecl);
2942
2943 // C++0x [temp.explicit]p9:
2944 // Except for inline functions, other explicit instantiation declarations
2945 // have the effect of suppressing the implicit instantiation of the entity
2946 // to which they refer.
2947 if (!HasPattern || !PatternDecl)
2948 return true;
2949
2950 return PatternDecl->isInlined();
2951}
2952
2953bool FunctionDecl::isTemplateInstantiation() const {
2954 switch (getTemplateSpecializationKind()) {
2955 case TSK_Undeclared:
2956 case TSK_ExplicitSpecialization:
2957 return false;
2958 case TSK_ImplicitInstantiation:
2959 case TSK_ExplicitInstantiationDeclaration:
2960 case TSK_ExplicitInstantiationDefinition:
2961 return true;
2962 }
2963 llvm_unreachable("All TSK values handled.");
2964}
2965
2966FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2967 // Handle class scope explicit specialization special case.
2968 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2969 return getClassScopeSpecializationPattern();
2970
2971 // If this is a generic lambda call operator specialization, its
2972 // instantiation pattern is always its primary template's pattern
2973 // even if its primary template was instantiated from another
2974 // member template (which happens with nested generic lambdas).
2975 // Since a lambda's call operator's body is transformed eagerly,
2976 // we don't have to go hunting for a prototype definition template
2977 // (i.e. instantiated-from-member-template) to use as an instantiation
2978 // pattern.
2979
2980 if (isGenericLambdaCallOperatorSpecialization(
2981 dyn_cast<CXXMethodDecl>(this))) {
2982 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
2983 "generated from a primary call operator "
2984 "template");
2985 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
2986 "A generic lambda call operator template must always have a body - "
2987 "even if instantiated from a prototype (i.e. as written) member "
2988 "template");
2989 return getPrimaryTemplate()->getTemplatedDecl();
2990 }
2991
2992 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2993 while (Primary->getInstantiatedFromMemberTemplate()) {
2994 // If we have hit a point where the user provided a specialization of
2995 // this template, we're done looking.
2996 if (Primary->isMemberSpecialization())
2997 break;
2998 Primary = Primary->getInstantiatedFromMemberTemplate();
2999 }
3000
3001 return Primary->getTemplatedDecl();
3002 }
3003
3004 return getInstantiatedFromMemberFunction();
3005}
3006
3007FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3008 if (FunctionTemplateSpecializationInfo *Info
3009 = TemplateOrSpecialization
3010 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3011 return Info->Template.getPointer();
3012 }
3013 return nullptr;
3014}
3015
3016FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3017 return getASTContext().getClassScopeSpecializationPattern(this);
3018}
3019
3020const TemplateArgumentList *
3021FunctionDecl::getTemplateSpecializationArgs() const {
3022 if (FunctionTemplateSpecializationInfo *Info
3023 = TemplateOrSpecialization
3024 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3025 return Info->TemplateArguments;
3026 }
3027 return nullptr;
3028}
3029
3030const ASTTemplateArgumentListInfo *
3031FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3032 if (FunctionTemplateSpecializationInfo *Info
3033 = TemplateOrSpecialization
3034 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3035 return Info->TemplateArgumentsAsWritten;
3036 }
3037 return nullptr;
3038}
3039
3040void
3041FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3042 FunctionTemplateDecl *Template,
3043 const TemplateArgumentList *TemplateArgs,
3044 void *InsertPos,
3045 TemplateSpecializationKind TSK,
3046 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3047 SourceLocation PointOfInstantiation) {
3048 assert(TSK != TSK_Undeclared &&
3049 "Must specify the type of function template specialization");
3050 FunctionTemplateSpecializationInfo *Info
3051 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3052 if (!Info)
3053 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3054 TemplateArgs,
3055 TemplateArgsAsWritten,
3056 PointOfInstantiation);
3057 TemplateOrSpecialization = Info;
3058 Template->addSpecialization(Info, InsertPos);
3059}
3060
3061void
3062FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3063 const UnresolvedSetImpl &Templates,
3064 const TemplateArgumentListInfo &TemplateArgs) {
3065 assert(TemplateOrSpecialization.isNull());
3066 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
3067 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
3068 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
3069 void *Buffer = Context.Allocate(Size);
3070 DependentFunctionTemplateSpecializationInfo *Info =
3071 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
3072 TemplateArgs);
3073 TemplateOrSpecialization = Info;
3074}
3075
3076DependentFunctionTemplateSpecializationInfo::
3077DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3078 const TemplateArgumentListInfo &TArgs)
3079 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3080
3081 d.NumTemplates = Ts.size();
3082 d.NumArgs = TArgs.size();
3083
3084 FunctionTemplateDecl **TsArray =
3085 const_cast<FunctionTemplateDecl**>(getTemplates());
3086 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3087 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3088
3089 TemplateArgumentLoc *ArgsArray =
3090 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
3091 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3092 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3093}
3094
3095TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3096 // For a function template specialization, query the specialization
3097 // information object.
3098 FunctionTemplateSpecializationInfo *FTSInfo
3099 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3100 if (FTSInfo)
3101 return FTSInfo->getTemplateSpecializationKind();
3102
3103 MemberSpecializationInfo *MSInfo
3104 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3105 if (MSInfo)
3106 return MSInfo->getTemplateSpecializationKind();
3107
3108 return TSK_Undeclared;
3109}
3110
3111void
3112FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3113 SourceLocation PointOfInstantiation) {
3114 if (FunctionTemplateSpecializationInfo *FTSInfo
3115 = TemplateOrSpecialization.dyn_cast<
3116 FunctionTemplateSpecializationInfo*>()) {
3117 FTSInfo->setTemplateSpecializationKind(TSK);
3118 if (TSK != TSK_ExplicitSpecialization &&
3119 PointOfInstantiation.isValid() &&
3120 FTSInfo->getPointOfInstantiation().isInvalid())
3121 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3122 } else if (MemberSpecializationInfo *MSInfo
3123 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3124 MSInfo->setTemplateSpecializationKind(TSK);
3125 if (TSK != TSK_ExplicitSpecialization &&
3126 PointOfInstantiation.isValid() &&
3127 MSInfo->getPointOfInstantiation().isInvalid())
3128 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3129 } else
3130 llvm_unreachable("Function cannot have a template specialization kind");
3131}
3132
3133SourceLocation FunctionDecl::getPointOfInstantiation() const {
3134 if (FunctionTemplateSpecializationInfo *FTSInfo
3135 = TemplateOrSpecialization.dyn_cast<
3136 FunctionTemplateSpecializationInfo*>())
3137 return FTSInfo->getPointOfInstantiation();
3138 else if (MemberSpecializationInfo *MSInfo
3139 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
3140 return MSInfo->getPointOfInstantiation();
3141
3142 return SourceLocation();
3143}
3144
3145bool FunctionDecl::isOutOfLine() const {
3146 if (Decl::isOutOfLine())
3147 return true;
3148
3149 // If this function was instantiated from a member function of a
3150 // class template, check whether that member function was defined out-of-line.
3151 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3152 const FunctionDecl *Definition;
3153 if (FD->hasBody(Definition))
3154 return Definition->isOutOfLine();
3155 }
3156
3157 // If this function was instantiated from a function template,
3158 // check whether that function template was defined out-of-line.
3159 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3160 const FunctionDecl *Definition;
3161 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3162 return Definition->isOutOfLine();
3163 }
3164
3165 return false;
3166}
3167
3168SourceRange FunctionDecl::getSourceRange() const {
3169 return SourceRange(getOuterLocStart(), EndRangeLoc);
3170}
3171
3172unsigned FunctionDecl::getMemoryFunctionKind() const {
3173 IdentifierInfo *FnInfo = getIdentifier();
3174
3175 if (!FnInfo)
3176 return 0;
3177
3178 // Builtin handling.
3179 switch (getBuiltinID()) {
3180 case Builtin::BI__builtin_memset:
3181 case Builtin::BI__builtin___memset_chk:
3182 case Builtin::BImemset:
3183 return Builtin::BImemset;
3184
3185 case Builtin::BI__builtin_memcpy:
3186 case Builtin::BI__builtin___memcpy_chk:
3187 case Builtin::BImemcpy:
3188 return Builtin::BImemcpy;
3189
3190 case Builtin::BI__builtin_memmove:
3191 case Builtin::BI__builtin___memmove_chk:
3192 case Builtin::BImemmove:
3193 return Builtin::BImemmove;
3194
3195 case Builtin::BIstrlcpy:
3196 case Builtin::BI__builtin___strlcpy_chk:
3197 return Builtin::BIstrlcpy;
3198
3199 case Builtin::BIstrlcat:
3200 case Builtin::BI__builtin___strlcat_chk:
3201 return Builtin::BIstrlcat;
3202
3203 case Builtin::BI__builtin_memcmp:
3204 case Builtin::BImemcmp:
3205 return Builtin::BImemcmp;
3206
3207 case Builtin::BI__builtin_strncpy:
3208 case Builtin::BI__builtin___strncpy_chk:
3209 case Builtin::BIstrncpy:
3210 return Builtin::BIstrncpy;
3211
3212 case Builtin::BI__builtin_strncmp:
3213 case Builtin::BIstrncmp:
3214 return Builtin::BIstrncmp;
3215
3216 case Builtin::BI__builtin_strncasecmp:
3217 case Builtin::BIstrncasecmp:
3218 return Builtin::BIstrncasecmp;
3219
3220 case Builtin::BI__builtin_strncat:
3221 case Builtin::BI__builtin___strncat_chk:
3222 case Builtin::BIstrncat:
3223 return Builtin::BIstrncat;
3224
3225 case Builtin::BI__builtin_strndup:
3226 case Builtin::BIstrndup:
3227 return Builtin::BIstrndup;
3228
3229 case Builtin::BI__builtin_strlen:
3230 case Builtin::BIstrlen:
3231 return Builtin::BIstrlen;
3232
3233 default:
3234 if (isExternC()) {
3235 if (FnInfo->isStr("memset"))
3236 return Builtin::BImemset;
3237 else if (FnInfo->isStr("memcpy"))
3238 return Builtin::BImemcpy;
3239 else if (FnInfo->isStr("memmove"))
3240 return Builtin::BImemmove;
3241 else if (FnInfo->isStr("memcmp"))
3242 return Builtin::BImemcmp;
3243 else if (FnInfo->isStr("strncpy"))
3244 return Builtin::BIstrncpy;
3245 else if (FnInfo->isStr("strncmp"))
3246 return Builtin::BIstrncmp;
3247 else if (FnInfo->isStr("strncasecmp"))
3248 return Builtin::BIstrncasecmp;
3249 else if (FnInfo->isStr("strncat"))
3250 return Builtin::BIstrncat;
3251 else if (FnInfo->isStr("strndup"))
3252 return Builtin::BIstrndup;
3253 else if (FnInfo->isStr("strlen"))
3254 return Builtin::BIstrlen;
3255 }
3256 break;
3257 }
3258 return 0;
3259}
3260
3261//===----------------------------------------------------------------------===//
3262// FieldDecl Implementation
3263//===----------------------------------------------------------------------===//
3264
3265FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3266 SourceLocation StartLoc, SourceLocation IdLoc,
3267 IdentifierInfo *Id, QualType T,
3268 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3269 InClassInitStyle InitStyle) {
3270 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3271 BW, Mutable, InitStyle);
3272}
3273
3274FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3275 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3276 SourceLocation(), nullptr, QualType(), nullptr,
3277 nullptr, false, ICIS_NoInit);
3278}
3279
3280bool FieldDecl::isAnonymousStructOrUnion() const {
3281 if (!isImplicit() || getDeclName())
3282 return false;
3283
3284 if (const RecordType *Record = getType()->getAs<RecordType>())
3285 return Record->getDecl()->isAnonymousStructOrUnion();
3286
3287 return false;
3288}
3289
3290unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3291 assert(isBitField() && "not a bitfield");
3292 Expr *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
3293 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3294}
3295
3296unsigned FieldDecl::getFieldIndex() const {
3297 const FieldDecl *Canonical = getCanonicalDecl();
3298 if (Canonical != this)
3299 return Canonical->getFieldIndex();
3300
3301 if (CachedFieldIndex) return CachedFieldIndex - 1;
3302
3303 unsigned Index = 0;
3304 const RecordDecl *RD = getParent();
3305
3306 for (auto *Field : RD->fields()) {
3307 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3308 ++Index;
3309 }
3310
3311 assert(CachedFieldIndex && "failed to find field in parent");
3312 return CachedFieldIndex - 1;
3313}
3314
3315SourceRange FieldDecl::getSourceRange() const {
3316 switch (InitStorage.getInt()) {
3317 // All three of these cases store an optional Expr*.
3318 case ISK_BitWidthOrNothing:
3319 case ISK_InClassCopyInit:
3320 case ISK_InClassListInit:
3321 if (const Expr *E = static_cast<const Expr *>(InitStorage.getPointer()))
3322 return SourceRange(getInnerLocStart(), E->getLocEnd());
3323 // FALLTHROUGH
3324
3325 case ISK_CapturedVLAType:
3326 return DeclaratorDecl::getSourceRange();
3327 }
3328 llvm_unreachable("bad init storage kind");
3329}
3330
3331void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
3332 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
3333 "capturing type in non-lambda or captured record.");
3334 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3335 InitStorage.getPointer() == nullptr &&
3336 "bit width, initializer or captured type already set");
3337 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3338 ISK_CapturedVLAType);
3339}
3340
3341//===----------------------------------------------------------------------===//
3342// TagDecl Implementation
3343//===----------------------------------------------------------------------===//
3344
3345SourceLocation TagDecl::getOuterLocStart() const {
3346 return getTemplateOrInnerLocStart(this);
3347}
3348
3349SourceRange TagDecl::getSourceRange() const {
3350 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3351 return SourceRange(getOuterLocStart(), E);
3352}
3353
3354TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3355
3356void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3357 NamedDeclOrQualifier = TDD;
3358 if (const Type *T = getTypeForDecl()) {
3359 (void)T;
3360 assert(T->isLinkageValid());
3361 }
3362 assert(isLinkageValid());
3363}
3364
3365void TagDecl::startDefinition() {
3366 IsBeingDefined = true;
3367
3368 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
3369 struct CXXRecordDecl::DefinitionData *Data =
3370 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3371 for (auto I : redecls())
3372 cast<CXXRecordDecl>(I)->DefinitionData = Data;
3373 }
3374}
3375
3376void TagDecl::completeDefinition() {
3377 assert((!isa<CXXRecordDecl>(this) ||
3378 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3379 "definition completed but not started");
3380
3381 IsCompleteDefinition = true;
3382 IsBeingDefined = false;
3383
3384 if (ASTMutationListener *L = getASTMutationListener())
3385 L->CompletedTagDefinition(this);
3386}
3387
3388TagDecl *TagDecl::getDefinition() const {
3389 if (isCompleteDefinition())
3390 return const_cast<TagDecl *>(this);
3391
3392 // If it's possible for us to have an out-of-date definition, check now.
3393 if (MayHaveOutOfDateDef) {
3394 if (IdentifierInfo *II = getIdentifier()) {
3395 if (II->isOutOfDate()) {
3396 updateOutOfDate(*II);
3397 }
3398 }
3399 }
3400
3401 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3402 return CXXRD->getDefinition();
3403
3404 for (auto R : redecls())
3405 if (R->isCompleteDefinition())
3406 return R;
3407
3408 return nullptr;
3409}
3410
3411void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3412 if (QualifierLoc) {
3413 // Make sure the extended qualifier info is allocated.
3414 if (!hasExtInfo())
3415 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3416 // Set qualifier info.
3417 getExtInfo()->QualifierLoc = QualifierLoc;
3418 } else {
3419 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3420 if (hasExtInfo()) {
3421 if (getExtInfo()->NumTemplParamLists == 0) {
3422 getASTContext().Deallocate(getExtInfo());
3423 NamedDeclOrQualifier = (TypedefNameDecl*)nullptr;
3424 }
3425 else
3426 getExtInfo()->QualifierLoc = QualifierLoc;
3427 }
3428 }
3429}
3430
3431void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3432 unsigned NumTPLists,
3433 TemplateParameterList **TPLists) {
3434 assert(NumTPLists > 0);
3435 // Make sure the extended decl info is allocated.
3436 if (!hasExtInfo())
3437 // Allocate external info struct.
3438 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3439 // Set the template parameter lists info.
3440 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3441}
3442
3443//===----------------------------------------------------------------------===//
3444// EnumDecl Implementation
3445//===----------------------------------------------------------------------===//
3446
3447void EnumDecl::anchor() { }
3448
3449EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3450 SourceLocation StartLoc, SourceLocation IdLoc,
3451 IdentifierInfo *Id,
3452 EnumDecl *PrevDecl, bool IsScoped,
3453 bool IsScopedUsingClassTag, bool IsFixed) {
3454 EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3455 IsScoped, IsScopedUsingClassTag,
3456 IsFixed);
3457 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3458 C.getTypeDeclType(Enum, PrevDecl);
3459 return Enum;
3460}
3461
3462EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3463 EnumDecl *Enum =
3464 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3465 nullptr, nullptr, false, false, false);
3466 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3467 return Enum;
3468}
3469
3470SourceRange EnumDecl::getIntegerTypeRange() const {
3471 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3472 return TI->getTypeLoc().getSourceRange();
3473 return SourceRange();
3474}
3475
3476void EnumDecl::completeDefinition(QualType NewType,
3477 QualType NewPromotionType,
3478 unsigned NumPositiveBits,
3479 unsigned NumNegativeBits) {
3480 assert(!isCompleteDefinition() && "Cannot redefine enums!");
3481 if (!IntegerType)
3482 IntegerType = NewType.getTypePtr();
3483 PromotionType = NewPromotionType;
3484 setNumPositiveBits(NumPositiveBits);
3485 setNumNegativeBits(NumNegativeBits);
3486 TagDecl::completeDefinition();
3487}
3488
3489TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3490 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3491 return MSI->getTemplateSpecializationKind();
3492
3493 return TSK_Undeclared;
3494}
3495
3496void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3497 SourceLocation PointOfInstantiation) {
3498 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3499 assert(MSI && "Not an instantiated member enumeration?");
3500 MSI->setTemplateSpecializationKind(TSK);
3501 if (TSK != TSK_ExplicitSpecialization &&
3502 PointOfInstantiation.isValid() &&
3503 MSI->getPointOfInstantiation().isInvalid())
3504 MSI->setPointOfInstantiation(PointOfInstantiation);
3505}
3506
3507EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3508 if (SpecializationInfo)
3509 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3510
3511 return nullptr;
3512}
3513
3514void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3515 TemplateSpecializationKind TSK) {
3516 assert(!SpecializationInfo && "Member enum is already a specialization");
3517 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3518}
3519
3520//===----------------------------------------------------------------------===//
3521// RecordDecl Implementation
3522//===----------------------------------------------------------------------===//
3523
3524RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3525 DeclContext *DC, SourceLocation StartLoc,
3526 SourceLocation IdLoc, IdentifierInfo *Id,
3527 RecordDecl *PrevDecl)
3528 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3529 HasFlexibleArrayMember = false;
3530 AnonymousStructOrUnion = false;
3531 HasObjectMember = false;
3532 HasVolatileMember = false;
3533 LoadedFieldsFromExternalStorage = false;
3534 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3535}
3536
3537RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3538 SourceLocation StartLoc, SourceLocation IdLoc,
3539 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3540 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3541 StartLoc, IdLoc, Id, PrevDecl);
3542 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3543
3544 C.getTypeDeclType(R, PrevDecl);
3545 return R;
3546}
3547
3548RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3549 RecordDecl *R =
3550 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3551 SourceLocation(), nullptr, nullptr);
3552 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3553 return R;
3554}
3555
3556bool RecordDecl::isInjectedClassName() const {
3557 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3558 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3559}
3560
3561bool RecordDecl::isLambda() const {
3562 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3563 return RD->isLambda();
3564 return false;
3565}
3566
3567bool RecordDecl::isCapturedRecord() const {
3568 return hasAttr<CapturedRecordAttr>();
3569}
3570
3571void RecordDecl::setCapturedRecord() {
3572 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3573}
3574
3575RecordDecl::field_iterator RecordDecl::field_begin() const {
3576 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3577 LoadFieldsFromExternalStorage();
3578
3579 return field_iterator(decl_iterator(FirstDecl));
3580}
3581
3582/// completeDefinition - Notes that the definition of this type is now
3583/// complete.
3584void RecordDecl::completeDefinition() {
3585 assert(!isCompleteDefinition() && "Cannot redefine record!");
3586 TagDecl::completeDefinition();
3587}
3588
3589/// isMsStruct - Get whether or not this record uses ms_struct layout.
3590/// This which can be turned on with an attribute, pragma, or the
3591/// -mms-bitfields command-line option.
3592bool RecordDecl::isMsStruct(const ASTContext &C) const {
3593 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3594}
3595
3596static bool isFieldOrIndirectField(Decl::Kind K) {
3597 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3598}
3599
3600void RecordDecl::LoadFieldsFromExternalStorage() const {
3601 ExternalASTSource *Source = getASTContext().getExternalSource();
3602 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3603
3604 // Notify that we have a RecordDecl doing some initialization.
3605 ExternalASTSource::Deserializing TheFields(Source);
3606
3607 SmallVector<Decl*, 64> Decls;
3608 LoadedFieldsFromExternalStorage = true;
3609 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3610 Decls)) {
3611 case ELR_Success:
3612 break;
3613
3614 case ELR_AlreadyLoaded:
3615 case ELR_Failure:
3616 return;
3617 }
3618
3619#ifndef NDEBUG
3620 // Check that all decls we got were FieldDecls.
3621 for (unsigned i=0, e=Decls.size(); i != e; ++i)
3622 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3623#endif
3624
3625 if (Decls.empty())
3626 return;
3627
3628 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3629 /*FieldsAlreadyLoaded=*/false);
3630}
3631
3632bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3633 ASTContext &Context = getASTContext();
3634 if (!Context.getLangOpts().Sanitize.has(SanitizerKind::Address) ||
3635 !Context.getLangOpts().SanitizeAddressFieldPadding)
3636 return false;
3637 const auto &Blacklist = Context.getSanitizerBlacklist();
3638 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this);
3639 // We may be able to relax some of these requirements.
3640 int ReasonToReject = -1;
3641 if (!CXXRD || CXXRD->isExternCContext())
3642 ReasonToReject = 0; // is not C++.
3643 else if (CXXRD->hasAttr<PackedAttr>())
3644 ReasonToReject = 1; // is packed.
3645 else if (CXXRD->isUnion())
3646 ReasonToReject = 2; // is a union.
3647 else if (CXXRD->isTriviallyCopyable())
3648 ReasonToReject = 3; // is trivially copyable.
3649 else if (CXXRD->hasTrivialDestructor())
3650 ReasonToReject = 4; // has trivial destructor.
3651 else if (CXXRD->isStandardLayout())
3652 ReasonToReject = 5; // is standard layout.
3653 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
3654 ReasonToReject = 6; // is in a blacklisted file.
3655 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3656 "field-padding"))
3657 ReasonToReject = 7; // is blacklisted.
3658
3659 if (EmitRemark) {
3660 if (ReasonToReject >= 0)
3661 Context.getDiagnostics().Report(
3662 getLocation(),
3663 diag::remark_sanitize_address_insert_extra_padding_rejected)
3664 << getQualifiedNameAsString() << ReasonToReject;
3665 else
3666 Context.getDiagnostics().Report(
3667 getLocation(),
3668 diag::remark_sanitize_address_insert_extra_padding_accepted)
3669 << getQualifiedNameAsString();
3670 }
3671 return ReasonToReject < 0;
3672}
3673
3674const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3675 for (const auto *I : fields()) {
3676 if (I->getIdentifier())
3677 return I;
3678
3679 if (const RecordType *RT = I->getType()->getAs<RecordType>())
3680 if (const FieldDecl *NamedDataMember =
3681 RT->getDecl()->findFirstNamedDataMember())
3682 return NamedDataMember;
3683 }
3684
3685 // We didn't find a named data member.
3686 return nullptr;
3687}
3688
3689
3690//===----------------------------------------------------------------------===//
3691// BlockDecl Implementation
3692//===----------------------------------------------------------------------===//
3693
3694void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3695 assert(!ParamInfo && "Already has param info!");
3696
3697 // Zero params -> null pointer.
3698 if (!NewParamInfo.empty()) {
3699 NumParams = NewParamInfo.size();
3700 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3701 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3702 }
3703}
3704
3705void BlockDecl::setCaptures(ASTContext &Context,
3706 const Capture *begin,
3707 const Capture *end,
3708 bool capturesCXXThis) {
3709 CapturesCXXThis = capturesCXXThis;
3710
3711 if (begin == end) {
3712 NumCaptures = 0;
3713 Captures = nullptr;
3714 return;
3715 }
3716
3717 NumCaptures = end - begin;
3718
3719 // Avoid new Capture[] because we don't want to provide a default
3720 // constructor.
3721 size_t allocationSize = NumCaptures * sizeof(Capture);
3722 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3723 memcpy(buffer, begin, allocationSize);
3724 Captures = static_cast<Capture*>(buffer);
3725}
3726
3727bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3728 for (const auto &I : captures())
3729 // Only auto vars can be captured, so no redeclaration worries.
3730 if (I.getVariable() == variable)
3731 return true;
3732
3733 return false;
3734}
3735
3736SourceRange BlockDecl::getSourceRange() const {
3737 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3738}
3739
3740//===----------------------------------------------------------------------===//
3741// Other Decl Allocation/Deallocation Method Implementations
3742//===----------------------------------------------------------------------===//
3743
3744void TranslationUnitDecl::anchor() { }
3745
3746TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3747 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
3748}
3749
3750void LabelDecl::anchor() { }
3751
3752LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3753 SourceLocation IdentL, IdentifierInfo *II) {
3754 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
3755}
3756
3757LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3758 SourceLocation IdentL, IdentifierInfo *II,
3759 SourceLocation GnuLabelL) {
3760 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3761 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
3762}
3763
3764LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3765 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3766 SourceLocation());
3767}
3768
3769void LabelDecl::setMSAsmLabel(StringRef Name) {
3770 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
3771 memcpy(Buffer, Name.data(), Name.size());
3772 Buffer[Name.size()] = '\0';
3773 MSAsmName = Buffer;
3774}
3775
3776void ValueDecl::anchor() { }
3777
3778bool ValueDecl::isWeak() const {
3779 for (const auto *I : attrs())
3780 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
3781 return true;
3782
3783 return isWeakImported();
3784}
3785
3786void ImplicitParamDecl::anchor() { }
3787
3788ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
3789 SourceLocation IdLoc,
3790 IdentifierInfo *Id,
3791 QualType Type) {
3792 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
3793}
3794
3795ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3796 unsigned ID) {
3797 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
3798 QualType());
3799}
3800
3801FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
3802 SourceLocation StartLoc,
3803 const DeclarationNameInfo &NameInfo,
3804 QualType T, TypeSourceInfo *TInfo,
3805 StorageClass SC,
3806 bool isInlineSpecified,
3807 bool hasWrittenPrototype,
3808 bool isConstexprSpecified) {
3809 FunctionDecl *New =
3810 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
3811 SC, isInlineSpecified, isConstexprSpecified);
3812 New->HasWrittenPrototype = hasWrittenPrototype;
3813 return New;
3814}
3815
3816FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3817 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
3818 DeclarationNameInfo(), QualType(), nullptr,
3819 SC_None, false, false);
3820}
3821
3822BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3823 return new (C, DC) BlockDecl(DC, L);
3824}
3825
3826BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3827 return new (C, ID) BlockDecl(nullptr, SourceLocation());
3828}
3829
3830CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3831 unsigned NumParams) {
3832 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3833 CapturedDecl(DC, NumParams);
3834}
3835
3836CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3837 unsigned NumParams) {
3838 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3839 CapturedDecl(nullptr, NumParams);
3840}
3841
3842EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3843 SourceLocation L,
3844 IdentifierInfo *Id, QualType T,
3845 Expr *E, const llvm::APSInt &V) {
3846 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
3847}
3848
3849EnumConstantDecl *
3850EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3851 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
3852 QualType(), nullptr, llvm::APSInt());
3853}
3854
3855void IndirectFieldDecl::anchor() { }
3856
3857IndirectFieldDecl *
3858IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3859 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3860 unsigned CHS) {
3861 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3862}
3863
3864IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3865 unsigned ID) {
3866 return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
3867 DeclarationName(), QualType(), nullptr,
3868 0);
3869}
3870
3871SourceRange EnumConstantDecl::getSourceRange() const {
3872 SourceLocation End = getLocation();
3873 if (Init)
3874 End = Init->getLocEnd();
3875 return SourceRange(getLocation(), End);
3876}
3877
3878void TypeDecl::anchor() { }
3879
3880TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
3881 SourceLocation StartLoc, SourceLocation IdLoc,
3882 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3883 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
3884}
3885
3886void TypedefNameDecl::anchor() { }
3887
3888TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3889 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
3890 nullptr, nullptr);
3891}
3892
3893TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3894 SourceLocation StartLoc,
3895 SourceLocation IdLoc, IdentifierInfo *Id,
3896 TypeSourceInfo *TInfo) {
3897 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
3898}
3899
3900TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3901 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
3902 SourceLocation(), nullptr, nullptr);
3903}
3904
3905SourceRange TypedefDecl::getSourceRange() const {
3906 SourceLocation RangeEnd = getLocation();
3907 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3908 if (typeIsPostfix(TInfo->getType()))
3909 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3910 }
3911 return SourceRange(getLocStart(), RangeEnd);
3912}
3913
3914SourceRange TypeAliasDecl::getSourceRange() const {
3915 SourceLocation RangeEnd = getLocStart();
3916 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3917 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3918 return SourceRange(getLocStart(), RangeEnd);
3919}
3920
3921void FileScopeAsmDecl::anchor() { }
3922
3923FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
3924 StringLiteral *Str,
3925 SourceLocation AsmLoc,
3926 SourceLocation RParenLoc) {
3927 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
3928}
3929
3930FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3931 unsigned ID) {
3932 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
3933 SourceLocation());
3934}
3935
3936void EmptyDecl::anchor() {}
3937
3938EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3939 return new (C, DC) EmptyDecl(DC, L);
3940}
3941
3942EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3943 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
3944}
3945
3946//===----------------------------------------------------------------------===//
3947// ImportDecl Implementation
3948//===----------------------------------------------------------------------===//
3949
3950/// \brief Retrieve the number of module identifiers needed to name the given
3951/// module.
3952static unsigned getNumModuleIdentifiers(Module *Mod) {
3953 unsigned Result = 1;
3954 while (Mod->Parent) {
3955 Mod = Mod->Parent;
3956 ++Result;
3957 }
3958 return Result;
3959}
3960
3961ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3962 Module *Imported,
3963 ArrayRef<SourceLocation> IdentifierLocs)
3964 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3965 NextLocalImport()
3966{
3967 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3968 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3969 memcpy(StoredLocs, IdentifierLocs.data(),
3970 IdentifierLocs.size() * sizeof(SourceLocation));
3971}
3972
3973ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3974 Module *Imported, SourceLocation EndLoc)
3975 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3976 NextLocalImport()
3977{
3978 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3979}
3980
3981ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3982 SourceLocation StartLoc, Module *Imported,
3983 ArrayRef<SourceLocation> IdentifierLocs) {
3984 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3985 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3986}
3987
3988ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3989 SourceLocation StartLoc,
3990 Module *Imported,
3991 SourceLocation EndLoc) {
3992 ImportDecl *Import =
3993 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3994 Imported, EndLoc);
3995 Import->setImplicit();
3996 return Import;
3997}
3998
3999ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4000 unsigned NumLocations) {
4001 return new (C, ID, NumLocations * sizeof(SourceLocation))
4002 ImportDecl(EmptyShell());
4003}
4004
4005ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4006 if (!ImportedAndComplete.getInt())
4007 return None;
4008
4009 const SourceLocation *StoredLocs
4010 = reinterpret_cast<const SourceLocation *>(this + 1);
4011 return llvm::makeArrayRef(StoredLocs,
4012 getNumModuleIdentifiers(getImportedModule()));
4013}
4014
4015SourceRange ImportDecl::getSourceRange() const {
4016 if (!ImportedAndComplete.getInt())
4017 return SourceRange(getLocation(),
4018 *reinterpret_cast<const SourceLocation *>(this + 1));
4019
4020 return SourceRange(getLocation(), getIdentifierLocs().back());
4021}