Decl.cpp revision a8426972609c908b529ab26c69c35586d8bc06a8
1//===--- Decl.cpp - Declaration AST Node Implementation -------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the Decl subclasses. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/AST/Decl.h" 15#include "clang/AST/DeclCXX.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/TypeLoc.h" 20#include "clang/AST/Stmt.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/PrettyPrinter.h" 24#include "clang/Basic/Builtins.h" 25#include "clang/Basic/IdentifierTable.h" 26#include "clang/Parse/DeclSpec.h" 27#include "llvm/Support/ErrorHandling.h" 28 29using namespace clang; 30 31/// \brief Return the TypeLoc wrapper for the type source info. 32TypeLoc TypeSourceInfo::getTypeLoc() const { 33 return TypeLoc(Ty, (void*)(this + 1)); 34} 35 36//===----------------------------------------------------------------------===// 37// NamedDecl Implementation 38//===----------------------------------------------------------------------===// 39 40/// \brief Get the most restrictive linkage for the types in the given 41/// template parameter list. 42static Linkage 43getLinkageForTemplateParameterList(const TemplateParameterList *Params) { 44 Linkage L = ExternalLinkage; 45 for (TemplateParameterList::const_iterator P = Params->begin(), 46 PEnd = Params->end(); 47 P != PEnd; ++P) { 48 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) 49 if (!NTTP->getType()->isDependentType()) { 50 L = minLinkage(L, NTTP->getType()->getLinkage()); 51 continue; 52 } 53 54 if (TemplateTemplateParmDecl *TTP 55 = dyn_cast<TemplateTemplateParmDecl>(*P)) { 56 L = minLinkage(L, 57 getLinkageForTemplateParameterList(TTP->getTemplateParameters())); 58 } 59 } 60 61 return L; 62} 63 64/// \brief Get the most restrictive linkage for the types and 65/// declarations in the given template argument list. 66static Linkage getLinkageForTemplateArgumentList(const TemplateArgument *Args, 67 unsigned NumArgs) { 68 Linkage L = ExternalLinkage; 69 70 for (unsigned I = 0; I != NumArgs; ++I) { 71 switch (Args[I].getKind()) { 72 case TemplateArgument::Null: 73 case TemplateArgument::Integral: 74 case TemplateArgument::Expression: 75 break; 76 77 case TemplateArgument::Type: 78 L = minLinkage(L, Args[I].getAsType()->getLinkage()); 79 break; 80 81 case TemplateArgument::Declaration: 82 if (NamedDecl *ND = dyn_cast<NamedDecl>(Args[I].getAsDecl())) 83 L = minLinkage(L, ND->getLinkage()); 84 if (ValueDecl *VD = dyn_cast<ValueDecl>(Args[I].getAsDecl())) 85 L = minLinkage(L, VD->getType()->getLinkage()); 86 break; 87 88 case TemplateArgument::Template: 89 if (TemplateDecl *Template 90 = Args[I].getAsTemplate().getAsTemplateDecl()) 91 L = minLinkage(L, Template->getLinkage()); 92 break; 93 94 case TemplateArgument::Pack: 95 L = minLinkage(L, 96 getLinkageForTemplateArgumentList(Args[I].pack_begin(), 97 Args[I].pack_size())); 98 break; 99 } 100 } 101 102 return L; 103} 104 105static Linkage getLinkageForNamespaceScopeDecl(const NamedDecl *D) { 106 assert(D->getDeclContext()->getLookupContext()->isFileContext() && 107 "Not a name having namespace scope"); 108 ASTContext &Context = D->getASTContext(); 109 110 // C++ [basic.link]p3: 111 // A name having namespace scope (3.3.6) has internal linkage if it 112 // is the name of 113 // - an object, reference, function or function template that is 114 // explicitly declared static; or, 115 // (This bullet corresponds to C99 6.2.2p3.) 116 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 117 // Explicitly declared static. 118 if (Var->getStorageClass() == VarDecl::Static) 119 return InternalLinkage; 120 121 // - an object or reference that is explicitly declared const 122 // and neither explicitly declared extern nor previously 123 // declared to have external linkage; or 124 // (there is no equivalent in C99) 125 if (Context.getLangOptions().CPlusPlus && 126 Var->getType().isConstant(Context) && 127 Var->getStorageClass() != VarDecl::Extern && 128 Var->getStorageClass() != VarDecl::PrivateExtern) { 129 bool FoundExtern = false; 130 for (const VarDecl *PrevVar = Var->getPreviousDeclaration(); 131 PrevVar && !FoundExtern; 132 PrevVar = PrevVar->getPreviousDeclaration()) 133 if (isExternalLinkage(PrevVar->getLinkage())) 134 FoundExtern = true; 135 136 if (!FoundExtern) 137 return InternalLinkage; 138 } 139 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) { 140 // C++ [temp]p4: 141 // A non-member function template can have internal linkage; any 142 // other template name shall have external linkage. 143 const FunctionDecl *Function = 0; 144 if (const FunctionTemplateDecl *FunTmpl 145 = dyn_cast<FunctionTemplateDecl>(D)) 146 Function = FunTmpl->getTemplatedDecl(); 147 else 148 Function = cast<FunctionDecl>(D); 149 150 // Explicitly declared static. 151 if (Function->getStorageClass() == FunctionDecl::Static) 152 return InternalLinkage; 153 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) { 154 // - a data member of an anonymous union. 155 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()) 156 return InternalLinkage; 157 } 158 159 // C++ [basic.link]p4: 160 161 // A name having namespace scope has external linkage if it is the 162 // name of 163 // 164 // - an object or reference, unless it has internal linkage; or 165 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 166 if (!Context.getLangOptions().CPlusPlus && 167 (Var->getStorageClass() == VarDecl::Extern || 168 Var->getStorageClass() == VarDecl::PrivateExtern)) { 169 // C99 6.2.2p4: 170 // For an identifier declared with the storage-class specifier 171 // extern in a scope in which a prior declaration of that 172 // identifier is visible, if the prior declaration specifies 173 // internal or external linkage, the linkage of the identifier 174 // at the later declaration is the same as the linkage 175 // specified at the prior declaration. If no prior declaration 176 // is visible, or if the prior declaration specifies no 177 // linkage, then the identifier has external linkage. 178 if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) { 179 if (Linkage L = PrevVar->getLinkage()) 180 return L; 181 } 182 } 183 184 // C99 6.2.2p5: 185 // If the declaration of an identifier for an object has file 186 // scope and no storage-class specifier, its linkage is 187 // external. 188 if (Var->isInAnonymousNamespace()) 189 return UniqueExternalLinkage; 190 191 return ExternalLinkage; 192 } 193 194 // - a function, unless it has internal linkage; or 195 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 196 // C99 6.2.2p5: 197 // If the declaration of an identifier for a function has no 198 // storage-class specifier, its linkage is determined exactly 199 // as if it were declared with the storage-class specifier 200 // extern. 201 if (!Context.getLangOptions().CPlusPlus && 202 (Function->getStorageClass() == FunctionDecl::Extern || 203 Function->getStorageClass() == FunctionDecl::PrivateExtern || 204 Function->getStorageClass() == FunctionDecl::None)) { 205 // C99 6.2.2p4: 206 // For an identifier declared with the storage-class specifier 207 // extern in a scope in which a prior declaration of that 208 // identifier is visible, if the prior declaration specifies 209 // internal or external linkage, the linkage of the identifier 210 // at the later declaration is the same as the linkage 211 // specified at the prior declaration. If no prior declaration 212 // is visible, or if the prior declaration specifies no 213 // linkage, then the identifier has external linkage. 214 if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) { 215 if (Linkage L = PrevFunc->getLinkage()) 216 return L; 217 } 218 } 219 220 if (Function->isInAnonymousNamespace()) 221 return UniqueExternalLinkage; 222 223 if (FunctionTemplateSpecializationInfo *SpecInfo 224 = Function->getTemplateSpecializationInfo()) { 225 Linkage L = SpecInfo->getTemplate()->getLinkage(); 226 const TemplateArgumentList &TemplateArgs = *SpecInfo->TemplateArguments; 227 L = minLinkage(L, 228 getLinkageForTemplateArgumentList( 229 TemplateArgs.getFlatArgumentList(), 230 TemplateArgs.flat_size())); 231 return L; 232 } 233 234 return ExternalLinkage; 235 } 236 237 // - a named class (Clause 9), or an unnamed class defined in a 238 // typedef declaration in which the class has the typedef name 239 // for linkage purposes (7.1.3); or 240 // - a named enumeration (7.2), or an unnamed enumeration 241 // defined in a typedef declaration in which the enumeration 242 // has the typedef name for linkage purposes (7.1.3); or 243 if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) 244 if (Tag->getDeclName() || Tag->getTypedefForAnonDecl()) { 245 if (Tag->isInAnonymousNamespace()) 246 return UniqueExternalLinkage; 247 248 // If this is a class template specialization, consider the 249 // linkage of the template and template arguments. 250 if (const ClassTemplateSpecializationDecl *Spec 251 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) { 252 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 253 Linkage L = getLinkageForTemplateArgumentList( 254 TemplateArgs.getFlatArgumentList(), 255 TemplateArgs.flat_size()); 256 return minLinkage(L, Spec->getSpecializedTemplate()->getLinkage()); 257 } 258 259 return ExternalLinkage; 260 } 261 262 // - an enumerator belonging to an enumeration with external linkage; 263 if (isa<EnumConstantDecl>(D)) { 264 Linkage L = cast<NamedDecl>(D->getDeclContext())->getLinkage(); 265 if (isExternalLinkage(L)) 266 return L; 267 } 268 269 // - a template, unless it is a function template that has 270 // internal linkage (Clause 14); 271 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 272 if (D->isInAnonymousNamespace()) 273 return UniqueExternalLinkage; 274 275 return getLinkageForTemplateParameterList( 276 Template->getTemplateParameters()); 277 } 278 279 // - a namespace (7.3), unless it is declared within an unnamed 280 // namespace. 281 if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) 282 return ExternalLinkage; 283 284 return NoLinkage; 285} 286 287Linkage NamedDecl::getLinkage() const { 288 289 // Objective-C: treat all Objective-C declarations as having external 290 // linkage. 291 switch (getKind()) { 292 default: 293 break; 294 case Decl::ObjCAtDefsField: 295 case Decl::ObjCCategory: 296 case Decl::ObjCCategoryImpl: 297 case Decl::ObjCClass: 298 case Decl::ObjCCompatibleAlias: 299 case Decl::ObjCForwardProtocol: 300 case Decl::ObjCImplementation: 301 case Decl::ObjCInterface: 302 case Decl::ObjCIvar: 303 case Decl::ObjCMethod: 304 case Decl::ObjCProperty: 305 case Decl::ObjCPropertyImpl: 306 case Decl::ObjCProtocol: 307 return ExternalLinkage; 308 } 309 310 // Handle linkage for namespace-scope names. 311 if (getDeclContext()->getLookupContext()->isFileContext()) 312 if (Linkage L = getLinkageForNamespaceScopeDecl(this)) 313 return L; 314 315 // C++ [basic.link]p5: 316 // In addition, a member function, static data member, a named 317 // class or enumeration of class scope, or an unnamed class or 318 // enumeration defined in a class-scope typedef declaration such 319 // that the class or enumeration has the typedef name for linkage 320 // purposes (7.1.3), has external linkage if the name of the class 321 // has external linkage. 322 if (getDeclContext()->isRecord() && 323 (isa<CXXMethodDecl>(this) || isa<VarDecl>(this) || 324 (isa<TagDecl>(this) && 325 (getDeclName() || cast<TagDecl>(this)->getTypedefForAnonDecl())))) { 326 Linkage L = cast<RecordDecl>(getDeclContext())->getLinkage(); 327 if (isExternalLinkage(L)) 328 return L; 329 } 330 331 // C++ [basic.link]p6: 332 // The name of a function declared in block scope and the name of 333 // an object declared by a block scope extern declaration have 334 // linkage. If there is a visible declaration of an entity with 335 // linkage having the same name and type, ignoring entities 336 // declared outside the innermost enclosing namespace scope, the 337 // block scope declaration declares that same entity and receives 338 // the linkage of the previous declaration. If there is more than 339 // one such matching entity, the program is ill-formed. Otherwise, 340 // if no matching entity is found, the block scope entity receives 341 // external linkage. 342 if (getLexicalDeclContext()->isFunctionOrMethod()) { 343 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) { 344 if (Function->getPreviousDeclaration()) 345 if (Linkage L = Function->getPreviousDeclaration()->getLinkage()) 346 return L; 347 348 if (Function->isInAnonymousNamespace()) 349 return UniqueExternalLinkage; 350 351 return ExternalLinkage; 352 } 353 354 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) 355 if (Var->getStorageClass() == VarDecl::Extern || 356 Var->getStorageClass() == VarDecl::PrivateExtern) { 357 if (Var->getPreviousDeclaration()) 358 if (Linkage L = Var->getPreviousDeclaration()->getLinkage()) 359 return L; 360 361 if (Var->isInAnonymousNamespace()) 362 return UniqueExternalLinkage; 363 364 return ExternalLinkage; 365 } 366 } 367 368 // C++ [basic.link]p6: 369 // Names not covered by these rules have no linkage. 370 return NoLinkage; 371 } 372 373std::string NamedDecl::getQualifiedNameAsString() const { 374 return getQualifiedNameAsString(getASTContext().getLangOptions()); 375} 376 377std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const { 378 const DeclContext *Ctx = getDeclContext(); 379 380 if (Ctx->isFunctionOrMethod()) 381 return getNameAsString(); 382 383 typedef llvm::SmallVector<const DeclContext *, 8> ContextsTy; 384 ContextsTy Contexts; 385 386 // Collect contexts. 387 while (Ctx && isa<NamedDecl>(Ctx)) { 388 Contexts.push_back(Ctx); 389 Ctx = Ctx->getParent(); 390 }; 391 392 std::string QualName; 393 llvm::raw_string_ostream OS(QualName); 394 395 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend(); 396 I != E; ++I) { 397 if (const ClassTemplateSpecializationDecl *Spec 398 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) { 399 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 400 std::string TemplateArgsStr 401 = TemplateSpecializationType::PrintTemplateArgumentList( 402 TemplateArgs.getFlatArgumentList(), 403 TemplateArgs.flat_size(), 404 P); 405 OS << Spec->getName() << TemplateArgsStr; 406 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) { 407 if (ND->isAnonymousNamespace()) 408 OS << "<anonymous namespace>"; 409 else 410 OS << ND; 411 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) { 412 if (!RD->getIdentifier()) 413 OS << "<anonymous " << RD->getKindName() << '>'; 414 else 415 OS << RD; 416 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 417 const FunctionProtoType *FT = 0; 418 if (FD->hasWrittenPrototype()) 419 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 420 421 OS << FD << '('; 422 if (FT) { 423 unsigned NumParams = FD->getNumParams(); 424 for (unsigned i = 0; i < NumParams; ++i) { 425 if (i) 426 OS << ", "; 427 std::string Param; 428 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P); 429 OS << Param; 430 } 431 432 if (FT->isVariadic()) { 433 if (NumParams > 0) 434 OS << ", "; 435 OS << "..."; 436 } 437 } 438 OS << ')'; 439 } else { 440 OS << cast<NamedDecl>(*I); 441 } 442 OS << "::"; 443 } 444 445 if (getDeclName()) 446 OS << this; 447 else 448 OS << "<anonymous>"; 449 450 return OS.str(); 451} 452 453bool NamedDecl::declarationReplaces(NamedDecl *OldD) const { 454 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 455 456 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name. 457 // We want to keep it, unless it nominates same namespace. 458 if (getKind() == Decl::UsingDirective) { 459 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() == 460 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace(); 461 } 462 463 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 464 // For function declarations, we keep track of redeclarations. 465 return FD->getPreviousDeclaration() == OldD; 466 467 // For function templates, the underlying function declarations are linked. 468 if (const FunctionTemplateDecl *FunctionTemplate 469 = dyn_cast<FunctionTemplateDecl>(this)) 470 if (const FunctionTemplateDecl *OldFunctionTemplate 471 = dyn_cast<FunctionTemplateDecl>(OldD)) 472 return FunctionTemplate->getTemplatedDecl() 473 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl()); 474 475 // For method declarations, we keep track of redeclarations. 476 if (isa<ObjCMethodDecl>(this)) 477 return false; 478 479 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD)) 480 return true; 481 482 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD)) 483 return cast<UsingShadowDecl>(this)->getTargetDecl() == 484 cast<UsingShadowDecl>(OldD)->getTargetDecl(); 485 486 // For non-function declarations, if the declarations are of the 487 // same kind then this must be a redeclaration, or semantic analysis 488 // would not have given us the new declaration. 489 return this->getKind() == OldD->getKind(); 490} 491 492bool NamedDecl::hasLinkage() const { 493 return getLinkage() != NoLinkage; 494} 495 496NamedDecl *NamedDecl::getUnderlyingDecl() { 497 NamedDecl *ND = this; 498 while (true) { 499 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND)) 500 ND = UD->getTargetDecl(); 501 else if (ObjCCompatibleAliasDecl *AD 502 = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 503 return AD->getClassInterface(); 504 else 505 return ND; 506 } 507} 508 509bool NamedDecl::isCXXInstanceMember() const { 510 assert(isCXXClassMember() && 511 "checking whether non-member is instance member"); 512 513 const NamedDecl *D = this; 514 if (isa<UsingShadowDecl>(D)) 515 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 516 517 if (isa<FieldDecl>(D)) 518 return true; 519 if (isa<CXXMethodDecl>(D)) 520 return cast<CXXMethodDecl>(D)->isInstance(); 521 if (isa<FunctionTemplateDecl>(D)) 522 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D) 523 ->getTemplatedDecl())->isInstance(); 524 return false; 525} 526 527//===----------------------------------------------------------------------===// 528// DeclaratorDecl Implementation 529//===----------------------------------------------------------------------===// 530 531DeclaratorDecl::~DeclaratorDecl() {} 532void DeclaratorDecl::Destroy(ASTContext &C) { 533 if (hasExtInfo()) 534 C.Deallocate(getExtInfo()); 535 ValueDecl::Destroy(C); 536} 537 538SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 539 if (DeclInfo) { 540 TypeLoc TL = getTypeSourceInfo()->getTypeLoc(); 541 while (true) { 542 TypeLoc NextTL = TL.getNextTypeLoc(); 543 if (!NextTL) 544 return TL.getSourceRange().getBegin(); 545 TL = NextTL; 546 } 547 } 548 return SourceLocation(); 549} 550 551void DeclaratorDecl::setQualifierInfo(NestedNameSpecifier *Qualifier, 552 SourceRange QualifierRange) { 553 if (Qualifier) { 554 // Make sure the extended decl info is allocated. 555 if (!hasExtInfo()) { 556 // Save (non-extended) type source info pointer. 557 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 558 // Allocate external info struct. 559 DeclInfo = new (getASTContext()) ExtInfo; 560 // Restore savedTInfo into (extended) decl info. 561 getExtInfo()->TInfo = savedTInfo; 562 } 563 // Set qualifier info. 564 getExtInfo()->NNS = Qualifier; 565 getExtInfo()->NNSRange = QualifierRange; 566 } 567 else { 568 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 569 assert(QualifierRange.isInvalid()); 570 if (hasExtInfo()) { 571 // Save type source info pointer. 572 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo; 573 // Deallocate the extended decl info. 574 getASTContext().Deallocate(getExtInfo()); 575 // Restore savedTInfo into (non-extended) decl info. 576 DeclInfo = savedTInfo; 577 } 578 } 579} 580 581//===----------------------------------------------------------------------===// 582// VarDecl Implementation 583//===----------------------------------------------------------------------===// 584 585const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 586 switch (SC) { 587 case VarDecl::None: break; 588 case VarDecl::Auto: return "auto"; break; 589 case VarDecl::Extern: return "extern"; break; 590 case VarDecl::PrivateExtern: return "__private_extern__"; break; 591 case VarDecl::Register: return "register"; break; 592 case VarDecl::Static: return "static"; break; 593 } 594 595 assert(0 && "Invalid storage class"); 596 return 0; 597} 598 599VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 600 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 601 StorageClass S, StorageClass SCAsWritten) { 602 return new (C) VarDecl(Var, DC, L, Id, T, TInfo, S, SCAsWritten); 603} 604 605void VarDecl::Destroy(ASTContext& C) { 606 Expr *Init = getInit(); 607 if (Init) { 608 Init->Destroy(C); 609 if (EvaluatedStmt *Eval = this->Init.dyn_cast<EvaluatedStmt *>()) { 610 Eval->~EvaluatedStmt(); 611 C.Deallocate(Eval); 612 } 613 } 614 this->~VarDecl(); 615 DeclaratorDecl::Destroy(C); 616} 617 618VarDecl::~VarDecl() { 619} 620 621SourceRange VarDecl::getSourceRange() const { 622 SourceLocation Start = getTypeSpecStartLoc(); 623 if (Start.isInvalid()) 624 Start = getLocation(); 625 626 if (getInit()) 627 return SourceRange(Start, getInit()->getLocEnd()); 628 return SourceRange(Start, getLocation()); 629} 630 631bool VarDecl::isExternC() const { 632 ASTContext &Context = getASTContext(); 633 if (!Context.getLangOptions().CPlusPlus) 634 return (getDeclContext()->isTranslationUnit() && 635 getStorageClass() != Static) || 636 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage()); 637 638 for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); 639 DC = DC->getParent()) { 640 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { 641 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) 642 return getStorageClass() != Static; 643 644 break; 645 } 646 647 if (DC->isFunctionOrMethod()) 648 return false; 649 } 650 651 return false; 652} 653 654VarDecl *VarDecl::getCanonicalDecl() { 655 return getFirstDeclaration(); 656} 657 658VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const { 659 // C++ [basic.def]p2: 660 // A declaration is a definition unless [...] it contains the 'extern' 661 // specifier or a linkage-specification and neither an initializer [...], 662 // it declares a static data member in a class declaration [...]. 663 // C++ [temp.expl.spec]p15: 664 // An explicit specialization of a static data member of a template is a 665 // definition if the declaration includes an initializer; otherwise, it is 666 // a declaration. 667 if (isStaticDataMember()) { 668 if (isOutOfLine() && (hasInit() || 669 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)) 670 return Definition; 671 else 672 return DeclarationOnly; 673 } 674 // C99 6.7p5: 675 // A definition of an identifier is a declaration for that identifier that 676 // [...] causes storage to be reserved for that object. 677 // Note: that applies for all non-file-scope objects. 678 // C99 6.9.2p1: 679 // If the declaration of an identifier for an object has file scope and an 680 // initializer, the declaration is an external definition for the identifier 681 if (hasInit()) 682 return Definition; 683 // AST for 'extern "C" int foo;' is annotated with 'extern'. 684 if (hasExternalStorage()) 685 return DeclarationOnly; 686 687 // C99 6.9.2p2: 688 // A declaration of an object that has file scope without an initializer, 689 // and without a storage class specifier or the scs 'static', constitutes 690 // a tentative definition. 691 // No such thing in C++. 692 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl()) 693 return TentativeDefinition; 694 695 // What's left is (in C, block-scope) declarations without initializers or 696 // external storage. These are definitions. 697 return Definition; 698} 699 700VarDecl *VarDecl::getActingDefinition() { 701 DefinitionKind Kind = isThisDeclarationADefinition(); 702 if (Kind != TentativeDefinition) 703 return 0; 704 705 VarDecl *LastTentative = false; 706 VarDecl *First = getFirstDeclaration(); 707 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 708 I != E; ++I) { 709 Kind = (*I)->isThisDeclarationADefinition(); 710 if (Kind == Definition) 711 return 0; 712 else if (Kind == TentativeDefinition) 713 LastTentative = *I; 714 } 715 return LastTentative; 716} 717 718bool VarDecl::isTentativeDefinitionNow() const { 719 DefinitionKind Kind = isThisDeclarationADefinition(); 720 if (Kind != TentativeDefinition) 721 return false; 722 723 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 724 if ((*I)->isThisDeclarationADefinition() == Definition) 725 return false; 726 } 727 return true; 728} 729 730VarDecl *VarDecl::getDefinition() { 731 VarDecl *First = getFirstDeclaration(); 732 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 733 I != E; ++I) { 734 if ((*I)->isThisDeclarationADefinition() == Definition) 735 return *I; 736 } 737 return 0; 738} 739 740const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 741 redecl_iterator I = redecls_begin(), E = redecls_end(); 742 while (I != E && !I->getInit()) 743 ++I; 744 745 if (I != E) { 746 D = *I; 747 return I->getInit(); 748 } 749 return 0; 750} 751 752bool VarDecl::isOutOfLine() const { 753 if (Decl::isOutOfLine()) 754 return true; 755 756 if (!isStaticDataMember()) 757 return false; 758 759 // If this static data member was instantiated from a static data member of 760 // a class template, check whether that static data member was defined 761 // out-of-line. 762 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 763 return VD->isOutOfLine(); 764 765 return false; 766} 767 768VarDecl *VarDecl::getOutOfLineDefinition() { 769 if (!isStaticDataMember()) 770 return 0; 771 772 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end(); 773 RD != RDEnd; ++RD) { 774 if (RD->getLexicalDeclContext()->isFileContext()) 775 return *RD; 776 } 777 778 return 0; 779} 780 781void VarDecl::setInit(Expr *I) { 782 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 783 Eval->~EvaluatedStmt(); 784 getASTContext().Deallocate(Eval); 785 } 786 787 Init = I; 788} 789 790VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 791 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 792 return cast<VarDecl>(MSI->getInstantiatedFrom()); 793 794 return 0; 795} 796 797TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 798 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 799 return MSI->getTemplateSpecializationKind(); 800 801 return TSK_Undeclared; 802} 803 804MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 805 return getASTContext().getInstantiatedFromStaticDataMember(this); 806} 807 808void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 809 SourceLocation PointOfInstantiation) { 810 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 811 assert(MSI && "Not an instantiated static data member?"); 812 MSI->setTemplateSpecializationKind(TSK); 813 if (TSK != TSK_ExplicitSpecialization && 814 PointOfInstantiation.isValid() && 815 MSI->getPointOfInstantiation().isInvalid()) 816 MSI->setPointOfInstantiation(PointOfInstantiation); 817} 818 819//===----------------------------------------------------------------------===// 820// ParmVarDecl Implementation 821//===----------------------------------------------------------------------===// 822 823ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 824 SourceLocation L, IdentifierInfo *Id, 825 QualType T, TypeSourceInfo *TInfo, 826 StorageClass S, StorageClass SCAsWritten, 827 Expr *DefArg) { 828 return new (C) ParmVarDecl(ParmVar, DC, L, Id, T, TInfo, 829 S, SCAsWritten, DefArg); 830} 831 832Expr *ParmVarDecl::getDefaultArg() { 833 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 834 assert(!hasUninstantiatedDefaultArg() && 835 "Default argument is not yet instantiated!"); 836 837 Expr *Arg = getInit(); 838 if (CXXExprWithTemporaries *E = dyn_cast_or_null<CXXExprWithTemporaries>(Arg)) 839 return E->getSubExpr(); 840 841 return Arg; 842} 843 844unsigned ParmVarDecl::getNumDefaultArgTemporaries() const { 845 if (const CXXExprWithTemporaries *E = 846 dyn_cast<CXXExprWithTemporaries>(getInit())) 847 return E->getNumTemporaries(); 848 849 return 0; 850} 851 852CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) { 853 assert(getNumDefaultArgTemporaries() && 854 "Default arguments does not have any temporaries!"); 855 856 CXXExprWithTemporaries *E = cast<CXXExprWithTemporaries>(getInit()); 857 return E->getTemporary(i); 858} 859 860SourceRange ParmVarDecl::getDefaultArgRange() const { 861 if (const Expr *E = getInit()) 862 return E->getSourceRange(); 863 864 if (hasUninstantiatedDefaultArg()) 865 return getUninstantiatedDefaultArg()->getSourceRange(); 866 867 return SourceRange(); 868} 869 870//===----------------------------------------------------------------------===// 871// FunctionDecl Implementation 872//===----------------------------------------------------------------------===// 873 874void FunctionDecl::Destroy(ASTContext& C) { 875 if (Body && Body.isOffset()) 876 Body.get(C.getExternalSource())->Destroy(C); 877 878 for (param_iterator I=param_begin(), E=param_end(); I!=E; ++I) 879 (*I)->Destroy(C); 880 881 FunctionTemplateSpecializationInfo *FTSInfo 882 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 883 if (FTSInfo) 884 C.Deallocate(FTSInfo); 885 886 MemberSpecializationInfo *MSInfo 887 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 888 if (MSInfo) 889 C.Deallocate(MSInfo); 890 891 C.Deallocate(ParamInfo); 892 893 DeclaratorDecl::Destroy(C); 894} 895 896void FunctionDecl::getNameForDiagnostic(std::string &S, 897 const PrintingPolicy &Policy, 898 bool Qualified) const { 899 NamedDecl::getNameForDiagnostic(S, Policy, Qualified); 900 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 901 if (TemplateArgs) 902 S += TemplateSpecializationType::PrintTemplateArgumentList( 903 TemplateArgs->getFlatArgumentList(), 904 TemplateArgs->flat_size(), 905 Policy); 906 907} 908 909bool FunctionDecl::isVariadic() const { 910 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>()) 911 return FT->isVariadic(); 912 return false; 913} 914 915Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 916 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 917 if (I->Body) { 918 Definition = *I; 919 return I->Body.get(getASTContext().getExternalSource()); 920 } 921 } 922 923 return 0; 924} 925 926void FunctionDecl::setBody(Stmt *B) { 927 Body = B; 928 if (B) 929 EndRangeLoc = B->getLocEnd(); 930} 931 932bool FunctionDecl::isMain() const { 933 ASTContext &Context = getASTContext(); 934 return !Context.getLangOptions().Freestanding && 935 getDeclContext()->getLookupContext()->isTranslationUnit() && 936 getIdentifier() && getIdentifier()->isStr("main"); 937} 938 939bool FunctionDecl::isExternC() const { 940 ASTContext &Context = getASTContext(); 941 // In C, any non-static, non-overloadable function has external 942 // linkage. 943 if (!Context.getLangOptions().CPlusPlus) 944 return getStorageClass() != Static && !getAttr<OverloadableAttr>(); 945 946 for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); 947 DC = DC->getParent()) { 948 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { 949 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) 950 return getStorageClass() != Static && 951 !getAttr<OverloadableAttr>(); 952 953 break; 954 } 955 } 956 957 return false; 958} 959 960bool FunctionDecl::isGlobal() const { 961 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this)) 962 return Method->isStatic(); 963 964 if (getStorageClass() == Static) 965 return false; 966 967 for (const DeclContext *DC = getDeclContext(); 968 DC->isNamespace(); 969 DC = DC->getParent()) { 970 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) { 971 if (!Namespace->getDeclName()) 972 return false; 973 break; 974 } 975 } 976 977 return true; 978} 979 980void 981FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 982 redeclarable_base::setPreviousDeclaration(PrevDecl); 983 984 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 985 FunctionTemplateDecl *PrevFunTmpl 986 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0; 987 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 988 FunTmpl->setPreviousDeclaration(PrevFunTmpl); 989 } 990} 991 992const FunctionDecl *FunctionDecl::getCanonicalDecl() const { 993 return getFirstDeclaration(); 994} 995 996FunctionDecl *FunctionDecl::getCanonicalDecl() { 997 return getFirstDeclaration(); 998} 999 1000/// \brief Returns a value indicating whether this function 1001/// corresponds to a builtin function. 1002/// 1003/// The function corresponds to a built-in function if it is 1004/// declared at translation scope or within an extern "C" block and 1005/// its name matches with the name of a builtin. The returned value 1006/// will be 0 for functions that do not correspond to a builtin, a 1007/// value of type \c Builtin::ID if in the target-independent range 1008/// \c [1,Builtin::First), or a target-specific builtin value. 1009unsigned FunctionDecl::getBuiltinID() const { 1010 ASTContext &Context = getASTContext(); 1011 if (!getIdentifier() || !getIdentifier()->getBuiltinID()) 1012 return 0; 1013 1014 unsigned BuiltinID = getIdentifier()->getBuiltinID(); 1015 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 1016 return BuiltinID; 1017 1018 // This function has the name of a known C library 1019 // function. Determine whether it actually refers to the C library 1020 // function or whether it just has the same name. 1021 1022 // If this is a static function, it's not a builtin. 1023 if (getStorageClass() == Static) 1024 return 0; 1025 1026 // If this function is at translation-unit scope and we're not in 1027 // C++, it refers to the C library function. 1028 if (!Context.getLangOptions().CPlusPlus && 1029 getDeclContext()->isTranslationUnit()) 1030 return BuiltinID; 1031 1032 // If the function is in an extern "C" linkage specification and is 1033 // not marked "overloadable", it's the real function. 1034 if (isa<LinkageSpecDecl>(getDeclContext()) && 1035 cast<LinkageSpecDecl>(getDeclContext())->getLanguage() 1036 == LinkageSpecDecl::lang_c && 1037 !getAttr<OverloadableAttr>()) 1038 return BuiltinID; 1039 1040 // Not a builtin 1041 return 0; 1042} 1043 1044 1045/// getNumParams - Return the number of parameters this function must have 1046/// based on its FunctionType. This is the length of the PararmInfo array 1047/// after it has been created. 1048unsigned FunctionDecl::getNumParams() const { 1049 const FunctionType *FT = getType()->getAs<FunctionType>(); 1050 if (isa<FunctionNoProtoType>(FT)) 1051 return 0; 1052 return cast<FunctionProtoType>(FT)->getNumArgs(); 1053 1054} 1055 1056void FunctionDecl::setParams(ParmVarDecl **NewParamInfo, unsigned NumParams) { 1057 assert(ParamInfo == 0 && "Already has param info!"); 1058 assert(NumParams == getNumParams() && "Parameter count mismatch!"); 1059 1060 // Zero params -> null pointer. 1061 if (NumParams) { 1062 void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams); 1063 ParamInfo = new (Mem) ParmVarDecl*[NumParams]; 1064 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); 1065 1066 // Update source range. The check below allows us to set EndRangeLoc before 1067 // setting the parameters. 1068 if (EndRangeLoc.isInvalid() || EndRangeLoc == getLocation()) 1069 EndRangeLoc = NewParamInfo[NumParams-1]->getLocEnd(); 1070 } 1071} 1072 1073/// getMinRequiredArguments - Returns the minimum number of arguments 1074/// needed to call this function. This may be fewer than the number of 1075/// function parameters, if some of the parameters have default 1076/// arguments (in C++). 1077unsigned FunctionDecl::getMinRequiredArguments() const { 1078 unsigned NumRequiredArgs = getNumParams(); 1079 while (NumRequiredArgs > 0 1080 && getParamDecl(NumRequiredArgs-1)->hasDefaultArg()) 1081 --NumRequiredArgs; 1082 1083 return NumRequiredArgs; 1084} 1085 1086bool FunctionDecl::isInlined() const { 1087 // FIXME: This is not enough. Consider: 1088 // 1089 // inline void f(); 1090 // void f() { } 1091 // 1092 // f is inlined, but does not have inline specified. 1093 // To fix this we should add an 'inline' flag to FunctionDecl. 1094 if (isInlineSpecified()) 1095 return true; 1096 1097 if (isa<CXXMethodDecl>(this)) { 1098 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified()) 1099 return true; 1100 } 1101 1102 switch (getTemplateSpecializationKind()) { 1103 case TSK_Undeclared: 1104 case TSK_ExplicitSpecialization: 1105 return false; 1106 1107 case TSK_ImplicitInstantiation: 1108 case TSK_ExplicitInstantiationDeclaration: 1109 case TSK_ExplicitInstantiationDefinition: 1110 // Handle below. 1111 break; 1112 } 1113 1114 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1115 Stmt *Pattern = 0; 1116 if (PatternDecl) 1117 Pattern = PatternDecl->getBody(PatternDecl); 1118 1119 if (Pattern && PatternDecl) 1120 return PatternDecl->isInlined(); 1121 1122 return false; 1123} 1124 1125/// \brief For an inline function definition in C or C++, determine whether the 1126/// definition will be externally visible. 1127/// 1128/// Inline function definitions are always available for inlining optimizations. 1129/// However, depending on the language dialect, declaration specifiers, and 1130/// attributes, the definition of an inline function may or may not be 1131/// "externally" visible to other translation units in the program. 1132/// 1133/// In C99, inline definitions are not externally visible by default. However, 1134/// if even one of the global-scope declarations is marked "extern inline", the 1135/// inline definition becomes externally visible (C99 6.7.4p6). 1136/// 1137/// In GNU89 mode, or if the gnu_inline attribute is attached to the function 1138/// definition, we use the GNU semantics for inline, which are nearly the 1139/// opposite of C99 semantics. In particular, "inline" by itself will create 1140/// an externally visible symbol, but "extern inline" will not create an 1141/// externally visible symbol. 1142bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 1143 assert(isThisDeclarationADefinition() && "Must have the function definition"); 1144 assert(isInlined() && "Function must be inline"); 1145 ASTContext &Context = getASTContext(); 1146 1147 if (!Context.getLangOptions().C99 || hasAttr<GNUInlineAttr>()) { 1148 // GNU inline semantics. Based on a number of examples, we came up with the 1149 // following heuristic: if the "inline" keyword is present on a 1150 // declaration of the function but "extern" is not present on that 1151 // declaration, then the symbol is externally visible. Otherwise, the GNU 1152 // "extern inline" semantics applies and the symbol is not externally 1153 // visible. 1154 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 1155 Redecl != RedeclEnd; 1156 ++Redecl) { 1157 if (Redecl->isInlineSpecified() && Redecl->getStorageClass() != Extern) 1158 return true; 1159 } 1160 1161 // GNU "extern inline" semantics; no externally visible symbol. 1162 return false; 1163 } 1164 1165 // C99 6.7.4p6: 1166 // [...] If all of the file scope declarations for a function in a 1167 // translation unit include the inline function specifier without extern, 1168 // then the definition in that translation unit is an inline definition. 1169 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 1170 Redecl != RedeclEnd; 1171 ++Redecl) { 1172 // Only consider file-scope declarations in this test. 1173 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 1174 continue; 1175 1176 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == Extern) 1177 return true; // Not an inline definition 1178 } 1179 1180 // C99 6.7.4p6: 1181 // An inline definition does not provide an external definition for the 1182 // function, and does not forbid an external definition in another 1183 // translation unit. 1184 return false; 1185} 1186 1187/// getOverloadedOperator - Which C++ overloaded operator this 1188/// function represents, if any. 1189OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 1190 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 1191 return getDeclName().getCXXOverloadedOperator(); 1192 else 1193 return OO_None; 1194} 1195 1196/// getLiteralIdentifier - The literal suffix identifier this function 1197/// represents, if any. 1198const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 1199 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 1200 return getDeclName().getCXXLiteralIdentifier(); 1201 else 1202 return 0; 1203} 1204 1205FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 1206 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 1207 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 1208 1209 return 0; 1210} 1211 1212MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 1213 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1214} 1215 1216void 1217FunctionDecl::setInstantiationOfMemberFunction(FunctionDecl *FD, 1218 TemplateSpecializationKind TSK) { 1219 assert(TemplateOrSpecialization.isNull() && 1220 "Member function is already a specialization"); 1221 MemberSpecializationInfo *Info 1222 = new (getASTContext()) MemberSpecializationInfo(FD, TSK); 1223 TemplateOrSpecialization = Info; 1224} 1225 1226bool FunctionDecl::isImplicitlyInstantiable() const { 1227 // If this function already has a definition or is invalid, it can't be 1228 // implicitly instantiated. 1229 if (isInvalidDecl() || getBody()) 1230 return false; 1231 1232 switch (getTemplateSpecializationKind()) { 1233 case TSK_Undeclared: 1234 case TSK_ExplicitSpecialization: 1235 case TSK_ExplicitInstantiationDefinition: 1236 return false; 1237 1238 case TSK_ImplicitInstantiation: 1239 return true; 1240 1241 case TSK_ExplicitInstantiationDeclaration: 1242 // Handled below. 1243 break; 1244 } 1245 1246 // Find the actual template from which we will instantiate. 1247 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1248 Stmt *Pattern = 0; 1249 if (PatternDecl) 1250 Pattern = PatternDecl->getBody(PatternDecl); 1251 1252 // C++0x [temp.explicit]p9: 1253 // Except for inline functions, other explicit instantiation declarations 1254 // have the effect of suppressing the implicit instantiation of the entity 1255 // to which they refer. 1256 if (!Pattern || !PatternDecl) 1257 return true; 1258 1259 return PatternDecl->isInlined(); 1260} 1261 1262FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { 1263 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 1264 while (Primary->getInstantiatedFromMemberTemplate()) { 1265 // If we have hit a point where the user provided a specialization of 1266 // this template, we're done looking. 1267 if (Primary->isMemberSpecialization()) 1268 break; 1269 1270 Primary = Primary->getInstantiatedFromMemberTemplate(); 1271 } 1272 1273 return Primary->getTemplatedDecl(); 1274 } 1275 1276 return getInstantiatedFromMemberFunction(); 1277} 1278 1279FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 1280 if (FunctionTemplateSpecializationInfo *Info 1281 = TemplateOrSpecialization 1282 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1283 return Info->Template.getPointer(); 1284 } 1285 return 0; 1286} 1287 1288const TemplateArgumentList * 1289FunctionDecl::getTemplateSpecializationArgs() const { 1290 if (FunctionTemplateSpecializationInfo *Info 1291 = TemplateOrSpecialization 1292 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1293 return Info->TemplateArguments; 1294 } 1295 return 0; 1296} 1297 1298void 1299FunctionDecl::setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, 1300 const TemplateArgumentList *TemplateArgs, 1301 void *InsertPos, 1302 TemplateSpecializationKind TSK) { 1303 assert(TSK != TSK_Undeclared && 1304 "Must specify the type of function template specialization"); 1305 FunctionTemplateSpecializationInfo *Info 1306 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 1307 if (!Info) 1308 Info = new (getASTContext()) FunctionTemplateSpecializationInfo; 1309 1310 Info->Function = this; 1311 Info->Template.setPointer(Template); 1312 Info->Template.setInt(TSK - 1); 1313 Info->TemplateArguments = TemplateArgs; 1314 TemplateOrSpecialization = Info; 1315 1316 // Insert this function template specialization into the set of known 1317 // function template specializations. 1318 if (InsertPos) 1319 Template->getSpecializations().InsertNode(Info, InsertPos); 1320 else { 1321 // Try to insert the new node. If there is an existing node, remove it 1322 // first. 1323 FunctionTemplateSpecializationInfo *Existing 1324 = Template->getSpecializations().GetOrInsertNode(Info); 1325 if (Existing) { 1326 Template->getSpecializations().RemoveNode(Existing); 1327 Template->getSpecializations().GetOrInsertNode(Info); 1328 } 1329 } 1330} 1331 1332void 1333FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 1334 const UnresolvedSetImpl &Templates, 1335 const TemplateArgumentListInfo &TemplateArgs) { 1336 assert(TemplateOrSpecialization.isNull()); 1337 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo); 1338 Size += Templates.size() * sizeof(FunctionTemplateDecl*); 1339 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc); 1340 void *Buffer = Context.Allocate(Size); 1341 DependentFunctionTemplateSpecializationInfo *Info = 1342 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates, 1343 TemplateArgs); 1344 TemplateOrSpecialization = Info; 1345} 1346 1347DependentFunctionTemplateSpecializationInfo:: 1348DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 1349 const TemplateArgumentListInfo &TArgs) 1350 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 1351 1352 d.NumTemplates = Ts.size(); 1353 d.NumArgs = TArgs.size(); 1354 1355 FunctionTemplateDecl **TsArray = 1356 const_cast<FunctionTemplateDecl**>(getTemplates()); 1357 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 1358 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 1359 1360 TemplateArgumentLoc *ArgsArray = 1361 const_cast<TemplateArgumentLoc*>(getTemplateArgs()); 1362 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 1363 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 1364} 1365 1366TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 1367 // For a function template specialization, query the specialization 1368 // information object. 1369 FunctionTemplateSpecializationInfo *FTSInfo 1370 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 1371 if (FTSInfo) 1372 return FTSInfo->getTemplateSpecializationKind(); 1373 1374 MemberSpecializationInfo *MSInfo 1375 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1376 if (MSInfo) 1377 return MSInfo->getTemplateSpecializationKind(); 1378 1379 return TSK_Undeclared; 1380} 1381 1382void 1383FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1384 SourceLocation PointOfInstantiation) { 1385 if (FunctionTemplateSpecializationInfo *FTSInfo 1386 = TemplateOrSpecialization.dyn_cast< 1387 FunctionTemplateSpecializationInfo*>()) { 1388 FTSInfo->setTemplateSpecializationKind(TSK); 1389 if (TSK != TSK_ExplicitSpecialization && 1390 PointOfInstantiation.isValid() && 1391 FTSInfo->getPointOfInstantiation().isInvalid()) 1392 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 1393 } else if (MemberSpecializationInfo *MSInfo 1394 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 1395 MSInfo->setTemplateSpecializationKind(TSK); 1396 if (TSK != TSK_ExplicitSpecialization && 1397 PointOfInstantiation.isValid() && 1398 MSInfo->getPointOfInstantiation().isInvalid()) 1399 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1400 } else 1401 assert(false && "Function cannot have a template specialization kind"); 1402} 1403 1404SourceLocation FunctionDecl::getPointOfInstantiation() const { 1405 if (FunctionTemplateSpecializationInfo *FTSInfo 1406 = TemplateOrSpecialization.dyn_cast< 1407 FunctionTemplateSpecializationInfo*>()) 1408 return FTSInfo->getPointOfInstantiation(); 1409 else if (MemberSpecializationInfo *MSInfo 1410 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) 1411 return MSInfo->getPointOfInstantiation(); 1412 1413 return SourceLocation(); 1414} 1415 1416bool FunctionDecl::isOutOfLine() const { 1417 if (Decl::isOutOfLine()) 1418 return true; 1419 1420 // If this function was instantiated from a member function of a 1421 // class template, check whether that member function was defined out-of-line. 1422 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 1423 const FunctionDecl *Definition; 1424 if (FD->getBody(Definition)) 1425 return Definition->isOutOfLine(); 1426 } 1427 1428 // If this function was instantiated from a function template, 1429 // check whether that function template was defined out-of-line. 1430 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 1431 const FunctionDecl *Definition; 1432 if (FunTmpl->getTemplatedDecl()->getBody(Definition)) 1433 return Definition->isOutOfLine(); 1434 } 1435 1436 return false; 1437} 1438 1439//===----------------------------------------------------------------------===// 1440// FieldDecl Implementation 1441//===----------------------------------------------------------------------===// 1442 1443FieldDecl *FieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 1444 IdentifierInfo *Id, QualType T, 1445 TypeSourceInfo *TInfo, Expr *BW, bool Mutable) { 1446 return new (C) FieldDecl(Decl::Field, DC, L, Id, T, TInfo, BW, Mutable); 1447} 1448 1449bool FieldDecl::isAnonymousStructOrUnion() const { 1450 if (!isImplicit() || getDeclName()) 1451 return false; 1452 1453 if (const RecordType *Record = getType()->getAs<RecordType>()) 1454 return Record->getDecl()->isAnonymousStructOrUnion(); 1455 1456 return false; 1457} 1458 1459//===----------------------------------------------------------------------===// 1460// TagDecl Implementation 1461//===----------------------------------------------------------------------===// 1462 1463void TagDecl::Destroy(ASTContext &C) { 1464 if (hasExtInfo()) 1465 C.Deallocate(getExtInfo()); 1466 TypeDecl::Destroy(C); 1467} 1468 1469SourceRange TagDecl::getSourceRange() const { 1470 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 1471 return SourceRange(TagKeywordLoc, E); 1472} 1473 1474TagDecl* TagDecl::getCanonicalDecl() { 1475 return getFirstDeclaration(); 1476} 1477 1478void TagDecl::startDefinition() { 1479 if (TagType *TagT = const_cast<TagType *>(TypeForDecl->getAs<TagType>())) { 1480 TagT->decl.setPointer(this); 1481 TagT->decl.setInt(1); 1482 } else if (InjectedClassNameType *Injected 1483 = const_cast<InjectedClassNameType *>( 1484 TypeForDecl->getAs<InjectedClassNameType>())) { 1485 Injected->Decl = cast<CXXRecordDecl>(this); 1486 } 1487 1488 if (isa<CXXRecordDecl>(this)) { 1489 CXXRecordDecl *D = cast<CXXRecordDecl>(this); 1490 struct CXXRecordDecl::DefinitionData *Data = 1491 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 1492 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) 1493 cast<CXXRecordDecl>(*I)->DefinitionData = Data; 1494 } 1495} 1496 1497void TagDecl::completeDefinition() { 1498 assert((!isa<CXXRecordDecl>(this) || 1499 cast<CXXRecordDecl>(this)->hasDefinition()) && 1500 "definition completed but not started"); 1501 1502 IsDefinition = true; 1503 if (TagType *TagT = const_cast<TagType *>(TypeForDecl->getAs<TagType>())) { 1504 assert(TagT->decl.getPointer() == this && 1505 "Attempt to redefine a tag definition?"); 1506 TagT->decl.setInt(0); 1507 } else if (InjectedClassNameType *Injected 1508 = const_cast<InjectedClassNameType *>( 1509 TypeForDecl->getAs<InjectedClassNameType>())) { 1510 assert(Injected->Decl == this && 1511 "Attempt to redefine a class template definition?"); 1512 (void)Injected; 1513 } 1514} 1515 1516TagDecl* TagDecl::getDefinition() const { 1517 if (isDefinition()) 1518 return const_cast<TagDecl *>(this); 1519 1520 for (redecl_iterator R = redecls_begin(), REnd = redecls_end(); 1521 R != REnd; ++R) 1522 if (R->isDefinition()) 1523 return *R; 1524 1525 return 0; 1526} 1527 1528TagDecl::TagKind TagDecl::getTagKindForTypeSpec(unsigned TypeSpec) { 1529 switch (TypeSpec) { 1530 default: llvm_unreachable("unexpected type specifier"); 1531 case DeclSpec::TST_struct: return TK_struct; 1532 case DeclSpec::TST_class: return TK_class; 1533 case DeclSpec::TST_union: return TK_union; 1534 case DeclSpec::TST_enum: return TK_enum; 1535 } 1536} 1537 1538void TagDecl::setQualifierInfo(NestedNameSpecifier *Qualifier, 1539 SourceRange QualifierRange) { 1540 if (Qualifier) { 1541 // Make sure the extended qualifier info is allocated. 1542 if (!hasExtInfo()) 1543 TypedefDeclOrQualifier = new (getASTContext()) ExtInfo; 1544 // Set qualifier info. 1545 getExtInfo()->NNS = Qualifier; 1546 getExtInfo()->NNSRange = QualifierRange; 1547 } 1548 else { 1549 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 1550 assert(QualifierRange.isInvalid()); 1551 if (hasExtInfo()) { 1552 getASTContext().Deallocate(getExtInfo()); 1553 TypedefDeclOrQualifier = (TypedefDecl*) 0; 1554 } 1555 } 1556} 1557 1558//===----------------------------------------------------------------------===// 1559// EnumDecl Implementation 1560//===----------------------------------------------------------------------===// 1561 1562EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 1563 IdentifierInfo *Id, SourceLocation TKL, 1564 EnumDecl *PrevDecl) { 1565 EnumDecl *Enum = new (C) EnumDecl(DC, L, Id, PrevDecl, TKL); 1566 C.getTypeDeclType(Enum, PrevDecl); 1567 return Enum; 1568} 1569 1570void EnumDecl::Destroy(ASTContext& C) { 1571 TagDecl::Destroy(C); 1572} 1573 1574void EnumDecl::completeDefinition(QualType NewType, 1575 QualType NewPromotionType) { 1576 assert(!isDefinition() && "Cannot redefine enums!"); 1577 IntegerType = NewType; 1578 PromotionType = NewPromotionType; 1579 TagDecl::completeDefinition(); 1580} 1581 1582//===----------------------------------------------------------------------===// 1583// RecordDecl Implementation 1584//===----------------------------------------------------------------------===// 1585 1586RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L, 1587 IdentifierInfo *Id, RecordDecl *PrevDecl, 1588 SourceLocation TKL) 1589 : TagDecl(DK, TK, DC, L, Id, PrevDecl, TKL) { 1590 HasFlexibleArrayMember = false; 1591 AnonymousStructOrUnion = false; 1592 HasObjectMember = false; 1593 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); 1594} 1595 1596RecordDecl *RecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC, 1597 SourceLocation L, IdentifierInfo *Id, 1598 SourceLocation TKL, RecordDecl* PrevDecl) { 1599 1600 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id, PrevDecl, TKL); 1601 C.getTypeDeclType(R, PrevDecl); 1602 return R; 1603} 1604 1605RecordDecl::~RecordDecl() { 1606} 1607 1608void RecordDecl::Destroy(ASTContext& C) { 1609 TagDecl::Destroy(C); 1610} 1611 1612bool RecordDecl::isInjectedClassName() const { 1613 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 1614 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 1615} 1616 1617/// completeDefinition - Notes that the definition of this type is now 1618/// complete. 1619void RecordDecl::completeDefinition() { 1620 assert(!isDefinition() && "Cannot redefine record!"); 1621 TagDecl::completeDefinition(); 1622} 1623 1624//===----------------------------------------------------------------------===// 1625// BlockDecl Implementation 1626//===----------------------------------------------------------------------===// 1627 1628BlockDecl::~BlockDecl() { 1629} 1630 1631void BlockDecl::Destroy(ASTContext& C) { 1632 if (Body) 1633 Body->Destroy(C); 1634 1635 for (param_iterator I=param_begin(), E=param_end(); I!=E; ++I) 1636 (*I)->Destroy(C); 1637 1638 C.Deallocate(ParamInfo); 1639 Decl::Destroy(C); 1640} 1641 1642void BlockDecl::setParams(ParmVarDecl **NewParamInfo, 1643 unsigned NParms) { 1644 assert(ParamInfo == 0 && "Already has param info!"); 1645 1646 // Zero params -> null pointer. 1647 if (NParms) { 1648 NumParams = NParms; 1649 void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams); 1650 ParamInfo = new (Mem) ParmVarDecl*[NumParams]; 1651 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); 1652 } 1653} 1654 1655unsigned BlockDecl::getNumParams() const { 1656 return NumParams; 1657} 1658 1659 1660//===----------------------------------------------------------------------===// 1661// Other Decl Allocation/Deallocation Method Implementations 1662//===----------------------------------------------------------------------===// 1663 1664TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 1665 return new (C) TranslationUnitDecl(C); 1666} 1667 1668NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, 1669 SourceLocation L, IdentifierInfo *Id) { 1670 return new (C) NamespaceDecl(DC, L, Id); 1671} 1672 1673void NamespaceDecl::Destroy(ASTContext& C) { 1674 // NamespaceDecl uses "NextDeclarator" to chain namespace declarations 1675 // together. They are all top-level Decls. 1676 1677 this->~NamespaceDecl(); 1678 Decl::Destroy(C); 1679} 1680 1681 1682ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 1683 SourceLocation L, IdentifierInfo *Id, QualType T) { 1684 return new (C) ImplicitParamDecl(ImplicitParam, DC, L, Id, T); 1685} 1686 1687FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, 1688 SourceLocation L, 1689 DeclarationName N, QualType T, 1690 TypeSourceInfo *TInfo, 1691 StorageClass S, StorageClass SCAsWritten, 1692 bool isInline, bool hasWrittenPrototype) { 1693 FunctionDecl *New = new (C) FunctionDecl(Function, DC, L, N, T, TInfo, 1694 S, SCAsWritten, isInline); 1695 New->HasWrittenPrototype = hasWrittenPrototype; 1696 return New; 1697} 1698 1699BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 1700 return new (C) BlockDecl(DC, L); 1701} 1702 1703EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 1704 SourceLocation L, 1705 IdentifierInfo *Id, QualType T, 1706 Expr *E, const llvm::APSInt &V) { 1707 return new (C) EnumConstantDecl(CD, L, Id, T, E, V); 1708} 1709 1710void EnumConstantDecl::Destroy(ASTContext& C) { 1711 if (Init) Init->Destroy(C); 1712 ValueDecl::Destroy(C); 1713} 1714 1715TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 1716 SourceLocation L, IdentifierInfo *Id, 1717 TypeSourceInfo *TInfo) { 1718 return new (C) TypedefDecl(DC, L, Id, TInfo); 1719} 1720 1721// Anchor TypedefDecl's vtable here. 1722TypedefDecl::~TypedefDecl() {} 1723 1724FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 1725 SourceLocation L, 1726 StringLiteral *Str) { 1727 return new (C) FileScopeAsmDecl(DC, L, Str); 1728} 1729