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