blob: aa7bb0812a3d28c9c78d9ccbd8e8785367a26bfd [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidise184bae2008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Reid Spencer5f016e22007-07-11 17:01:13 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Douglas Gregor2a3009a2009-02-03 19:21:40 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff0de21fd2009-02-22 19:35:57 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregor7da97d02009-05-10 22:57:19 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattner6c2b6eb2008-03-15 06:12:44 +000018#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Stmt.h"
Nuno Lopes99f06ba2008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson337cba42009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregord249e1d1f2009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +000024#include "clang/AST/ASTMutationListener.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000026#include "clang/Basic/IdentifierTable.h"
Douglas Gregor15de72c2011-12-02 23:23:56 +000027#include "clang/Basic/Module.h"
Abramo Bagnara465d41b2010-05-11 21:36:43 +000028#include "clang/Basic/Specifiers.h"
Douglas Gregor4421d2b2011-03-26 12:10:19 +000029#include "clang/Basic/TargetInfo.h"
John McCallf1bbbb42009-09-04 01:14:41 +000030#include "llvm/Support/ErrorHandling.h"
Ted Kremenek27f8a282008-05-20 00:43:19 +000031
David Blaikie4278c652011-09-21 18:16:56 +000032#include <algorithm>
33
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
35
Chris Lattnerd3b90652008-03-15 05:43:15 +000036//===----------------------------------------------------------------------===//
Douglas Gregor4afa39d2009-01-20 01:17:11 +000037// NamedDecl Implementation
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000038//===----------------------------------------------------------------------===//
39
Douglas Gregor4421d2b2011-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 McCall1fb0caa2010-10-22 21:05:15 +000051 }
Douglas Gregor4421d2b2011-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 Gregorbcfd1f52011-09-02 00:18:52 +000055 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor4421d2b2011-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 McCall1fb0caa2010-10-22 21:05:15 +000065}
66
John McCallaf146032010-10-30 11:50:40 +000067typedef NamedDecl::LinkageInfo LinkageInfo;
John McCallaf146032010-10-30 11:50:40 +000068
Benjamin Kramer752c2e92010-11-05 19:56:37 +000069namespace {
John McCall36987482010-11-02 01:45:15 +000070/// Flags controlling the computation of linkage and visibility.
71struct LVFlags {
72 bool ConsiderGlobalVisibility;
73 bool ConsiderVisibilityAttributes;
John McCall1a0918a2011-03-04 10:39:25 +000074 bool ConsiderTemplateParameterTypes;
John McCall36987482010-11-02 01:45:15 +000075
76 LVFlags() : ConsiderGlobalVisibility(true),
John McCall1a0918a2011-03-04 10:39:25 +000077 ConsiderVisibilityAttributes(true),
78 ConsiderTemplateParameterTypes(true) {
John McCall36987482010-11-02 01:45:15 +000079 }
80
Douglas Gregor381d34e2010-12-06 18:36:25 +000081 /// \brief Returns a set of flags that is only useful for computing the
82 /// linkage, not the visibility, of a declaration.
83 static LVFlags CreateOnlyDeclLinkage() {
84 LVFlags F;
85 F.ConsiderGlobalVisibility = false;
86 F.ConsiderVisibilityAttributes = false;
John McCall1a0918a2011-03-04 10:39:25 +000087 F.ConsiderTemplateParameterTypes = false;
Douglas Gregor381d34e2010-12-06 18:36:25 +000088 return F;
89 }
90
John McCall36987482010-11-02 01:45:15 +000091 /// Returns a set of flags, otherwise based on these, which ignores
92 /// off all sources of visibility except template arguments.
93 LVFlags onlyTemplateVisibility() const {
94 LVFlags F = *this;
95 F.ConsiderGlobalVisibility = false;
96 F.ConsiderVisibilityAttributes = false;
John McCall1a0918a2011-03-04 10:39:25 +000097 F.ConsiderTemplateParameterTypes = false;
John McCall36987482010-11-02 01:45:15 +000098 return F;
99 }
Douglas Gregor89d63e52010-12-06 18:50:56 +0000100};
Benjamin Kramer752c2e92010-11-05 19:56:37 +0000101} // end anonymous namespace
John McCall36987482010-11-02 01:45:15 +0000102
Rafael Espindola093ecc92012-01-14 00:30:36 +0000103static LinkageInfo getLVForType(QualType T) {
104 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
105 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
106}
107
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000108/// \brief Get the most restrictive linkage for the types in the given
109/// template parameter list.
Rafael Espindola093ecc92012-01-14 00:30:36 +0000110static LinkageInfo
John McCall1fb0caa2010-10-22 21:05:15 +0000111getLVForTemplateParameterList(const TemplateParameterList *Params) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000112 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000113 for (TemplateParameterList::const_iterator P = Params->begin(),
114 PEnd = Params->end();
115 P != PEnd; ++P) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000116 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
117 if (NTTP->isExpandedParameterPack()) {
118 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
119 QualType T = NTTP->getExpansionType(I);
120 if (!T->isDependentType())
Rafael Espindola093ecc92012-01-14 00:30:36 +0000121 LV.merge(getLVForType(T));
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000122 }
123 continue;
124 }
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000125
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000126 if (!NTTP->getType()->isDependentType()) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000127 LV.merge(getLVForType(NTTP->getType()));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000128 continue;
129 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000130 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000131
132 if (TemplateTemplateParmDecl *TTP
133 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000134 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000135 }
136 }
137
John McCall1fb0caa2010-10-22 21:05:15 +0000138 return LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000139}
140
Douglas Gregor381d34e2010-12-06 18:36:25 +0000141/// getLVForDecl - Get the linkage and visibility for the given declaration.
142static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
143
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000144/// \brief Get the most restrictive linkage for the types and
145/// declarations in the given template argument list.
Rafael Espindola093ecc92012-01-14 00:30:36 +0000146static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Args,
147 unsigned NumArgs,
148 LVFlags &F) {
149 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000150
151 for (unsigned I = 0; I != NumArgs; ++I) {
152 switch (Args[I].getKind()) {
153 case TemplateArgument::Null:
154 case TemplateArgument::Integral:
155 case TemplateArgument::Expression:
156 break;
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000157
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000158 case TemplateArgument::Type:
Rafael Espindola093ecc92012-01-14 00:30:36 +0000159 LV.merge(getLVForType(Args[I].getAsType()));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000160 break;
161
162 case TemplateArgument::Declaration:
John McCall1fb0caa2010-10-22 21:05:15 +0000163 // The decl can validly be null as the representation of nullptr
164 // arguments, valid only in C++0x.
165 if (Decl *D = Args[I].getAsDecl()) {
Douglas Gregor89d63e52010-12-06 18:50:56 +0000166 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
167 LV = merge(LV, getLVForDecl(ND, F));
John McCall1fb0caa2010-10-22 21:05:15 +0000168 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000169 break;
170
171 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +0000172 case TemplateArgument::TemplateExpansion:
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000173 if (TemplateDecl *Template
Douglas Gregora7fc9012011-01-05 18:58:31 +0000174 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindola093ecc92012-01-14 00:30:36 +0000175 LV.merge(getLVForDecl(Template, F));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000176 break;
177
178 case TemplateArgument::Pack:
Rafael Espindola093ecc92012-01-14 00:30:36 +0000179 LV.merge(getLVForTemplateArgumentList(Args[I].pack_begin(),
180 Args[I].pack_size(),
181 F));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000182 break;
183 }
184 }
185
John McCall1fb0caa2010-10-22 21:05:15 +0000186 return LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000187}
188
Rafael Espindola093ecc92012-01-14 00:30:36 +0000189static LinkageInfo
Douglas Gregor381d34e2010-12-06 18:36:25 +0000190getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
191 LVFlags &F) {
192 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
John McCall3cdfc4d2010-08-13 08:35:10 +0000193}
194
John McCall6ce51ee2011-06-27 23:06:04 +0000195static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
196 const FunctionTemplateSpecializationInfo *spec) {
197 return !(spec->isExplicitSpecialization() &&
198 fn->hasAttr<VisibilityAttr>());
199}
200
201static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
202 return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
203}
204
John McCall36987482010-11-02 01:45:15 +0000205static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000206 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregord85b5b92009-11-25 22:24:25 +0000207 "Not a name having namespace scope");
208 ASTContext &Context = D->getASTContext();
209
210 // C++ [basic.link]p3:
211 // A name having namespace scope (3.3.6) has internal linkage if it
212 // is the name of
213 // - an object, reference, function or function template that is
214 // explicitly declared static; or,
215 // (This bullet corresponds to C99 6.2.2p3.)
216 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
217 // Explicitly declared static.
John McCalld931b082010-08-26 03:08:43 +0000218 if (Var->getStorageClass() == SC_Static)
John McCallaf146032010-10-30 11:50:40 +0000219 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000220
221 // - an object or reference that is explicitly declared const
222 // and neither explicitly declared extern nor previously
223 // declared to have external linkage; or
224 // (there is no equivalent in C99)
225 if (Context.getLangOptions().CPlusPlus &&
Eli Friedmane9d65542009-11-26 03:04:01 +0000226 Var->getType().isConstant(Context) &&
John McCalld931b082010-08-26 03:08:43 +0000227 Var->getStorageClass() != SC_Extern &&
228 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregord85b5b92009-11-25 22:24:25 +0000229 bool FoundExtern = false;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000230 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000231 PrevVar && !FoundExtern;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000232 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000233 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregord85b5b92009-11-25 22:24:25 +0000234 FoundExtern = true;
235
236 if (!FoundExtern)
John McCallaf146032010-10-30 11:50:40 +0000237 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000238 }
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000239 if (Var->getStorageClass() == SC_None) {
Douglas Gregoref96ee02012-01-14 16:38:05 +0000240 const VarDecl *PrevVar = Var->getPreviousDecl();
241 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000242 if (PrevVar->getStorageClass() == SC_PrivateExtern)
243 break;
244 if (PrevVar)
245 return PrevVar->getLinkageAndVisibility();
246 }
Douglas Gregord85b5b92009-11-25 22:24:25 +0000247 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000248 // C++ [temp]p4:
249 // A non-member function template can have internal linkage; any
250 // other template name shall have external linkage.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000251 const FunctionDecl *Function = 0;
252 if (const FunctionTemplateDecl *FunTmpl
253 = dyn_cast<FunctionTemplateDecl>(D))
254 Function = FunTmpl->getTemplatedDecl();
255 else
256 Function = cast<FunctionDecl>(D);
257
258 // Explicitly declared static.
John McCalld931b082010-08-26 03:08:43 +0000259 if (Function->getStorageClass() == SC_Static)
John McCallaf146032010-10-30 11:50:40 +0000260 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000261 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
262 // - a data member of an anonymous union.
263 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallaf146032010-10-30 11:50:40 +0000264 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000265 }
266
Chandler Carruth094b6432011-02-24 19:03:39 +0000267 if (D->isInAnonymousNamespace()) {
268 const VarDecl *Var = dyn_cast<VarDecl>(D);
269 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Eli Friedman750dc2b2012-01-15 01:23:58 +0000270 if ((!Var || !Var->getDeclContext()->isExternCContext()) &&
271 (!Func || !Func->getDeclContext()->isExternCContext()))
Chandler Carruth094b6432011-02-24 19:03:39 +0000272 return LinkageInfo::uniqueExternal();
273 }
John McCalle7bc9722010-10-28 04:18:25 +0000274
John McCall1fb0caa2010-10-22 21:05:15 +0000275 // Set up the defaults.
276
277 // C99 6.2.2p5:
278 // If the declaration of an identifier for an object has file
279 // scope and no storage-class specifier, its linkage is
280 // external.
John McCallaf146032010-10-30 11:50:40 +0000281 LinkageInfo LV;
282
John McCall36987482010-11-02 01:45:15 +0000283 if (F.ConsiderVisibilityAttributes) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000284 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
285 LV.setVisibility(*Vis, true);
John McCall36987482010-11-02 01:45:15 +0000286 F.ConsiderGlobalVisibility = false;
John McCall90f14502010-12-10 02:59:44 +0000287 } else {
288 // If we're declared in a namespace with a visibility attribute,
289 // use that namespace's visibility, but don't call it explicit.
290 for (const DeclContext *DC = D->getDeclContext();
291 !isa<TranslationUnitDecl>(DC);
292 DC = DC->getParent()) {
Rafael Espindola6f26b5e2012-01-01 17:48:19 +0000293 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
294 if (!ND) continue;
295 if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) {
Rafael Espindola71cb8a22012-01-01 18:06:40 +0000296 LV.setVisibility(*Vis, true);
John McCall90f14502010-12-10 02:59:44 +0000297 F.ConsiderGlobalVisibility = false;
298 break;
299 }
300 }
John McCall36987482010-11-02 01:45:15 +0000301 }
John McCallaf146032010-10-30 11:50:40 +0000302 }
John McCall1fb0caa2010-10-22 21:05:15 +0000303
Douglas Gregord85b5b92009-11-25 22:24:25 +0000304 // C++ [basic.link]p4:
John McCall1fb0caa2010-10-22 21:05:15 +0000305
Douglas Gregord85b5b92009-11-25 22:24:25 +0000306 // A name having namespace scope has external linkage if it is the
307 // name of
308 //
309 // - an object or reference, unless it has internal linkage; or
310 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall110e8e52010-10-29 22:22:43 +0000311 // GCC applies the following optimization to variables and static
312 // data members, but not to functions:
313 //
John McCall1fb0caa2010-10-22 21:05:15 +0000314 // Modify the variable's LV by the LV of its type unless this is
315 // C or extern "C". This follows from [basic.link]p9:
316 // A type without linkage shall not be used as the type of a
317 // variable or function with external linkage unless
318 // - the entity has C language linkage, or
319 // - the entity is declared within an unnamed namespace, or
320 // - the entity is not used or is defined in the same
321 // translation unit.
322 // and [basic.link]p10:
323 // ...the types specified by all declarations referring to a
324 // given variable or function shall be identical...
325 // C does not have an equivalent rule.
326 //
John McCallac65c622010-10-26 04:59:26 +0000327 // Ignore this if we've got an explicit attribute; the user
328 // probably knows what they're doing.
329 //
John McCall1fb0caa2010-10-22 21:05:15 +0000330 // Note that we don't want to make the variable non-external
331 // because of this, but unique-external linkage suits us.
Eli Friedman750dc2b2012-01-15 01:23:58 +0000332 if (Context.getLangOptions().CPlusPlus &&
333 !Var->getDeclContext()->isExternCContext()) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000334 LinkageInfo TypeLV = getLVForType(Var->getType());
335 if (TypeLV.linkage() != ExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000336 return LinkageInfo::uniqueExternal();
337 if (!LV.visibilityExplicit())
Rafael Espindola093ecc92012-01-14 00:30:36 +0000338 LV.mergeVisibility(TypeLV.visibility(), TypeLV.visibilityExplicit());
John McCall110e8e52010-10-29 22:22:43 +0000339 }
340
John McCall35cebc32010-11-02 18:38:13 +0000341 if (Var->getStorageClass() == SC_PrivateExtern)
342 LV.setVisibility(HiddenVisibility, true);
343
Douglas Gregord85b5b92009-11-25 22:24:25 +0000344 if (!Context.getLangOptions().CPlusPlus &&
John McCalld931b082010-08-26 03:08:43 +0000345 (Var->getStorageClass() == SC_Extern ||
346 Var->getStorageClass() == SC_PrivateExtern)) {
John McCall1fb0caa2010-10-22 21:05:15 +0000347
Douglas Gregord85b5b92009-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 Gregoref96ee02012-01-14 16:38:05 +0000357 if (const VarDecl *PrevVar = Var->getPreviousDecl()) {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000358 LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
John McCallaf146032010-10-30 11:50:40 +0000359 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
360 LV.mergeVisibility(PrevLV);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000361 }
362 }
363
Douglas Gregord85b5b92009-11-25 22:24:25 +0000364 // - a function, unless it has internal linkage; or
John McCall1fb0caa2010-10-22 21:05:15 +0000365 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall67fa6d52010-10-28 07:07:52 +0000366 // In theory, we can modify the function's LV by the LV of its
367 // type unless it has C linkage (see comment above about variables
368 // for justification). In practice, GCC doesn't do this, so it's
369 // just too painful to make work.
John McCall1fb0caa2010-10-22 21:05:15 +0000370
John McCall35cebc32010-11-02 18:38:13 +0000371 if (Function->getStorageClass() == SC_PrivateExtern)
372 LV.setVisibility(HiddenVisibility, true);
373
Douglas Gregord85b5b92009-11-25 22:24:25 +0000374 // C99 6.2.2p5:
375 // If the declaration of an identifier for a function has no
376 // storage-class specifier, its linkage is determined exactly
377 // as if it were declared with the storage-class specifier
378 // extern.
379 if (!Context.getLangOptions().CPlusPlus &&
John McCalld931b082010-08-26 03:08:43 +0000380 (Function->getStorageClass() == SC_Extern ||
381 Function->getStorageClass() == SC_PrivateExtern ||
382 Function->getStorageClass() == SC_None)) {
Douglas Gregord85b5b92009-11-25 22:24:25 +0000383 // C99 6.2.2p4:
384 // For an identifier declared with the storage-class specifier
385 // extern in a scope in which a prior declaration of that
386 // identifier is visible, if the prior declaration specifies
387 // internal or external linkage, the linkage of the identifier
388 // at the later declaration is the same as the linkage
389 // specified at the prior declaration. If no prior declaration
390 // is visible, or if the prior declaration specifies no
391 // linkage, then the identifier has external linkage.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000392 if (const FunctionDecl *PrevFunc = Function->getPreviousDecl()) {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000393 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
John McCallaf146032010-10-30 11:50:40 +0000394 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
395 LV.mergeVisibility(PrevLV);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000396 }
397 }
398
John McCallaf8ca372011-02-10 06:50:24 +0000399 // In C++, then if the type of the function uses a type with
400 // unique-external linkage, it's not legally usable from outside
401 // this translation unit. However, we should use the C linkage
402 // rules instead for extern "C" declarations.
Eli Friedman750dc2b2012-01-15 01:23:58 +0000403 if (Context.getLangOptions().CPlusPlus &&
404 !Function->getDeclContext()->isExternCContext() &&
John McCallaf8ca372011-02-10 06:50:24 +0000405 Function->getType()->getLinkage() == UniqueExternalLinkage)
406 return LinkageInfo::uniqueExternal();
407
John McCall6ce51ee2011-06-27 23:06:04 +0000408 // Consider LV from the template and the template arguments unless
409 // this is an explicit specialization with a visibility attribute.
410 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000411 = Function->getTemplateSpecializationInfo()) {
John McCall6ce51ee2011-06-27 23:06:04 +0000412 if (shouldConsiderTemplateLV(Function, specInfo)) {
413 LV.merge(getLVForDecl(specInfo->getTemplate(),
414 F.onlyTemplateVisibility()));
415 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
416 LV.merge(getLVForTemplateArgumentList(templateArgs, F));
417 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000418 }
419
Douglas Gregord85b5b92009-11-25 22:24:25 +0000420 // - a named class (Clause 9), or an unnamed class defined in a
421 // typedef declaration in which the class has the typedef name
422 // for linkage purposes (7.1.3); or
423 // - a named enumeration (7.2), or an unnamed enumeration
424 // defined in a typedef declaration in which the enumeration
425 // has the typedef name for linkage purposes (7.1.3); or
John McCall1fb0caa2010-10-22 21:05:15 +0000426 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
427 // Unnamed tags have no linkage.
Richard Smith162e1c12011-04-15 14:24:37 +0000428 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallaf146032010-10-30 11:50:40 +0000429 return LinkageInfo::none();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000430
John McCall1fb0caa2010-10-22 21:05:15 +0000431 // If this is a class template specialization, consider the
432 // linkage of the template and template arguments.
John McCall6ce51ee2011-06-27 23:06:04 +0000433 if (const ClassTemplateSpecializationDecl *spec
John McCall1fb0caa2010-10-22 21:05:15 +0000434 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCall6ce51ee2011-06-27 23:06:04 +0000435 if (shouldConsiderTemplateLV(spec)) {
436 // From the template.
437 LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
438 F.onlyTemplateVisibility()));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000439
John McCall6ce51ee2011-06-27 23:06:04 +0000440 // The arguments at which the template was instantiated.
441 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
442 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
443 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000444 }
Douglas Gregord85b5b92009-11-25 22:24:25 +0000445
John McCallac65c622010-10-26 04:59:26 +0000446 // Consider -fvisibility unless the type has C linkage.
John McCall36987482010-11-02 01:45:15 +0000447 if (F.ConsiderGlobalVisibility)
448 F.ConsiderGlobalVisibility =
John McCallac65c622010-10-26 04:59:26 +0000449 (Context.getLangOptions().CPlusPlus &&
450 !Tag->getDeclContext()->isExternCContext());
John McCall1fb0caa2010-10-22 21:05:15 +0000451
Douglas Gregord85b5b92009-11-25 22:24:25 +0000452 // - an enumerator belonging to an enumeration with external linkage;
John McCall1fb0caa2010-10-22 21:05:15 +0000453 } else if (isa<EnumConstantDecl>(D)) {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000454 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
John McCallaf146032010-10-30 11:50:40 +0000455 if (!isExternalLinkage(EnumLV.linkage()))
456 return LinkageInfo::none();
457 LV.merge(EnumLV);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000458
459 // - a template, unless it is a function template that has
460 // internal linkage (Clause 14);
John McCall1a0918a2011-03-04 10:39:25 +0000461 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
462 if (F.ConsiderTemplateParameterTypes)
463 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000464
Douglas Gregord85b5b92009-11-25 22:24:25 +0000465 // - a namespace (7.3), unless it is declared within an unnamed
466 // namespace.
John McCall1fb0caa2010-10-22 21:05:15 +0000467 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
468 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000469
John McCall1fb0caa2010-10-22 21:05:15 +0000470 // By extension, we assign external linkage to Objective-C
471 // interfaces.
472 } else if (isa<ObjCInterfaceDecl>(D)) {
473 // fallout
474
475 // Everything not covered here has no linkage.
476 } else {
John McCallaf146032010-10-30 11:50:40 +0000477 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +0000478 }
479
480 // If we ended up with non-external linkage, visibility should
481 // always be default.
John McCallaf146032010-10-30 11:50:40 +0000482 if (LV.linkage() != ExternalLinkage)
483 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall1fb0caa2010-10-22 21:05:15 +0000484
485 // If we didn't end up with hidden visibility, consider attributes
486 // and -fvisibility.
John McCall36987482010-11-02 01:45:15 +0000487 if (F.ConsiderGlobalVisibility)
John McCallaf146032010-10-30 11:50:40 +0000488 LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
John McCall1fb0caa2010-10-22 21:05:15 +0000489
490 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000491}
492
John McCall36987482010-11-02 01:45:15 +0000493static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
John McCall1fb0caa2010-10-22 21:05:15 +0000494 // Only certain class members have linkage. Note that fields don't
495 // really have linkage, but it's convenient to say they do for the
496 // purposes of calculating linkage of pointer-to-data-member
497 // template arguments.
John McCall3cdfc4d2010-08-13 08:35:10 +0000498 if (!(isa<CXXMethodDecl>(D) ||
499 isa<VarDecl>(D) ||
John McCall1fb0caa2010-10-22 21:05:15 +0000500 isa<FieldDecl>(D) ||
John McCall3cdfc4d2010-08-13 08:35:10 +0000501 (isa<TagDecl>(D) &&
Richard Smith162e1c12011-04-15 14:24:37 +0000502 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
John McCallaf146032010-10-30 11:50:40 +0000503 return LinkageInfo::none();
John McCall3cdfc4d2010-08-13 08:35:10 +0000504
John McCall36987482010-11-02 01:45:15 +0000505 LinkageInfo LV;
506
507 // The flags we're going to use to compute the class's visibility.
508 LVFlags ClassF = F;
509
510 // If we have an explicit visibility attribute, merge that in.
511 if (F.ConsiderVisibilityAttributes) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000512 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
513 LV.mergeVisibility(*Vis, true);
John McCall36987482010-11-02 01:45:15 +0000514
515 // Ignore global visibility later, but not this attribute.
516 F.ConsiderGlobalVisibility = false;
517
518 // Ignore both global visibility and attributes when computing our
519 // parent's visibility.
520 ClassF = F.onlyTemplateVisibility();
521 }
522 }
John McCallaf146032010-10-30 11:50:40 +0000523
524 // Class members only have linkage if their class has external
John McCall36987482010-11-02 01:45:15 +0000525 // linkage.
526 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
527 if (!isExternalLinkage(LV.linkage()))
John McCallaf146032010-10-30 11:50:40 +0000528 return LinkageInfo::none();
John McCall3cdfc4d2010-08-13 08:35:10 +0000529
530 // If the class already has unique-external linkage, we can't improve.
John McCall36987482010-11-02 01:45:15 +0000531 if (LV.linkage() == UniqueExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000532 return LinkageInfo::uniqueExternal();
John McCall3cdfc4d2010-08-13 08:35:10 +0000533
John McCall3cdfc4d2010-08-13 08:35:10 +0000534 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallaf8ca372011-02-10 06:50:24 +0000535 // If the type of the function uses a type with unique-external
536 // linkage, it's not legally usable from outside this translation unit.
537 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
538 return LinkageInfo::uniqueExternal();
539
John McCall110e8e52010-10-29 22:22:43 +0000540 TemplateSpecializationKind TSK = TSK_Undeclared;
541
John McCall1fb0caa2010-10-22 21:05:15 +0000542 // If this is a method template specialization, use the linkage for
543 // the template parameters and arguments.
John McCall6ce51ee2011-06-27 23:06:04 +0000544 if (FunctionTemplateSpecializationInfo *spec
John McCall3cdfc4d2010-08-13 08:35:10 +0000545 = MD->getTemplateSpecializationInfo()) {
John McCall6ce51ee2011-06-27 23:06:04 +0000546 if (shouldConsiderTemplateLV(MD, spec)) {
547 LV.merge(getLVForTemplateArgumentList(*spec->TemplateArguments, F));
548 if (F.ConsiderTemplateParameterTypes)
549 LV.merge(getLVForTemplateParameterList(
550 spec->getTemplate()->getTemplateParameters()));
551 }
John McCall110e8e52010-10-29 22:22:43 +0000552
John McCall6ce51ee2011-06-27 23:06:04 +0000553 TSK = spec->getTemplateSpecializationKind();
John McCall110e8e52010-10-29 22:22:43 +0000554 } else if (MemberSpecializationInfo *MSI =
555 MD->getMemberSpecializationInfo()) {
556 TSK = MSI->getTemplateSpecializationKind();
John McCall3cdfc4d2010-08-13 08:35:10 +0000557 }
558
John McCall110e8e52010-10-29 22:22:43 +0000559 // If we're paying attention to global visibility, apply
560 // -finline-visibility-hidden if this is an inline method.
561 //
John McCallaf146032010-10-30 11:50:40 +0000562 // Note that ConsiderGlobalVisibility doesn't yet have information
563 // about whether containing classes have visibility attributes,
564 // and that's intentional.
565 if (TSK != TSK_ExplicitInstantiationDeclaration &&
Rafael Espindolafedb6ec2011-12-27 21:15:28 +0000566 TSK != TSK_ExplicitInstantiationDefinition &&
John McCall36987482010-11-02 01:45:15 +0000567 F.ConsiderGlobalVisibility &&
John McCall66cbcf32010-11-01 01:29:57 +0000568 MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
569 // InlineVisibilityHidden only applies to definitions, and
570 // isInlined() only gives meaningful answers on definitions
571 // anyway.
572 const FunctionDecl *Def = 0;
573 if (MD->hasBody(Def) && Def->isInlined())
574 LV.setVisibility(HiddenVisibility);
575 }
John McCall1fb0caa2010-10-22 21:05:15 +0000576
John McCall110e8e52010-10-29 22:22:43 +0000577 // Note that in contrast to basically every other situation, we
578 // *do* apply -fvisibility to method declarations.
579
580 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCall6ce51ee2011-06-27 23:06:04 +0000581 if (const ClassTemplateSpecializationDecl *spec
John McCall110e8e52010-10-29 22:22:43 +0000582 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCall6ce51ee2011-06-27 23:06:04 +0000583 if (shouldConsiderTemplateLV(spec)) {
584 // Merge template argument/parameter information for member
585 // class template specializations.
586 LV.merge(getLVForTemplateArgumentList(spec->getTemplateArgs(), F));
John McCall1a0918a2011-03-04 10:39:25 +0000587 if (F.ConsiderTemplateParameterTypes)
588 LV.merge(getLVForTemplateParameterList(
John McCall6ce51ee2011-06-27 23:06:04 +0000589 spec->getSpecializedTemplate()->getTemplateParameters()));
590 }
John McCall110e8e52010-10-29 22:22:43 +0000591 }
592
John McCall110e8e52010-10-29 22:22:43 +0000593 // Static data members.
594 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallee301022010-10-30 09:18:49 +0000595 // Modify the variable's linkage by its type, but ignore the
596 // type's visibility unless it's a definition.
Rafael Espindola093ecc92012-01-14 00:30:36 +0000597 LinkageInfo TypeLV = getLVForType(VD->getType());
598 if (TypeLV.linkage() != ExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000599 LV.mergeLinkage(UniqueExternalLinkage);
600 if (!LV.visibilityExplicit())
Rafael Espindola093ecc92012-01-14 00:30:36 +0000601 LV.mergeVisibility(TypeLV.visibility(), TypeLV.visibilityExplicit());
John McCall110e8e52010-10-29 22:22:43 +0000602 }
603
John McCall36987482010-11-02 01:45:15 +0000604 F.ConsiderGlobalVisibility &= !LV.visibilityExplicit();
John McCall110e8e52010-10-29 22:22:43 +0000605
606 // Apply -fvisibility if desired.
John McCall36987482010-11-02 01:45:15 +0000607 if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) {
John McCallaf146032010-10-30 11:50:40 +0000608 LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode());
John McCall3cdfc4d2010-08-13 08:35:10 +0000609 }
610
John McCall1fb0caa2010-10-22 21:05:15 +0000611 return LV;
John McCall3cdfc4d2010-08-13 08:35:10 +0000612}
613
John McCallf76b0922011-02-08 19:01:05 +0000614static void clearLinkageForClass(const CXXRecordDecl *record) {
615 for (CXXRecordDecl::decl_iterator
616 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
617 Decl *child = *i;
618 if (isa<NamedDecl>(child))
619 cast<NamedDecl>(child)->ClearLinkageCache();
620 }
621}
622
David Blaikie99ba9e32011-12-20 02:48:34 +0000623void NamedDecl::anchor() { }
624
John McCallf76b0922011-02-08 19:01:05 +0000625void NamedDecl::ClearLinkageCache() {
626 // Note that we can't skip clearing the linkage of children just
627 // because the parent doesn't have cached linkage: we don't cache
628 // when computing linkage for parent contexts.
629
630 HasCachedLinkage = 0;
631
632 // If we're changing the linkage of a class, we need to reset the
633 // linkage of child declarations, too.
634 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
635 clearLinkageForClass(record);
636
John McCall15e310a2011-02-19 02:53:41 +0000637 if (ClassTemplateDecl *temp =
638 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
John McCallf76b0922011-02-08 19:01:05 +0000639 // Clear linkage for the template pattern.
640 CXXRecordDecl *record = temp->getTemplatedDecl();
641 record->HasCachedLinkage = 0;
642 clearLinkageForClass(record);
643
John McCall15e310a2011-02-19 02:53:41 +0000644 // We need to clear linkage for specializations, too.
645 for (ClassTemplateDecl::spec_iterator
646 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
647 i->ClearLinkageCache();
John McCallf76b0922011-02-08 19:01:05 +0000648 }
John McCall15e310a2011-02-19 02:53:41 +0000649
650 // Clear cached linkage for function template decls, too.
651 if (FunctionTemplateDecl *temp =
John McCall78951942011-03-22 06:58:49 +0000652 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
653 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall15e310a2011-02-19 02:53:41 +0000654 for (FunctionTemplateDecl::spec_iterator
655 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
656 i->ClearLinkageCache();
John McCall78951942011-03-22 06:58:49 +0000657 }
John McCall15e310a2011-02-19 02:53:41 +0000658
John McCallf76b0922011-02-08 19:01:05 +0000659}
660
Douglas Gregor381d34e2010-12-06 18:36:25 +0000661Linkage NamedDecl::getLinkage() const {
662 if (HasCachedLinkage) {
Benjamin Kramer56ed7922010-12-07 15:51:48 +0000663 assert(Linkage(CachedLinkage) ==
664 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
Douglas Gregor381d34e2010-12-06 18:36:25 +0000665 return Linkage(CachedLinkage);
666 }
667
668 CachedLinkage = getLVForDecl(this,
669 LVFlags::CreateOnlyDeclLinkage()).linkage();
670 HasCachedLinkage = 1;
671 return Linkage(CachedLinkage);
672}
673
John McCallaf146032010-10-30 11:50:40 +0000674LinkageInfo NamedDecl::getLinkageAndVisibility() const {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000675 LinkageInfo LI = getLVForDecl(this, LVFlags());
Benjamin Kramer56ed7922010-12-07 15:51:48 +0000676 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
Douglas Gregor381d34e2010-12-06 18:36:25 +0000677 HasCachedLinkage = 1;
678 CachedLinkage = LI.linkage();
679 return LI;
John McCall0df95872010-10-29 00:29:13 +0000680}
Ted Kremenekbecc3082010-04-20 23:15:35 +0000681
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000682llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
683 // Use the most recent declaration of a variable.
684 if (const VarDecl *var = dyn_cast<VarDecl>(this))
Douglas Gregoref96ee02012-01-14 16:38:05 +0000685 return getVisibilityOf(var->getMostRecentDecl());
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000686
687 // Use the most recent declaration of a function, and also handle
688 // function template specializations.
689 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
690 if (llvm::Optional<Visibility> V
Douglas Gregoref96ee02012-01-14 16:38:05 +0000691 = getVisibilityOf(fn->getMostRecentDecl()))
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000692 return V;
693
694 // If the function is a specialization of a template with an
695 // explicit visibility attribute, use that.
696 if (FunctionTemplateSpecializationInfo *templateInfo
697 = fn->getTemplateSpecializationInfo())
698 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
699
700 return llvm::Optional<Visibility>();
701 }
702
703 // Otherwise, just check the declaration itself first.
704 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
705 return V;
706
707 // If there wasn't explicit visibility there, and this is a
708 // specialization of a class template, check for visibility
709 // on the pattern.
710 if (const ClassTemplateSpecializationDecl *spec
711 = dyn_cast<ClassTemplateSpecializationDecl>(this))
712 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
713
714 return llvm::Optional<Visibility>();
715}
716
John McCall36987482010-11-02 01:45:15 +0000717static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
Ted Kremenekbecc3082010-04-20 23:15:35 +0000718 // Objective-C: treat all Objective-C declarations as having external
719 // linkage.
John McCall0df95872010-10-29 00:29:13 +0000720 switch (D->getKind()) {
Ted Kremenekbecc3082010-04-20 23:15:35 +0000721 default:
722 break;
Argyrios Kyrtzidisf8d34ed2011-12-01 01:28:21 +0000723 case Decl::ParmVar:
724 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +0000725 case Decl::TemplateTemplateParm: // count these as external
726 case Decl::NonTypeTemplateParm:
Ted Kremenekbecc3082010-04-20 23:15:35 +0000727 case Decl::ObjCAtDefsField:
728 case Decl::ObjCCategory:
729 case Decl::ObjCCategoryImpl:
Ted Kremenekbecc3082010-04-20 23:15:35 +0000730 case Decl::ObjCCompatibleAlias:
Ted Kremenekbecc3082010-04-20 23:15:35 +0000731 case Decl::ObjCImplementation:
Ted Kremenekbecc3082010-04-20 23:15:35 +0000732 case Decl::ObjCMethod:
733 case Decl::ObjCProperty:
734 case Decl::ObjCPropertyImpl:
735 case Decl::ObjCProtocol:
John McCallaf146032010-10-30 11:50:40 +0000736 return LinkageInfo::external();
Ted Kremenekbecc3082010-04-20 23:15:35 +0000737 }
738
Douglas Gregord85b5b92009-11-25 22:24:25 +0000739 // Handle linkage for namespace-scope names.
John McCall0df95872010-10-29 00:29:13 +0000740 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCall36987482010-11-02 01:45:15 +0000741 return getLVForNamespaceScopeDecl(D, Flags);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000742
743 // C++ [basic.link]p5:
744 // In addition, a member function, static data member, a named
745 // class or enumeration of class scope, or an unnamed class or
746 // enumeration defined in a class-scope typedef declaration such
747 // that the class or enumeration has the typedef name for linkage
748 // purposes (7.1.3), has external linkage if the name of the class
749 // has external linkage.
John McCall0df95872010-10-29 00:29:13 +0000750 if (D->getDeclContext()->isRecord())
John McCall36987482010-11-02 01:45:15 +0000751 return getLVForClassMember(D, Flags);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000752
753 // C++ [basic.link]p6:
754 // The name of a function declared in block scope and the name of
755 // an object declared by a block scope extern declaration have
756 // linkage. If there is a visible declaration of an entity with
757 // linkage having the same name and type, ignoring entities
758 // declared outside the innermost enclosing namespace scope, the
759 // block scope declaration declares that same entity and receives
760 // the linkage of the previous declaration. If there is more than
761 // one such matching entity, the program is ill-formed. Otherwise,
762 // if no matching entity is found, the block scope entity receives
763 // external linkage.
John McCall0df95872010-10-29 00:29:13 +0000764 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
765 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Eli Friedman750dc2b2012-01-15 01:23:58 +0000766 if (Function->isInAnonymousNamespace() &&
767 !Function->getDeclContext()->isExternCContext())
John McCallaf146032010-10-30 11:50:40 +0000768 return LinkageInfo::uniqueExternal();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000769
John McCallaf146032010-10-30 11:50:40 +0000770 LinkageInfo LV;
Douglas Gregor381d34e2010-12-06 18:36:25 +0000771 if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000772 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
773 LV.setVisibility(*Vis);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000774 }
775
Douglas Gregoref96ee02012-01-14 16:38:05 +0000776 if (const FunctionDecl *Prev = Function->getPreviousDecl()) {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000777 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallaf146032010-10-30 11:50:40 +0000778 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
779 LV.mergeVisibility(PrevLV);
John McCall1fb0caa2010-10-22 21:05:15 +0000780 }
781
782 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000783 }
784
John McCall0df95872010-10-29 00:29:13 +0000785 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
John McCalld931b082010-08-26 03:08:43 +0000786 if (Var->getStorageClass() == SC_Extern ||
787 Var->getStorageClass() == SC_PrivateExtern) {
Eli Friedman750dc2b2012-01-15 01:23:58 +0000788 if (Var->isInAnonymousNamespace() &&
789 !Var->getDeclContext()->isExternCContext())
John McCallaf146032010-10-30 11:50:40 +0000790 return LinkageInfo::uniqueExternal();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000791
John McCallaf146032010-10-30 11:50:40 +0000792 LinkageInfo LV;
John McCall1fb0caa2010-10-22 21:05:15 +0000793 if (Var->getStorageClass() == SC_PrivateExtern)
John McCallaf146032010-10-30 11:50:40 +0000794 LV.setVisibility(HiddenVisibility);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000795 else if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000796 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
797 LV.setVisibility(*Vis);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000798 }
799
Douglas Gregoref96ee02012-01-14 16:38:05 +0000800 if (const VarDecl *Prev = Var->getPreviousDecl()) {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000801 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallaf146032010-10-30 11:50:40 +0000802 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
803 LV.mergeVisibility(PrevLV);
John McCall1fb0caa2010-10-22 21:05:15 +0000804 }
805
806 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000807 }
808 }
809
810 // C++ [basic.link]p6:
811 // Names not covered by these rules have no linkage.
John McCallaf146032010-10-30 11:50:40 +0000812 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +0000813}
Douglas Gregord85b5b92009-11-25 22:24:25 +0000814
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000815std::string NamedDecl::getQualifiedNameAsString() const {
Anders Carlsson3a082d82009-09-08 18:24:21 +0000816 return getQualifiedNameAsString(getASTContext().getLangOptions());
817}
818
819std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000820 const DeclContext *Ctx = getDeclContext();
821
822 if (Ctx->isFunctionOrMethod())
823 return getNameAsString();
824
Chris Lattner5f9e2722011-07-23 10:55:15 +0000825 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000826 ContextsTy Contexts;
827
828 // Collect contexts.
829 while (Ctx && isa<NamedDecl>(Ctx)) {
830 Contexts.push_back(Ctx);
831 Ctx = Ctx->getParent();
832 };
833
834 std::string QualName;
835 llvm::raw_string_ostream OS(QualName);
836
837 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
838 I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000839 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000840 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000841 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
842 std::string TemplateArgsStr
843 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +0000844 TemplateArgs.data(),
845 TemplateArgs.size(),
Anders Carlsson3a082d82009-09-08 18:24:21 +0000846 P);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000847 OS << Spec->getName() << TemplateArgsStr;
848 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig6be11202009-12-24 23:15:03 +0000849 if (ND->isAnonymousNamespace())
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000850 OS << "<anonymous namespace>";
Sam Weinig6be11202009-12-24 23:15:03 +0000851 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000852 OS << *ND;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000853 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
854 if (!RD->getIdentifier())
855 OS << "<anonymous " << RD->getKindName() << '>';
856 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000857 OS << *RD;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000858 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinig3521d012009-12-28 03:19:38 +0000859 const FunctionProtoType *FT = 0;
860 if (FD->hasWrittenPrototype())
861 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
862
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000863 OS << *FD << '(';
Sam Weinig3521d012009-12-28 03:19:38 +0000864 if (FT) {
Sam Weinig3521d012009-12-28 03:19:38 +0000865 unsigned NumParams = FD->getNumParams();
866 for (unsigned i = 0; i < NumParams; ++i) {
867 if (i)
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000868 OS << ", ";
Sam Weinig3521d012009-12-28 03:19:38 +0000869 std::string Param;
870 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000871 OS << Param;
Sam Weinig3521d012009-12-28 03:19:38 +0000872 }
873
874 if (FT->isVariadic()) {
875 if (NumParams > 0)
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000876 OS << ", ";
877 OS << "...";
Sam Weinig3521d012009-12-28 03:19:38 +0000878 }
879 }
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000880 OS << ')';
881 } else {
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000882 OS << *cast<NamedDecl>(*I);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000883 }
884 OS << "::";
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000885 }
886
John McCall8472af42010-03-16 21:48:18 +0000887 if (getDeclName())
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000888 OS << *this;
John McCall8472af42010-03-16 21:48:18 +0000889 else
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000890 OS << "<anonymous>";
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000891
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000892 return OS.str();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000893}
894
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000895bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000896 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
897
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000898 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
899 // We want to keep it, unless it nominates same namespace.
900 if (getKind() == Decl::UsingDirective) {
Douglas Gregordb992412011-02-25 16:33:46 +0000901 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
902 ->getOriginalNamespace() ==
903 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
904 ->getOriginalNamespace();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000905 }
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000907 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
908 // For function declarations, we keep track of redeclarations.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000909 return FD->getPreviousDecl() == OldD;
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000910
Douglas Gregore53060f2009-06-25 22:08:12 +0000911 // For function templates, the underlying function declarations are linked.
912 if (const FunctionTemplateDecl *FunctionTemplate
913 = dyn_cast<FunctionTemplateDecl>(this))
914 if (const FunctionTemplateDecl *OldFunctionTemplate
915 = dyn_cast<FunctionTemplateDecl>(OldD))
916 return FunctionTemplate->getTemplatedDecl()
917 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Steve Naroff0de21fd2009-02-22 19:35:57 +0000919 // For method declarations, we keep track of redeclarations.
920 if (isa<ObjCMethodDecl>(this))
921 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000922
John McCallf36e02d2009-10-09 21:13:30 +0000923 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
924 return true;
925
John McCall9488ea12009-11-17 05:59:44 +0000926 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
927 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
928 cast<UsingShadowDecl>(OldD)->getTargetDecl();
929
Douglas Gregordc355712011-02-25 00:36:19 +0000930 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
931 ASTContext &Context = getASTContext();
932 return Context.getCanonicalNestedNameSpecifier(
933 cast<UsingDecl>(this)->getQualifier()) ==
934 Context.getCanonicalNestedNameSpecifier(
935 cast<UsingDecl>(OldD)->getQualifier());
936 }
Argyrios Kyrtzidisc80117e2010-11-04 08:48:52 +0000937
Douglas Gregor7a537402012-01-03 23:26:26 +0000938 // A typedef of an Objective-C class type can replace an Objective-C class
939 // declaration or definition, and vice versa.
940 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
941 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
942 return true;
943
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000944 // For non-function declarations, if the declarations are of the
945 // same kind then this must be a redeclaration, or semantic analysis
946 // would not have given us the new declaration.
947 return this->getKind() == OldD->getKind();
948}
949
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000950bool NamedDecl::hasLinkage() const {
Douglas Gregord85b5b92009-11-25 22:24:25 +0000951 return getLinkage() != NoLinkage;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000952}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000953
Anders Carlssone136e0e2009-06-26 06:29:23 +0000954NamedDecl *NamedDecl::getUnderlyingDecl() {
955 NamedDecl *ND = this;
956 while (true) {
John McCall9488ea12009-11-17 05:59:44 +0000957 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
Anders Carlssone136e0e2009-06-26 06:29:23 +0000958 ND = UD->getTargetDecl();
959 else if (ObjCCompatibleAliasDecl *AD
960 = dyn_cast<ObjCCompatibleAliasDecl>(ND))
961 return AD->getClassInterface();
962 else
963 return ND;
964 }
965}
966
John McCall161755a2010-04-06 21:38:20 +0000967bool NamedDecl::isCXXInstanceMember() const {
968 assert(isCXXClassMember() &&
969 "checking whether non-member is instance member");
970
971 const NamedDecl *D = this;
972 if (isa<UsingShadowDecl>(D))
973 D = cast<UsingShadowDecl>(D)->getTargetDecl();
974
Francois Pichet87c2e122010-11-21 06:08:52 +0000975 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCall161755a2010-04-06 21:38:20 +0000976 return true;
977 if (isa<CXXMethodDecl>(D))
978 return cast<CXXMethodDecl>(D)->isInstance();
979 if (isa<FunctionTemplateDecl>(D))
980 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
981 ->getTemplatedDecl())->isInstance();
982 return false;
983}
984
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +0000985//===----------------------------------------------------------------------===//
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000986// DeclaratorDecl Implementation
987//===----------------------------------------------------------------------===//
988
Douglas Gregor1693e152010-07-06 18:42:40 +0000989template <typename DeclT>
990static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
991 if (decl->getNumTemplateParameterLists() > 0)
992 return decl->getTemplateParameterList(0)->getTemplateLoc();
993 else
994 return decl->getInnerLocStart();
995}
996
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000997SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCall4e449832010-05-28 23:32:21 +0000998 TypeSourceInfo *TSI = getTypeSourceInfo();
999 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001000 return SourceLocation();
1001}
1002
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001003void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1004 if (QualifierLoc) {
John McCallb6217662010-03-15 10:12:16 +00001005 // Make sure the extended decl info is allocated.
1006 if (!hasExtInfo()) {
1007 // Save (non-extended) type source info pointer.
1008 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1009 // Allocate external info struct.
1010 DeclInfo = new (getASTContext()) ExtInfo;
1011 // Restore savedTInfo into (extended) decl info.
1012 getExtInfo()->TInfo = savedTInfo;
1013 }
1014 // Set qualifier info.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001015 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier30601782011-08-17 23:08:45 +00001016 } else {
John McCallb6217662010-03-15 10:12:16 +00001017 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCallb6217662010-03-15 10:12:16 +00001018 if (hasExtInfo()) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001019 if (getExtInfo()->NumTemplParamLists == 0) {
1020 // Save type source info pointer.
1021 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1022 // Deallocate the extended decl info.
1023 getASTContext().Deallocate(getExtInfo());
1024 // Restore savedTInfo into (non-extended) decl info.
1025 DeclInfo = savedTInfo;
1026 }
1027 else
1028 getExtInfo()->QualifierLoc = QualifierLoc;
John McCallb6217662010-03-15 10:12:16 +00001029 }
1030 }
1031}
1032
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001033void
1034DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1035 unsigned NumTPLists,
1036 TemplateParameterList **TPLists) {
1037 assert(NumTPLists > 0);
1038 // Make sure the extended decl info is allocated.
1039 if (!hasExtInfo()) {
1040 // Save (non-extended) type source info pointer.
1041 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1042 // Allocate external info struct.
1043 DeclInfo = new (getASTContext()) ExtInfo;
1044 // Restore savedTInfo into (extended) decl info.
1045 getExtInfo()->TInfo = savedTInfo;
1046 }
1047 // Set the template parameter lists info.
1048 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1049}
1050
Douglas Gregor1693e152010-07-06 18:42:40 +00001051SourceLocation DeclaratorDecl::getOuterLocStart() const {
1052 return getTemplateOrInnerLocStart(this);
1053}
1054
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001055namespace {
1056
1057// Helper function: returns true if QT is or contains a type
1058// having a postfix component.
1059bool typeIsPostfix(clang::QualType QT) {
1060 while (true) {
1061 const Type* T = QT.getTypePtr();
1062 switch (T->getTypeClass()) {
1063 default:
1064 return false;
1065 case Type::Pointer:
1066 QT = cast<PointerType>(T)->getPointeeType();
1067 break;
1068 case Type::BlockPointer:
1069 QT = cast<BlockPointerType>(T)->getPointeeType();
1070 break;
1071 case Type::MemberPointer:
1072 QT = cast<MemberPointerType>(T)->getPointeeType();
1073 break;
1074 case Type::LValueReference:
1075 case Type::RValueReference:
1076 QT = cast<ReferenceType>(T)->getPointeeType();
1077 break;
1078 case Type::PackExpansion:
1079 QT = cast<PackExpansionType>(T)->getPattern();
1080 break;
1081 case Type::Paren:
1082 case Type::ConstantArray:
1083 case Type::DependentSizedArray:
1084 case Type::IncompleteArray:
1085 case Type::VariableArray:
1086 case Type::FunctionProto:
1087 case Type::FunctionNoProto:
1088 return true;
1089 }
1090 }
1091}
1092
1093} // namespace
1094
1095SourceRange DeclaratorDecl::getSourceRange() const {
1096 SourceLocation RangeEnd = getLocation();
1097 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1098 if (typeIsPostfix(TInfo->getType()))
1099 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1100 }
1101 return SourceRange(getOuterLocStart(), RangeEnd);
1102}
1103
Abramo Bagnara9b934882010-06-12 08:15:14 +00001104void
Douglas Gregorc722ea42010-06-15 17:44:38 +00001105QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1106 unsigned NumTPLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00001107 TemplateParameterList **TPLists) {
1108 assert((NumTPLists == 0 || TPLists != 0) &&
1109 "Empty array of template parameters with positive size!");
Abramo Bagnara9b934882010-06-12 08:15:14 +00001110
1111 // Free previous template parameters (if any).
1112 if (NumTemplParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00001113 Context.Deallocate(TemplParamLists);
Abramo Bagnara9b934882010-06-12 08:15:14 +00001114 TemplParamLists = 0;
1115 NumTemplParamLists = 0;
1116 }
1117 // Set info on matched template parameter lists (if any).
1118 if (NumTPLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00001119 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnara9b934882010-06-12 08:15:14 +00001120 NumTemplParamLists = NumTPLists;
1121 for (unsigned i = NumTPLists; i-- > 0; )
1122 TemplParamLists[i] = TPLists[i];
1123 }
1124}
1125
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001126//===----------------------------------------------------------------------===//
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001127// VarDecl Implementation
1128//===----------------------------------------------------------------------===//
1129
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001130const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1131 switch (SC) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00001132 case SC_None: break;
Peter Collingbourne8be0c742011-09-20 12:40:26 +00001133 case SC_Auto: return "auto";
1134 case SC_Extern: return "extern";
1135 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1136 case SC_PrivateExtern: return "__private_extern__";
1137 case SC_Register: return "register";
1138 case SC_Static: return "static";
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001139 }
1140
Peter Collingbourne8be0c742011-09-20 12:40:26 +00001141 llvm_unreachable("Invalid storage class");
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001142}
1143
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001144VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1145 SourceLocation StartL, SourceLocation IdL,
John McCalla93c9342009-12-07 02:54:59 +00001146 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001147 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001148 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001149}
1150
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00001151VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1152 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1153 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1154 QualType(), 0, SC_None, SC_None);
1155}
1156
Douglas Gregor381d34e2010-12-06 18:36:25 +00001157void VarDecl::setStorageClass(StorageClass SC) {
1158 assert(isLegalForVariable(SC));
1159 if (getStorageClass() != SC)
1160 ClearLinkageCache();
1161
John McCallf1e4fbf2011-05-01 02:13:58 +00001162 VarDeclBits.SClass = SC;
Douglas Gregor381d34e2010-12-06 18:36:25 +00001163}
1164
Douglas Gregor1693e152010-07-06 18:42:40 +00001165SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001166 if (getInit())
Douglas Gregor1693e152010-07-06 18:42:40 +00001167 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001168 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001169}
1170
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001171bool VarDecl::isExternC() const {
Eli Friedman750dc2b2012-01-15 01:23:58 +00001172 if (getLinkage() != ExternalLinkage)
Chandler Carruth10aad442011-02-25 00:05:02 +00001173 return false;
1174
Eli Friedman750dc2b2012-01-15 01:23:58 +00001175 const DeclContext *DC = getDeclContext();
1176 if (DC->isRecord())
1177 return false;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001178
Eli Friedman750dc2b2012-01-15 01:23:58 +00001179 ASTContext &Context = getASTContext();
1180 if (!Context.getLangOptions().CPlusPlus)
1181 return true;
1182 return DC->isExternCContext();
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001183}
1184
1185VarDecl *VarDecl::getCanonicalDecl() {
1186 return getFirstDeclaration();
1187}
1188
Sebastian Redle9d12b62010-01-31 22:27:38 +00001189VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
1190 // C++ [basic.def]p2:
1191 // A declaration is a definition unless [...] it contains the 'extern'
1192 // specifier or a linkage-specification and neither an initializer [...],
1193 // it declares a static data member in a class declaration [...].
1194 // C++ [temp.expl.spec]p15:
1195 // An explicit specialization of a static data member of a template is a
1196 // definition if the declaration includes an initializer; otherwise, it is
1197 // a declaration.
1198 if (isStaticDataMember()) {
1199 if (isOutOfLine() && (hasInit() ||
1200 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1201 return Definition;
1202 else
1203 return DeclarationOnly;
1204 }
1205 // C99 6.7p5:
1206 // A definition of an identifier is a declaration for that identifier that
1207 // [...] causes storage to be reserved for that object.
1208 // Note: that applies for all non-file-scope objects.
1209 // C99 6.9.2p1:
1210 // If the declaration of an identifier for an object has file scope and an
1211 // initializer, the declaration is an external definition for the identifier
1212 if (hasInit())
1213 return Definition;
1214 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1215 if (hasExternalStorage())
1216 return DeclarationOnly;
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001217
John McCalld931b082010-08-26 03:08:43 +00001218 if (getStorageClassAsWritten() == SC_Extern ||
1219 getStorageClassAsWritten() == SC_PrivateExtern) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00001220 for (const VarDecl *PrevVar = getPreviousDecl();
1221 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001222 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1223 return DeclarationOnly;
1224 }
1225 }
Sebastian Redle9d12b62010-01-31 22:27:38 +00001226 // C99 6.9.2p2:
1227 // A declaration of an object that has file scope without an initializer,
1228 // and without a storage class specifier or the scs 'static', constitutes
1229 // a tentative definition.
1230 // No such thing in C++.
1231 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
1232 return TentativeDefinition;
1233
1234 // What's left is (in C, block-scope) declarations without initializers or
1235 // external storage. These are definitions.
1236 return Definition;
1237}
1238
Sebastian Redle9d12b62010-01-31 22:27:38 +00001239VarDecl *VarDecl::getActingDefinition() {
1240 DefinitionKind Kind = isThisDeclarationADefinition();
1241 if (Kind != TentativeDefinition)
1242 return 0;
1243
Chris Lattnerf0ed9ef2010-06-14 18:31:46 +00001244 VarDecl *LastTentative = 0;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001245 VarDecl *First = getFirstDeclaration();
1246 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1247 I != E; ++I) {
1248 Kind = (*I)->isThisDeclarationADefinition();
1249 if (Kind == Definition)
1250 return 0;
1251 else if (Kind == TentativeDefinition)
1252 LastTentative = *I;
1253 }
1254 return LastTentative;
1255}
1256
1257bool VarDecl::isTentativeDefinitionNow() const {
1258 DefinitionKind Kind = isThisDeclarationADefinition();
1259 if (Kind != TentativeDefinition)
1260 return false;
1261
1262 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1263 if ((*I)->isThisDeclarationADefinition() == Definition)
1264 return false;
1265 }
Sebastian Redl31310a22010-02-01 20:16:42 +00001266 return true;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001267}
1268
Sebastian Redl31310a22010-02-01 20:16:42 +00001269VarDecl *VarDecl::getDefinition() {
Sebastian Redle2c52d22010-02-02 17:55:12 +00001270 VarDecl *First = getFirstDeclaration();
1271 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1272 I != E; ++I) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001273 if ((*I)->isThisDeclarationADefinition() == Definition)
1274 return *I;
1275 }
1276 return 0;
1277}
1278
John McCall110e8e52010-10-29 22:22:43 +00001279VarDecl::DefinitionKind VarDecl::hasDefinition() const {
1280 DefinitionKind Kind = DeclarationOnly;
1281
1282 const VarDecl *First = getFirstDeclaration();
1283 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1284 I != E; ++I)
1285 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition());
1286
1287 return Kind;
1288}
1289
Sebastian Redl31310a22010-02-01 20:16:42 +00001290const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001291 redecl_iterator I = redecls_begin(), E = redecls_end();
1292 while (I != E && !I->getInit())
1293 ++I;
1294
1295 if (I != E) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001296 D = *I;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001297 return I->getInit();
1298 }
1299 return 0;
1300}
1301
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001302bool VarDecl::isOutOfLine() const {
Douglas Gregorda2142f2011-02-19 18:51:44 +00001303 if (Decl::isOutOfLine())
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001304 return true;
Chandler Carruth8761d682010-02-21 07:08:09 +00001305
1306 if (!isStaticDataMember())
1307 return false;
1308
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001309 // If this static data member was instantiated from a static data member of
1310 // a class template, check whether that static data member was defined
1311 // out-of-line.
1312 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1313 return VD->isOutOfLine();
1314
1315 return false;
1316}
1317
Douglas Gregor0d035142009-10-27 18:42:08 +00001318VarDecl *VarDecl::getOutOfLineDefinition() {
1319 if (!isStaticDataMember())
1320 return 0;
1321
1322 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1323 RD != RDEnd; ++RD) {
1324 if (RD->getLexicalDeclContext()->isFileContext())
1325 return *RD;
1326 }
1327
1328 return 0;
1329}
1330
Douglas Gregor838db382010-02-11 01:19:42 +00001331void VarDecl::setInit(Expr *I) {
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001332 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1333 Eval->~EvaluatedStmt();
Douglas Gregor838db382010-02-11 01:19:42 +00001334 getASTContext().Deallocate(Eval);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001335 }
1336
1337 Init = I;
1338}
1339
Richard Smith1d238ea2011-12-21 02:55:12 +00001340bool VarDecl::isUsableInConstantExpressions() const {
1341 const LangOptions &Lang = getASTContext().getLangOptions();
1342
1343 // Only const variables can be used in constant expressions in C++. C++98 does
1344 // not require the variable to be non-volatile, but we consider this to be a
1345 // defect.
1346 if (!Lang.CPlusPlus ||
1347 !getType().isConstQualified() || getType().isVolatileQualified())
1348 return false;
1349
1350 // In C++, const, non-volatile variables of integral or enumeration types
1351 // can be used in constant expressions.
1352 if (getType()->isIntegralOrEnumerationType())
1353 return true;
1354
1355 // Additionally, in C++11, non-volatile constexpr variables and references can
1356 // be used in constant expressions.
1357 return Lang.CPlusPlus0x && (isConstexpr() || getType()->isReferenceType());
1358}
1359
Richard Smith099e7f62011-12-19 06:19:21 +00001360/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1361/// form, which contains extra information on the evaluated value of the
1362/// initializer.
1363EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1364 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1365 if (!Eval) {
1366 Stmt *S = Init.get<Stmt *>();
1367 Eval = new (getASTContext()) EvaluatedStmt;
1368 Eval->Value = S;
1369 Init = Eval;
1370 }
1371 return Eval;
1372}
1373
Richard Smith2d6a5672012-01-14 04:30:29 +00001374APValue *VarDecl::evaluateValue() const {
1375 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1376 return evaluateValue(Notes);
1377}
1378
1379APValue *VarDecl::evaluateValue(
1380 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith099e7f62011-12-19 06:19:21 +00001381 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1382
1383 // We only produce notes indicating why an initializer is non-constant the
1384 // first time it is evaluated. FIXME: The notes won't always be emitted the
1385 // first time we try evaluation, so might not be produced at all.
1386 if (Eval->WasEvaluated)
Richard Smith2d6a5672012-01-14 04:30:29 +00001387 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smith099e7f62011-12-19 06:19:21 +00001388
1389 const Expr *Init = cast<Expr>(Eval->Value);
1390 assert(!Init->isValueDependent());
1391
1392 if (Eval->IsEvaluating) {
1393 // FIXME: Produce a diagnostic for self-initialization.
1394 Eval->CheckedICE = true;
1395 Eval->IsICE = false;
Richard Smith2d6a5672012-01-14 04:30:29 +00001396 return 0;
Richard Smith099e7f62011-12-19 06:19:21 +00001397 }
1398
1399 Eval->IsEvaluating = true;
1400
1401 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1402 this, Notes);
1403
1404 // Ensure the result is an uninitialized APValue if evaluation fails.
1405 if (!Result)
1406 Eval->Evaluated = APValue();
1407
1408 Eval->IsEvaluating = false;
1409 Eval->WasEvaluated = true;
1410
1411 // In C++11, we have determined whether the initializer was a constant
1412 // expression as a side-effect.
1413 if (getASTContext().getLangOptions().CPlusPlus0x && !Eval->CheckedICE) {
1414 Eval->CheckedICE = true;
1415 Eval->IsICE = Notes.empty();
1416 }
1417
Richard Smith2d6a5672012-01-14 04:30:29 +00001418 return Result ? &Eval->Evaluated : 0;
Richard Smith099e7f62011-12-19 06:19:21 +00001419}
1420
1421bool VarDecl::checkInitIsICE() const {
John McCall73076432012-01-05 00:13:19 +00001422 // Initializers of weak variables are never ICEs.
1423 if (isWeak())
1424 return false;
1425
Richard Smith099e7f62011-12-19 06:19:21 +00001426 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1427 if (Eval->CheckedICE)
1428 // We have already checked whether this subexpression is an
1429 // integral constant expression.
1430 return Eval->IsICE;
1431
1432 const Expr *Init = cast<Expr>(Eval->Value);
1433 assert(!Init->isValueDependent());
1434
1435 // In C++11, evaluate the initializer to check whether it's a constant
1436 // expression.
1437 if (getASTContext().getLangOptions().CPlusPlus0x) {
1438 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1439 evaluateValue(Notes);
1440 return Eval->IsICE;
1441 }
1442
1443 // It's an ICE whether or not the definition we found is
1444 // out-of-line. See DR 721 and the discussion in Clang PR
1445 // 6206 for details.
1446
1447 if (Eval->CheckingICE)
1448 return false;
1449 Eval->CheckingICE = true;
1450
1451 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1452 Eval->CheckingICE = false;
1453 Eval->CheckedICE = true;
1454 return Eval->IsICE;
1455}
1456
Douglas Gregor03e80032011-06-21 17:03:29 +00001457bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregor0b581082011-06-21 18:20:46 +00001458 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregor03e80032011-06-21 17:03:29 +00001459
1460 const Expr *E = getInit();
1461 if (!E)
1462 return false;
1463
1464 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1465 E = Cleanups->getSubExpr();
1466
1467 return isa<MaterializeTemporaryExpr>(E);
1468}
1469
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001470VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001471 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001472 return cast<VarDecl>(MSI->getInstantiatedFrom());
1473
1474 return 0;
1475}
1476
Douglas Gregor663b5a02009-10-14 20:14:33 +00001477TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redle9d12b62010-01-31 22:27:38 +00001478 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001479 return MSI->getTemplateSpecializationKind();
1480
1481 return TSK_Undeclared;
1482}
1483
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001484MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001485 return getASTContext().getInstantiatedFromStaticDataMember(this);
1486}
1487
Douglas Gregor0a897e32009-10-15 17:21:20 +00001488void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1489 SourceLocation PointOfInstantiation) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001490 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001491 assert(MSI && "Not an instantiated static data member?");
1492 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor0a897e32009-10-15 17:21:20 +00001493 if (TSK != TSK_ExplicitSpecialization &&
1494 PointOfInstantiation.isValid() &&
1495 MSI->getPointOfInstantiation().isInvalid())
1496 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001497}
1498
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001499//===----------------------------------------------------------------------===//
1500// ParmVarDecl Implementation
1501//===----------------------------------------------------------------------===//
Douglas Gregor275a3692009-03-10 23:43:53 +00001502
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001503ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001504 SourceLocation StartLoc,
1505 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001506 QualType T, TypeSourceInfo *TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001507 StorageClass S, StorageClass SCAsWritten,
1508 Expr *DefArg) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001509 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001510 S, SCAsWritten, DefArg);
Douglas Gregor275a3692009-03-10 23:43:53 +00001511}
1512
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00001513ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1514 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1515 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1516 0, QualType(), 0, SC_None, SC_None, 0);
1517}
1518
Argyrios Kyrtzidis0bfe83b2011-07-30 17:23:26 +00001519SourceRange ParmVarDecl::getSourceRange() const {
1520 if (!hasInheritedDefaultArg()) {
1521 SourceRange ArgRange = getDefaultArgRange();
1522 if (ArgRange.isValid())
1523 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1524 }
1525
1526 return DeclaratorDecl::getSourceRange();
1527}
1528
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001529Expr *ParmVarDecl::getDefaultArg() {
1530 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1531 assert(!hasUninstantiatedDefaultArg() &&
1532 "Default argument is not yet instantiated!");
1533
1534 Expr *Arg = getInit();
John McCall4765fa02010-12-06 08:20:24 +00001535 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001536 return E->getSubExpr();
Douglas Gregor275a3692009-03-10 23:43:53 +00001537
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001538 return Arg;
1539}
1540
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001541SourceRange ParmVarDecl::getDefaultArgRange() const {
1542 if (const Expr *E = getInit())
1543 return E->getSourceRange();
1544
1545 if (hasUninstantiatedDefaultArg())
1546 return getUninstantiatedDefaultArg()->getSourceRange();
1547
1548 return SourceRange();
Argyrios Kyrtzidisfc7e2a82009-07-05 22:21:56 +00001549}
1550
Douglas Gregor1fe85ea2011-01-05 21:11:38 +00001551bool ParmVarDecl::isParameterPack() const {
1552 return isa<PackExpansionType>(getType());
1553}
1554
Ted Kremenekd211cb72011-10-06 05:00:56 +00001555void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1556 getASTContext().setParameterIndex(this, parameterIndex);
1557 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1558}
1559
1560unsigned ParmVarDecl::getParameterIndexLarge() const {
1561 return getASTContext().getParameterIndex(this);
1562}
1563
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001564//===----------------------------------------------------------------------===//
Chris Lattner8a934232008-03-31 00:36:02 +00001565// FunctionDecl Implementation
1566//===----------------------------------------------------------------------===//
1567
Douglas Gregorda2142f2011-02-19 18:51:44 +00001568void FunctionDecl::getNameForDiagnostic(std::string &S,
1569 const PrintingPolicy &Policy,
1570 bool Qualified) const {
1571 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1572 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1573 if (TemplateArgs)
1574 S += TemplateSpecializationType::PrintTemplateArgumentList(
1575 TemplateArgs->data(),
1576 TemplateArgs->size(),
1577 Policy);
1578
1579}
1580
Ted Kremenek9498d382010-04-29 16:49:01 +00001581bool FunctionDecl::isVariadic() const {
1582 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1583 return FT->isVariadic();
1584 return false;
1585}
1586
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001587bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1588 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001589 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001590 Definition = *I;
1591 return true;
1592 }
1593 }
1594
1595 return false;
1596}
1597
Anders Carlssonffb945f2011-05-14 23:26:09 +00001598bool FunctionDecl::hasTrivialBody() const
1599{
1600 Stmt *S = getBody();
1601 if (!S) {
1602 // Since we don't have a body for this function, we don't know if it's
1603 // trivial or not.
1604 return false;
1605 }
1606
1607 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1608 return true;
1609 return false;
1610}
1611
Sean Hunt10620eb2011-05-06 20:44:56 +00001612bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1613 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Sean Huntcd10dec2011-05-23 23:14:04 +00001614 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Sean Hunt10620eb2011-05-06 20:44:56 +00001615 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1616 return true;
1617 }
1618 }
1619
1620 return false;
1621}
1622
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001623Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidisc37929c2009-07-14 03:20:21 +00001624 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1625 if (I->Body) {
1626 Definition = *I;
1627 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet8387e2a2011-04-22 22:18:13 +00001628 } else if (I->IsLateTemplateParsed) {
1629 Definition = *I;
1630 return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +00001631 }
1632 }
1633
1634 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001635}
1636
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001637void FunctionDecl::setBody(Stmt *B) {
1638 Body = B;
Douglas Gregorb5f35ba2010-12-06 17:49:01 +00001639 if (B)
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001640 EndRangeLoc = B->getLocEnd();
1641}
1642
Douglas Gregor21386642010-09-28 21:55:22 +00001643void FunctionDecl::setPure(bool P) {
1644 IsPure = P;
1645 if (P)
1646 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1647 Parent->markedVirtualFunctionPure();
1648}
1649
Douglas Gregor48a83b52009-09-12 00:17:51 +00001650bool FunctionDecl::isMain() const {
John McCall23c608d2011-05-15 17:49:20 +00001651 const TranslationUnitDecl *tunit =
1652 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1653 return tunit &&
Sean Hunt55878032011-05-15 20:59:31 +00001654 !tunit->getASTContext().getLangOptions().Freestanding &&
John McCall23c608d2011-05-15 17:49:20 +00001655 getIdentifier() &&
1656 getIdentifier()->isStr("main");
1657}
1658
1659bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1660 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1661 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1662 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1663 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1664 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1665
1666 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1667 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1668
1669 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1670 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1671
1672 ASTContext &Context =
1673 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1674 ->getASTContext();
1675
1676 // The result type and first argument type are constant across all
1677 // these operators. The second argument must be exactly void*.
1678 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregor04495c82009-02-24 01:23:02 +00001679}
1680
Douglas Gregor48a83b52009-09-12 00:17:51 +00001681bool FunctionDecl::isExternC() const {
Eli Friedman750dc2b2012-01-15 01:23:58 +00001682 if (getLinkage() != ExternalLinkage)
1683 return false;
1684
1685 if (getAttr<OverloadableAttr>())
1686 return false;
Douglas Gregor63935192009-03-02 00:19:53 +00001687
Chandler Carruth10aad442011-02-25 00:05:02 +00001688 const DeclContext *DC = getDeclContext();
1689 if (DC->isRecord())
1690 return false;
1691
Eli Friedman750dc2b2012-01-15 01:23:58 +00001692 ASTContext &Context = getASTContext();
1693 if (!Context.getLangOptions().CPlusPlus)
1694 return true;
Douglas Gregor63935192009-03-02 00:19:53 +00001695
Eli Friedman750dc2b2012-01-15 01:23:58 +00001696 return isMain() || DC->isExternCContext();
Douglas Gregor63935192009-03-02 00:19:53 +00001697}
1698
Douglas Gregor8499f3f2009-03-31 16:35:03 +00001699bool FunctionDecl::isGlobal() const {
1700 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1701 return Method->isStatic();
1702
John McCalld931b082010-08-26 03:08:43 +00001703 if (getStorageClass() == SC_Static)
Douglas Gregor8499f3f2009-03-31 16:35:03 +00001704 return false;
1705
Mike Stump1eb44332009-09-09 15:08:12 +00001706 for (const DeclContext *DC = getDeclContext();
Douglas Gregor8499f3f2009-03-31 16:35:03 +00001707 DC->isNamespace();
1708 DC = DC->getParent()) {
1709 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1710 if (!Namespace->getDeclName())
1711 return false;
1712 break;
1713 }
1714 }
1715
1716 return true;
1717}
1718
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001719void
1720FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1721 redeclarable_base::setPreviousDeclaration(PrevDecl);
1722
1723 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1724 FunctionTemplateDecl *PrevFunTmpl
1725 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1726 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1727 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1728 }
Douglas Gregor8f150942010-12-09 16:59:22 +00001729
Axel Naumannd9d137e2011-11-08 18:21:06 +00001730 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregor8f150942010-12-09 16:59:22 +00001731 IsInline = true;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001732}
1733
1734const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1735 return getFirstDeclaration();
1736}
1737
1738FunctionDecl *FunctionDecl::getCanonicalDecl() {
1739 return getFirstDeclaration();
1740}
1741
Douglas Gregor381d34e2010-12-06 18:36:25 +00001742void FunctionDecl::setStorageClass(StorageClass SC) {
1743 assert(isLegalForFunction(SC));
1744 if (getStorageClass() != SC)
1745 ClearLinkageCache();
1746
1747 SClass = SC;
1748}
1749
Douglas Gregor3e41d602009-02-13 23:20:09 +00001750/// \brief Returns a value indicating whether this function
1751/// corresponds to a builtin function.
1752///
1753/// The function corresponds to a built-in function if it is
1754/// declared at translation scope or within an extern "C" block and
1755/// its name matches with the name of a builtin. The returned value
1756/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump1eb44332009-09-09 15:08:12 +00001757/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregor3e41d602009-02-13 23:20:09 +00001758/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001759unsigned FunctionDecl::getBuiltinID() const {
1760 ASTContext &Context = getASTContext();
Douglas Gregor3c385e52009-02-14 18:57:46 +00001761 if (!getIdentifier() || !getIdentifier()->getBuiltinID())
1762 return 0;
1763
1764 unsigned BuiltinID = getIdentifier()->getBuiltinID();
1765 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1766 return BuiltinID;
1767
1768 // This function has the name of a known C library
1769 // function. Determine whether it actually refers to the C library
1770 // function or whether it just has the same name.
1771
Douglas Gregor9add3172009-02-17 03:23:10 +00001772 // If this is a static function, it's not a builtin.
John McCalld931b082010-08-26 03:08:43 +00001773 if (getStorageClass() == SC_Static)
Douglas Gregor9add3172009-02-17 03:23:10 +00001774 return 0;
1775
Douglas Gregor3c385e52009-02-14 18:57:46 +00001776 // If this function is at translation-unit scope and we're not in
1777 // C++, it refers to the C library function.
1778 if (!Context.getLangOptions().CPlusPlus &&
1779 getDeclContext()->isTranslationUnit())
1780 return BuiltinID;
1781
1782 // If the function is in an extern "C" linkage specification and is
1783 // not marked "overloadable", it's the real function.
1784 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001785 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregor3c385e52009-02-14 18:57:46 +00001786 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001787 !getAttr<OverloadableAttr>())
Douglas Gregor3c385e52009-02-14 18:57:46 +00001788 return BuiltinID;
1789
1790 // Not a builtin
Douglas Gregor3e41d602009-02-13 23:20:09 +00001791 return 0;
1792}
1793
1794
Chris Lattner1ad9b282009-04-25 06:03:53 +00001795/// getNumParams - Return the number of parameters this function must have
Bob Wilson8dbfbf42011-01-10 18:23:55 +00001796/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner1ad9b282009-04-25 06:03:53 +00001797/// after it has been created.
1798unsigned FunctionDecl::getNumParams() const {
John McCall183700f2009-09-21 23:43:11 +00001799 const FunctionType *FT = getType()->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001800 if (isa<FunctionNoProtoType>(FT))
Chris Lattnerd3b90652008-03-15 05:43:15 +00001801 return 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001802 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Reid Spencer5f016e22007-07-11 17:01:13 +00001804}
1805
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00001806void FunctionDecl::setParams(ASTContext &C,
David Blaikie4278c652011-09-21 18:16:56 +00001807 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie4278c652011-09-21 18:16:56 +00001809 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Reid Spencer5f016e22007-07-11 17:01:13 +00001811 // Zero params -> null pointer.
David Blaikie4278c652011-09-21 18:16:56 +00001812 if (!NewParamInfo.empty()) {
1813 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1814 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001815 }
1816}
1817
Chris Lattner8123a952008-04-10 02:22:51 +00001818/// getMinRequiredArguments - Returns the minimum number of arguments
1819/// needed to call this function. This may be fewer than the number of
1820/// function parameters, if some of the parameters have default
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00001821/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner8123a952008-04-10 02:22:51 +00001822unsigned FunctionDecl::getMinRequiredArguments() const {
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00001823 if (!getASTContext().getLangOptions().CPlusPlus)
1824 return getNumParams();
1825
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00001826 unsigned NumRequiredArgs = getNumParams();
1827
1828 // If the last parameter is a parameter pack, we don't need an argument for
1829 // it.
1830 if (NumRequiredArgs > 0 &&
1831 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1832 --NumRequiredArgs;
1833
1834 // If this parameter has a default argument, we don't need an argument for
1835 // it.
1836 while (NumRequiredArgs > 0 &&
1837 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner8123a952008-04-10 02:22:51 +00001838 --NumRequiredArgs;
1839
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00001840 // We might have parameter packs before the end. These can't be deduced,
1841 // but they can still handle multiple arguments.
1842 unsigned ArgIdx = NumRequiredArgs;
1843 while (ArgIdx > 0) {
1844 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1845 NumRequiredArgs = ArgIdx;
1846
1847 --ArgIdx;
1848 }
1849
Chris Lattner8123a952008-04-10 02:22:51 +00001850 return NumRequiredArgs;
1851}
1852
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001853bool FunctionDecl::isInlined() const {
Douglas Gregor8f150942010-12-09 16:59:22 +00001854 if (IsInline)
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001855 return true;
Anders Carlsson48eda2c2009-12-04 22:35:50 +00001856
1857 if (isa<CXXMethodDecl>(this)) {
1858 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1859 return true;
1860 }
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001861
1862 switch (getTemplateSpecializationKind()) {
1863 case TSK_Undeclared:
1864 case TSK_ExplicitSpecialization:
1865 return false;
1866
1867 case TSK_ImplicitInstantiation:
1868 case TSK_ExplicitInstantiationDeclaration:
1869 case TSK_ExplicitInstantiationDefinition:
1870 // Handle below.
1871 break;
1872 }
1873
1874 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001875 bool HasPattern = false;
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001876 if (PatternDecl)
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001877 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001878
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001879 if (HasPattern && PatternDecl)
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001880 return PatternDecl->isInlined();
1881
1882 return false;
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001883}
1884
Nick Lewyckydce67a72011-07-18 05:26:13 +00001885/// \brief For a function declaration in C or C++, determine whether this
1886/// declaration causes the definition to be externally visible.
1887///
1888/// Determines whether this is the first non-inline redeclaration of an inline
1889/// function in a language where "inline" does not normally require an
1890/// externally visible definition.
1891bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1892 assert(!doesThisDeclarationHaveABody() &&
1893 "Must have a declaration without a body.");
1894
1895 ASTContext &Context = getASTContext();
1896
1897 // In C99 mode, a function may have an inline definition (causing it to
1898 // be deferred) then redeclared later. As a special case, "extern inline"
1899 // is not required to produce an external symbol.
1900 if (Context.getLangOptions().GNUInline || !Context.getLangOptions().C99 ||
1901 Context.getLangOptions().CPlusPlus)
1902 return false;
1903 if (getLinkage() != ExternalLinkage || isInlineSpecified())
1904 return false;
Nick Lewyckyf57ef052011-07-18 07:11:55 +00001905 const FunctionDecl *Definition = 0;
1906 if (hasBody(Definition))
1907 return Definition->isInlined() &&
1908 Definition->isInlineDefinitionExternallyVisible();
Nick Lewyckydce67a72011-07-18 05:26:13 +00001909 return false;
1910}
1911
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001912/// \brief For an inline function definition in C or C++, determine whether the
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001913/// definition will be externally visible.
1914///
1915/// Inline function definitions are always available for inlining optimizations.
1916/// However, depending on the language dialect, declaration specifiers, and
1917/// attributes, the definition of an inline function may or may not be
1918/// "externally" visible to other translation units in the program.
1919///
1920/// In C99, inline definitions are not externally visible by default. However,
Mike Stump1e5fd7f2010-01-06 02:05:39 +00001921/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001922/// inline definition becomes externally visible (C99 6.7.4p6).
1923///
1924/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1925/// definition, we use the GNU semantics for inline, which are nearly the
1926/// opposite of C99 semantics. In particular, "inline" by itself will create
1927/// an externally visible symbol, but "extern inline" will not create an
1928/// externally visible symbol.
1929bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Sean Hunt10620eb2011-05-06 20:44:56 +00001930 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001931 assert(isInlined() && "Function must be inline");
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001932 ASTContext &Context = getASTContext();
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001933
Rafael Espindolafb3f4aa2011-06-02 16:13:27 +00001934 if (Context.getLangOptions().GNUInline || hasAttr<GNUInlineAttr>()) {
Douglas Gregor8f150942010-12-09 16:59:22 +00001935 // If it's not the case that both 'inline' and 'extern' are
1936 // specified on the definition, then this inline definition is
1937 // externally visible.
1938 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
1939 return true;
1940
1941 // If any declaration is 'inline' but not 'extern', then this definition
1942 // is externally visible.
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001943 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1944 Redecl != RedeclEnd;
1945 ++Redecl) {
Douglas Gregor8f150942010-12-09 16:59:22 +00001946 if (Redecl->isInlineSpecified() &&
1947 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001948 return true;
Douglas Gregor8f150942010-12-09 16:59:22 +00001949 }
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001950
Douglas Gregor9f9bf252009-04-28 06:37:30 +00001951 return false;
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001952 }
1953
1954 // C99 6.7.4p6:
1955 // [...] If all of the file scope declarations for a function in a
1956 // translation unit include the inline function specifier without extern,
1957 // then the definition in that translation unit is an inline definition.
1958 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1959 Redecl != RedeclEnd;
1960 ++Redecl) {
1961 // Only consider file-scope declarations in this test.
1962 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1963 continue;
Eli Friedman8a1d6a52011-10-11 22:09:24 +00001964
1965 // Only consider explicit declarations; the presence of a builtin for a
1966 // libcall shouldn't affect whether a definition is externally visible.
1967 if (Redecl->isImplicit())
1968 continue;
1969
John McCalld931b082010-08-26 03:08:43 +00001970 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001971 return true; // Not an inline definition
1972 }
1973
1974 // C99 6.7.4p6:
1975 // An inline definition does not provide an external definition for the
1976 // function, and does not forbid an external definition in another
1977 // translation unit.
Douglas Gregor9f9bf252009-04-28 06:37:30 +00001978 return false;
1979}
1980
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001981/// getOverloadedOperator - Which C++ overloaded operator this
1982/// function represents, if any.
1983OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001984 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
1985 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001986 else
1987 return OO_None;
1988}
1989
Sean Hunta6c058d2010-01-13 09:01:02 +00001990/// getLiteralIdentifier - The literal suffix identifier this function
1991/// represents, if any.
1992const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
1993 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
1994 return getDeclName().getCXXLiteralIdentifier();
1995 else
1996 return 0;
1997}
1998
Argyrios Kyrtzidisd0913552010-06-22 09:54:51 +00001999FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2000 if (TemplateOrSpecialization.isNull())
2001 return TK_NonTemplate;
2002 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2003 return TK_FunctionTemplate;
2004 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2005 return TK_MemberSpecialization;
2006 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2007 return TK_FunctionTemplateSpecialization;
2008 if (TemplateOrSpecialization.is
2009 <DependentFunctionTemplateSpecializationInfo*>())
2010 return TK_DependentFunctionTemplateSpecialization;
2011
David Blaikieb219cfc2011-09-23 05:06:16 +00002012 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidisd0913552010-06-22 09:54:51 +00002013}
2014
Douglas Gregor2db32322009-10-07 23:56:10 +00002015FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002016 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregor2db32322009-10-07 23:56:10 +00002017 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2018
2019 return 0;
2020}
2021
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002022MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2023 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2024}
2025
Douglas Gregor2db32322009-10-07 23:56:10 +00002026void
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002027FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2028 FunctionDecl *FD,
Douglas Gregor2db32322009-10-07 23:56:10 +00002029 TemplateSpecializationKind TSK) {
2030 assert(TemplateOrSpecialization.isNull() &&
2031 "Member function is already a specialization");
2032 MemberSpecializationInfo *Info
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002033 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregor2db32322009-10-07 23:56:10 +00002034 TemplateOrSpecialization = Info;
2035}
2036
Douglas Gregor3b846b62009-10-27 20:53:28 +00002037bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002038 // If the function is invalid, it can't be implicitly instantiated.
2039 if (isInvalidDecl())
Douglas Gregor3b846b62009-10-27 20:53:28 +00002040 return false;
2041
2042 switch (getTemplateSpecializationKind()) {
2043 case TSK_Undeclared:
Douglas Gregor3b846b62009-10-27 20:53:28 +00002044 case TSK_ExplicitInstantiationDefinition:
2045 return false;
2046
2047 case TSK_ImplicitInstantiation:
2048 return true;
2049
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002050 // It is possible to instantiate TSK_ExplicitSpecialization kind
2051 // if the FunctionDecl has a class scope specialization pattern.
2052 case TSK_ExplicitSpecialization:
2053 return getClassScopeSpecializationPattern() != 0;
2054
Douglas Gregor3b846b62009-10-27 20:53:28 +00002055 case TSK_ExplicitInstantiationDeclaration:
2056 // Handled below.
2057 break;
2058 }
2059
2060 // Find the actual template from which we will instantiate.
2061 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002062 bool HasPattern = false;
Douglas Gregor3b846b62009-10-27 20:53:28 +00002063 if (PatternDecl)
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002064 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregor3b846b62009-10-27 20:53:28 +00002065
2066 // C++0x [temp.explicit]p9:
2067 // Except for inline functions, other explicit instantiation declarations
2068 // have the effect of suppressing the implicit instantiation of the entity
2069 // to which they refer.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002070 if (!HasPattern || !PatternDecl)
Douglas Gregor3b846b62009-10-27 20:53:28 +00002071 return true;
2072
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002073 return PatternDecl->isInlined();
Ted Kremenek75df4ee2011-12-01 00:59:17 +00002074}
2075
2076bool FunctionDecl::isTemplateInstantiation() const {
2077 switch (getTemplateSpecializationKind()) {
2078 case TSK_Undeclared:
2079 case TSK_ExplicitSpecialization:
2080 return false;
2081 case TSK_ImplicitInstantiation:
2082 case TSK_ExplicitInstantiationDeclaration:
2083 case TSK_ExplicitInstantiationDefinition:
2084 return true;
2085 }
2086 llvm_unreachable("All TSK values handled.");
2087}
Douglas Gregor3b846b62009-10-27 20:53:28 +00002088
2089FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002090 // Handle class scope explicit specialization special case.
2091 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2092 return getClassScopeSpecializationPattern();
2093
Douglas Gregor3b846b62009-10-27 20:53:28 +00002094 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2095 while (Primary->getInstantiatedFromMemberTemplate()) {
2096 // If we have hit a point where the user provided a specialization of
2097 // this template, we're done looking.
2098 if (Primary->isMemberSpecialization())
2099 break;
2100
2101 Primary = Primary->getInstantiatedFromMemberTemplate();
2102 }
2103
2104 return Primary->getTemplatedDecl();
2105 }
2106
2107 return getInstantiatedFromMemberFunction();
2108}
2109
Douglas Gregor16e8be22009-06-29 17:30:29 +00002110FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002111 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor16e8be22009-06-29 17:30:29 +00002112 = TemplateOrSpecialization
2113 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002114 return Info->Template.getPointer();
Douglas Gregor16e8be22009-06-29 17:30:29 +00002115 }
2116 return 0;
2117}
2118
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002119FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2120 return getASTContext().getClassScopeSpecializationPattern(this);
2121}
2122
Douglas Gregor16e8be22009-06-29 17:30:29 +00002123const TemplateArgumentList *
2124FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002125 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002126 = TemplateOrSpecialization
2127 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor16e8be22009-06-29 17:30:29 +00002128 return Info->TemplateArguments;
2129 }
2130 return 0;
2131}
2132
Argyrios Kyrtzidis71a76052011-09-22 20:07:09 +00002133const ASTTemplateArgumentListInfo *
Abramo Bagnarae03db982010-05-20 15:32:11 +00002134FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2135 if (FunctionTemplateSpecializationInfo *Info
2136 = TemplateOrSpecialization
2137 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2138 return Info->TemplateArgumentsAsWritten;
2139 }
2140 return 0;
2141}
2142
Mike Stump1eb44332009-09-09 15:08:12 +00002143void
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002144FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2145 FunctionTemplateDecl *Template,
Douglas Gregor127102b2009-06-29 20:59:39 +00002146 const TemplateArgumentList *TemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002147 void *InsertPos,
Abramo Bagnarae03db982010-05-20 15:32:11 +00002148 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis7b081c82010-07-05 10:37:55 +00002149 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2150 SourceLocation PointOfInstantiation) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002151 assert(TSK != TSK_Undeclared &&
2152 "Must specify the type of function template specialization");
Mike Stump1eb44332009-09-09 15:08:12 +00002153 FunctionTemplateSpecializationInfo *Info
Douglas Gregor16e8be22009-06-29 17:30:29 +00002154 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor1637be72009-06-26 00:10:03 +00002155 if (!Info)
Argyrios Kyrtzidisa626a3d2010-09-09 11:28:23 +00002156 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2157 TemplateArgs,
2158 TemplateArgsAsWritten,
2159 PointOfInstantiation);
Douglas Gregor1637be72009-06-26 00:10:03 +00002160 TemplateOrSpecialization = Info;
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Douglas Gregor127102b2009-06-29 20:59:39 +00002162 // Insert this function template specialization into the set of known
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002163 // function template specializations.
2164 if (InsertPos)
Sebastian Redl5bbcdbf2011-04-14 14:07:59 +00002165 Template->addSpecialization(Info, InsertPos);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002166 else {
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00002167 // Try to insert the new node. If there is an existing node, leave it, the
2168 // set will contain the canonical decls while
2169 // FunctionTemplateDecl::findSpecialization will return
2170 // the most recent redeclarations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002171 FunctionTemplateSpecializationInfo *Existing
2172 = Template->getSpecializations().GetOrInsertNode(Info);
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00002173 (void)Existing;
2174 assert((!Existing || Existing->Function->isCanonicalDecl()) &&
2175 "Set is supposed to only contain canonical decls");
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002176 }
Douglas Gregor1637be72009-06-26 00:10:03 +00002177}
2178
John McCallaf2094e2010-04-08 09:05:18 +00002179void
2180FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2181 const UnresolvedSetImpl &Templates,
2182 const TemplateArgumentListInfo &TemplateArgs) {
2183 assert(TemplateOrSpecialization.isNull());
2184 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2185 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall21c01602010-04-13 22:18:28 +00002186 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallaf2094e2010-04-08 09:05:18 +00002187 void *Buffer = Context.Allocate(Size);
2188 DependentFunctionTemplateSpecializationInfo *Info =
2189 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2190 TemplateArgs);
2191 TemplateOrSpecialization = Info;
2192}
2193
2194DependentFunctionTemplateSpecializationInfo::
2195DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2196 const TemplateArgumentListInfo &TArgs)
2197 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2198
2199 d.NumTemplates = Ts.size();
2200 d.NumArgs = TArgs.size();
2201
2202 FunctionTemplateDecl **TsArray =
2203 const_cast<FunctionTemplateDecl**>(getTemplates());
2204 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2205 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2206
2207 TemplateArgumentLoc *ArgsArray =
2208 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2209 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2210 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2211}
2212
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002213TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002214 // For a function template specialization, query the specialization
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002215 // information object.
Douglas Gregor2db32322009-10-07 23:56:10 +00002216 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002217 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor2db32322009-10-07 23:56:10 +00002218 if (FTSInfo)
2219 return FTSInfo->getTemplateSpecializationKind();
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Douglas Gregor2db32322009-10-07 23:56:10 +00002221 MemberSpecializationInfo *MSInfo
2222 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2223 if (MSInfo)
2224 return MSInfo->getTemplateSpecializationKind();
2225
2226 return TSK_Undeclared;
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002227}
2228
Mike Stump1eb44332009-09-09 15:08:12 +00002229void
Douglas Gregor0a897e32009-10-15 17:21:20 +00002230FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2231 SourceLocation PointOfInstantiation) {
2232 if (FunctionTemplateSpecializationInfo *FTSInfo
2233 = TemplateOrSpecialization.dyn_cast<
2234 FunctionTemplateSpecializationInfo*>()) {
2235 FTSInfo->setTemplateSpecializationKind(TSK);
2236 if (TSK != TSK_ExplicitSpecialization &&
2237 PointOfInstantiation.isValid() &&
2238 FTSInfo->getPointOfInstantiation().isInvalid())
2239 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2240 } else if (MemberSpecializationInfo *MSInfo
2241 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2242 MSInfo->setTemplateSpecializationKind(TSK);
2243 if (TSK != TSK_ExplicitSpecialization &&
2244 PointOfInstantiation.isValid() &&
2245 MSInfo->getPointOfInstantiation().isInvalid())
2246 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2247 } else
David Blaikieb219cfc2011-09-23 05:06:16 +00002248 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor0a897e32009-10-15 17:21:20 +00002249}
2250
2251SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregor2db32322009-10-07 23:56:10 +00002252 if (FunctionTemplateSpecializationInfo *FTSInfo
2253 = TemplateOrSpecialization.dyn_cast<
2254 FunctionTemplateSpecializationInfo*>())
Douglas Gregor0a897e32009-10-15 17:21:20 +00002255 return FTSInfo->getPointOfInstantiation();
Douglas Gregor2db32322009-10-07 23:56:10 +00002256 else if (MemberSpecializationInfo *MSInfo
2257 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor0a897e32009-10-15 17:21:20 +00002258 return MSInfo->getPointOfInstantiation();
2259
2260 return SourceLocation();
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002261}
2262
Douglas Gregor9f185072009-09-11 20:15:17 +00002263bool FunctionDecl::isOutOfLine() const {
Douglas Gregorda2142f2011-02-19 18:51:44 +00002264 if (Decl::isOutOfLine())
Douglas Gregor9f185072009-09-11 20:15:17 +00002265 return true;
2266
2267 // If this function was instantiated from a member function of a
2268 // class template, check whether that member function was defined out-of-line.
2269 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2270 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002271 if (FD->hasBody(Definition))
Douglas Gregor9f185072009-09-11 20:15:17 +00002272 return Definition->isOutOfLine();
2273 }
2274
2275 // If this function was instantiated from a function template,
2276 // check whether that function template was defined out-of-line.
2277 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2278 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002279 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor9f185072009-09-11 20:15:17 +00002280 return Definition->isOutOfLine();
2281 }
2282
2283 return false;
2284}
2285
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00002286SourceRange FunctionDecl::getSourceRange() const {
2287 return SourceRange(getOuterLocStart(), EndRangeLoc);
2288}
2289
Anna Zaks9392d4e2012-01-18 02:45:01 +00002290unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaksd9b859a2012-01-13 21:52:01 +00002291 IdentifierInfo *FnInfo = getIdentifier();
2292
2293 if (!FnInfo)
Anna Zaks0a151a12012-01-17 00:37:07 +00002294 return 0;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002295
2296 // Builtin handling.
2297 switch (getBuiltinID()) {
2298 case Builtin::BI__builtin_memset:
2299 case Builtin::BI__builtin___memset_chk:
2300 case Builtin::BImemset:
Anna Zaks0a151a12012-01-17 00:37:07 +00002301 return Builtin::BImemset;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002302
2303 case Builtin::BI__builtin_memcpy:
2304 case Builtin::BI__builtin___memcpy_chk:
2305 case Builtin::BImemcpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00002306 return Builtin::BImemcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002307
2308 case Builtin::BI__builtin_memmove:
2309 case Builtin::BI__builtin___memmove_chk:
2310 case Builtin::BImemmove:
Anna Zaks0a151a12012-01-17 00:37:07 +00002311 return Builtin::BImemmove;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002312
2313 case Builtin::BIstrlcpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00002314 return Builtin::BIstrlcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002315 case Builtin::BIstrlcat:
Anna Zaks0a151a12012-01-17 00:37:07 +00002316 return Builtin::BIstrlcat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002317
2318 case Builtin::BI__builtin_memcmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00002319 case Builtin::BImemcmp:
2320 return Builtin::BImemcmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002321
2322 case Builtin::BI__builtin_strncpy:
2323 case Builtin::BI__builtin___strncpy_chk:
2324 case Builtin::BIstrncpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00002325 return Builtin::BIstrncpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002326
2327 case Builtin::BI__builtin_strncmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00002328 case Builtin::BIstrncmp:
2329 return Builtin::BIstrncmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002330
2331 case Builtin::BI__builtin_strncasecmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00002332 case Builtin::BIstrncasecmp:
2333 return Builtin::BIstrncasecmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002334
2335 case Builtin::BI__builtin_strncat:
Anna Zaksc36bedc2012-02-01 19:08:57 +00002336 case Builtin::BI__builtin___strncat_chk:
Anna Zaksd9b859a2012-01-13 21:52:01 +00002337 case Builtin::BIstrncat:
Anna Zaks0a151a12012-01-17 00:37:07 +00002338 return Builtin::BIstrncat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002339
2340 case Builtin::BI__builtin_strndup:
2341 case Builtin::BIstrndup:
Anna Zaks0a151a12012-01-17 00:37:07 +00002342 return Builtin::BIstrndup;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002343
Anna Zaksc36bedc2012-02-01 19:08:57 +00002344 case Builtin::BI__builtin_strlen:
2345 case Builtin::BIstrlen:
2346 return Builtin::BIstrlen;
2347
Anna Zaksd9b859a2012-01-13 21:52:01 +00002348 default:
Eli Friedman750dc2b2012-01-15 01:23:58 +00002349 if (isExternC()) {
Anna Zaksd9b859a2012-01-13 21:52:01 +00002350 if (FnInfo->isStr("memset"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002351 return Builtin::BImemset;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002352 else if (FnInfo->isStr("memcpy"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002353 return Builtin::BImemcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002354 else if (FnInfo->isStr("memmove"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002355 return Builtin::BImemmove;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002356 else if (FnInfo->isStr("memcmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002357 return Builtin::BImemcmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002358 else if (FnInfo->isStr("strncpy"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002359 return Builtin::BIstrncpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002360 else if (FnInfo->isStr("strncmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002361 return Builtin::BIstrncmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002362 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002363 return Builtin::BIstrncasecmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002364 else if (FnInfo->isStr("strncat"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002365 return Builtin::BIstrncat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002366 else if (FnInfo->isStr("strndup"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002367 return Builtin::BIstrndup;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002368 else if (FnInfo->isStr("strlen"))
2369 return Builtin::BIstrlen;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002370 }
2371 break;
2372 }
Anna Zaks0a151a12012-01-17 00:37:07 +00002373 return 0;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002374}
2375
Chris Lattner8a934232008-03-31 00:36:02 +00002376//===----------------------------------------------------------------------===//
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002377// FieldDecl Implementation
2378//===----------------------------------------------------------------------===//
2379
Jay Foad4ba2a172011-01-12 09:06:06 +00002380FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002381 SourceLocation StartLoc, SourceLocation IdLoc,
2382 IdentifierInfo *Id, QualType T,
Richard Smith7a614d82011-06-11 17:19:42 +00002383 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2384 bool HasInit) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002385 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00002386 BW, Mutable, HasInit);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002387}
2388
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002389FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2390 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2391 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
2392 0, QualType(), 0, 0, false, false);
2393}
2394
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002395bool FieldDecl::isAnonymousStructOrUnion() const {
2396 if (!isImplicit() || getDeclName())
2397 return false;
2398
2399 if (const RecordType *Record = getType()->getAs<RecordType>())
2400 return Record->getDecl()->isAnonymousStructOrUnion();
2401
2402 return false;
2403}
2404
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002405unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2406 assert(isBitField() && "not a bitfield");
2407 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2408 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2409}
2410
John McCallba4f5d52011-01-20 07:57:12 +00002411unsigned FieldDecl::getFieldIndex() const {
2412 if (CachedFieldIndex) return CachedFieldIndex - 1;
2413
Richard Smith180f4792011-11-10 06:34:14 +00002414 unsigned Index = 0;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002415 const RecordDecl *RD = getParent();
2416 const FieldDecl *LastFD = 0;
2417 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
Richard Smith180f4792011-11-10 06:34:14 +00002418
2419 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2420 I != E; ++I, ++Index) {
2421 (*I)->CachedFieldIndex = Index + 1;
John McCallba4f5d52011-01-20 07:57:12 +00002422
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002423 if (IsMsStruct) {
2424 // Zero-length bitfields following non-bitfield members are ignored.
Richard Smith180f4792011-11-10 06:34:14 +00002425 if (getASTContext().ZeroBitfieldFollowsNonBitfield((*I), LastFD)) {
2426 --Index;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002427 continue;
2428 }
Richard Smith180f4792011-11-10 06:34:14 +00002429 LastFD = (*I);
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002430 }
John McCallba4f5d52011-01-20 07:57:12 +00002431 }
2432
Richard Smith180f4792011-11-10 06:34:14 +00002433 assert(CachedFieldIndex && "failed to find field in parent");
2434 return CachedFieldIndex - 1;
John McCallba4f5d52011-01-20 07:57:12 +00002435}
2436
Abramo Bagnaraf2cf5622011-03-08 11:07:11 +00002437SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnarad330e232011-08-05 08:02:55 +00002438 if (const Expr *E = InitializerOrBitWidth.getPointer())
2439 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00002440 return DeclaratorDecl::getSourceRange();
Abramo Bagnaraf2cf5622011-03-08 11:07:11 +00002441}
2442
Richard Smith7a614d82011-06-11 17:19:42 +00002443void FieldDecl::setInClassInitializer(Expr *Init) {
2444 assert(!InitializerOrBitWidth.getPointer() &&
2445 "bit width or initializer already set");
2446 InitializerOrBitWidth.setPointer(Init);
2447 InitializerOrBitWidth.setInt(0);
2448}
2449
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002450//===----------------------------------------------------------------------===//
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002451// TagDecl Implementation
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002452//===----------------------------------------------------------------------===//
2453
Douglas Gregor1693e152010-07-06 18:42:40 +00002454SourceLocation TagDecl::getOuterLocStart() const {
2455 return getTemplateOrInnerLocStart(this);
2456}
2457
Argyrios Kyrtzidisf602c8b2009-07-14 03:17:17 +00002458SourceRange TagDecl::getSourceRange() const {
2459 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregor1693e152010-07-06 18:42:40 +00002460 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidisf602c8b2009-07-14 03:17:17 +00002461}
2462
Argyrios Kyrtzidisb57a4fe2009-07-18 00:34:07 +00002463TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002464 return getFirstDeclaration();
Argyrios Kyrtzidisb57a4fe2009-07-18 00:34:07 +00002465}
2466
Richard Smith162e1c12011-04-15 14:24:37 +00002467void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2468 TypedefNameDeclOrQualifier = TDD;
Douglas Gregor60e70642010-05-19 18:39:18 +00002469 if (TypeForDecl)
John McCallf4c73712011-01-19 06:33:43 +00002470 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
Douglas Gregor381d34e2010-12-06 18:36:25 +00002471 ClearLinkageCache();
Douglas Gregor60e70642010-05-19 18:39:18 +00002472}
2473
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002474void TagDecl::startDefinition() {
Sebastian Redled48a8f2010-08-02 18:27:05 +00002475 IsBeingDefined = true;
John McCall86ff3082010-02-04 22:26:26 +00002476
2477 if (isa<CXXRecordDecl>(this)) {
2478 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2479 struct CXXRecordDecl::DefinitionData *Data =
2480 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall22432882010-03-26 21:56:38 +00002481 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2482 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall86ff3082010-02-04 22:26:26 +00002483 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002484}
2485
2486void TagDecl::completeDefinition() {
John McCall5cfa0112010-02-05 01:33:36 +00002487 assert((!isa<CXXRecordDecl>(this) ||
2488 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2489 "definition completed but not started");
2490
John McCall5e1cdac2011-10-07 06:10:15 +00002491 IsCompleteDefinition = true;
Sebastian Redled48a8f2010-08-02 18:27:05 +00002492 IsBeingDefined = false;
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00002493
2494 if (ASTMutationListener *L = getASTMutationListener())
2495 L->CompletedTagDefinition(this);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002496}
2497
John McCall5e1cdac2011-10-07 06:10:15 +00002498TagDecl *TagDecl::getDefinition() const {
2499 if (isCompleteDefinition())
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002500 return const_cast<TagDecl *>(this);
Andrew Trick220a9c82010-10-19 21:54:32 +00002501 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2502 return CXXRD->getDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002503
2504 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002505 R != REnd; ++R)
John McCall5e1cdac2011-10-07 06:10:15 +00002506 if (R->isCompleteDefinition())
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002507 return *R;
Mike Stump1eb44332009-09-09 15:08:12 +00002508
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002509 return 0;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002510}
2511
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002512void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2513 if (QualifierLoc) {
John McCallb6217662010-03-15 10:12:16 +00002514 // Make sure the extended qualifier info is allocated.
2515 if (!hasExtInfo())
Richard Smith162e1c12011-04-15 14:24:37 +00002516 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCallb6217662010-03-15 10:12:16 +00002517 // Set qualifier info.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002518 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier30601782011-08-17 23:08:45 +00002519 } else {
John McCallb6217662010-03-15 10:12:16 +00002520 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCallb6217662010-03-15 10:12:16 +00002521 if (hasExtInfo()) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002522 if (getExtInfo()->NumTemplParamLists == 0) {
2523 getASTContext().Deallocate(getExtInfo());
Richard Smith162e1c12011-04-15 14:24:37 +00002524 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002525 }
2526 else
2527 getExtInfo()->QualifierLoc = QualifierLoc;
John McCallb6217662010-03-15 10:12:16 +00002528 }
2529 }
2530}
2531
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002532void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2533 unsigned NumTPLists,
2534 TemplateParameterList **TPLists) {
2535 assert(NumTPLists > 0);
2536 // Make sure the extended decl info is allocated.
2537 if (!hasExtInfo())
2538 // Allocate external info struct.
Richard Smith162e1c12011-04-15 14:24:37 +00002539 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002540 // Set the template parameter lists info.
2541 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2542}
2543
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002544//===----------------------------------------------------------------------===//
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002545// EnumDecl Implementation
2546//===----------------------------------------------------------------------===//
2547
David Blaikie99ba9e32011-12-20 02:48:34 +00002548void EnumDecl::anchor() { }
2549
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002550EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2551 SourceLocation StartLoc, SourceLocation IdLoc,
2552 IdentifierInfo *Id,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00002553 EnumDecl *PrevDecl, bool IsScoped,
2554 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002555 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00002556 IsScoped, IsScopedUsingClassTag, IsFixed);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002557 C.getTypeDeclType(Enum, PrevDecl);
2558 return Enum;
2559}
2560
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002561EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2562 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
2563 return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
2564 false, false, false);
Argyrios Kyrtzidisb8b03e62010-07-02 11:54:55 +00002565}
2566
Douglas Gregor838db382010-02-11 01:19:42 +00002567void EnumDecl::completeDefinition(QualType NewType,
John McCall1b5a6182010-05-06 08:49:23 +00002568 QualType NewPromotionType,
2569 unsigned NumPositiveBits,
2570 unsigned NumNegativeBits) {
John McCall5e1cdac2011-10-07 06:10:15 +00002571 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor1274ccd2010-10-08 23:50:27 +00002572 if (!IntegerType)
2573 IntegerType = NewType.getTypePtr();
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002574 PromotionType = NewPromotionType;
John McCall1b5a6182010-05-06 08:49:23 +00002575 setNumPositiveBits(NumPositiveBits);
2576 setNumNegativeBits(NumNegativeBits);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002577 TagDecl::completeDefinition();
2578}
2579
2580//===----------------------------------------------------------------------===//
Chris Lattner8a934232008-03-31 00:36:02 +00002581// RecordDecl Implementation
2582//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00002583
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002584RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2585 SourceLocation StartLoc, SourceLocation IdLoc,
2586 IdentifierInfo *Id, RecordDecl *PrevDecl)
2587 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek63597922008-09-02 21:12:32 +00002588 HasFlexibleArrayMember = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002589 AnonymousStructOrUnion = false;
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002590 HasObjectMember = false;
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002591 LoadedFieldsFromExternalStorage = false;
Ted Kremenek63597922008-09-02 21:12:32 +00002592 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek63597922008-09-02 21:12:32 +00002593}
2594
Jay Foad4ba2a172011-01-12 09:06:06 +00002595RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002596 SourceLocation StartLoc, SourceLocation IdLoc,
2597 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2598 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2599 PrevDecl);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002600 C.getTypeDeclType(R, PrevDecl);
2601 return R;
Ted Kremenek63597922008-09-02 21:12:32 +00002602}
2603
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002604RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
2605 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
2606 return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2607 SourceLocation(), 0, 0);
Argyrios Kyrtzidisb8b03e62010-07-02 11:54:55 +00002608}
2609
Douglas Gregorc9b5b402009-03-25 15:59:44 +00002610bool RecordDecl::isInjectedClassName() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002611 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregorc9b5b402009-03-25 15:59:44 +00002612 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2613}
2614
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002615RecordDecl::field_iterator RecordDecl::field_begin() const {
2616 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2617 LoadFieldsFromExternalStorage();
2618
2619 return field_iterator(decl_iterator(FirstDecl));
2620}
2621
Douglas Gregorda2142f2011-02-19 18:51:44 +00002622/// completeDefinition - Notes that the definition of this type is now
2623/// complete.
2624void RecordDecl::completeDefinition() {
John McCall5e1cdac2011-10-07 06:10:15 +00002625 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorda2142f2011-02-19 18:51:44 +00002626 TagDecl::completeDefinition();
2627}
2628
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002629void RecordDecl::LoadFieldsFromExternalStorage() const {
2630 ExternalASTSource *Source = getASTContext().getExternalSource();
2631 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2632
2633 // Notify that we have a RecordDecl doing some initialization.
2634 ExternalASTSource::Deserializing TheFields(Source);
2635
Chris Lattner5f9e2722011-07-23 10:55:15 +00002636 SmallVector<Decl*, 64> Decls;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00002637 LoadedFieldsFromExternalStorage = true;
2638 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2639 case ELR_Success:
2640 break;
2641
2642 case ELR_AlreadyLoaded:
2643 case ELR_Failure:
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002644 return;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00002645 }
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002646
2647#ifndef NDEBUG
2648 // Check that all decls we got were FieldDecls.
2649 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2650 assert(isa<FieldDecl>(Decls[i]));
2651#endif
2652
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002653 if (Decls.empty())
2654 return;
2655
Argyrios Kyrtzidisec2ec1f2011-10-07 21:55:43 +00002656 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2657 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002658}
2659
Steve Naroff56ee6892008-10-08 17:01:13 +00002660//===----------------------------------------------------------------------===//
2661// BlockDecl Implementation
2662//===----------------------------------------------------------------------===//
2663
David Blaikie4278c652011-09-21 18:16:56 +00002664void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffe78b8092009-03-13 16:56:44 +00002665 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Steve Naroffe78b8092009-03-13 16:56:44 +00002667 // Zero params -> null pointer.
David Blaikie4278c652011-09-21 18:16:56 +00002668 if (!NewParamInfo.empty()) {
2669 NumParams = NewParamInfo.size();
2670 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2671 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffe78b8092009-03-13 16:56:44 +00002672 }
2673}
2674
John McCall6b5a61b2011-02-07 10:33:21 +00002675void BlockDecl::setCaptures(ASTContext &Context,
2676 const Capture *begin,
2677 const Capture *end,
2678 bool capturesCXXThis) {
John McCall469a1eb2011-02-02 13:00:07 +00002679 CapturesCXXThis = capturesCXXThis;
2680
2681 if (begin == end) {
John McCall6b5a61b2011-02-07 10:33:21 +00002682 NumCaptures = 0;
2683 Captures = 0;
John McCall469a1eb2011-02-02 13:00:07 +00002684 return;
2685 }
2686
John McCall6b5a61b2011-02-07 10:33:21 +00002687 NumCaptures = end - begin;
2688
2689 // Avoid new Capture[] because we don't want to provide a default
2690 // constructor.
2691 size_t allocationSize = NumCaptures * sizeof(Capture);
2692 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2693 memcpy(buffer, begin, allocationSize);
2694 Captures = static_cast<Capture*>(buffer);
Steve Naroffe78b8092009-03-13 16:56:44 +00002695}
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002696
John McCall204e1332011-06-15 22:51:16 +00002697bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2698 for (capture_const_iterator
2699 i = capture_begin(), e = capture_end(); i != e; ++i)
2700 // Only auto vars can be captured, so no redeclaration worries.
2701 if (i->getVariable() == variable)
2702 return true;
2703
2704 return false;
2705}
2706
Douglas Gregor2fcbcef2010-12-21 16:27:07 +00002707SourceRange BlockDecl::getSourceRange() const {
2708 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2709}
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002710
2711//===----------------------------------------------------------------------===//
2712// Other Decl Allocation/Deallocation Method Implementations
2713//===----------------------------------------------------------------------===//
2714
David Blaikie99ba9e32011-12-20 02:48:34 +00002715void TranslationUnitDecl::anchor() { }
2716
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002717TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2718 return new (C) TranslationUnitDecl(C);
2719}
2720
David Blaikie99ba9e32011-12-20 02:48:34 +00002721void LabelDecl::anchor() { }
2722
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002723LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara67843042011-03-05 18:21:20 +00002724 SourceLocation IdentL, IdentifierInfo *II) {
2725 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2726}
2727
2728LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2729 SourceLocation IdentL, IdentifierInfo *II,
2730 SourceLocation GnuLabelL) {
2731 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2732 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002733}
2734
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002735LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2736 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
2737 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor06c91932010-10-27 19:49:05 +00002738}
2739
David Blaikie99ba9e32011-12-20 02:48:34 +00002740void ValueDecl::anchor() { }
2741
2742void ImplicitParamDecl::anchor() { }
2743
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002744ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002745 SourceLocation IdLoc,
2746 IdentifierInfo *Id,
2747 QualType Type) {
2748 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002749}
2750
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002751ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
2752 unsigned ID) {
2753 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
2754 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
2755}
2756
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002757FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002758 SourceLocation StartLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +00002759 const DeclarationNameInfo &NameInfo,
2760 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002761 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregor8f150942010-12-09 16:59:22 +00002762 bool isInlineSpecified,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00002763 bool hasWrittenPrototype,
2764 bool isConstexprSpecified) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002765 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2766 T, TInfo, SC, SCAsWritten,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00002767 isInlineSpecified,
2768 isConstexprSpecified);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002769 New->HasWrittenPrototype = hasWrittenPrototype;
2770 return New;
2771}
2772
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002773FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2774 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
2775 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
2776 DeclarationNameInfo(), QualType(), 0,
2777 SC_None, SC_None, false, false);
2778}
2779
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002780BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2781 return new (C) BlockDecl(DC, L);
2782}
2783
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002784BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2785 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
2786 return new (Mem) BlockDecl(0, SourceLocation());
2787}
2788
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002789EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2790 SourceLocation L,
2791 IdentifierInfo *Id, QualType T,
2792 Expr *E, const llvm::APSInt &V) {
2793 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2794}
2795
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002796EnumConstantDecl *
2797EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2798 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
2799 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
2800 llvm::APSInt());
2801}
2802
David Blaikie99ba9e32011-12-20 02:48:34 +00002803void IndirectFieldDecl::anchor() { }
2804
Benjamin Kramerd9811462010-11-21 14:11:41 +00002805IndirectFieldDecl *
2806IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2807 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2808 unsigned CHS) {
Francois Pichet87c2e122010-11-21 06:08:52 +00002809 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2810}
2811
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002812IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
2813 unsigned ID) {
2814 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
2815 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
2816 QualType(), 0, 0);
2817}
2818
Douglas Gregor8e7139c2010-09-01 20:41:53 +00002819SourceRange EnumConstantDecl::getSourceRange() const {
2820 SourceLocation End = getLocation();
2821 if (Init)
2822 End = Init->getLocEnd();
2823 return SourceRange(getLocation(), End);
2824}
2825
David Blaikie99ba9e32011-12-20 02:48:34 +00002826void TypeDecl::anchor() { }
2827
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002828TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara344577e2011-03-06 15:48:19 +00002829 SourceLocation StartLoc, SourceLocation IdLoc,
2830 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2831 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002832}
2833
David Blaikie99ba9e32011-12-20 02:48:34 +00002834void TypedefNameDecl::anchor() { }
2835
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002836TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2837 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
2838 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2839}
2840
Richard Smith162e1c12011-04-15 14:24:37 +00002841TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2842 SourceLocation StartLoc,
2843 SourceLocation IdLoc, IdentifierInfo *Id,
2844 TypeSourceInfo *TInfo) {
2845 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2846}
2847
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002848TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2849 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
2850 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2851}
2852
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00002853SourceRange TypedefDecl::getSourceRange() const {
2854 SourceLocation RangeEnd = getLocation();
2855 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2856 if (typeIsPostfix(TInfo->getType()))
2857 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2858 }
2859 return SourceRange(getLocStart(), RangeEnd);
2860}
2861
Richard Smith162e1c12011-04-15 14:24:37 +00002862SourceRange TypeAliasDecl::getSourceRange() const {
2863 SourceLocation RangeEnd = getLocStart();
2864 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2865 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2866 return SourceRange(getLocStart(), RangeEnd);
2867}
2868
David Blaikie99ba9e32011-12-20 02:48:34 +00002869void FileScopeAsmDecl::anchor() { }
2870
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002871FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara21e006e2011-03-03 14:20:18 +00002872 StringLiteral *Str,
2873 SourceLocation AsmLoc,
2874 SourceLocation RParenLoc) {
2875 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002876}
Douglas Gregor15de72c2011-12-02 23:23:56 +00002877
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002878FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
2879 unsigned ID) {
2880 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
2881 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
2882}
2883
Douglas Gregor15de72c2011-12-02 23:23:56 +00002884//===----------------------------------------------------------------------===//
2885// ImportDecl Implementation
2886//===----------------------------------------------------------------------===//
2887
2888/// \brief Retrieve the number of module identifiers needed to name the given
2889/// module.
2890static unsigned getNumModuleIdentifiers(Module *Mod) {
2891 unsigned Result = 1;
2892 while (Mod->Parent) {
2893 Mod = Mod->Parent;
2894 ++Result;
2895 }
2896 return Result;
2897}
2898
Douglas Gregor5948ae12012-01-03 18:04:46 +00002899ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00002900 Module *Imported,
2901 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor5948ae12012-01-03 18:04:46 +00002902 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregore6649772011-12-03 00:30:27 +00002903 NextLocalImport()
Douglas Gregor15de72c2011-12-02 23:23:56 +00002904{
2905 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
2906 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
2907 memcpy(StoredLocs, IdentifierLocs.data(),
2908 IdentifierLocs.size() * sizeof(SourceLocation));
2909}
2910
Douglas Gregor5948ae12012-01-03 18:04:46 +00002911ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00002912 Module *Imported, SourceLocation EndLoc)
Douglas Gregor5948ae12012-01-03 18:04:46 +00002913 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregore6649772011-12-03 00:30:27 +00002914 NextLocalImport()
Douglas Gregor15de72c2011-12-02 23:23:56 +00002915{
2916 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
2917}
2918
2919ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor5948ae12012-01-03 18:04:46 +00002920 SourceLocation StartLoc, Module *Imported,
Douglas Gregor15de72c2011-12-02 23:23:56 +00002921 ArrayRef<SourceLocation> IdentifierLocs) {
2922 void *Mem = C.Allocate(sizeof(ImportDecl) +
2923 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor5948ae12012-01-03 18:04:46 +00002924 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +00002925}
2926
2927ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor5948ae12012-01-03 18:04:46 +00002928 SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00002929 Module *Imported,
2930 SourceLocation EndLoc) {
2931 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor5948ae12012-01-03 18:04:46 +00002932 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregor15de72c2011-12-02 23:23:56 +00002933 Import->setImplicit();
2934 return Import;
2935}
2936
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002937ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
2938 unsigned NumLocations) {
2939 void *Mem = AllocateDeserializedDecl(C, ID,
2940 (sizeof(ImportDecl) +
2941 NumLocations * sizeof(SourceLocation)));
Douglas Gregor15de72c2011-12-02 23:23:56 +00002942 return new (Mem) ImportDecl(EmptyShell());
2943}
2944
2945ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
2946 if (!ImportedAndComplete.getInt())
2947 return ArrayRef<SourceLocation>();
2948
2949 const SourceLocation *StoredLocs
2950 = reinterpret_cast<const SourceLocation *>(this + 1);
2951 return ArrayRef<SourceLocation>(StoredLocs,
2952 getNumModuleIdentifiers(getImportedModule()));
2953}
2954
2955SourceRange ImportDecl::getSourceRange() const {
2956 if (!ImportedAndComplete.getInt())
2957 return SourceRange(getLocation(),
2958 *reinterpret_cast<const SourceLocation *>(this + 1));
2959
2960 return SourceRange(getLocation(), getIdentifierLocs().back());
2961}