blob: 8bc9eb396e3499ad7f3013a689c0e72067ddf1a6 [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Douglas Gregor889ceb72009-02-03 19:21:40 +000015#include "clang/AST/DeclCXX.h"
Steve Naroffc4173fa2009-02-22 19:35:57 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregore362cea2009-05-10 22:57:19 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000018#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Stmt.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +000024#include "clang/AST/ASTMutationListener.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000026#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000027#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000028#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000029#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000030#include "llvm/Support/ErrorHandling.h"
Ted Kremenekce20e8f2008-05-20 00:43:19 +000031
David Blaikie9c70e042011-09-21 18:16:56 +000032#include <algorithm>
33
Chris Lattner6d9a6852006-10-25 05:11:20 +000034using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000035
Chris Lattner88f70d62008-03-15 05:43:15 +000036//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000037// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000038//===----------------------------------------------------------------------===//
39
Douglas Gregor1baf38f2011-03-26 12:10:19 +000040static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
41 // If this declaration has an explicit visibility attribute, use it.
42 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
43 switch (A->getVisibility()) {
44 case VisibilityAttr::Default:
45 return DefaultVisibility;
46 case VisibilityAttr::Hidden:
47 return HiddenVisibility;
48 case VisibilityAttr::Protected:
49 return ProtectedVisibility;
50 }
John McCall457a04e2010-10-22 21:05:15 +000051 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +000052
53 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
54 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +000055 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +000056 for (specific_attr_iterator<AvailabilityAttr>
57 A = D->specific_attr_begin<AvailabilityAttr>(),
58 AEnd = D->specific_attr_end<AvailabilityAttr>();
59 A != AEnd; ++A)
60 if ((*A)->getPlatform()->getName().equals("macosx"))
61 return DefaultVisibility;
62 }
63
64 return llvm::Optional<Visibility>();
John McCall457a04e2010-10-22 21:05:15 +000065}
66
John McCallc273f242010-10-30 11:50:40 +000067typedef NamedDecl::LinkageInfo LinkageInfo;
John McCallc273f242010-10-30 11:50:40 +000068
Rafael Espindola2f869a32012-01-14 00:30:36 +000069static LinkageInfo getLVForType(QualType T) {
70 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
71 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
72}
73
Douglas Gregor7dc5c172010-02-03 09:33:45 +000074/// \brief Get the most restrictive linkage for the types in the given
75/// template parameter list.
Rafael Espindola2f869a32012-01-14 00:30:36 +000076static LinkageInfo
John McCall457a04e2010-10-22 21:05:15 +000077getLVForTemplateParameterList(const TemplateParameterList *Params) {
Rafael Espindola2f869a32012-01-14 00:30:36 +000078 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
Douglas Gregor7dc5c172010-02-03 09:33:45 +000079 for (TemplateParameterList::const_iterator P = Params->begin(),
80 PEnd = Params->end();
81 P != PEnd; ++P) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +000082 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
83 if (NTTP->isExpandedParameterPack()) {
84 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
85 QualType T = NTTP->getExpansionType(I);
86 if (!T->isDependentType())
Rafael Espindola2f869a32012-01-14 00:30:36 +000087 LV.merge(getLVForType(T));
Douglas Gregor0231d8d2011-01-19 20:10:05 +000088 }
89 continue;
90 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +000091
Douglas Gregor7dc5c172010-02-03 09:33:45 +000092 if (!NTTP->getType()->isDependentType()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +000093 LV.merge(getLVForType(NTTP->getType()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +000094 continue;
95 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +000096 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +000097
98 if (TemplateTemplateParmDecl *TTP
99 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000100 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000101 }
102 }
103
John McCall457a04e2010-10-22 21:05:15 +0000104 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000105}
106
Douglas Gregorbf62d642010-12-06 18:36:25 +0000107/// getLVForDecl - Get the linkage and visibility for the given declaration.
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000108static LinkageInfo getLVForDecl(const NamedDecl *D, bool OnlyTemplate);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000109
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000110/// \brief Get the most restrictive linkage for the types and
111/// declarations in the given template argument list.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000112static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Args,
113 unsigned NumArgs,
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000114 bool OnlyTemplate) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000115 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000116
117 for (unsigned I = 0; I != NumArgs; ++I) {
118 switch (Args[I].getKind()) {
119 case TemplateArgument::Null:
120 case TemplateArgument::Integral:
121 case TemplateArgument::Expression:
122 break;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000123
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000124 case TemplateArgument::Type:
Rafael Espindolab522a5f2012-04-23 17:51:55 +0000125 LV.mergeWithMin(getLVForType(Args[I].getAsType()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000126 break;
127
128 case TemplateArgument::Declaration:
John McCall457a04e2010-10-22 21:05:15 +0000129 // The decl can validly be null as the representation of nullptr
130 // arguments, valid only in C++0x.
131 if (Decl *D = Args[I].getAsDecl()) {
Douglas Gregor91df6cf2010-12-06 18:50:56 +0000132 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Rafael Espindolab522a5f2012-04-23 17:51:55 +0000133 LV.mergeWithMin(getLVForDecl(ND, OnlyTemplate));
John McCall457a04e2010-10-22 21:05:15 +0000134 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000135 break;
136
137 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000138 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000139 if (TemplateDecl *Template
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000140 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolab522a5f2012-04-23 17:51:55 +0000141 LV.mergeWithMin(getLVForDecl(Template, OnlyTemplate));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000142 break;
143
144 case TemplateArgument::Pack:
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000145 LV.mergeWithMin(getLVForTemplateArgumentList(Args[I].pack_begin(),
146 Args[I].pack_size(),
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000147 OnlyTemplate));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000148 break;
149 }
150 }
151
John McCall457a04e2010-10-22 21:05:15 +0000152 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000153}
154
Rafael Espindola2f869a32012-01-14 00:30:36 +0000155static LinkageInfo
Douglas Gregorbf62d642010-12-06 18:36:25 +0000156getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000157 bool OnlyTemplate) {
158 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), OnlyTemplate);
John McCall8823c652010-08-13 08:35:10 +0000159}
160
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000161static bool shouldConsiderTemplateLV(const FunctionDecl *fn) {
162 return !fn->hasAttr<VisibilityAttr>();
John McCallb8c604a2011-06-27 23:06:04 +0000163}
164
165static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
Rafael Espindola93c289c2012-05-21 20:15:56 +0000166 return !d->hasAttr<VisibilityAttr>() || d->isExplicitSpecialization();
John McCallb8c604a2011-06-27 23:06:04 +0000167}
168
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000169static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
170 bool OnlyTemplate) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000171 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000172 "Not a name having namespace scope");
173 ASTContext &Context = D->getASTContext();
174
175 // C++ [basic.link]p3:
176 // A name having namespace scope (3.3.6) has internal linkage if it
177 // is the name of
178 // - an object, reference, function or function template that is
179 // explicitly declared static; or,
180 // (This bullet corresponds to C99 6.2.2p3.)
181 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
182 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000183 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000184 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000185
186 // - an object or reference that is explicitly declared const
187 // and neither explicitly declared extern nor previously
188 // declared to have external linkage; or
189 // (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000190 if (Context.getLangOpts().CPlusPlus &&
Eli Friedmanf873c2f2009-11-26 03:04:01 +0000191 Var->getType().isConstant(Context) &&
John McCall8e7d6562010-08-26 03:08:43 +0000192 Var->getStorageClass() != SC_Extern &&
193 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000194 bool FoundExtern = false;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000195 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000196 PrevVar && !FoundExtern;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000197 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000198 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregorf73b2822009-11-25 22:24:25 +0000199 FoundExtern = true;
200
201 if (!FoundExtern)
John McCallc273f242010-10-30 11:50:40 +0000202 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000203 }
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000204 if (Var->getStorageClass() == SC_None) {
Douglas Gregorec9fd132012-01-14 16:38:05 +0000205 const VarDecl *PrevVar = Var->getPreviousDecl();
206 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000207 if (PrevVar->getStorageClass() == SC_PrivateExtern)
208 break;
209 if (PrevVar)
210 return PrevVar->getLinkageAndVisibility();
211 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000212 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000213 // C++ [temp]p4:
214 // A non-member function template can have internal linkage; any
215 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000216 const FunctionDecl *Function = 0;
217 if (const FunctionTemplateDecl *FunTmpl
218 = dyn_cast<FunctionTemplateDecl>(D))
219 Function = FunTmpl->getTemplatedDecl();
220 else
221 Function = cast<FunctionDecl>(D);
222
223 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000224 if (Function->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000225 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000226 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
227 // - a data member of an anonymous union.
228 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000229 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000230 }
231
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000232 if (D->isInAnonymousNamespace()) {
233 const VarDecl *Var = dyn_cast<VarDecl>(D);
234 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Eli Friedman839192f2012-01-15 01:23:58 +0000235 if ((!Var || !Var->getDeclContext()->isExternCContext()) &&
236 (!Func || !Func->getDeclContext()->isExternCContext()))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000237 return LinkageInfo::uniqueExternal();
238 }
John McCallb7139c42010-10-28 04:18:25 +0000239
John McCall457a04e2010-10-22 21:05:15 +0000240 // Set up the defaults.
241
242 // C99 6.2.2p5:
243 // If the declaration of an identifier for an object has file
244 // scope and no storage-class specifier, its linkage is
245 // external.
John McCallc273f242010-10-30 11:50:40 +0000246 LinkageInfo LV;
247
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000248 if (!OnlyTemplate) {
Rafael Espindola78158af2012-04-16 18:46:26 +0000249 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000250 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000251 } else {
252 // If we're declared in a namespace with a visibility attribute,
253 // use that namespace's visibility, but don't call it explicit.
254 for (const DeclContext *DC = D->getDeclContext();
255 !isa<TranslationUnitDecl>(DC);
256 DC = DC->getParent()) {
257 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
258 if (!ND) continue;
259 if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000260 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000261 break;
262 }
263 }
264 }
265 }
266
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000267 if (!OnlyTemplate)
Rafael Espindolab660efd2012-04-19 04:37:16 +0000268 LV.mergeVisibility(Context.getLangOpts().getVisibilityMode());
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000269
Douglas Gregorf73b2822009-11-25 22:24:25 +0000270 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000271
Douglas Gregorf73b2822009-11-25 22:24:25 +0000272 // A name having namespace scope has external linkage if it is the
273 // name of
274 //
275 // - an object or reference, unless it has internal linkage; or
276 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000277 // GCC applies the following optimization to variables and static
278 // data members, but not to functions:
279 //
John McCall457a04e2010-10-22 21:05:15 +0000280 // Modify the variable's LV by the LV of its type unless this is
281 // C or extern "C". This follows from [basic.link]p9:
282 // A type without linkage shall not be used as the type of a
283 // variable or function with external linkage unless
284 // - the entity has C language linkage, or
285 // - the entity is declared within an unnamed namespace, or
286 // - the entity is not used or is defined in the same
287 // translation unit.
288 // and [basic.link]p10:
289 // ...the types specified by all declarations referring to a
290 // given variable or function shall be identical...
291 // C does not have an equivalent rule.
292 //
John McCall5fe84122010-10-26 04:59:26 +0000293 // Ignore this if we've got an explicit attribute; the user
294 // probably knows what they're doing.
295 //
John McCall457a04e2010-10-22 21:05:15 +0000296 // Note that we don't want to make the variable non-external
297 // because of this, but unique-external linkage suits us.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000298 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000299 !Var->getDeclContext()->isExternCContext()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000300 LinkageInfo TypeLV = getLVForType(Var->getType());
301 if (TypeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000302 return LinkageInfo::uniqueExternal();
Rafael Espindola1f073332012-04-19 05:24:05 +0000303 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000304 }
305
John McCall23032652010-11-02 18:38:13 +0000306 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000307 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000308
David Blaikiebbafb8a2012-03-11 07:00:24 +0000309 if (!Context.getLangOpts().CPlusPlus &&
John McCall8e7d6562010-08-26 03:08:43 +0000310 (Var->getStorageClass() == SC_Extern ||
311 Var->getStorageClass() == SC_PrivateExtern)) {
John McCall457a04e2010-10-22 21:05:15 +0000312
Douglas Gregorf73b2822009-11-25 22:24:25 +0000313 // C99 6.2.2p4:
314 // For an identifier declared with the storage-class specifier
315 // extern in a scope in which a prior declaration of that
316 // identifier is visible, if the prior declaration specifies
317 // internal or external linkage, the linkage of the identifier
318 // at the later declaration is the same as the linkage
319 // specified at the prior declaration. If no prior declaration
320 // is visible, or if the prior declaration specifies no
321 // linkage, then the identifier has external linkage.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000322 if (const VarDecl *PrevVar = Var->getPreviousDecl()) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000323 LinkageInfo PrevLV = getLVForDecl(PrevVar, OnlyTemplate);
John McCallc273f242010-10-30 11:50:40 +0000324 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
325 LV.mergeVisibility(PrevLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000326 }
327 }
328
Douglas Gregorf73b2822009-11-25 22:24:25 +0000329 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000330 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000331 // In theory, we can modify the function's LV by the LV of its
332 // type unless it has C linkage (see comment above about variables
333 // for justification). In practice, GCC doesn't do this, so it's
334 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000335
John McCall23032652010-11-02 18:38:13 +0000336 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000337 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000338
Douglas Gregorf73b2822009-11-25 22:24:25 +0000339 // C99 6.2.2p5:
340 // If the declaration of an identifier for a function has no
341 // storage-class specifier, its linkage is determined exactly
342 // as if it were declared with the storage-class specifier
343 // extern.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000344 if (!Context.getLangOpts().CPlusPlus &&
John McCall8e7d6562010-08-26 03:08:43 +0000345 (Function->getStorageClass() == SC_Extern ||
346 Function->getStorageClass() == SC_PrivateExtern ||
347 Function->getStorageClass() == SC_None)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000348 // C99 6.2.2p4:
349 // For an identifier declared with the storage-class specifier
350 // extern in a scope in which a prior declaration of that
351 // identifier is visible, if the prior declaration specifies
352 // internal or external linkage, the linkage of the identifier
353 // at the later declaration is the same as the linkage
354 // specified at the prior declaration. If no prior declaration
355 // is visible, or if the prior declaration specifies no
356 // linkage, then the identifier has external linkage.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000357 if (const FunctionDecl *PrevFunc = Function->getPreviousDecl()) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000358 LinkageInfo PrevLV = getLVForDecl(PrevFunc, OnlyTemplate);
John McCallc273f242010-10-30 11:50:40 +0000359 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
360 LV.mergeVisibility(PrevLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000361 }
362 }
363
John McCallf768aa72011-02-10 06:50:24 +0000364 // In C++, then if the type of the function uses a type with
365 // unique-external linkage, it's not legally usable from outside
366 // this translation unit. However, we should use the C linkage
367 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000368 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000369 !Function->getDeclContext()->isExternCContext() &&
John McCallf768aa72011-02-10 06:50:24 +0000370 Function->getType()->getLinkage() == UniqueExternalLinkage)
371 return LinkageInfo::uniqueExternal();
372
John McCallb8c604a2011-06-27 23:06:04 +0000373 // Consider LV from the template and the template arguments unless
374 // this is an explicit specialization with a visibility attribute.
375 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000376 = Function->getTemplateSpecializationInfo()) {
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000377 if (shouldConsiderTemplateLV(Function)) {
John McCallb8c604a2011-06-27 23:06:04 +0000378 LV.merge(getLVForDecl(specInfo->getTemplate(),
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000379 true));
John McCallb8c604a2011-06-27 23:06:04 +0000380 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000381 LV.mergeWithMin(getLVForTemplateArgumentList(templateArgs,
382 OnlyTemplate));
John McCallb8c604a2011-06-27 23:06:04 +0000383 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000384 }
385
Douglas Gregorf73b2822009-11-25 22:24:25 +0000386 // - a named class (Clause 9), or an unnamed class defined in a
387 // typedef declaration in which the class has the typedef name
388 // for linkage purposes (7.1.3); or
389 // - a named enumeration (7.2), or an unnamed enumeration
390 // defined in a typedef declaration in which the enumeration
391 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000392 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
393 // Unnamed tags have no linkage.
Richard Smithdda56e42011-04-15 14:24:37 +0000394 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallc273f242010-10-30 11:50:40 +0000395 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000396
John McCall457a04e2010-10-22 21:05:15 +0000397 // If this is a class template specialization, consider the
398 // linkage of the template and template arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000399 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000400 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCallb8c604a2011-06-27 23:06:04 +0000401 if (shouldConsiderTemplateLV(spec)) {
402 // From the template.
403 LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000404 true));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000405
John McCallb8c604a2011-06-27 23:06:04 +0000406 // The arguments at which the template was instantiated.
407 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000408 LV.mergeWithMin(getLVForTemplateArgumentList(TemplateArgs,
409 OnlyTemplate));
John McCallb8c604a2011-06-27 23:06:04 +0000410 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000411 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000412
413 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000414 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000415 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
416 OnlyTemplate);
John McCallc273f242010-10-30 11:50:40 +0000417 if (!isExternalLinkage(EnumLV.linkage()))
418 return LinkageInfo::none();
419 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000420
421 // - a template, unless it is a function template that has
422 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000423 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
Rafael Espindola8add48e2012-04-22 00:43:48 +0000424 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
Douglas Gregorf73b2822009-11-25 22:24:25 +0000425 // - a namespace (7.3), unless it is declared within an unnamed
426 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000427 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
428 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000429
John McCall457a04e2010-10-22 21:05:15 +0000430 // By extension, we assign external linkage to Objective-C
431 // interfaces.
432 } else if (isa<ObjCInterfaceDecl>(D)) {
433 // fallout
434
435 // Everything not covered here has no linkage.
436 } else {
John McCallc273f242010-10-30 11:50:40 +0000437 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000438 }
439
440 // If we ended up with non-external linkage, visibility should
441 // always be default.
John McCallc273f242010-10-30 11:50:40 +0000442 if (LV.linkage() != ExternalLinkage)
443 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000444
John McCall457a04e2010-10-22 21:05:15 +0000445 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000446}
447
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000448static LinkageInfo getLVForClassMember(const NamedDecl *D, bool OnlyTemplate) {
John McCall457a04e2010-10-22 21:05:15 +0000449 // Only certain class members have linkage. Note that fields don't
450 // really have linkage, but it's convenient to say they do for the
451 // purposes of calculating linkage of pointer-to-data-member
452 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000453 if (!(isa<CXXMethodDecl>(D) ||
454 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000455 isa<FieldDecl>(D) ||
John McCall8823c652010-08-13 08:35:10 +0000456 (isa<TagDecl>(D) &&
Richard Smithdda56e42011-04-15 14:24:37 +0000457 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
John McCallc273f242010-10-30 11:50:40 +0000458 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000459
John McCall07072662010-11-02 01:45:15 +0000460 LinkageInfo LV;
461
John McCall07072662010-11-02 01:45:15 +0000462 // If we have an explicit visibility attribute, merge that in.
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000463 if (!OnlyTemplate) {
Rafael Espindola3d3d3392012-04-19 04:27:47 +0000464 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility())
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000465 LV.mergeVisibility(*Vis, true);
John McCall07072662010-11-02 01:45:15 +0000466 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000467
468 // If this class member has an explicit visibility attribute, the only
469 // thing that can change its visibility is the template arguments, so
470 // only look for them when processing the the class.
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000471 bool ClassOnlyTemplate = LV.visibilityExplicit() ? true : OnlyTemplate;
Rafael Espindola505a7c82012-04-16 18:25:01 +0000472
473 // If we're paying attention to global visibility, apply
474 // -finline-visibility-hidden if this is an inline method.
475 //
476 // Note that we do this before merging information about
477 // the class visibility.
478 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
479 TemplateSpecializationKind TSK = TSK_Undeclared;
480 if (FunctionTemplateSpecializationInfo *spec
481 = MD->getTemplateSpecializationInfo()) {
482 TSK = spec->getTemplateSpecializationKind();
483 } else if (MemberSpecializationInfo *MSI =
484 MD->getMemberSpecializationInfo()) {
485 TSK = MSI->getTemplateSpecializationKind();
486 }
487
488 const FunctionDecl *Def = 0;
489 // InlineVisibilityHidden only applies to definitions, and
490 // isInlined() only gives meaningful answers on definitions
491 // anyway.
492 if (TSK != TSK_ExplicitInstantiationDeclaration &&
493 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000494 !OnlyTemplate &&
Rafael Espindola505a7c82012-04-16 18:25:01 +0000495 !LV.visibilityExplicit() &&
496 MD->getASTContext().getLangOpts().InlineVisibilityHidden &&
497 MD->hasBody(Def) && Def->isInlined())
498 LV.mergeVisibility(HiddenVisibility, true);
499 }
John McCallc273f242010-10-30 11:50:40 +0000500
Rafael Espindola53cf2192012-04-19 05:50:08 +0000501 // If this member has an visibility attribute, ClassF will exclude
502 // attributes on the class or command line options, keeping only information
503 // about the template instantiation. If the member has no visibility
504 // attributes, mergeWithMin behaves like merge, so in both cases mergeWithMin
505 // produces the desired result.
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000506 LV.mergeWithMin(getLVForDecl(cast<RecordDecl>(D->getDeclContext()),
507 ClassOnlyTemplate));
John McCall07072662010-11-02 01:45:15 +0000508 if (!isExternalLinkage(LV.linkage()))
John McCallc273f242010-10-30 11:50:40 +0000509 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000510
511 // If the class already has unique-external linkage, we can't improve.
John McCall07072662010-11-02 01:45:15 +0000512 if (LV.linkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000513 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000514
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000515 if (!OnlyTemplate)
Rafael Espindolab660efd2012-04-19 04:37:16 +0000516 LV.mergeVisibility(D->getASTContext().getLangOpts().getVisibilityMode());
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000517
John McCall8823c652010-08-13 08:35:10 +0000518 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000519 // If the type of the function uses a type with unique-external
520 // linkage, it's not legally usable from outside this translation unit.
521 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
522 return LinkageInfo::uniqueExternal();
523
John McCall457a04e2010-10-22 21:05:15 +0000524 // If this is a method template specialization, use the linkage for
525 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000526 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000527 = MD->getTemplateSpecializationInfo()) {
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000528 if (shouldConsiderTemplateLV(MD)) {
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000529 LV.mergeWithMin(getLVForTemplateArgumentList(*spec->TemplateArguments,
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000530 OnlyTemplate));
531 if (!OnlyTemplate)
John McCallb8c604a2011-06-27 23:06:04 +0000532 LV.merge(getLVForTemplateParameterList(
533 spec->getTemplate()->getTemplateParameters()));
534 }
John McCalle6e622e2010-11-01 01:29:57 +0000535 }
John McCall457a04e2010-10-22 21:05:15 +0000536
John McCall37bb6c92010-10-29 22:22:43 +0000537 // Note that in contrast to basically every other situation, we
538 // *do* apply -fvisibility to method declarations.
539
540 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000541 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000542 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCallb8c604a2011-06-27 23:06:04 +0000543 if (shouldConsiderTemplateLV(spec)) {
544 // Merge template argument/parameter information for member
545 // class template specializations.
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000546 LV.mergeWithMin(getLVForTemplateArgumentList(spec->getTemplateArgs(),
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000547 OnlyTemplate));
548 if (!OnlyTemplate)
John McCall8bc6d5b2011-03-04 10:39:25 +0000549 LV.merge(getLVForTemplateParameterList(
John McCallb8c604a2011-06-27 23:06:04 +0000550 spec->getSpecializedTemplate()->getTemplateParameters()));
551 }
John McCall37bb6c92010-10-29 22:22:43 +0000552 }
553
John McCall37bb6c92010-10-29 22:22:43 +0000554 // Static data members.
555 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000556 // Modify the variable's linkage by its type, but ignore the
557 // type's visibility unless it's a definition.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000558 LinkageInfo TypeLV = getLVForType(VD->getType());
559 if (TypeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000560 LV.mergeLinkage(UniqueExternalLinkage);
Rafael Espindola53cf2192012-04-19 05:50:08 +0000561 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000562 }
563
John McCall457a04e2010-10-22 21:05:15 +0000564 return LV;
John McCall8823c652010-08-13 08:35:10 +0000565}
566
John McCalld396b972011-02-08 19:01:05 +0000567static void clearLinkageForClass(const CXXRecordDecl *record) {
568 for (CXXRecordDecl::decl_iterator
569 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
570 Decl *child = *i;
571 if (isa<NamedDecl>(child))
572 cast<NamedDecl>(child)->ClearLinkageCache();
573 }
574}
575
David Blaikie68e081d2011-12-20 02:48:34 +0000576void NamedDecl::anchor() { }
577
John McCalld396b972011-02-08 19:01:05 +0000578void NamedDecl::ClearLinkageCache() {
579 // Note that we can't skip clearing the linkage of children just
580 // because the parent doesn't have cached linkage: we don't cache
581 // when computing linkage for parent contexts.
582
583 HasCachedLinkage = 0;
584
585 // If we're changing the linkage of a class, we need to reset the
586 // linkage of child declarations, too.
587 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
588 clearLinkageForClass(record);
589
John McCall83779672011-02-19 02:53:41 +0000590 if (ClassTemplateDecl *temp =
591 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
John McCalld396b972011-02-08 19:01:05 +0000592 // Clear linkage for the template pattern.
593 CXXRecordDecl *record = temp->getTemplatedDecl();
594 record->HasCachedLinkage = 0;
595 clearLinkageForClass(record);
596
John McCall83779672011-02-19 02:53:41 +0000597 // We need to clear linkage for specializations, too.
598 for (ClassTemplateDecl::spec_iterator
599 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
600 i->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000601 }
John McCall83779672011-02-19 02:53:41 +0000602
603 // Clear cached linkage for function template decls, too.
604 if (FunctionTemplateDecl *temp =
John McCall8f9a4292011-03-22 06:58:49 +0000605 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
606 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall83779672011-02-19 02:53:41 +0000607 for (FunctionTemplateDecl::spec_iterator
608 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
609 i->ClearLinkageCache();
John McCall8f9a4292011-03-22 06:58:49 +0000610 }
John McCall83779672011-02-19 02:53:41 +0000611
John McCalld396b972011-02-08 19:01:05 +0000612}
613
Douglas Gregorbf62d642010-12-06 18:36:25 +0000614Linkage NamedDecl::getLinkage() const {
615 if (HasCachedLinkage) {
Benjamin Kramer87368ac2010-12-07 15:51:48 +0000616 assert(Linkage(CachedLinkage) ==
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000617 getLVForDecl(this, true).linkage());
Douglas Gregorbf62d642010-12-06 18:36:25 +0000618 return Linkage(CachedLinkage);
619 }
620
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000621 CachedLinkage = getLVForDecl(this, true).linkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +0000622 HasCachedLinkage = 1;
623 return Linkage(CachedLinkage);
624}
625
John McCallc273f242010-10-30 11:50:40 +0000626LinkageInfo NamedDecl::getLinkageAndVisibility() const {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000627 LinkageInfo LI = getLVForDecl(this, false);
Benjamin Kramer87368ac2010-12-07 15:51:48 +0000628 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
Douglas Gregorbf62d642010-12-06 18:36:25 +0000629 HasCachedLinkage = 1;
630 CachedLinkage = LI.linkage();
631 return LI;
John McCall033caa52010-10-29 00:29:13 +0000632}
Ted Kremenek926d8602010-04-20 23:15:35 +0000633
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000634llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
635 // Use the most recent declaration of a variable.
Rafael Espindola96e68242012-05-16 02:10:38 +0000636 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
637 if (llvm::Optional<Visibility> V =
638 getVisibilityOf(Var->getMostRecentDecl()))
639 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000640
Rafael Espindola96e68242012-05-16 02:10:38 +0000641 if (Var->isStaticDataMember()) {
642 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
643 if (InstantiatedFrom)
644 return getVisibilityOf(InstantiatedFrom);
645 }
646
647 return llvm::Optional<Visibility>();
648 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000649 // Use the most recent declaration of a function, and also handle
650 // function template specializations.
651 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
652 if (llvm::Optional<Visibility> V
Douglas Gregorec9fd132012-01-14 16:38:05 +0000653 = getVisibilityOf(fn->getMostRecentDecl()))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000654 return V;
655
656 // If the function is a specialization of a template with an
657 // explicit visibility attribute, use that.
658 if (FunctionTemplateSpecializationInfo *templateInfo
659 = fn->getTemplateSpecializationInfo())
660 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
661
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000662 // If the function is a member of a specialization of a class template
663 // and the corresponding decl has explicit visibility, use that.
664 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
665 if (InstantiatedFrom)
666 return getVisibilityOf(InstantiatedFrom);
667
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000668 return llvm::Optional<Visibility>();
669 }
670
671 // Otherwise, just check the declaration itself first.
672 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
673 return V;
674
675 // If there wasn't explicit visibility there, and this is a
676 // specialization of a class template, check for visibility
677 // on the pattern.
678 if (const ClassTemplateSpecializationDecl *spec
679 = dyn_cast<ClassTemplateSpecializationDecl>(this))
680 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
681
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000682 // If this is a member class of a specialization of a class template
683 // and the corresponding decl has explicit visibility, use that.
684 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
685 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
686 if (InstantiatedFrom)
687 return getVisibilityOf(InstantiatedFrom);
688 }
689
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000690 return llvm::Optional<Visibility>();
691}
692
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000693static LinkageInfo getLVForDecl(const NamedDecl *D, bool OnlyTemplate) {
Ted Kremenek926d8602010-04-20 23:15:35 +0000694 // Objective-C: treat all Objective-C declarations as having external
695 // linkage.
John McCall033caa52010-10-29 00:29:13 +0000696 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +0000697 default:
698 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +0000699 case Decl::ParmVar:
700 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000701 case Decl::TemplateTemplateParm: // count these as external
702 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +0000703 case Decl::ObjCAtDefsField:
704 case Decl::ObjCCategory:
705 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +0000706 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +0000707 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +0000708 case Decl::ObjCMethod:
709 case Decl::ObjCProperty:
710 case Decl::ObjCPropertyImpl:
711 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +0000712 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +0000713
714 case Decl::CXXRecord: {
715 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
716 if (Record->isLambda()) {
717 if (!Record->getLambdaManglingNumber()) {
718 // This lambda has no mangling number, so it's internal.
719 return LinkageInfo::internal();
720 }
721
722 // This lambda has its linkage/visibility determined by its owner.
723 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
724 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
725 if (isa<ParmVarDecl>(ContextDecl))
726 DC = ContextDecl->getDeclContext()->getRedeclContext();
727 else
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000728 return getLVForDecl(cast<NamedDecl>(ContextDecl),
729 OnlyTemplate);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +0000730 }
731
732 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000733 return getLVForDecl(ND, OnlyTemplate);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +0000734
735 return LinkageInfo::external();
736 }
737
738 break;
739 }
Ted Kremenek926d8602010-04-20 23:15:35 +0000740 }
741
Douglas Gregorf73b2822009-11-25 22:24:25 +0000742 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +0000743 if (D->getDeclContext()->getRedeclContext()->isFileContext())
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000744 return getLVForNamespaceScopeDecl(D, OnlyTemplate);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000745
746 // C++ [basic.link]p5:
747 // In addition, a member function, static data member, a named
748 // class or enumeration of class scope, or an unnamed class or
749 // enumeration defined in a class-scope typedef declaration such
750 // that the class or enumeration has the typedef name for linkage
751 // purposes (7.1.3), has external linkage if the name of the class
752 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +0000753 if (D->getDeclContext()->isRecord())
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000754 return getLVForClassMember(D, OnlyTemplate);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000755
756 // C++ [basic.link]p6:
757 // The name of a function declared in block scope and the name of
758 // an object declared by a block scope extern declaration have
759 // linkage. If there is a visible declaration of an entity with
760 // linkage having the same name and type, ignoring entities
761 // declared outside the innermost enclosing namespace scope, the
762 // block scope declaration declares that same entity and receives
763 // the linkage of the previous declaration. If there is more than
764 // one such matching entity, the program is ill-formed. Otherwise,
765 // if no matching entity is found, the block scope entity receives
766 // external linkage.
John McCall033caa52010-10-29 00:29:13 +0000767 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
768 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Eli Friedman839192f2012-01-15 01:23:58 +0000769 if (Function->isInAnonymousNamespace() &&
770 !Function->getDeclContext()->isExternCContext())
John McCallc273f242010-10-30 11:50:40 +0000771 return LinkageInfo::uniqueExternal();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000772
John McCallc273f242010-10-30 11:50:40 +0000773 LinkageInfo LV;
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000774 if (!OnlyTemplate) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000775 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000776 LV.mergeVisibility(*Vis, true);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000777 }
778
Douglas Gregorec9fd132012-01-14 16:38:05 +0000779 if (const FunctionDecl *Prev = Function->getPreviousDecl()) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000780 LinkageInfo PrevLV = getLVForDecl(Prev, OnlyTemplate);
John McCallc273f242010-10-30 11:50:40 +0000781 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
782 LV.mergeVisibility(PrevLV);
John McCall457a04e2010-10-22 21:05:15 +0000783 }
784
785 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000786 }
787
John McCall033caa52010-10-29 00:29:13 +0000788 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
John McCall8e7d6562010-08-26 03:08:43 +0000789 if (Var->getStorageClass() == SC_Extern ||
790 Var->getStorageClass() == SC_PrivateExtern) {
Eli Friedman839192f2012-01-15 01:23:58 +0000791 if (Var->isInAnonymousNamespace() &&
792 !Var->getDeclContext()->isExternCContext())
John McCallc273f242010-10-30 11:50:40 +0000793 return LinkageInfo::uniqueExternal();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000794
John McCallc273f242010-10-30 11:50:40 +0000795 LinkageInfo LV;
John McCall457a04e2010-10-22 21:05:15 +0000796 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000797 LV.mergeVisibility(HiddenVisibility, true);
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000798 else if (!OnlyTemplate) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000799 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000800 LV.mergeVisibility(*Vis, true);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000801 }
802
Douglas Gregorec9fd132012-01-14 16:38:05 +0000803 if (const VarDecl *Prev = Var->getPreviousDecl()) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000804 LinkageInfo PrevLV = getLVForDecl(Prev, OnlyTemplate);
John McCallc273f242010-10-30 11:50:40 +0000805 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
806 LV.mergeVisibility(PrevLV);
John McCall457a04e2010-10-22 21:05:15 +0000807 }
808
809 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000810 }
811 }
812
813 // C++ [basic.link]p6:
814 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +0000815 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000816}
Douglas Gregorf73b2822009-11-25 22:24:25 +0000817
Douglas Gregor2ada0482009-02-04 17:27:36 +0000818std::string NamedDecl::getQualifiedNameAsString() const {
Douglas Gregor78254c82012-03-27 23:34:16 +0000819 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
Anders Carlsson2fb08242009-09-08 18:24:21 +0000820}
821
822std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000823 const DeclContext *Ctx = getDeclContext();
824
825 if (Ctx->isFunctionOrMethod())
826 return getNameAsString();
827
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000828 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000829 ContextsTy Contexts;
830
831 // Collect contexts.
832 while (Ctx && isa<NamedDecl>(Ctx)) {
833 Contexts.push_back(Ctx);
834 Ctx = Ctx->getParent();
835 };
836
837 std::string QualName;
838 llvm::raw_string_ostream OS(QualName);
839
840 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
841 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000842 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000843 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Douglas Gregor85673582009-05-18 17:01:57 +0000844 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
845 std::string TemplateArgsStr
846 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +0000847 TemplateArgs.data(),
848 TemplateArgs.size(),
Anders Carlsson2fb08242009-09-08 18:24:21 +0000849 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000850 OS << Spec->getName() << TemplateArgsStr;
851 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +0000852 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000853 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +0000854 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000855 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000856 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
857 if (!RD->getIdentifier())
858 OS << "<anonymous " << RD->getKindName() << '>';
859 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000860 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000861 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +0000862 const FunctionProtoType *FT = 0;
863 if (FD->hasWrittenPrototype())
864 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
865
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000866 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +0000867 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +0000868 unsigned NumParams = FD->getNumParams();
869 for (unsigned i = 0; i < NumParams; ++i) {
870 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000871 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000872 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +0000873 }
874
875 if (FT->isVariadic()) {
876 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000877 OS << ", ";
878 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +0000879 }
880 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000881 OS << ')';
882 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000883 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000884 }
885 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +0000886 }
887
John McCalla2a3f7d2010-03-16 21:48:18 +0000888 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000889 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +0000890 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000891 OS << "<anonymous>";
Douglas Gregor2ada0482009-02-04 17:27:36 +0000892
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000893 return OS.str();
Douglas Gregor2ada0482009-02-04 17:27:36 +0000894}
895
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000896bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000897 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
898
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
900 // We want to keep it, unless it nominates same namespace.
901 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +0000902 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
903 ->getOriginalNamespace() ==
904 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
905 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000906 }
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000908 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
909 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000910 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000911
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000912 // For function templates, the underlying function declarations are linked.
913 if (const FunctionTemplateDecl *FunctionTemplate
914 = dyn_cast<FunctionTemplateDecl>(this))
915 if (const FunctionTemplateDecl *OldFunctionTemplate
916 = dyn_cast<FunctionTemplateDecl>(OldD))
917 return FunctionTemplate->getTemplatedDecl()
918 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000919
Steve Naroffc4173fa2009-02-22 19:35:57 +0000920 // For method declarations, we keep track of redeclarations.
921 if (isa<ObjCMethodDecl>(this))
922 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000923
John McCall9f3059a2009-10-09 21:13:30 +0000924 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
925 return true;
926
John McCall3f746822009-11-17 05:59:44 +0000927 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
928 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
929 cast<UsingShadowDecl>(OldD)->getTargetDecl();
930
Douglas Gregora9d87bc2011-02-25 00:36:19 +0000931 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
932 ASTContext &Context = getASTContext();
933 return Context.getCanonicalNestedNameSpecifier(
934 cast<UsingDecl>(this)->getQualifier()) ==
935 Context.getCanonicalNestedNameSpecifier(
936 cast<UsingDecl>(OldD)->getQualifier());
937 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +0000938
Douglas Gregorb59643b2012-01-03 23:26:26 +0000939 // A typedef of an Objective-C class type can replace an Objective-C class
940 // declaration or definition, and vice versa.
941 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
942 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
943 return true;
944
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000945 // For non-function declarations, if the declarations are of the
946 // same kind then this must be a redeclaration, or semantic analysis
947 // would not have given us the new declaration.
948 return this->getKind() == OldD->getKind();
949}
950
Douglas Gregoreddf4332009-02-24 20:03:32 +0000951bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000952 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +0000953}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000954
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +0000955NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +0000956 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +0000957 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
958 ND = UD->getTargetDecl();
959
960 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
961 return AD->getClassInterface();
962
963 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +0000964}
965
John McCalla8ae2222010-04-06 21:38:20 +0000966bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +0000967 if (!isCXXClassMember())
968 return false;
969
John McCalla8ae2222010-04-06 21:38:20 +0000970 const NamedDecl *D = this;
971 if (isa<UsingShadowDecl>(D))
972 D = cast<UsingShadowDecl>(D)->getTargetDecl();
973
Francois Pichet783dd6e2010-11-21 06:08:52 +0000974 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +0000975 return true;
976 if (isa<CXXMethodDecl>(D))
977 return cast<CXXMethodDecl>(D)->isInstance();
978 if (isa<FunctionTemplateDecl>(D))
979 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
980 ->getTemplatedDecl())->isInstance();
981 return false;
982}
983
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000984//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000985// DeclaratorDecl Implementation
986//===----------------------------------------------------------------------===//
987
Douglas Gregorec9c6ae2010-07-06 18:42:40 +0000988template <typename DeclT>
989static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
990 if (decl->getNumTemplateParameterLists() > 0)
991 return decl->getTemplateParameterList(0)->getTemplateLoc();
992 else
993 return decl->getInnerLocStart();
994}
995
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000996SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +0000997 TypeSourceInfo *TSI = getTypeSourceInfo();
998 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000999 return SourceLocation();
1000}
1001
Douglas Gregor14454802011-02-25 02:25:35 +00001002void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1003 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001004 // Make sure the extended decl info is allocated.
1005 if (!hasExtInfo()) {
1006 // Save (non-extended) type source info pointer.
1007 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1008 // Allocate external info struct.
1009 DeclInfo = new (getASTContext()) ExtInfo;
1010 // Restore savedTInfo into (extended) decl info.
1011 getExtInfo()->TInfo = savedTInfo;
1012 }
1013 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001014 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001015 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001016 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001017 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001018 if (getExtInfo()->NumTemplParamLists == 0) {
1019 // Save type source info pointer.
1020 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1021 // Deallocate the extended decl info.
1022 getASTContext().Deallocate(getExtInfo());
1023 // Restore savedTInfo into (non-extended) decl info.
1024 DeclInfo = savedTInfo;
1025 }
1026 else
1027 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001028 }
1029 }
1030}
1031
Abramo Bagnara60804e12011-03-18 15:16:37 +00001032void
1033DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1034 unsigned NumTPLists,
1035 TemplateParameterList **TPLists) {
1036 assert(NumTPLists > 0);
1037 // Make sure the extended decl info is allocated.
1038 if (!hasExtInfo()) {
1039 // Save (non-extended) type source info pointer.
1040 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1041 // Allocate external info struct.
1042 DeclInfo = new (getASTContext()) ExtInfo;
1043 // Restore savedTInfo into (extended) decl info.
1044 getExtInfo()->TInfo = savedTInfo;
1045 }
1046 // Set the template parameter lists info.
1047 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1048}
1049
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001050SourceLocation DeclaratorDecl::getOuterLocStart() const {
1051 return getTemplateOrInnerLocStart(this);
1052}
1053
Abramo Bagnaraea947882011-03-08 16:41:52 +00001054namespace {
1055
1056// Helper function: returns true if QT is or contains a type
1057// having a postfix component.
1058bool typeIsPostfix(clang::QualType QT) {
1059 while (true) {
1060 const Type* T = QT.getTypePtr();
1061 switch (T->getTypeClass()) {
1062 default:
1063 return false;
1064 case Type::Pointer:
1065 QT = cast<PointerType>(T)->getPointeeType();
1066 break;
1067 case Type::BlockPointer:
1068 QT = cast<BlockPointerType>(T)->getPointeeType();
1069 break;
1070 case Type::MemberPointer:
1071 QT = cast<MemberPointerType>(T)->getPointeeType();
1072 break;
1073 case Type::LValueReference:
1074 case Type::RValueReference:
1075 QT = cast<ReferenceType>(T)->getPointeeType();
1076 break;
1077 case Type::PackExpansion:
1078 QT = cast<PackExpansionType>(T)->getPattern();
1079 break;
1080 case Type::Paren:
1081 case Type::ConstantArray:
1082 case Type::DependentSizedArray:
1083 case Type::IncompleteArray:
1084 case Type::VariableArray:
1085 case Type::FunctionProto:
1086 case Type::FunctionNoProto:
1087 return true;
1088 }
1089 }
1090}
1091
1092} // namespace
1093
1094SourceRange DeclaratorDecl::getSourceRange() const {
1095 SourceLocation RangeEnd = getLocation();
1096 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1097 if (typeIsPostfix(TInfo->getType()))
1098 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1099 }
1100 return SourceRange(getOuterLocStart(), RangeEnd);
1101}
1102
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001103void
Douglas Gregor20527e22010-06-15 17:44:38 +00001104QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1105 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001106 TemplateParameterList **TPLists) {
1107 assert((NumTPLists == 0 || TPLists != 0) &&
1108 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001109
1110 // Free previous template parameters (if any).
1111 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001112 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001113 TemplParamLists = 0;
1114 NumTemplParamLists = 0;
1115 }
1116 // Set info on matched template parameter lists (if any).
1117 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001118 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001119 NumTemplParamLists = NumTPLists;
1120 for (unsigned i = NumTPLists; i-- > 0; )
1121 TemplParamLists[i] = TPLists[i];
1122 }
1123}
1124
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001125//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001126// VarDecl Implementation
1127//===----------------------------------------------------------------------===//
1128
Sebastian Redl833ef452010-01-26 22:01:41 +00001129const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1130 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001131 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001132 case SC_Auto: return "auto";
1133 case SC_Extern: return "extern";
1134 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1135 case SC_PrivateExtern: return "__private_extern__";
1136 case SC_Register: return "register";
1137 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001138 }
1139
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001140 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001141}
1142
Abramo Bagnaradff19302011-03-08 08:55:46 +00001143VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1144 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001145 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001146 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001147 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes394ec982008-12-17 23:39:55 +00001148}
1149
Douglas Gregor72172e92012-01-05 21:55:30 +00001150VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1151 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1152 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1153 QualType(), 0, SC_None, SC_None);
1154}
1155
Douglas Gregorbf62d642010-12-06 18:36:25 +00001156void VarDecl::setStorageClass(StorageClass SC) {
1157 assert(isLegalForVariable(SC));
1158 if (getStorageClass() != SC)
1159 ClearLinkageCache();
1160
John McCallbeaa11c2011-05-01 02:13:58 +00001161 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001162}
1163
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001164SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001165 if (getInit())
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001166 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00001167 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001168}
1169
Sebastian Redl833ef452010-01-26 22:01:41 +00001170bool VarDecl::isExternC() const {
Eli Friedman839192f2012-01-15 01:23:58 +00001171 if (getLinkage() != ExternalLinkage)
Chandler Carruth4322a282011-02-25 00:05:02 +00001172 return false;
1173
Eli Friedman839192f2012-01-15 01:23:58 +00001174 const DeclContext *DC = getDeclContext();
1175 if (DC->isRecord())
1176 return false;
Sebastian Redl833ef452010-01-26 22:01:41 +00001177
Eli Friedman839192f2012-01-15 01:23:58 +00001178 ASTContext &Context = getASTContext();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001179 if (!Context.getLangOpts().CPlusPlus)
Eli Friedman839192f2012-01-15 01:23:58 +00001180 return true;
1181 return DC->isExternCContext();
Sebastian Redl833ef452010-01-26 22:01:41 +00001182}
1183
1184VarDecl *VarDecl::getCanonicalDecl() {
1185 return getFirstDeclaration();
1186}
1187
Daniel Dunbar9d355812012-03-09 01:51:51 +00001188VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1189 ASTContext &C) const
1190{
Sebastian Redl35351a92010-01-31 22:27:38 +00001191 // C++ [basic.def]p2:
1192 // A declaration is a definition unless [...] it contains the 'extern'
1193 // specifier or a linkage-specification and neither an initializer [...],
1194 // it declares a static data member in a class declaration [...].
1195 // C++ [temp.expl.spec]p15:
1196 // An explicit specialization of a static data member of a template is a
1197 // definition if the declaration includes an initializer; otherwise, it is
1198 // a declaration.
1199 if (isStaticDataMember()) {
1200 if (isOutOfLine() && (hasInit() ||
1201 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1202 return Definition;
1203 else
1204 return DeclarationOnly;
1205 }
1206 // C99 6.7p5:
1207 // A definition of an identifier is a declaration for that identifier that
1208 // [...] causes storage to be reserved for that object.
1209 // Note: that applies for all non-file-scope objects.
1210 // C99 6.9.2p1:
1211 // If the declaration of an identifier for an object has file scope and an
1212 // initializer, the declaration is an external definition for the identifier
1213 if (hasInit())
1214 return Definition;
1215 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1216 if (hasExternalStorage())
1217 return DeclarationOnly;
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001218
John McCall8e7d6562010-08-26 03:08:43 +00001219 if (getStorageClassAsWritten() == SC_Extern ||
1220 getStorageClassAsWritten() == SC_PrivateExtern) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00001221 for (const VarDecl *PrevVar = getPreviousDecl();
1222 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001223 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1224 return DeclarationOnly;
1225 }
1226 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001227 // C99 6.9.2p2:
1228 // A declaration of an object that has file scope without an initializer,
1229 // and without a storage class specifier or the scs 'static', constitutes
1230 // a tentative definition.
1231 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001232 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001233 return TentativeDefinition;
1234
1235 // What's left is (in C, block-scope) declarations without initializers or
1236 // external storage. These are definitions.
1237 return Definition;
1238}
1239
Sebastian Redl35351a92010-01-31 22:27:38 +00001240VarDecl *VarDecl::getActingDefinition() {
1241 DefinitionKind Kind = isThisDeclarationADefinition();
1242 if (Kind != TentativeDefinition)
1243 return 0;
1244
Chris Lattner48eb14d2010-06-14 18:31:46 +00001245 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001246 VarDecl *First = getFirstDeclaration();
1247 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1248 I != E; ++I) {
1249 Kind = (*I)->isThisDeclarationADefinition();
1250 if (Kind == Definition)
1251 return 0;
1252 else if (Kind == TentativeDefinition)
1253 LastTentative = *I;
1254 }
1255 return LastTentative;
1256}
1257
1258bool VarDecl::isTentativeDefinitionNow() const {
1259 DefinitionKind Kind = isThisDeclarationADefinition();
1260 if (Kind != TentativeDefinition)
1261 return false;
1262
1263 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1264 if ((*I)->isThisDeclarationADefinition() == Definition)
1265 return false;
1266 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001267 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001268}
1269
Daniel Dunbar9d355812012-03-09 01:51:51 +00001270VarDecl *VarDecl::getDefinition(ASTContext &C) {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001271 VarDecl *First = getFirstDeclaration();
1272 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1273 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001274 if ((*I)->isThisDeclarationADefinition(C) == Definition)
Sebastian Redl5ca79842010-02-01 20:16:42 +00001275 return *I;
1276 }
1277 return 0;
1278}
1279
Daniel Dunbar9d355812012-03-09 01:51:51 +00001280VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001281 DefinitionKind Kind = DeclarationOnly;
1282
1283 const VarDecl *First = getFirstDeclaration();
1284 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001285 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001286 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001287 if (Kind == Definition)
1288 break;
1289 }
John McCall37bb6c92010-10-29 22:22:43 +00001290
1291 return Kind;
1292}
1293
Sebastian Redl5ca79842010-02-01 20:16:42 +00001294const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001295 redecl_iterator I = redecls_begin(), E = redecls_end();
1296 while (I != E && !I->getInit())
1297 ++I;
1298
1299 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001300 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001301 return I->getInit();
1302 }
1303 return 0;
1304}
1305
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001306bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001307 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001308 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001309
1310 if (!isStaticDataMember())
1311 return false;
1312
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001313 // If this static data member was instantiated from a static data member of
1314 // a class template, check whether that static data member was defined
1315 // out-of-line.
1316 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1317 return VD->isOutOfLine();
1318
1319 return false;
1320}
1321
Douglas Gregor1d957a32009-10-27 18:42:08 +00001322VarDecl *VarDecl::getOutOfLineDefinition() {
1323 if (!isStaticDataMember())
1324 return 0;
1325
1326 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1327 RD != RDEnd; ++RD) {
1328 if (RD->getLexicalDeclContext()->isFileContext())
1329 return *RD;
1330 }
1331
1332 return 0;
1333}
1334
Douglas Gregord5058122010-02-11 01:19:42 +00001335void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001336 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1337 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001338 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001339 }
1340
1341 Init = I;
1342}
1343
Daniel Dunbar9d355812012-03-09 01:51:51 +00001344bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001345 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001346
Richard Smith35ecb362012-03-02 04:14:40 +00001347 if (!Lang.CPlusPlus)
1348 return false;
1349
1350 // In C++11, any variable of reference type can be used in a constant
1351 // expression if it is initialized by a constant expression.
1352 if (Lang.CPlusPlus0x && getType()->isReferenceType())
1353 return true;
1354
1355 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001356 // not require the variable to be non-volatile, but we consider this to be a
1357 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001358 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001359 return false;
1360
1361 // In C++, const, non-volatile variables of integral or enumeration types
1362 // can be used in constant expressions.
1363 if (getType()->isIntegralOrEnumerationType())
1364 return true;
1365
Richard Smith35ecb362012-03-02 04:14:40 +00001366 // Additionally, in C++11, non-volatile constexpr variables can be used in
1367 // constant expressions.
1368 return Lang.CPlusPlus0x && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001369}
1370
Richard Smithd0b4dd62011-12-19 06:19:21 +00001371/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1372/// form, which contains extra information on the evaluated value of the
1373/// initializer.
1374EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1375 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1376 if (!Eval) {
1377 Stmt *S = Init.get<Stmt *>();
1378 Eval = new (getASTContext()) EvaluatedStmt;
1379 Eval->Value = S;
1380 Init = Eval;
1381 }
1382 return Eval;
1383}
1384
Richard Smithdafff942012-01-14 04:30:29 +00001385APValue *VarDecl::evaluateValue() const {
1386 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1387 return evaluateValue(Notes);
1388}
1389
1390APValue *VarDecl::evaluateValue(
1391 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001392 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1393
1394 // We only produce notes indicating why an initializer is non-constant the
1395 // first time it is evaluated. FIXME: The notes won't always be emitted the
1396 // first time we try evaluation, so might not be produced at all.
1397 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001398 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001399
1400 const Expr *Init = cast<Expr>(Eval->Value);
1401 assert(!Init->isValueDependent());
1402
1403 if (Eval->IsEvaluating) {
1404 // FIXME: Produce a diagnostic for self-initialization.
1405 Eval->CheckedICE = true;
1406 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001407 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001408 }
1409
1410 Eval->IsEvaluating = true;
1411
1412 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1413 this, Notes);
1414
1415 // Ensure the result is an uninitialized APValue if evaluation fails.
1416 if (!Result)
1417 Eval->Evaluated = APValue();
1418
1419 Eval->IsEvaluating = false;
1420 Eval->WasEvaluated = true;
1421
1422 // In C++11, we have determined whether the initializer was a constant
1423 // expression as a side-effect.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001424 if (getASTContext().getLangOpts().CPlusPlus0x && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001425 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001426 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001427 }
1428
Richard Smithdafff942012-01-14 04:30:29 +00001429 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001430}
1431
1432bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001433 // Initializers of weak variables are never ICEs.
1434 if (isWeak())
1435 return false;
1436
Richard Smithd0b4dd62011-12-19 06:19:21 +00001437 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1438 if (Eval->CheckedICE)
1439 // We have already checked whether this subexpression is an
1440 // integral constant expression.
1441 return Eval->IsICE;
1442
1443 const Expr *Init = cast<Expr>(Eval->Value);
1444 assert(!Init->isValueDependent());
1445
1446 // In C++11, evaluate the initializer to check whether it's a constant
1447 // expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001448 if (getASTContext().getLangOpts().CPlusPlus0x) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001449 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1450 evaluateValue(Notes);
1451 return Eval->IsICE;
1452 }
1453
1454 // It's an ICE whether or not the definition we found is
1455 // out-of-line. See DR 721 and the discussion in Clang PR
1456 // 6206 for details.
1457
1458 if (Eval->CheckingICE)
1459 return false;
1460 Eval->CheckingICE = true;
1461
1462 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1463 Eval->CheckingICE = false;
1464 Eval->CheckedICE = true;
1465 return Eval->IsICE;
1466}
1467
Douglas Gregorfe314812011-06-21 17:03:29 +00001468bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001469 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001470
1471 const Expr *E = getInit();
1472 if (!E)
1473 return false;
1474
1475 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1476 E = Cleanups->getSubExpr();
1477
1478 return isa<MaterializeTemporaryExpr>(E);
1479}
1480
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001481VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001482 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001483 return cast<VarDecl>(MSI->getInstantiatedFrom());
1484
1485 return 0;
1486}
1487
Douglas Gregor3c74d412009-10-14 20:14:33 +00001488TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001489 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001490 return MSI->getTemplateSpecializationKind();
1491
1492 return TSK_Undeclared;
1493}
1494
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001495MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001496 return getASTContext().getInstantiatedFromStaticDataMember(this);
1497}
1498
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001499void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1500 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001501 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001502 assert(MSI && "Not an instantiated static data member?");
1503 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001504 if (TSK != TSK_ExplicitSpecialization &&
1505 PointOfInstantiation.isValid() &&
1506 MSI->getPointOfInstantiation().isInvalid())
1507 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001508}
1509
Sebastian Redl833ef452010-01-26 22:01:41 +00001510//===----------------------------------------------------------------------===//
1511// ParmVarDecl Implementation
1512//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001513
Sebastian Redl833ef452010-01-26 22:01:41 +00001514ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001515 SourceLocation StartLoc,
1516 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001517 QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001518 StorageClass S, StorageClass SCAsWritten,
1519 Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001520 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001521 S, SCAsWritten, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001522}
1523
Douglas Gregor72172e92012-01-05 21:55:30 +00001524ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1525 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1526 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1527 0, QualType(), 0, SC_None, SC_None, 0);
1528}
1529
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001530SourceRange ParmVarDecl::getSourceRange() const {
1531 if (!hasInheritedDefaultArg()) {
1532 SourceRange ArgRange = getDefaultArgRange();
1533 if (ArgRange.isValid())
1534 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1535 }
1536
1537 return DeclaratorDecl::getSourceRange();
1538}
1539
Sebastian Redl833ef452010-01-26 22:01:41 +00001540Expr *ParmVarDecl::getDefaultArg() {
1541 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1542 assert(!hasUninstantiatedDefaultArg() &&
1543 "Default argument is not yet instantiated!");
1544
1545 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001546 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001547 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001548
Sebastian Redl833ef452010-01-26 22:01:41 +00001549 return Arg;
1550}
1551
Sebastian Redl833ef452010-01-26 22:01:41 +00001552SourceRange ParmVarDecl::getDefaultArgRange() const {
1553 if (const Expr *E = getInit())
1554 return E->getSourceRange();
1555
1556 if (hasUninstantiatedDefaultArg())
1557 return getUninstantiatedDefaultArg()->getSourceRange();
1558
1559 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001560}
1561
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001562bool ParmVarDecl::isParameterPack() const {
1563 return isa<PackExpansionType>(getType());
1564}
1565
Ted Kremenek540017e2011-10-06 05:00:56 +00001566void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1567 getASTContext().setParameterIndex(this, parameterIndex);
1568 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1569}
1570
1571unsigned ParmVarDecl::getParameterIndexLarge() const {
1572 return getASTContext().getParameterIndex(this);
1573}
1574
Nuno Lopes394ec982008-12-17 23:39:55 +00001575//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001576// FunctionDecl Implementation
1577//===----------------------------------------------------------------------===//
1578
Douglas Gregorb11aad82011-02-19 18:51:44 +00001579void FunctionDecl::getNameForDiagnostic(std::string &S,
1580 const PrintingPolicy &Policy,
1581 bool Qualified) const {
1582 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1583 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1584 if (TemplateArgs)
1585 S += TemplateSpecializationType::PrintTemplateArgumentList(
1586 TemplateArgs->data(),
1587 TemplateArgs->size(),
1588 Policy);
1589
1590}
1591
Ted Kremenek186a0742010-04-29 16:49:01 +00001592bool FunctionDecl::isVariadic() const {
1593 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1594 return FT->isVariadic();
1595 return false;
1596}
1597
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001598bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1599 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001600 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001601 Definition = *I;
1602 return true;
1603 }
1604 }
1605
1606 return false;
1607}
1608
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001609bool FunctionDecl::hasTrivialBody() const
1610{
1611 Stmt *S = getBody();
1612 if (!S) {
1613 // Since we don't have a body for this function, we don't know if it's
1614 // trivial or not.
1615 return false;
1616 }
1617
1618 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1619 return true;
1620 return false;
1621}
1622
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001623bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1624 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001625 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001626 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1627 return true;
1628 }
1629 }
1630
1631 return false;
1632}
1633
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001634Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00001635 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1636 if (I->Body) {
1637 Definition = *I;
1638 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00001639 } else if (I->IsLateTemplateParsed) {
1640 Definition = *I;
1641 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00001642 }
1643 }
1644
1645 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001646}
1647
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001648void FunctionDecl::setBody(Stmt *B) {
1649 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00001650 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001651 EndRangeLoc = B->getLocEnd();
1652}
1653
Douglas Gregor7d9120c2010-09-28 21:55:22 +00001654void FunctionDecl::setPure(bool P) {
1655 IsPure = P;
1656 if (P)
1657 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1658 Parent->markedVirtualFunctionPure();
1659}
1660
Douglas Gregor16618f22009-09-12 00:17:51 +00001661bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00001662 const TranslationUnitDecl *tunit =
1663 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1664 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001665 !tunit->getASTContext().getLangOpts().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00001666 getIdentifier() &&
1667 getIdentifier()->isStr("main");
1668}
1669
1670bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1671 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1672 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1673 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1674 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1675 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1676
1677 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1678 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1679
1680 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1681 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1682
1683 ASTContext &Context =
1684 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1685 ->getASTContext();
1686
1687 // The result type and first argument type are constant across all
1688 // these operators. The second argument must be exactly void*.
1689 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001690}
1691
Douglas Gregor16618f22009-09-12 00:17:51 +00001692bool FunctionDecl::isExternC() const {
Eli Friedman839192f2012-01-15 01:23:58 +00001693 if (getLinkage() != ExternalLinkage)
1694 return false;
1695
1696 if (getAttr<OverloadableAttr>())
1697 return false;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001698
Chandler Carruth4322a282011-02-25 00:05:02 +00001699 const DeclContext *DC = getDeclContext();
1700 if (DC->isRecord())
1701 return false;
1702
Eli Friedman839192f2012-01-15 01:23:58 +00001703 ASTContext &Context = getASTContext();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001704 if (!Context.getLangOpts().CPlusPlus)
Eli Friedman839192f2012-01-15 01:23:58 +00001705 return true;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001706
Eli Friedman839192f2012-01-15 01:23:58 +00001707 return isMain() || DC->isExternCContext();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001708}
1709
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001710bool FunctionDecl::isGlobal() const {
1711 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1712 return Method->isStatic();
1713
John McCall8e7d6562010-08-26 03:08:43 +00001714 if (getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001715 return false;
1716
Mike Stump11289f42009-09-09 15:08:12 +00001717 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001718 DC->isNamespace();
1719 DC = DC->getParent()) {
1720 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1721 if (!Namespace->getDeclName())
1722 return false;
1723 break;
1724 }
1725 }
1726
1727 return true;
1728}
1729
Sebastian Redl833ef452010-01-26 22:01:41 +00001730void
1731FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1732 redeclarable_base::setPreviousDeclaration(PrevDecl);
1733
1734 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1735 FunctionTemplateDecl *PrevFunTmpl
1736 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1737 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1738 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1739 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00001740
Axel Naumannfbc7b982011-11-08 18:21:06 +00001741 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00001742 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00001743}
1744
1745const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1746 return getFirstDeclaration();
1747}
1748
1749FunctionDecl *FunctionDecl::getCanonicalDecl() {
1750 return getFirstDeclaration();
1751}
1752
Douglas Gregorbf62d642010-12-06 18:36:25 +00001753void FunctionDecl::setStorageClass(StorageClass SC) {
1754 assert(isLegalForFunction(SC));
1755 if (getStorageClass() != SC)
1756 ClearLinkageCache();
1757
1758 SClass = SC;
1759}
1760
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001761/// \brief Returns a value indicating whether this function
1762/// corresponds to a builtin function.
1763///
1764/// The function corresponds to a built-in function if it is
1765/// declared at translation scope or within an extern "C" block and
1766/// its name matches with the name of a builtin. The returned value
1767/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00001768/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001769/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001770unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00001771 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00001772 return 0;
1773
1774 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00001775 if (!BuiltinID)
1776 return 0;
1777
1778 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00001779 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1780 return BuiltinID;
1781
1782 // This function has the name of a known C library
1783 // function. Determine whether it actually refers to the C library
1784 // function or whether it just has the same name.
1785
Douglas Gregora908e7f2009-02-17 03:23:10 +00001786 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00001787 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00001788 return 0;
1789
Douglas Gregore711f702009-02-14 18:57:46 +00001790 // If this function is at translation-unit scope and we're not in
1791 // C++, it refers to the C library function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001792 if (!Context.getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00001793 getDeclContext()->isTranslationUnit())
1794 return BuiltinID;
1795
1796 // If the function is in an extern "C" linkage specification and is
1797 // not marked "overloadable", it's the real function.
1798 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001799 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00001800 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001801 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00001802 return BuiltinID;
1803
1804 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001805 return 0;
1806}
1807
1808
Chris Lattner47c0d002009-04-25 06:03:53 +00001809/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00001810/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00001811/// after it has been created.
1812unsigned FunctionDecl::getNumParams() const {
John McCall9dd450b2009-09-21 23:43:11 +00001813 const FunctionType *FT = getType()->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001814 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00001815 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001816 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00001817
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001818}
1819
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00001820void FunctionDecl::setParams(ASTContext &C,
David Blaikie9c70e042011-09-21 18:16:56 +00001821 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001822 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00001823 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00001824
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00001825 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00001826 if (!NewParamInfo.empty()) {
1827 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1828 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00001829 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001830}
Chris Lattner41943152007-01-25 04:52:46 +00001831
James Molloy6f8780b2012-02-29 10:24:19 +00001832void FunctionDecl::setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls) {
1833 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
1834
1835 if (!NewDecls.empty()) {
1836 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
1837 std::copy(NewDecls.begin(), NewDecls.end(), A);
1838 DeclsInPrototypeScope = llvm::ArrayRef<NamedDecl*>(A, NewDecls.size());
1839 }
1840}
1841
Chris Lattner58258242008-04-10 02:22:51 +00001842/// getMinRequiredArguments - Returns the minimum number of arguments
1843/// needed to call this function. This may be fewer than the number of
1844/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00001845/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00001846unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001847 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00001848 return getNumParams();
1849
Douglas Gregor7825bf32011-01-06 22:09:01 +00001850 unsigned NumRequiredArgs = getNumParams();
1851
1852 // If the last parameter is a parameter pack, we don't need an argument for
1853 // it.
1854 if (NumRequiredArgs > 0 &&
1855 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1856 --NumRequiredArgs;
1857
1858 // If this parameter has a default argument, we don't need an argument for
1859 // it.
1860 while (NumRequiredArgs > 0 &&
1861 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00001862 --NumRequiredArgs;
1863
Douglas Gregor0dd423e2011-01-11 01:52:23 +00001864 // We might have parameter packs before the end. These can't be deduced,
1865 // but they can still handle multiple arguments.
1866 unsigned ArgIdx = NumRequiredArgs;
1867 while (ArgIdx > 0) {
1868 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1869 NumRequiredArgs = ArgIdx;
1870
1871 --ArgIdx;
1872 }
1873
Chris Lattner58258242008-04-10 02:22:51 +00001874 return NumRequiredArgs;
1875}
1876
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001877bool FunctionDecl::isInlined() const {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001878 if (IsInline)
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001879 return true;
Anders Carlssoncfb65d72009-12-04 22:35:50 +00001880
1881 if (isa<CXXMethodDecl>(this)) {
1882 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1883 return true;
1884 }
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001885
1886 switch (getTemplateSpecializationKind()) {
1887 case TSK_Undeclared:
1888 case TSK_ExplicitSpecialization:
1889 return false;
1890
1891 case TSK_ImplicitInstantiation:
1892 case TSK_ExplicitInstantiationDeclaration:
1893 case TSK_ExplicitInstantiationDefinition:
1894 // Handle below.
1895 break;
1896 }
1897
1898 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001899 bool HasPattern = false;
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001900 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001901 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001902
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001903 if (HasPattern && PatternDecl)
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001904 return PatternDecl->isInlined();
1905
1906 return false;
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001907}
1908
Eli Friedman1b125c32012-02-07 03:50:18 +00001909static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
1910 // Only consider file-scope declarations in this test.
1911 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1912 return false;
1913
1914 // Only consider explicit declarations; the presence of a builtin for a
1915 // libcall shouldn't affect whether a definition is externally visible.
1916 if (Redecl->isImplicit())
1917 return false;
1918
1919 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
1920 return true; // Not an inline definition
1921
1922 return false;
1923}
1924
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001925/// \brief For a function declaration in C or C++, determine whether this
1926/// declaration causes the definition to be externally visible.
1927///
Eli Friedman1b125c32012-02-07 03:50:18 +00001928/// Specifically, this determines if adding the current declaration to the set
1929/// of redeclarations of the given functions causes
1930/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001931bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1932 assert(!doesThisDeclarationHaveABody() &&
1933 "Must have a declaration without a body.");
1934
1935 ASTContext &Context = getASTContext();
1936
David Blaikiebbafb8a2012-03-11 07:00:24 +00001937 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00001938 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
1939 // an externally visible definition.
1940 //
1941 // FIXME: What happens if gnu_inline gets added on after the first
1942 // declaration?
1943 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
1944 return false;
1945
1946 const FunctionDecl *Prev = this;
1947 bool FoundBody = false;
1948 while ((Prev = Prev->getPreviousDecl())) {
1949 FoundBody |= Prev->Body;
1950
1951 if (Prev->Body) {
1952 // If it's not the case that both 'inline' and 'extern' are
1953 // specified on the definition, then it is always externally visible.
1954 if (!Prev->isInlineSpecified() ||
1955 Prev->getStorageClassAsWritten() != SC_Extern)
1956 return false;
1957 } else if (Prev->isInlineSpecified() &&
1958 Prev->getStorageClassAsWritten() != SC_Extern) {
1959 return false;
1960 }
1961 }
1962 return FoundBody;
1963 }
1964
David Blaikiebbafb8a2012-03-11 07:00:24 +00001965 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001966 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00001967
1968 // C99 6.7.4p6:
1969 // [...] If all of the file scope declarations for a function in a
1970 // translation unit include the inline function specifier without extern,
1971 // then the definition in that translation unit is an inline definition.
1972 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001973 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00001974 const FunctionDecl *Prev = this;
1975 bool FoundBody = false;
1976 while ((Prev = Prev->getPreviousDecl())) {
1977 FoundBody |= Prev->Body;
1978 if (RedeclForcesDefC99(Prev))
1979 return false;
1980 }
1981 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001982}
1983
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001984/// \brief For an inline function definition in C or C++, determine whether the
Douglas Gregor299d76e2009-09-13 07:46:26 +00001985/// definition will be externally visible.
1986///
1987/// Inline function definitions are always available for inlining optimizations.
1988/// However, depending on the language dialect, declaration specifiers, and
1989/// attributes, the definition of an inline function may or may not be
1990/// "externally" visible to other translation units in the program.
1991///
1992/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00001993/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00001994/// inline definition becomes externally visible (C99 6.7.4p6).
1995///
1996/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1997/// definition, we use the GNU semantics for inline, which are nearly the
1998/// opposite of C99 semantics. In particular, "inline" by itself will create
1999/// an externally visible symbol, but "extern inline" will not create an
2000/// externally visible symbol.
2001bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002002 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002003 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002004 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002005
David Blaikiebbafb8a2012-03-11 07:00:24 +00002006 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002007 // Note: If you change the logic here, please change
2008 // doesDeclarationForceExternallyVisibleDefinition as well.
2009 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002010 // If it's not the case that both 'inline' and 'extern' are
2011 // specified on the definition, then this inline definition is
2012 // externally visible.
2013 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2014 return true;
2015
2016 // If any declaration is 'inline' but not 'extern', then this definition
2017 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002018 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2019 Redecl != RedeclEnd;
2020 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002021 if (Redecl->isInlineSpecified() &&
2022 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002023 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002024 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002025
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002026 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002027 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002028
Douglas Gregor299d76e2009-09-13 07:46:26 +00002029 // C99 6.7.4p6:
2030 // [...] If all of the file scope declarations for a function in a
2031 // translation unit include the inline function specifier without extern,
2032 // then the definition in that translation unit is an inline definition.
2033 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2034 Redecl != RedeclEnd;
2035 ++Redecl) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002036 if (RedeclForcesDefC99(*Redecl))
2037 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002038 }
2039
2040 // C99 6.7.4p6:
2041 // An inline definition does not provide an external definition for the
2042 // function, and does not forbid an external definition in another
2043 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002044 return false;
2045}
2046
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002047/// getOverloadedOperator - Which C++ overloaded operator this
2048/// function represents, if any.
2049OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002050 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2051 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002052 else
2053 return OO_None;
2054}
2055
Alexis Huntc88db062010-01-13 09:01:02 +00002056/// getLiteralIdentifier - The literal suffix identifier this function
2057/// represents, if any.
2058const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2059 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2060 return getDeclName().getCXXLiteralIdentifier();
2061 else
2062 return 0;
2063}
2064
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002065FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2066 if (TemplateOrSpecialization.isNull())
2067 return TK_NonTemplate;
2068 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2069 return TK_FunctionTemplate;
2070 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2071 return TK_MemberSpecialization;
2072 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2073 return TK_FunctionTemplateSpecialization;
2074 if (TemplateOrSpecialization.is
2075 <DependentFunctionTemplateSpecializationInfo*>())
2076 return TK_DependentFunctionTemplateSpecialization;
2077
David Blaikie83d382b2011-09-23 05:06:16 +00002078 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002079}
2080
Douglas Gregord801b062009-10-07 23:56:10 +00002081FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002082 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002083 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2084
2085 return 0;
2086}
2087
Douglas Gregor06db9f52009-10-12 20:18:28 +00002088MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2089 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2090}
2091
Douglas Gregord801b062009-10-07 23:56:10 +00002092void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002093FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2094 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002095 TemplateSpecializationKind TSK) {
2096 assert(TemplateOrSpecialization.isNull() &&
2097 "Member function is already a specialization");
2098 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002099 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002100 TemplateOrSpecialization = Info;
2101}
2102
Douglas Gregorafca3b42009-10-27 20:53:28 +00002103bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002104 // If the function is invalid, it can't be implicitly instantiated.
2105 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002106 return false;
2107
2108 switch (getTemplateSpecializationKind()) {
2109 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002110 case TSK_ExplicitInstantiationDefinition:
2111 return false;
2112
2113 case TSK_ImplicitInstantiation:
2114 return true;
2115
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002116 // It is possible to instantiate TSK_ExplicitSpecialization kind
2117 // if the FunctionDecl has a class scope specialization pattern.
2118 case TSK_ExplicitSpecialization:
2119 return getClassScopeSpecializationPattern() != 0;
2120
Douglas Gregorafca3b42009-10-27 20:53:28 +00002121 case TSK_ExplicitInstantiationDeclaration:
2122 // Handled below.
2123 break;
2124 }
2125
2126 // Find the actual template from which we will instantiate.
2127 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002128 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002129 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002130 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002131
2132 // C++0x [temp.explicit]p9:
2133 // Except for inline functions, other explicit instantiation declarations
2134 // have the effect of suppressing the implicit instantiation of the entity
2135 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002136 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002137 return true;
2138
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002139 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002140}
2141
2142bool FunctionDecl::isTemplateInstantiation() const {
2143 switch (getTemplateSpecializationKind()) {
2144 case TSK_Undeclared:
2145 case TSK_ExplicitSpecialization:
2146 return false;
2147 case TSK_ImplicitInstantiation:
2148 case TSK_ExplicitInstantiationDeclaration:
2149 case TSK_ExplicitInstantiationDefinition:
2150 return true;
2151 }
2152 llvm_unreachable("All TSK values handled.");
2153}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002154
2155FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002156 // Handle class scope explicit specialization special case.
2157 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2158 return getClassScopeSpecializationPattern();
2159
Douglas Gregorafca3b42009-10-27 20:53:28 +00002160 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2161 while (Primary->getInstantiatedFromMemberTemplate()) {
2162 // If we have hit a point where the user provided a specialization of
2163 // this template, we're done looking.
2164 if (Primary->isMemberSpecialization())
2165 break;
2166
2167 Primary = Primary->getInstantiatedFromMemberTemplate();
2168 }
2169
2170 return Primary->getTemplatedDecl();
2171 }
2172
2173 return getInstantiatedFromMemberFunction();
2174}
2175
Douglas Gregor70d83e22009-06-29 17:30:29 +00002176FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002177 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002178 = TemplateOrSpecialization
2179 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002180 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002181 }
2182 return 0;
2183}
2184
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002185FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2186 return getASTContext().getClassScopeSpecializationPattern(this);
2187}
2188
Douglas Gregor70d83e22009-06-29 17:30:29 +00002189const TemplateArgumentList *
2190FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002191 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002192 = TemplateOrSpecialization
2193 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002194 return Info->TemplateArguments;
2195 }
2196 return 0;
2197}
2198
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002199const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002200FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2201 if (FunctionTemplateSpecializationInfo *Info
2202 = TemplateOrSpecialization
2203 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2204 return Info->TemplateArgumentsAsWritten;
2205 }
2206 return 0;
2207}
2208
Mike Stump11289f42009-09-09 15:08:12 +00002209void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002210FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2211 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002212 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002213 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002214 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002215 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2216 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002217 assert(TSK != TSK_Undeclared &&
2218 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002219 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002220 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002221 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002222 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2223 TemplateArgs,
2224 TemplateArgsAsWritten,
2225 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002226 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002227 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002228}
2229
John McCallb9c78482010-04-08 09:05:18 +00002230void
2231FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2232 const UnresolvedSetImpl &Templates,
2233 const TemplateArgumentListInfo &TemplateArgs) {
2234 assert(TemplateOrSpecialization.isNull());
2235 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2236 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002237 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002238 void *Buffer = Context.Allocate(Size);
2239 DependentFunctionTemplateSpecializationInfo *Info =
2240 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2241 TemplateArgs);
2242 TemplateOrSpecialization = Info;
2243}
2244
2245DependentFunctionTemplateSpecializationInfo::
2246DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2247 const TemplateArgumentListInfo &TArgs)
2248 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2249
2250 d.NumTemplates = Ts.size();
2251 d.NumArgs = TArgs.size();
2252
2253 FunctionTemplateDecl **TsArray =
2254 const_cast<FunctionTemplateDecl**>(getTemplates());
2255 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2256 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2257
2258 TemplateArgumentLoc *ArgsArray =
2259 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2260 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2261 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2262}
2263
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002264TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002265 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002266 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002267 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002268 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002269 if (FTSInfo)
2270 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002271
Douglas Gregord801b062009-10-07 23:56:10 +00002272 MemberSpecializationInfo *MSInfo
2273 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2274 if (MSInfo)
2275 return MSInfo->getTemplateSpecializationKind();
2276
2277 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002278}
2279
Mike Stump11289f42009-09-09 15:08:12 +00002280void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002281FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2282 SourceLocation PointOfInstantiation) {
2283 if (FunctionTemplateSpecializationInfo *FTSInfo
2284 = TemplateOrSpecialization.dyn_cast<
2285 FunctionTemplateSpecializationInfo*>()) {
2286 FTSInfo->setTemplateSpecializationKind(TSK);
2287 if (TSK != TSK_ExplicitSpecialization &&
2288 PointOfInstantiation.isValid() &&
2289 FTSInfo->getPointOfInstantiation().isInvalid())
2290 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2291 } else if (MemberSpecializationInfo *MSInfo
2292 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2293 MSInfo->setTemplateSpecializationKind(TSK);
2294 if (TSK != TSK_ExplicitSpecialization &&
2295 PointOfInstantiation.isValid() &&
2296 MSInfo->getPointOfInstantiation().isInvalid())
2297 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2298 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002299 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002300}
2301
2302SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002303 if (FunctionTemplateSpecializationInfo *FTSInfo
2304 = TemplateOrSpecialization.dyn_cast<
2305 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002306 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002307 else if (MemberSpecializationInfo *MSInfo
2308 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002309 return MSInfo->getPointOfInstantiation();
2310
2311 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002312}
2313
Douglas Gregor6411b922009-09-11 20:15:17 +00002314bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002315 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002316 return true;
2317
2318 // If this function was instantiated from a member function of a
2319 // class template, check whether that member function was defined out-of-line.
2320 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2321 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002322 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002323 return Definition->isOutOfLine();
2324 }
2325
2326 // If this function was instantiated from a function template,
2327 // check whether that function template was defined out-of-line.
2328 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2329 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002330 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002331 return Definition->isOutOfLine();
2332 }
2333
2334 return false;
2335}
2336
Abramo Bagnaraea947882011-03-08 16:41:52 +00002337SourceRange FunctionDecl::getSourceRange() const {
2338 return SourceRange(getOuterLocStart(), EndRangeLoc);
2339}
2340
Anna Zaks28db7ce2012-01-18 02:45:01 +00002341unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002342 IdentifierInfo *FnInfo = getIdentifier();
2343
2344 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002345 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002346
2347 // Builtin handling.
2348 switch (getBuiltinID()) {
2349 case Builtin::BI__builtin_memset:
2350 case Builtin::BI__builtin___memset_chk:
2351 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00002352 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002353
2354 case Builtin::BI__builtin_memcpy:
2355 case Builtin::BI__builtin___memcpy_chk:
2356 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002357 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002358
2359 case Builtin::BI__builtin_memmove:
2360 case Builtin::BI__builtin___memmove_chk:
2361 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00002362 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002363
2364 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002365 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002366 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00002367 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00002368
2369 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00002370 case Builtin::BImemcmp:
2371 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002372
2373 case Builtin::BI__builtin_strncpy:
2374 case Builtin::BI__builtin___strncpy_chk:
2375 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00002376 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002377
2378 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00002379 case Builtin::BIstrncmp:
2380 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002381
2382 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00002383 case Builtin::BIstrncasecmp:
2384 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002385
2386 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00002387 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00002388 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00002389 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002390
2391 case Builtin::BI__builtin_strndup:
2392 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00002393 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00002394
Anna Zaks314cd092012-02-01 19:08:57 +00002395 case Builtin::BI__builtin_strlen:
2396 case Builtin::BIstrlen:
2397 return Builtin::BIstrlen;
2398
Anna Zaks201d4892012-01-13 21:52:01 +00002399 default:
Eli Friedman839192f2012-01-15 01:23:58 +00002400 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00002401 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00002402 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002403 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002404 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002405 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00002406 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002407 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002408 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002409 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002410 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002411 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002412 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002413 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002414 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002415 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00002416 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002417 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00002418 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00002419 else if (FnInfo->isStr("strlen"))
2420 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00002421 }
2422 break;
2423 }
Anna Zaks22122702012-01-17 00:37:07 +00002424 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002425}
2426
Chris Lattner59a25942008-03-31 00:36:02 +00002427//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002428// FieldDecl Implementation
2429//===----------------------------------------------------------------------===//
2430
Jay Foad39c79802011-01-12 09:06:06 +00002431FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002432 SourceLocation StartLoc, SourceLocation IdLoc,
2433 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002434 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2435 bool HasInit) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002436 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002437 BW, Mutable, HasInit);
Sebastian Redl833ef452010-01-26 22:01:41 +00002438}
2439
Douglas Gregor72172e92012-01-05 21:55:30 +00002440FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2441 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2442 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
2443 0, QualType(), 0, 0, false, false);
2444}
2445
Sebastian Redl833ef452010-01-26 22:01:41 +00002446bool FieldDecl::isAnonymousStructOrUnion() const {
2447 if (!isImplicit() || getDeclName())
2448 return false;
2449
2450 if (const RecordType *Record = getType()->getAs<RecordType>())
2451 return Record->getDecl()->isAnonymousStructOrUnion();
2452
2453 return false;
2454}
2455
Richard Smithcaf33902011-10-10 18:28:20 +00002456unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2457 assert(isBitField() && "not a bitfield");
2458 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2459 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2460}
2461
John McCall4e819612011-01-20 07:57:12 +00002462unsigned FieldDecl::getFieldIndex() const {
2463 if (CachedFieldIndex) return CachedFieldIndex - 1;
2464
Richard Smithd62306a2011-11-10 06:34:14 +00002465 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002466 const RecordDecl *RD = getParent();
2467 const FieldDecl *LastFD = 0;
2468 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
Richard Smithd62306a2011-11-10 06:34:14 +00002469
2470 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2471 I != E; ++I, ++Index) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00002472 I->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002473
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002474 if (IsMsStruct) {
2475 // Zero-length bitfields following non-bitfield members are ignored.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002476 if (getASTContext().ZeroBitfieldFollowsNonBitfield(&*I, LastFD)) {
Richard Smithd62306a2011-11-10 06:34:14 +00002477 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002478 continue;
2479 }
David Blaikie2d7c57e2012-04-30 02:36:29 +00002480 LastFD = &*I;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002481 }
John McCall4e819612011-01-20 07:57:12 +00002482 }
2483
Richard Smithd62306a2011-11-10 06:34:14 +00002484 assert(CachedFieldIndex && "failed to find field in parent");
2485 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002486}
2487
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002488SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002489 if (const Expr *E = InitializerOrBitWidth.getPointer())
2490 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002491 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002492}
2493
Richard Smith938f40b2011-06-11 17:19:42 +00002494void FieldDecl::setInClassInitializer(Expr *Init) {
2495 assert(!InitializerOrBitWidth.getPointer() &&
2496 "bit width or initializer already set");
2497 InitializerOrBitWidth.setPointer(Init);
2498 InitializerOrBitWidth.setInt(0);
2499}
2500
Sebastian Redl833ef452010-01-26 22:01:41 +00002501//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002502// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002503//===----------------------------------------------------------------------===//
2504
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002505SourceLocation TagDecl::getOuterLocStart() const {
2506 return getTemplateOrInnerLocStart(this);
2507}
2508
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002509SourceRange TagDecl::getSourceRange() const {
2510 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002511 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002512}
2513
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002514TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002515 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002516}
2517
Richard Smithdda56e42011-04-15 14:24:37 +00002518void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2519 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002520 if (TypeForDecl)
John McCall424cec92011-01-19 06:33:43 +00002521 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00002522 ClearLinkageCache();
Douglas Gregora72a4e32010-05-19 18:39:18 +00002523}
2524
Douglas Gregordee1be82009-01-17 00:42:38 +00002525void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002526 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002527
2528 if (isa<CXXRecordDecl>(this)) {
2529 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2530 struct CXXRecordDecl::DefinitionData *Data =
2531 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002532 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2533 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002534 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002535}
2536
2537void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002538 assert((!isa<CXXRecordDecl>(this) ||
2539 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2540 "definition completed but not started");
2541
John McCallf937c022011-10-07 06:10:15 +00002542 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002543 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002544
2545 if (ASTMutationListener *L = getASTMutationListener())
2546 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002547}
2548
John McCallf937c022011-10-07 06:10:15 +00002549TagDecl *TagDecl::getDefinition() const {
2550 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002551 return const_cast<TagDecl *>(this);
Andrew Trickba266ee2010-10-19 21:54:32 +00002552 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2553 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002554
2555 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002556 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002557 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002558 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002559
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002560 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002561}
2562
Douglas Gregor14454802011-02-25 02:25:35 +00002563void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2564 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002565 // Make sure the extended qualifier info is allocated.
2566 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002567 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002568 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002569 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002570 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002571 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002572 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002573 if (getExtInfo()->NumTemplParamLists == 0) {
2574 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002575 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002576 }
2577 else
2578 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002579 }
2580 }
2581}
2582
Abramo Bagnara60804e12011-03-18 15:16:37 +00002583void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2584 unsigned NumTPLists,
2585 TemplateParameterList **TPLists) {
2586 assert(NumTPLists > 0);
2587 // Make sure the extended decl info is allocated.
2588 if (!hasExtInfo())
2589 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002590 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002591 // Set the template parameter lists info.
2592 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2593}
2594
Ted Kremenek21475702008-09-05 17:16:31 +00002595//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002596// EnumDecl Implementation
2597//===----------------------------------------------------------------------===//
2598
David Blaikie68e081d2011-12-20 02:48:34 +00002599void EnumDecl::anchor() { }
2600
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002601EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2602 SourceLocation StartLoc, SourceLocation IdLoc,
2603 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002604 EnumDecl *PrevDecl, bool IsScoped,
2605 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002606 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002607 IsScoped, IsScopedUsingClassTag, IsFixed);
Sebastian Redl833ef452010-01-26 22:01:41 +00002608 C.getTypeDeclType(Enum, PrevDecl);
2609 return Enum;
2610}
2611
Douglas Gregor72172e92012-01-05 21:55:30 +00002612EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2613 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
2614 return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
2615 false, false, false);
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002616}
2617
Douglas Gregord5058122010-02-11 01:19:42 +00002618void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002619 QualType NewPromotionType,
2620 unsigned NumPositiveBits,
2621 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002622 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002623 if (!IntegerType)
2624 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002625 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002626 setNumPositiveBits(NumPositiveBits);
2627 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002628 TagDecl::completeDefinition();
2629}
2630
Richard Smith7d137e32012-03-23 03:33:32 +00002631TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2632 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2633 return MSI->getTemplateSpecializationKind();
2634
2635 return TSK_Undeclared;
2636}
2637
2638void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2639 SourceLocation PointOfInstantiation) {
2640 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
2641 assert(MSI && "Not an instantiated member enumeration?");
2642 MSI->setTemplateSpecializationKind(TSK);
2643 if (TSK != TSK_ExplicitSpecialization &&
2644 PointOfInstantiation.isValid() &&
2645 MSI->getPointOfInstantiation().isInvalid())
2646 MSI->setPointOfInstantiation(PointOfInstantiation);
2647}
2648
Richard Smith4b38ded2012-03-14 23:13:10 +00002649EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
2650 if (SpecializationInfo)
2651 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
2652
2653 return 0;
2654}
2655
2656void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2657 TemplateSpecializationKind TSK) {
2658 assert(!SpecializationInfo && "Member enum is already a specialization");
2659 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
2660}
2661
Sebastian Redl833ef452010-01-26 22:01:41 +00002662//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002663// RecordDecl Implementation
2664//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00002665
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002666RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2667 SourceLocation StartLoc, SourceLocation IdLoc,
2668 IdentifierInfo *Id, RecordDecl *PrevDecl)
2669 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00002670 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002671 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002672 HasObjectMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002673 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00002674 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00002675}
2676
Jay Foad39c79802011-01-12 09:06:06 +00002677RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002678 SourceLocation StartLoc, SourceLocation IdLoc,
2679 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2680 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2681 PrevDecl);
Ted Kremenek21475702008-09-05 17:16:31 +00002682 C.getTypeDeclType(R, PrevDecl);
2683 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00002684}
2685
Douglas Gregor72172e92012-01-05 21:55:30 +00002686RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
2687 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
2688 return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2689 SourceLocation(), 0, 0);
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002690}
2691
Douglas Gregordfcad112009-03-25 15:59:44 +00002692bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00002693 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00002694 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2695}
2696
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002697RecordDecl::field_iterator RecordDecl::field_begin() const {
2698 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2699 LoadFieldsFromExternalStorage();
2700
2701 return field_iterator(decl_iterator(FirstDecl));
2702}
2703
Douglas Gregorb11aad82011-02-19 18:51:44 +00002704/// completeDefinition - Notes that the definition of this type is now
2705/// complete.
2706void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00002707 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00002708 TagDecl::completeDefinition();
2709}
2710
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002711void RecordDecl::LoadFieldsFromExternalStorage() const {
2712 ExternalASTSource *Source = getASTContext().getExternalSource();
2713 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2714
2715 // Notify that we have a RecordDecl doing some initialization.
2716 ExternalASTSource::Deserializing TheFields(Source);
2717
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002718 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00002719 LoadedFieldsFromExternalStorage = true;
2720 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2721 case ELR_Success:
2722 break;
2723
2724 case ELR_AlreadyLoaded:
2725 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002726 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00002727 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002728
2729#ifndef NDEBUG
2730 // Check that all decls we got were FieldDecls.
2731 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2732 assert(isa<FieldDecl>(Decls[i]));
2733#endif
2734
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002735 if (Decls.empty())
2736 return;
2737
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00002738 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2739 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002740}
2741
Steve Naroff415d3d52008-10-08 17:01:13 +00002742//===----------------------------------------------------------------------===//
2743// BlockDecl Implementation
2744//===----------------------------------------------------------------------===//
2745
David Blaikie9c70e042011-09-21 18:16:56 +00002746void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00002747 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00002748
Steve Naroffc4b30e52009-03-13 16:56:44 +00002749 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002750 if (!NewParamInfo.empty()) {
2751 NumParams = NewParamInfo.size();
2752 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2753 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00002754 }
2755}
2756
John McCall351762c2011-02-07 10:33:21 +00002757void BlockDecl::setCaptures(ASTContext &Context,
2758 const Capture *begin,
2759 const Capture *end,
2760 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00002761 CapturesCXXThis = capturesCXXThis;
2762
2763 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00002764 NumCaptures = 0;
2765 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00002766 return;
2767 }
2768
John McCall351762c2011-02-07 10:33:21 +00002769 NumCaptures = end - begin;
2770
2771 // Avoid new Capture[] because we don't want to provide a default
2772 // constructor.
2773 size_t allocationSize = NumCaptures * sizeof(Capture);
2774 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2775 memcpy(buffer, begin, allocationSize);
2776 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00002777}
Sebastian Redl833ef452010-01-26 22:01:41 +00002778
John McCallce45f882011-06-15 22:51:16 +00002779bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2780 for (capture_const_iterator
2781 i = capture_begin(), e = capture_end(); i != e; ++i)
2782 // Only auto vars can be captured, so no redeclaration worries.
2783 if (i->getVariable() == variable)
2784 return true;
2785
2786 return false;
2787}
2788
Douglas Gregor70226da2010-12-21 16:27:07 +00002789SourceRange BlockDecl::getSourceRange() const {
2790 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2791}
Sebastian Redl833ef452010-01-26 22:01:41 +00002792
2793//===----------------------------------------------------------------------===//
2794// Other Decl Allocation/Deallocation Method Implementations
2795//===----------------------------------------------------------------------===//
2796
David Blaikie68e081d2011-12-20 02:48:34 +00002797void TranslationUnitDecl::anchor() { }
2798
Sebastian Redl833ef452010-01-26 22:01:41 +00002799TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2800 return new (C) TranslationUnitDecl(C);
2801}
2802
David Blaikie68e081d2011-12-20 02:48:34 +00002803void LabelDecl::anchor() { }
2804
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002805LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002806 SourceLocation IdentL, IdentifierInfo *II) {
2807 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2808}
2809
2810LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2811 SourceLocation IdentL, IdentifierInfo *II,
2812 SourceLocation GnuLabelL) {
2813 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2814 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002815}
2816
Douglas Gregor72172e92012-01-05 21:55:30 +00002817LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2818 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
2819 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00002820}
2821
David Blaikie68e081d2011-12-20 02:48:34 +00002822void ValueDecl::anchor() { }
2823
2824void ImplicitParamDecl::anchor() { }
2825
Sebastian Redl833ef452010-01-26 22:01:41 +00002826ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002827 SourceLocation IdLoc,
2828 IdentifierInfo *Id,
2829 QualType Type) {
2830 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00002831}
2832
Douglas Gregor72172e92012-01-05 21:55:30 +00002833ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
2834 unsigned ID) {
2835 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
2836 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
2837}
2838
Sebastian Redl833ef452010-01-26 22:01:41 +00002839FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002840 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002841 const DeclarationNameInfo &NameInfo,
2842 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002843 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregorff76cb92010-12-09 16:59:22 +00002844 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00002845 bool hasWrittenPrototype,
2846 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002847 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2848 T, TInfo, SC, SCAsWritten,
Richard Smitha77a0a62011-08-15 21:04:07 +00002849 isInlineSpecified,
2850 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00002851 New->HasWrittenPrototype = hasWrittenPrototype;
2852 return New;
2853}
2854
Douglas Gregor72172e92012-01-05 21:55:30 +00002855FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2856 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
2857 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
2858 DeclarationNameInfo(), QualType(), 0,
2859 SC_None, SC_None, false, false);
2860}
2861
Sebastian Redl833ef452010-01-26 22:01:41 +00002862BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2863 return new (C) BlockDecl(DC, L);
2864}
2865
Douglas Gregor72172e92012-01-05 21:55:30 +00002866BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2867 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
2868 return new (Mem) BlockDecl(0, SourceLocation());
2869}
2870
Sebastian Redl833ef452010-01-26 22:01:41 +00002871EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2872 SourceLocation L,
2873 IdentifierInfo *Id, QualType T,
2874 Expr *E, const llvm::APSInt &V) {
2875 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2876}
2877
Douglas Gregor72172e92012-01-05 21:55:30 +00002878EnumConstantDecl *
2879EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2880 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
2881 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
2882 llvm::APSInt());
2883}
2884
David Blaikie68e081d2011-12-20 02:48:34 +00002885void IndirectFieldDecl::anchor() { }
2886
Benjamin Kramer39593702010-11-21 14:11:41 +00002887IndirectFieldDecl *
2888IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2889 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2890 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00002891 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2892}
2893
Douglas Gregor72172e92012-01-05 21:55:30 +00002894IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
2895 unsigned ID) {
2896 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
2897 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
2898 QualType(), 0, 0);
2899}
2900
Douglas Gregorbe996932010-09-01 20:41:53 +00002901SourceRange EnumConstantDecl::getSourceRange() const {
2902 SourceLocation End = getLocation();
2903 if (Init)
2904 End = Init->getLocEnd();
2905 return SourceRange(getLocation(), End);
2906}
2907
David Blaikie68e081d2011-12-20 02:48:34 +00002908void TypeDecl::anchor() { }
2909
Sebastian Redl833ef452010-01-26 22:01:41 +00002910TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00002911 SourceLocation StartLoc, SourceLocation IdLoc,
2912 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2913 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00002914}
2915
David Blaikie68e081d2011-12-20 02:48:34 +00002916void TypedefNameDecl::anchor() { }
2917
Douglas Gregor72172e92012-01-05 21:55:30 +00002918TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2919 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
2920 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2921}
2922
Richard Smithdda56e42011-04-15 14:24:37 +00002923TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2924 SourceLocation StartLoc,
2925 SourceLocation IdLoc, IdentifierInfo *Id,
2926 TypeSourceInfo *TInfo) {
2927 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2928}
2929
Douglas Gregor72172e92012-01-05 21:55:30 +00002930TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2931 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
2932 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2933}
2934
Abramo Bagnaraea947882011-03-08 16:41:52 +00002935SourceRange TypedefDecl::getSourceRange() const {
2936 SourceLocation RangeEnd = getLocation();
2937 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2938 if (typeIsPostfix(TInfo->getType()))
2939 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2940 }
2941 return SourceRange(getLocStart(), RangeEnd);
2942}
2943
Richard Smithdda56e42011-04-15 14:24:37 +00002944SourceRange TypeAliasDecl::getSourceRange() const {
2945 SourceLocation RangeEnd = getLocStart();
2946 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2947 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2948 return SourceRange(getLocStart(), RangeEnd);
2949}
2950
David Blaikie68e081d2011-12-20 02:48:34 +00002951void FileScopeAsmDecl::anchor() { }
2952
Sebastian Redl833ef452010-01-26 22:01:41 +00002953FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00002954 StringLiteral *Str,
2955 SourceLocation AsmLoc,
2956 SourceLocation RParenLoc) {
2957 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00002958}
Douglas Gregorba345522011-12-02 23:23:56 +00002959
Douglas Gregor72172e92012-01-05 21:55:30 +00002960FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
2961 unsigned ID) {
2962 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
2963 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
2964}
2965
Douglas Gregorba345522011-12-02 23:23:56 +00002966//===----------------------------------------------------------------------===//
2967// ImportDecl Implementation
2968//===----------------------------------------------------------------------===//
2969
2970/// \brief Retrieve the number of module identifiers needed to name the given
2971/// module.
2972static unsigned getNumModuleIdentifiers(Module *Mod) {
2973 unsigned Result = 1;
2974 while (Mod->Parent) {
2975 Mod = Mod->Parent;
2976 ++Result;
2977 }
2978 return Result;
2979}
2980
Douglas Gregor22d09742012-01-03 18:04:46 +00002981ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00002982 Module *Imported,
2983 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00002984 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00002985 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00002986{
2987 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
2988 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
2989 memcpy(StoredLocs, IdentifierLocs.data(),
2990 IdentifierLocs.size() * sizeof(SourceLocation));
2991}
2992
Douglas Gregor22d09742012-01-03 18:04:46 +00002993ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00002994 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00002995 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00002996 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00002997{
2998 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
2999}
3000
3001ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003002 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003003 ArrayRef<SourceLocation> IdentifierLocs) {
3004 void *Mem = C.Allocate(sizeof(ImportDecl) +
3005 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003006 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003007}
3008
3009ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003010 SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003011 Module *Imported,
3012 SourceLocation EndLoc) {
3013 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003014 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003015 Import->setImplicit();
3016 return Import;
3017}
3018
Douglas Gregor72172e92012-01-05 21:55:30 +00003019ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3020 unsigned NumLocations) {
3021 void *Mem = AllocateDeserializedDecl(C, ID,
3022 (sizeof(ImportDecl) +
3023 NumLocations * sizeof(SourceLocation)));
Douglas Gregorba345522011-12-02 23:23:56 +00003024 return new (Mem) ImportDecl(EmptyShell());
3025}
3026
3027ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3028 if (!ImportedAndComplete.getInt())
3029 return ArrayRef<SourceLocation>();
3030
3031 const SourceLocation *StoredLocs
3032 = reinterpret_cast<const SourceLocation *>(this + 1);
3033 return ArrayRef<SourceLocation>(StoredLocs,
3034 getNumModuleIdentifiers(getImportedModule()));
3035}
3036
3037SourceRange ImportDecl::getSourceRange() const {
3038 if (!ImportedAndComplete.getInt())
3039 return SourceRange(getLocation(),
3040 *reinterpret_cast<const SourceLocation *>(this + 1));
3041
3042 return SourceRange(getLocation(), getIdentifierLocs().back());
3043}