1 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Decl subclasses. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/Decl.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/PrettyPrinter.h" 24 #include "clang/AST/Stmt.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/Basic/Builtins.h" 27 #include "clang/Basic/IdentifierTable.h" 28 #include "clang/Basic/Module.h" 29 #include "clang/Basic/Specifiers.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include <algorithm> 33 34 using namespace clang; 35 36 //===----------------------------------------------------------------------===// 37 // NamedDecl Implementation 38 //===----------------------------------------------------------------------===// 39 40 static 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 } 51 } 52 53 // If we're on Mac OS X, an 'availability' for Mac OS X attribute 54 // implies visibility(default). 55 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) { 56 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>(); 65 } 66 67 typedef NamedDecl::LinkageInfo LinkageInfo; 68 69 static LinkageInfo getLVForType(QualType T) { 70 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility(); 71 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit()); 72 } 73 74 /// \brief Get the most restrictive linkage for the types in the given 75 /// template parameter list. 76 static LinkageInfo 77 getLVForTemplateParameterList(const TemplateParameterList *Params) { 78 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false); 79 for (TemplateParameterList::const_iterator P = Params->begin(), 80 PEnd = Params->end(); 81 P != PEnd; ++P) { 82 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 83 if (NTTP->isExpandedParameterPack()) { 84 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 85 QualType T = NTTP->getExpansionType(I); 86 if (!T->isDependentType()) 87 LV.merge(getLVForType(T)); 88 } 89 continue; 90 } 91 92 if (!NTTP->getType()->isDependentType()) { 93 LV.merge(getLVForType(NTTP->getType())); 94 continue; 95 } 96 } 97 98 if (TemplateTemplateParmDecl *TTP 99 = dyn_cast<TemplateTemplateParmDecl>(*P)) { 100 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters())); 101 } 102 } 103 104 return LV; 105 } 106 107 /// Compute the linkage and visibility for the given declaration. 108 static LinkageInfo computeLVForDecl(const NamedDecl *D, bool OnlyTemplate); 109 110 static LinkageInfo getLVForDecl(const NamedDecl *D, bool OnlyTemplate) { 111 if (!OnlyTemplate) 112 return D->getLinkageAndVisibility(); 113 return computeLVForDecl(D, OnlyTemplate); 114 } 115 116 /// \brief Get the most restrictive linkage for the types and 117 /// declarations in the given template argument list. 118 static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Args, 119 unsigned NumArgs, 120 bool OnlyTemplate) { 121 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false); 122 123 for (unsigned I = 0; I != NumArgs; ++I) { 124 switch (Args[I].getKind()) { 125 case TemplateArgument::Null: 126 case TemplateArgument::Integral: 127 case TemplateArgument::Expression: 128 break; 129 130 case TemplateArgument::Type: 131 LV.mergeWithMin(getLVForType(Args[I].getAsType())); 132 break; 133 134 case TemplateArgument::Declaration: 135 if (NamedDecl *ND = dyn_cast<NamedDecl>(Args[I].getAsDecl())) 136 LV.mergeWithMin(getLVForDecl(ND, OnlyTemplate)); 137 break; 138 139 case TemplateArgument::NullPtr: 140 LV.mergeWithMin(getLVForType(Args[I].getNullPtrType())); 141 break; 142 143 case TemplateArgument::Template: 144 case TemplateArgument::TemplateExpansion: 145 if (TemplateDecl *Template 146 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl()) 147 LV.mergeWithMin(getLVForDecl(Template, OnlyTemplate)); 148 break; 149 150 case TemplateArgument::Pack: 151 LV.mergeWithMin(getLVForTemplateArgumentList(Args[I].pack_begin(), 152 Args[I].pack_size(), 153 OnlyTemplate)); 154 break; 155 } 156 } 157 158 return LV; 159 } 160 161 static LinkageInfo 162 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs, 163 bool OnlyTemplate) { 164 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), OnlyTemplate); 165 } 166 167 static bool shouldConsiderTemplateVis(const FunctionDecl *fn, 168 const FunctionTemplateSpecializationInfo *spec) { 169 return !fn->hasAttr<VisibilityAttr>() || spec->isExplicitSpecialization(); 170 } 171 172 static bool 173 shouldConsiderTemplateVis(const ClassTemplateSpecializationDecl *d) { 174 return !d->hasAttr<VisibilityAttr>() || d->isExplicitSpecialization(); 175 } 176 177 static bool useInlineVisibilityHidden(const NamedDecl *D) { 178 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c. 179 const LangOptions &Opts = D->getASTContext().getLangOpts(); 180 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden) 181 return false; 182 183 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 184 if (!FD) 185 return false; 186 187 TemplateSpecializationKind TSK = TSK_Undeclared; 188 if (FunctionTemplateSpecializationInfo *spec 189 = FD->getTemplateSpecializationInfo()) { 190 TSK = spec->getTemplateSpecializationKind(); 191 } else if (MemberSpecializationInfo *MSI = 192 FD->getMemberSpecializationInfo()) { 193 TSK = MSI->getTemplateSpecializationKind(); 194 } 195 196 const FunctionDecl *Def = 0; 197 // InlineVisibilityHidden only applies to definitions, and 198 // isInlined() only gives meaningful answers on definitions 199 // anyway. 200 return TSK != TSK_ExplicitInstantiationDeclaration && 201 TSK != TSK_ExplicitInstantiationDefinition && 202 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>(); 203 } 204 205 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, 206 bool OnlyTemplate) { 207 assert(D->getDeclContext()->getRedeclContext()->isFileContext() && 208 "Not a name having namespace scope"); 209 ASTContext &Context = D->getASTContext(); 210 211 // C++ [basic.link]p3: 212 // A name having namespace scope (3.3.6) has internal linkage if it 213 // is the name of 214 // - an object, reference, function or function template that is 215 // explicitly declared static; or, 216 // (This bullet corresponds to C99 6.2.2p3.) 217 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 218 // Explicitly declared static. 219 if (Var->getStorageClass() == SC_Static) 220 return LinkageInfo::internal(); 221 222 // - a non-volatile object or reference that is explicitly declared const 223 // or constexpr and neither explicitly declared extern nor previously 224 // declared to have external linkage; or (there is no equivalent in C99) 225 if (Context.getLangOpts().CPlusPlus && 226 Var->getType().isConstQualified() && 227 !Var->getType().isVolatileQualified() && 228 Var->getStorageClass() != SC_Extern && 229 Var->getStorageClass() != SC_PrivateExtern) { 230 bool FoundExtern = false; 231 for (const VarDecl *PrevVar = Var->getPreviousDecl(); 232 PrevVar && !FoundExtern; 233 PrevVar = PrevVar->getPreviousDecl()) 234 if (isExternalLinkage(PrevVar->getLinkage())) 235 FoundExtern = true; 236 237 if (!FoundExtern) 238 return LinkageInfo::internal(); 239 } 240 if (Var->getStorageClass() == SC_None) { 241 const VarDecl *PrevVar = Var->getPreviousDecl(); 242 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl()) 243 if (PrevVar->getStorageClass() == SC_PrivateExtern) 244 break; 245 if (PrevVar) 246 return PrevVar->getLinkageAndVisibility(); 247 } 248 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) { 249 // C++ [temp]p4: 250 // A non-member function template can have internal linkage; any 251 // other template name shall have external linkage. 252 const FunctionDecl *Function = 0; 253 if (const FunctionTemplateDecl *FunTmpl 254 = dyn_cast<FunctionTemplateDecl>(D)) 255 Function = FunTmpl->getTemplatedDecl(); 256 else 257 Function = cast<FunctionDecl>(D); 258 259 // Explicitly declared static. 260 if (Function->getStorageClass() == SC_Static) 261 return LinkageInfo(InternalLinkage, DefaultVisibility, false); 262 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) { 263 // - a data member of an anonymous union. 264 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()) 265 return LinkageInfo::internal(); 266 } 267 268 if (D->isInAnonymousNamespace()) { 269 const VarDecl *Var = dyn_cast<VarDecl>(D); 270 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D); 271 if ((!Var || !Var->getDeclContext()->isExternCContext()) && 272 (!Func || !Func->getDeclContext()->isExternCContext())) 273 return LinkageInfo::uniqueExternal(); 274 } 275 276 // Set up the defaults. 277 278 // C99 6.2.2p5: 279 // If the declaration of an identifier for an object has file 280 // scope and no storage-class specifier, its linkage is 281 // external. 282 LinkageInfo LV; 283 284 if (!OnlyTemplate) { 285 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) { 286 LV.mergeVisibility(*Vis, true); 287 } 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()) { 293 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC); 294 if (!ND) continue; 295 if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) { 296 LV.mergeVisibility(*Vis, true); 297 break; 298 } 299 } 300 } 301 } 302 303 if (!OnlyTemplate) { 304 LV.mergeVisibility(Context.getLangOpts().getVisibilityMode()); 305 // If we're paying attention to global visibility, apply 306 // -finline-visibility-hidden if this is an inline method. 307 if (!LV.visibilityExplicit() && useInlineVisibilityHidden(D)) 308 LV.mergeVisibility(HiddenVisibility, true); 309 } 310 311 // C++ [basic.link]p4: 312 313 // A name having namespace scope has external linkage if it is the 314 // name of 315 // 316 // - an object or reference, unless it has internal linkage; or 317 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 318 // GCC applies the following optimization to variables and static 319 // data members, but not to functions: 320 // 321 // Modify the variable's LV by the LV of its type unless this is 322 // C or extern "C". This follows from [basic.link]p9: 323 // A type without linkage shall not be used as the type of a 324 // variable or function with external linkage unless 325 // - the entity has C language linkage, or 326 // - the entity is declared within an unnamed namespace, or 327 // - the entity is not used or is defined in the same 328 // translation unit. 329 // and [basic.link]p10: 330 // ...the types specified by all declarations referring to a 331 // given variable or function shall be identical... 332 // C does not have an equivalent rule. 333 // 334 // Ignore this if we've got an explicit attribute; the user 335 // probably knows what they're doing. 336 // 337 // Note that we don't want to make the variable non-external 338 // because of this, but unique-external linkage suits us. 339 if (Context.getLangOpts().CPlusPlus && 340 !Var->getDeclContext()->isExternCContext()) { 341 LinkageInfo TypeLV = getLVForType(Var->getType()); 342 if (TypeLV.linkage() != ExternalLinkage) 343 return LinkageInfo::uniqueExternal(); 344 LV.mergeVisibility(TypeLV); 345 } 346 347 if (Var->getStorageClass() == SC_PrivateExtern) 348 LV.mergeVisibility(HiddenVisibility, true); 349 350 // Note that Sema::MergeVarDecl already takes care of implementing 351 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have 352 // to do it here. 353 354 // - a function, unless it has internal linkage; or 355 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 356 // In theory, we can modify the function's LV by the LV of its 357 // type unless it has C linkage (see comment above about variables 358 // for justification). In practice, GCC doesn't do this, so it's 359 // just too painful to make work. 360 361 if (Function->getStorageClass() == SC_PrivateExtern) 362 LV.mergeVisibility(HiddenVisibility, true); 363 364 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 365 // merging storage classes and visibility attributes, so we don't have to 366 // look at previous decls in here. 367 368 // In C++, then if the type of the function uses a type with 369 // unique-external linkage, it's not legally usable from outside 370 // this translation unit. However, we should use the C linkage 371 // rules instead for extern "C" declarations. 372 if (Context.getLangOpts().CPlusPlus && 373 !Function->getDeclContext()->isExternCContext() && 374 Function->getType()->getLinkage() == UniqueExternalLinkage) 375 return LinkageInfo::uniqueExternal(); 376 377 // Consider LV from the template and the template arguments unless 378 // this is an explicit specialization with a visibility attribute. 379 if (FunctionTemplateSpecializationInfo *specInfo 380 = Function->getTemplateSpecializationInfo()) { 381 LinkageInfo TempLV = getLVForDecl(specInfo->getTemplate(), true); 382 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments; 383 LinkageInfo ArgsLV = getLVForTemplateArgumentList(templateArgs, 384 OnlyTemplate); 385 if (shouldConsiderTemplateVis(Function, specInfo)) { 386 LV.mergeWithMin(TempLV); 387 LV.mergeWithMin(ArgsLV); 388 } else { 389 LV.mergeLinkage(TempLV); 390 LV.mergeLinkage(ArgsLV); 391 } 392 } 393 394 // - a named class (Clause 9), or an unnamed class defined in a 395 // typedef declaration in which the class has the typedef name 396 // for linkage purposes (7.1.3); or 397 // - a named enumeration (7.2), or an unnamed enumeration 398 // defined in a typedef declaration in which the enumeration 399 // has the typedef name for linkage purposes (7.1.3); or 400 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) { 401 // Unnamed tags have no linkage. 402 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) 403 return LinkageInfo::none(); 404 405 // If this is a class template specialization, consider the 406 // linkage of the template and template arguments. 407 if (const ClassTemplateSpecializationDecl *spec 408 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) { 409 // From the template. 410 LinkageInfo TempLV = getLVForDecl(spec->getSpecializedTemplate(), true); 411 412 // The arguments at which the template was instantiated. 413 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs(); 414 LinkageInfo ArgsLV = getLVForTemplateArgumentList(TemplateArgs, 415 OnlyTemplate); 416 if (shouldConsiderTemplateVis(spec)) { 417 LV.mergeWithMin(TempLV); 418 LV.mergeWithMin(ArgsLV); 419 } else { 420 LV.mergeLinkage(TempLV); 421 LV.mergeLinkage(ArgsLV); 422 } 423 } 424 425 // - an enumerator belonging to an enumeration with external linkage; 426 } else if (isa<EnumConstantDecl>(D)) { 427 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), 428 OnlyTemplate); 429 if (!isExternalLinkage(EnumLV.linkage())) 430 return LinkageInfo::none(); 431 LV.merge(EnumLV); 432 433 // - a template, unless it is a function template that has 434 // internal linkage (Clause 14); 435 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) { 436 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters())); 437 // - a namespace (7.3), unless it is declared within an unnamed 438 // namespace. 439 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) { 440 return LV; 441 442 // By extension, we assign external linkage to Objective-C 443 // interfaces. 444 } else if (isa<ObjCInterfaceDecl>(D)) { 445 // fallout 446 447 // Everything not covered here has no linkage. 448 } else { 449 return LinkageInfo::none(); 450 } 451 452 // If we ended up with non-external linkage, visibility should 453 // always be default. 454 if (LV.linkage() != ExternalLinkage) 455 return LinkageInfo(LV.linkage(), DefaultVisibility, false); 456 457 return LV; 458 } 459 460 static LinkageInfo getLVForClassMember(const NamedDecl *D, bool OnlyTemplate) { 461 // Only certain class members have linkage. Note that fields don't 462 // really have linkage, but it's convenient to say they do for the 463 // purposes of calculating linkage of pointer-to-data-member 464 // template arguments. 465 if (!(isa<CXXMethodDecl>(D) || 466 isa<VarDecl>(D) || 467 isa<FieldDecl>(D) || 468 isa<TagDecl>(D))) 469 return LinkageInfo::none(); 470 471 LinkageInfo LV; 472 473 // If we have an explicit visibility attribute, merge that in. 474 if (!OnlyTemplate) { 475 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) 476 LV.mergeVisibility(*Vis, true); 477 // If we're paying attention to global visibility, apply 478 // -finline-visibility-hidden if this is an inline method. 479 // 480 // Note that we do this before merging information about 481 // the class visibility. 482 if (!LV.visibilityExplicit() && useInlineVisibilityHidden(D)) 483 LV.mergeVisibility(HiddenVisibility, true); 484 } 485 486 // If this class member has an explicit visibility attribute, the only 487 // thing that can change its visibility is the template arguments, so 488 // only look for them when processing the class. 489 bool ClassOnlyTemplate = LV.visibilityExplicit() ? true : OnlyTemplate; 490 491 // If this member has an visibility attribute, ClassF will exclude 492 // attributes on the class or command line options, keeping only information 493 // about the template instantiation. If the member has no visibility 494 // attributes, mergeWithMin behaves like merge, so in both cases mergeWithMin 495 // produces the desired result. 496 LV.mergeWithMin(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), 497 ClassOnlyTemplate)); 498 if (!isExternalLinkage(LV.linkage())) 499 return LinkageInfo::none(); 500 501 // If the class already has unique-external linkage, we can't improve. 502 if (LV.linkage() == UniqueExternalLinkage) 503 return LinkageInfo::uniqueExternal(); 504 505 if (!OnlyTemplate) 506 LV.mergeVisibility(D->getASTContext().getLangOpts().getVisibilityMode()); 507 508 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 509 // If the type of the function uses a type with unique-external 510 // linkage, it's not legally usable from outside this translation unit. 511 if (MD->getType()->getLinkage() == UniqueExternalLinkage) 512 return LinkageInfo::uniqueExternal(); 513 514 // If this is a method template specialization, use the linkage for 515 // the template parameters and arguments. 516 if (FunctionTemplateSpecializationInfo *spec 517 = MD->getTemplateSpecializationInfo()) { 518 const TemplateArgumentList &TemplateArgs = *spec->TemplateArguments; 519 LinkageInfo ArgsLV = getLVForTemplateArgumentList(TemplateArgs, 520 OnlyTemplate); 521 TemplateParameterList *TemplateParams = 522 spec->getTemplate()->getTemplateParameters(); 523 LinkageInfo ParamsLV = getLVForTemplateParameterList(TemplateParams); 524 if (shouldConsiderTemplateVis(MD, spec)) { 525 LV.mergeWithMin(ArgsLV); 526 if (!OnlyTemplate) 527 LV.mergeWithMin(ParamsLV); 528 } else { 529 LV.mergeLinkage(ArgsLV); 530 if (!OnlyTemplate) 531 LV.mergeLinkage(ParamsLV); 532 } 533 } 534 535 // Note that in contrast to basically every other situation, we 536 // *do* apply -fvisibility to method declarations. 537 538 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 539 if (const ClassTemplateSpecializationDecl *spec 540 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 541 // Merge template argument/parameter information for member 542 // class template specializations. 543 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs(); 544 LinkageInfo ArgsLV = getLVForTemplateArgumentList(TemplateArgs, 545 OnlyTemplate); 546 TemplateParameterList *TemplateParams = 547 spec->getSpecializedTemplate()->getTemplateParameters(); 548 LinkageInfo ParamsLV = getLVForTemplateParameterList(TemplateParams); 549 if (shouldConsiderTemplateVis(spec)) { 550 LV.mergeWithMin(ArgsLV); 551 if (!OnlyTemplate) 552 LV.mergeWithMin(ParamsLV); 553 } else { 554 LV.mergeLinkage(ArgsLV); 555 if (!OnlyTemplate) 556 LV.mergeLinkage(ParamsLV); 557 } 558 } 559 560 // Static data members. 561 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 562 // Modify the variable's linkage by its type, but ignore the 563 // type's visibility unless it's a definition. 564 LinkageInfo TypeLV = getLVForType(VD->getType()); 565 if (TypeLV.linkage() != ExternalLinkage) 566 LV.mergeLinkage(UniqueExternalLinkage); 567 LV.mergeVisibility(TypeLV); 568 } 569 570 return LV; 571 } 572 573 static void clearLinkageForClass(const CXXRecordDecl *record) { 574 for (CXXRecordDecl::decl_iterator 575 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) { 576 Decl *child = *i; 577 if (isa<NamedDecl>(child)) 578 cast<NamedDecl>(child)->ClearLVCache(); 579 } 580 } 581 582 void NamedDecl::anchor() { } 583 584 void NamedDecl::ClearLVCache() { 585 // Note that we can't skip clearing the linkage of children just 586 // because the parent doesn't have cached linkage: we don't cache 587 // when computing linkage for parent contexts. 588 589 CacheValidAndVisibility = 0; 590 591 // If we're changing the linkage of a class, we need to reset the 592 // linkage of child declarations, too. 593 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this)) 594 clearLinkageForClass(record); 595 596 if (ClassTemplateDecl *temp = 597 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) { 598 // Clear linkage for the template pattern. 599 CXXRecordDecl *record = temp->getTemplatedDecl(); 600 record->CacheValidAndVisibility = 0; 601 clearLinkageForClass(record); 602 603 // We need to clear linkage for specializations, too. 604 for (ClassTemplateDecl::spec_iterator 605 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i) 606 i->ClearLVCache(); 607 } 608 609 // Clear cached linkage for function template decls, too. 610 if (FunctionTemplateDecl *temp = 611 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) { 612 temp->getTemplatedDecl()->ClearLVCache(); 613 for (FunctionTemplateDecl::spec_iterator 614 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i) 615 i->ClearLVCache(); 616 } 617 618 } 619 620 Linkage NamedDecl::getLinkage() const { 621 return getLinkageAndVisibility().linkage(); 622 } 623 624 LinkageInfo NamedDecl::getLinkageAndVisibility() const { 625 if (CacheValidAndVisibility) { 626 Linkage L = static_cast<Linkage>(CachedLinkage); 627 Visibility V = static_cast<Visibility>(CacheValidAndVisibility - 1); 628 bool Explicit = CachedVisibilityExplicit; 629 LinkageInfo LV(L, V, Explicit); 630 assert(LV == computeLVForDecl(this, false)); 631 return LV; 632 } 633 LinkageInfo LV = computeLVForDecl(this, false); 634 CachedLinkage = LV.linkage(); 635 CacheValidAndVisibility = LV.visibility() + 1; 636 CachedVisibilityExplicit = LV.visibilityExplicit(); 637 return LV; 638 } 639 640 llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const { 641 // Use the most recent declaration of a variable. 642 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) { 643 if (llvm::Optional<Visibility> V = getVisibilityOf(Var)) 644 return V; 645 646 if (Var->isStaticDataMember()) { 647 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember(); 648 if (InstantiatedFrom) 649 return getVisibilityOf(InstantiatedFrom); 650 } 651 652 return llvm::Optional<Visibility>(); 653 } 654 // Use the most recent declaration of a function, and also handle 655 // function template specializations. 656 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) { 657 if (llvm::Optional<Visibility> V = getVisibilityOf(fn)) 658 return V; 659 660 // If the function is a specialization of a template with an 661 // explicit visibility attribute, use that. 662 if (FunctionTemplateSpecializationInfo *templateInfo 663 = fn->getTemplateSpecializationInfo()) 664 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl()); 665 666 // If the function is a member of a specialization of a class template 667 // and the corresponding decl has explicit visibility, use that. 668 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction(); 669 if (InstantiatedFrom) 670 return getVisibilityOf(InstantiatedFrom); 671 672 return llvm::Optional<Visibility>(); 673 } 674 675 // Otherwise, just check the declaration itself first. 676 if (llvm::Optional<Visibility> V = getVisibilityOf(this)) 677 return V; 678 679 // The visibility of a template is stored in the templated decl. 680 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this)) 681 return getVisibilityOf(TD->getTemplatedDecl()); 682 683 // If there wasn't explicit visibility there, and this is a 684 // specialization of a class template, check for visibility 685 // on the pattern. 686 if (const ClassTemplateSpecializationDecl *spec 687 = dyn_cast<ClassTemplateSpecializationDecl>(this)) 688 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl()); 689 690 // If this is a member class of a specialization of a class template 691 // and the corresponding decl has explicit visibility, use that. 692 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) { 693 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass(); 694 if (InstantiatedFrom) 695 return getVisibilityOf(InstantiatedFrom); 696 } 697 698 return llvm::Optional<Visibility>(); 699 } 700 701 static LinkageInfo computeLVForDecl(const NamedDecl *D, bool OnlyTemplate) { 702 // Objective-C: treat all Objective-C declarations as having external 703 // linkage. 704 switch (D->getKind()) { 705 default: 706 break; 707 case Decl::ParmVar: 708 return LinkageInfo::none(); 709 case Decl::TemplateTemplateParm: // count these as external 710 case Decl::NonTypeTemplateParm: 711 case Decl::ObjCAtDefsField: 712 case Decl::ObjCCategory: 713 case Decl::ObjCCategoryImpl: 714 case Decl::ObjCCompatibleAlias: 715 case Decl::ObjCImplementation: 716 case Decl::ObjCMethod: 717 case Decl::ObjCProperty: 718 case Decl::ObjCPropertyImpl: 719 case Decl::ObjCProtocol: 720 return LinkageInfo::external(); 721 722 case Decl::CXXRecord: { 723 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D); 724 if (Record->isLambda()) { 725 if (!Record->getLambdaManglingNumber()) { 726 // This lambda has no mangling number, so it's internal. 727 return LinkageInfo::internal(); 728 } 729 730 // This lambda has its linkage/visibility determined by its owner. 731 const DeclContext *DC = D->getDeclContext()->getRedeclContext(); 732 if (Decl *ContextDecl = Record->getLambdaContextDecl()) { 733 if (isa<ParmVarDecl>(ContextDecl)) 734 DC = ContextDecl->getDeclContext()->getRedeclContext(); 735 else 736 return getLVForDecl(cast<NamedDecl>(ContextDecl), 737 OnlyTemplate); 738 } 739 740 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) 741 return getLVForDecl(ND, OnlyTemplate); 742 743 return LinkageInfo::external(); 744 } 745 746 break; 747 } 748 } 749 750 // Handle linkage for namespace-scope names. 751 if (D->getDeclContext()->getRedeclContext()->isFileContext()) 752 return getLVForNamespaceScopeDecl(D, OnlyTemplate); 753 754 // C++ [basic.link]p5: 755 // In addition, a member function, static data member, a named 756 // class or enumeration of class scope, or an unnamed class or 757 // enumeration defined in a class-scope typedef declaration such 758 // that the class or enumeration has the typedef name for linkage 759 // purposes (7.1.3), has external linkage if the name of the class 760 // has external linkage. 761 if (D->getDeclContext()->isRecord()) 762 return getLVForClassMember(D, OnlyTemplate); 763 764 // C++ [basic.link]p6: 765 // The name of a function declared in block scope and the name of 766 // an object declared by a block scope extern declaration have 767 // linkage. If there is a visible declaration of an entity with 768 // linkage having the same name and type, ignoring entities 769 // declared outside the innermost enclosing namespace scope, the 770 // block scope declaration declares that same entity and receives 771 // the linkage of the previous declaration. If there is more than 772 // one such matching entity, the program is ill-formed. Otherwise, 773 // if no matching entity is found, the block scope entity receives 774 // external linkage. 775 if (D->getLexicalDeclContext()->isFunctionOrMethod()) { 776 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 777 if (Function->isInAnonymousNamespace() && 778 !Function->getDeclContext()->isExternCContext()) 779 return LinkageInfo::uniqueExternal(); 780 781 LinkageInfo LV; 782 if (!OnlyTemplate) { 783 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility()) 784 LV.mergeVisibility(*Vis, true); 785 } 786 787 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 788 // merging storage classes and visibility attributes, so we don't have to 789 // look at previous decls in here. 790 791 return LV; 792 } 793 794 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) 795 if (Var->getStorageClassAsWritten() == SC_Extern || 796 Var->getStorageClassAsWritten() == SC_PrivateExtern) { 797 if (Var->isInAnonymousNamespace() && 798 !Var->getDeclContext()->isExternCContext()) 799 return LinkageInfo::uniqueExternal(); 800 801 // This is an "extern int foo;" which got merged with a file static. 802 if (Var->getStorageClass() == SC_Static) 803 return LinkageInfo::internal(); 804 805 LinkageInfo LV; 806 if (Var->getStorageClass() == SC_PrivateExtern) 807 LV.mergeVisibility(HiddenVisibility, true); 808 else if (!OnlyTemplate) { 809 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility()) 810 LV.mergeVisibility(*Vis, true); 811 } 812 813 // Note that Sema::MergeVarDecl already takes care of implementing 814 // C99 6.2.2p4 and propagating the visibility attribute, so we don't 815 // have to do it here. 816 return LV; 817 } 818 } 819 820 // C++ [basic.link]p6: 821 // Names not covered by these rules have no linkage. 822 return LinkageInfo::none(); 823 } 824 825 std::string NamedDecl::getQualifiedNameAsString() const { 826 return getQualifiedNameAsString(getASTContext().getPrintingPolicy()); 827 } 828 829 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const { 830 const DeclContext *Ctx = getDeclContext(); 831 832 if (Ctx->isFunctionOrMethod()) 833 return getNameAsString(); 834 835 typedef SmallVector<const DeclContext *, 8> ContextsTy; 836 ContextsTy Contexts; 837 838 // Collect contexts. 839 while (Ctx && isa<NamedDecl>(Ctx)) { 840 Contexts.push_back(Ctx); 841 Ctx = Ctx->getParent(); 842 }; 843 844 std::string QualName; 845 llvm::raw_string_ostream OS(QualName); 846 847 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend(); 848 I != E; ++I) { 849 if (const ClassTemplateSpecializationDecl *Spec 850 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) { 851 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 852 std::string TemplateArgsStr 853 = TemplateSpecializationType::PrintTemplateArgumentList( 854 TemplateArgs.data(), 855 TemplateArgs.size(), 856 P); 857 OS << Spec->getName() << TemplateArgsStr; 858 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) { 859 if (ND->isAnonymousNamespace()) 860 OS << "<anonymous namespace>"; 861 else 862 OS << *ND; 863 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) { 864 if (!RD->getIdentifier()) 865 OS << "<anonymous " << RD->getKindName() << '>'; 866 else 867 OS << *RD; 868 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 869 const FunctionProtoType *FT = 0; 870 if (FD->hasWrittenPrototype()) 871 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>()); 872 873 OS << *FD << '('; 874 if (FT) { 875 unsigned NumParams = FD->getNumParams(); 876 for (unsigned i = 0; i < NumParams; ++i) { 877 if (i) 878 OS << ", "; 879 OS << FD->getParamDecl(i)->getType().stream(P); 880 } 881 882 if (FT->isVariadic()) { 883 if (NumParams > 0) 884 OS << ", "; 885 OS << "..."; 886 } 887 } 888 OS << ')'; 889 } else { 890 OS << *cast<NamedDecl>(*I); 891 } 892 OS << "::"; 893 } 894 895 if (getDeclName()) 896 OS << *this; 897 else 898 OS << "<anonymous>"; 899 900 return OS.str(); 901 } 902 903 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const { 904 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 905 906 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name. 907 // We want to keep it, unless it nominates same namespace. 908 if (getKind() == Decl::UsingDirective) { 909 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() 910 ->getOriginalNamespace() == 911 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace() 912 ->getOriginalNamespace(); 913 } 914 915 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 916 // For function declarations, we keep track of redeclarations. 917 return FD->getPreviousDecl() == OldD; 918 919 // For function templates, the underlying function declarations are linked. 920 if (const FunctionTemplateDecl *FunctionTemplate 921 = dyn_cast<FunctionTemplateDecl>(this)) 922 if (const FunctionTemplateDecl *OldFunctionTemplate 923 = dyn_cast<FunctionTemplateDecl>(OldD)) 924 return FunctionTemplate->getTemplatedDecl() 925 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl()); 926 927 // For method declarations, we keep track of redeclarations. 928 if (isa<ObjCMethodDecl>(this)) 929 return false; 930 931 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD)) 932 return true; 933 934 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD)) 935 return cast<UsingShadowDecl>(this)->getTargetDecl() == 936 cast<UsingShadowDecl>(OldD)->getTargetDecl(); 937 938 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) { 939 ASTContext &Context = getASTContext(); 940 return Context.getCanonicalNestedNameSpecifier( 941 cast<UsingDecl>(this)->getQualifier()) == 942 Context.getCanonicalNestedNameSpecifier( 943 cast<UsingDecl>(OldD)->getQualifier()); 944 } 945 946 // A typedef of an Objective-C class type can replace an Objective-C class 947 // declaration or definition, and vice versa. 948 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) || 949 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD))) 950 return true; 951 952 // For non-function declarations, if the declarations are of the 953 // same kind then this must be a redeclaration, or semantic analysis 954 // would not have given us the new declaration. 955 return this->getKind() == OldD->getKind(); 956 } 957 958 bool NamedDecl::hasLinkage() const { 959 return getLinkage() != NoLinkage; 960 } 961 962 NamedDecl *NamedDecl::getUnderlyingDeclImpl() { 963 NamedDecl *ND = this; 964 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND)) 965 ND = UD->getTargetDecl(); 966 967 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 968 return AD->getClassInterface(); 969 970 return ND; 971 } 972 973 bool NamedDecl::isCXXInstanceMember() const { 974 if (!isCXXClassMember()) 975 return false; 976 977 const NamedDecl *D = this; 978 if (isa<UsingShadowDecl>(D)) 979 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 980 981 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 982 return true; 983 if (isa<CXXMethodDecl>(D)) 984 return cast<CXXMethodDecl>(D)->isInstance(); 985 if (isa<FunctionTemplateDecl>(D)) 986 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D) 987 ->getTemplatedDecl())->isInstance(); 988 return false; 989 } 990 991 //===----------------------------------------------------------------------===// 992 // DeclaratorDecl Implementation 993 //===----------------------------------------------------------------------===// 994 995 template <typename DeclT> 996 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 997 if (decl->getNumTemplateParameterLists() > 0) 998 return decl->getTemplateParameterList(0)->getTemplateLoc(); 999 else 1000 return decl->getInnerLocStart(); 1001 } 1002 1003 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 1004 TypeSourceInfo *TSI = getTypeSourceInfo(); 1005 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 1006 return SourceLocation(); 1007 } 1008 1009 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 1010 if (QualifierLoc) { 1011 // Make sure the extended decl info is allocated. 1012 if (!hasExtInfo()) { 1013 // Save (non-extended) type source info pointer. 1014 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1015 // Allocate external info struct. 1016 DeclInfo = new (getASTContext()) ExtInfo; 1017 // Restore savedTInfo into (extended) decl info. 1018 getExtInfo()->TInfo = savedTInfo; 1019 } 1020 // Set qualifier info. 1021 getExtInfo()->QualifierLoc = QualifierLoc; 1022 } else { 1023 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 1024 if (hasExtInfo()) { 1025 if (getExtInfo()->NumTemplParamLists == 0) { 1026 // Save type source info pointer. 1027 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo; 1028 // Deallocate the extended decl info. 1029 getASTContext().Deallocate(getExtInfo()); 1030 // Restore savedTInfo into (non-extended) decl info. 1031 DeclInfo = savedTInfo; 1032 } 1033 else 1034 getExtInfo()->QualifierLoc = QualifierLoc; 1035 } 1036 } 1037 } 1038 1039 void 1040 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context, 1041 unsigned NumTPLists, 1042 TemplateParameterList **TPLists) { 1043 assert(NumTPLists > 0); 1044 // Make sure the extended decl info is allocated. 1045 if (!hasExtInfo()) { 1046 // Save (non-extended) type source info pointer. 1047 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1048 // Allocate external info struct. 1049 DeclInfo = new (getASTContext()) ExtInfo; 1050 // Restore savedTInfo into (extended) decl info. 1051 getExtInfo()->TInfo = savedTInfo; 1052 } 1053 // Set the template parameter lists info. 1054 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists); 1055 } 1056 1057 SourceLocation DeclaratorDecl::getOuterLocStart() const { 1058 return getTemplateOrInnerLocStart(this); 1059 } 1060 1061 namespace { 1062 1063 // Helper function: returns true if QT is or contains a type 1064 // having a postfix component. 1065 bool typeIsPostfix(clang::QualType QT) { 1066 while (true) { 1067 const Type* T = QT.getTypePtr(); 1068 switch (T->getTypeClass()) { 1069 default: 1070 return false; 1071 case Type::Pointer: 1072 QT = cast<PointerType>(T)->getPointeeType(); 1073 break; 1074 case Type::BlockPointer: 1075 QT = cast<BlockPointerType>(T)->getPointeeType(); 1076 break; 1077 case Type::MemberPointer: 1078 QT = cast<MemberPointerType>(T)->getPointeeType(); 1079 break; 1080 case Type::LValueReference: 1081 case Type::RValueReference: 1082 QT = cast<ReferenceType>(T)->getPointeeType(); 1083 break; 1084 case Type::PackExpansion: 1085 QT = cast<PackExpansionType>(T)->getPattern(); 1086 break; 1087 case Type::Paren: 1088 case Type::ConstantArray: 1089 case Type::DependentSizedArray: 1090 case Type::IncompleteArray: 1091 case Type::VariableArray: 1092 case Type::FunctionProto: 1093 case Type::FunctionNoProto: 1094 return true; 1095 } 1096 } 1097 } 1098 1099 } // namespace 1100 1101 SourceRange DeclaratorDecl::getSourceRange() const { 1102 SourceLocation RangeEnd = getLocation(); 1103 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 1104 if (typeIsPostfix(TInfo->getType())) 1105 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 1106 } 1107 return SourceRange(getOuterLocStart(), RangeEnd); 1108 } 1109 1110 void 1111 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context, 1112 unsigned NumTPLists, 1113 TemplateParameterList **TPLists) { 1114 assert((NumTPLists == 0 || TPLists != 0) && 1115 "Empty array of template parameters with positive size!"); 1116 1117 // Free previous template parameters (if any). 1118 if (NumTemplParamLists > 0) { 1119 Context.Deallocate(TemplParamLists); 1120 TemplParamLists = 0; 1121 NumTemplParamLists = 0; 1122 } 1123 // Set info on matched template parameter lists (if any). 1124 if (NumTPLists > 0) { 1125 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists]; 1126 NumTemplParamLists = NumTPLists; 1127 for (unsigned i = NumTPLists; i-- > 0; ) 1128 TemplParamLists[i] = TPLists[i]; 1129 } 1130 } 1131 1132 //===----------------------------------------------------------------------===// 1133 // VarDecl Implementation 1134 //===----------------------------------------------------------------------===// 1135 1136 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 1137 switch (SC) { 1138 case SC_None: break; 1139 case SC_Auto: return "auto"; 1140 case SC_Extern: return "extern"; 1141 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>"; 1142 case SC_PrivateExtern: return "__private_extern__"; 1143 case SC_Register: return "register"; 1144 case SC_Static: return "static"; 1145 } 1146 1147 llvm_unreachable("Invalid storage class"); 1148 } 1149 1150 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, 1151 SourceLocation StartL, SourceLocation IdL, 1152 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 1153 StorageClass S, StorageClass SCAsWritten) { 1154 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten); 1155 } 1156 1157 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1158 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl)); 1159 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0, 1160 QualType(), 0, SC_None, SC_None); 1161 } 1162 1163 void VarDecl::setStorageClass(StorageClass SC) { 1164 assert(isLegalForVariable(SC)); 1165 if (getStorageClass() != SC) 1166 ClearLVCache(); 1167 1168 VarDeclBits.SClass = SC; 1169 } 1170 1171 SourceRange VarDecl::getSourceRange() const { 1172 if (const Expr *Init = getInit()) { 1173 SourceLocation InitEnd = Init->getLocEnd(); 1174 if (InitEnd.isValid()) 1175 return SourceRange(getOuterLocStart(), InitEnd); 1176 } 1177 return DeclaratorDecl::getSourceRange(); 1178 } 1179 1180 template<typename decl_type> 1181 static bool hasCLanguageLinkageTemplate(const decl_type &D) { 1182 // Language linkage is a C++ concept, but saying that everything in C has 1183 // C language linkage fits the implementation nicelly. 1184 ASTContext &Context = D.getASTContext(); 1185 if (!Context.getLangOpts().CPlusPlus) 1186 return true; 1187 1188 // dcl.link 4: A C language linkage is ignored in determining the language 1189 // linkage of the names of class members and the function type of class member 1190 // functions. 1191 const DeclContext *DC = D.getDeclContext(); 1192 if (DC->isRecord()) 1193 return false; 1194 1195 // If the first decl is in an extern "C" context, any other redeclaration 1196 // will have C language linkage. If the first one is not in an extern "C" 1197 // context, we would have reported an error for any other decl being in one. 1198 const decl_type *First = D.getFirstDeclaration(); 1199 return First->getDeclContext()->isExternCContext(); 1200 } 1201 1202 bool VarDecl::hasCLanguageLinkage() const { 1203 return hasCLanguageLinkageTemplate(*this); 1204 } 1205 1206 bool VarDecl::isExternC() const { 1207 if (getLinkage() != ExternalLinkage) 1208 return false; 1209 1210 const DeclContext *DC = getDeclContext(); 1211 if (DC->isRecord()) 1212 return false; 1213 1214 ASTContext &Context = getASTContext(); 1215 if (!Context.getLangOpts().CPlusPlus) 1216 return true; 1217 return DC->isExternCContext(); 1218 } 1219 1220 VarDecl *VarDecl::getCanonicalDecl() { 1221 return getFirstDeclaration(); 1222 } 1223 1224 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition( 1225 ASTContext &C) const 1226 { 1227 // C++ [basic.def]p2: 1228 // A declaration is a definition unless [...] it contains the 'extern' 1229 // specifier or a linkage-specification and neither an initializer [...], 1230 // it declares a static data member in a class declaration [...]. 1231 // C++ [temp.expl.spec]p15: 1232 // An explicit specialization of a static data member of a template is a 1233 // definition if the declaration includes an initializer; otherwise, it is 1234 // a declaration. 1235 if (isStaticDataMember()) { 1236 if (isOutOfLine() && (hasInit() || 1237 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)) 1238 return Definition; 1239 else 1240 return DeclarationOnly; 1241 } 1242 // C99 6.7p5: 1243 // A definition of an identifier is a declaration for that identifier that 1244 // [...] causes storage to be reserved for that object. 1245 // Note: that applies for all non-file-scope objects. 1246 // C99 6.9.2p1: 1247 // If the declaration of an identifier for an object has file scope and an 1248 // initializer, the declaration is an external definition for the identifier 1249 if (hasInit()) 1250 return Definition; 1251 // AST for 'extern "C" int foo;' is annotated with 'extern'. 1252 if (hasExternalStorage()) 1253 return DeclarationOnly; 1254 1255 if (getStorageClassAsWritten() == SC_Extern || 1256 getStorageClassAsWritten() == SC_PrivateExtern) { 1257 for (const VarDecl *PrevVar = getPreviousDecl(); 1258 PrevVar; PrevVar = PrevVar->getPreviousDecl()) { 1259 if (PrevVar->getLinkage() == InternalLinkage) 1260 return DeclarationOnly; 1261 } 1262 } 1263 // C99 6.9.2p2: 1264 // A declaration of an object that has file scope without an initializer, 1265 // and without a storage class specifier or the scs 'static', constitutes 1266 // a tentative definition. 1267 // No such thing in C++. 1268 if (!C.getLangOpts().CPlusPlus && isFileVarDecl()) 1269 return TentativeDefinition; 1270 1271 // What's left is (in C, block-scope) declarations without initializers or 1272 // external storage. These are definitions. 1273 return Definition; 1274 } 1275 1276 VarDecl *VarDecl::getActingDefinition() { 1277 DefinitionKind Kind = isThisDeclarationADefinition(); 1278 if (Kind != TentativeDefinition) 1279 return 0; 1280 1281 VarDecl *LastTentative = 0; 1282 VarDecl *First = getFirstDeclaration(); 1283 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1284 I != E; ++I) { 1285 Kind = (*I)->isThisDeclarationADefinition(); 1286 if (Kind == Definition) 1287 return 0; 1288 else if (Kind == TentativeDefinition) 1289 LastTentative = *I; 1290 } 1291 return LastTentative; 1292 } 1293 1294 bool VarDecl::isTentativeDefinitionNow() const { 1295 DefinitionKind Kind = isThisDeclarationADefinition(); 1296 if (Kind != TentativeDefinition) 1297 return false; 1298 1299 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1300 if ((*I)->isThisDeclarationADefinition() == Definition) 1301 return false; 1302 } 1303 return true; 1304 } 1305 1306 VarDecl *VarDecl::getDefinition(ASTContext &C) { 1307 VarDecl *First = getFirstDeclaration(); 1308 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1309 I != E; ++I) { 1310 if ((*I)->isThisDeclarationADefinition(C) == Definition) 1311 return *I; 1312 } 1313 return 0; 1314 } 1315 1316 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const { 1317 DefinitionKind Kind = DeclarationOnly; 1318 1319 const VarDecl *First = getFirstDeclaration(); 1320 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1321 I != E; ++I) { 1322 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C)); 1323 if (Kind == Definition) 1324 break; 1325 } 1326 1327 return Kind; 1328 } 1329 1330 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 1331 redecl_iterator I = redecls_begin(), E = redecls_end(); 1332 while (I != E && !I->getInit()) 1333 ++I; 1334 1335 if (I != E) { 1336 D = *I; 1337 return I->getInit(); 1338 } 1339 return 0; 1340 } 1341 1342 bool VarDecl::isOutOfLine() const { 1343 if (Decl::isOutOfLine()) 1344 return true; 1345 1346 if (!isStaticDataMember()) 1347 return false; 1348 1349 // If this static data member was instantiated from a static data member of 1350 // a class template, check whether that static data member was defined 1351 // out-of-line. 1352 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 1353 return VD->isOutOfLine(); 1354 1355 return false; 1356 } 1357 1358 VarDecl *VarDecl::getOutOfLineDefinition() { 1359 if (!isStaticDataMember()) 1360 return 0; 1361 1362 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end(); 1363 RD != RDEnd; ++RD) { 1364 if (RD->getLexicalDeclContext()->isFileContext()) 1365 return *RD; 1366 } 1367 1368 return 0; 1369 } 1370 1371 void VarDecl::setInit(Expr *I) { 1372 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 1373 Eval->~EvaluatedStmt(); 1374 getASTContext().Deallocate(Eval); 1375 } 1376 1377 Init = I; 1378 } 1379 1380 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const { 1381 const LangOptions &Lang = C.getLangOpts(); 1382 1383 if (!Lang.CPlusPlus) 1384 return false; 1385 1386 // In C++11, any variable of reference type can be used in a constant 1387 // expression if it is initialized by a constant expression. 1388 if (Lang.CPlusPlus11 && getType()->isReferenceType()) 1389 return true; 1390 1391 // Only const objects can be used in constant expressions in C++. C++98 does 1392 // not require the variable to be non-volatile, but we consider this to be a 1393 // defect. 1394 if (!getType().isConstQualified() || getType().isVolatileQualified()) 1395 return false; 1396 1397 // In C++, const, non-volatile variables of integral or enumeration types 1398 // can be used in constant expressions. 1399 if (getType()->isIntegralOrEnumerationType()) 1400 return true; 1401 1402 // Additionally, in C++11, non-volatile constexpr variables can be used in 1403 // constant expressions. 1404 return Lang.CPlusPlus11 && isConstexpr(); 1405 } 1406 1407 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt 1408 /// form, which contains extra information on the evaluated value of the 1409 /// initializer. 1410 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const { 1411 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>(); 1412 if (!Eval) { 1413 Stmt *S = Init.get<Stmt *>(); 1414 Eval = new (getASTContext()) EvaluatedStmt; 1415 Eval->Value = S; 1416 Init = Eval; 1417 } 1418 return Eval; 1419 } 1420 1421 APValue *VarDecl::evaluateValue() const { 1422 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 1423 return evaluateValue(Notes); 1424 } 1425 1426 APValue *VarDecl::evaluateValue( 1427 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 1428 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 1429 1430 // We only produce notes indicating why an initializer is non-constant the 1431 // first time it is evaluated. FIXME: The notes won't always be emitted the 1432 // first time we try evaluation, so might not be produced at all. 1433 if (Eval->WasEvaluated) 1434 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated; 1435 1436 const Expr *Init = cast<Expr>(Eval->Value); 1437 assert(!Init->isValueDependent()); 1438 1439 if (Eval->IsEvaluating) { 1440 // FIXME: Produce a diagnostic for self-initialization. 1441 Eval->CheckedICE = true; 1442 Eval->IsICE = false; 1443 return 0; 1444 } 1445 1446 Eval->IsEvaluating = true; 1447 1448 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(), 1449 this, Notes); 1450 1451 // Ensure the result is an uninitialized APValue if evaluation fails. 1452 if (!Result) 1453 Eval->Evaluated = APValue(); 1454 1455 Eval->IsEvaluating = false; 1456 Eval->WasEvaluated = true; 1457 1458 // In C++11, we have determined whether the initializer was a constant 1459 // expression as a side-effect. 1460 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) { 1461 Eval->CheckedICE = true; 1462 Eval->IsICE = Result && Notes.empty(); 1463 } 1464 1465 return Result ? &Eval->Evaluated : 0; 1466 } 1467 1468 bool VarDecl::checkInitIsICE() const { 1469 // Initializers of weak variables are never ICEs. 1470 if (isWeak()) 1471 return false; 1472 1473 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 1474 if (Eval->CheckedICE) 1475 // We have already checked whether this subexpression is an 1476 // integral constant expression. 1477 return Eval->IsICE; 1478 1479 const Expr *Init = cast<Expr>(Eval->Value); 1480 assert(!Init->isValueDependent()); 1481 1482 // In C++11, evaluate the initializer to check whether it's a constant 1483 // expression. 1484 if (getASTContext().getLangOpts().CPlusPlus11) { 1485 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 1486 evaluateValue(Notes); 1487 return Eval->IsICE; 1488 } 1489 1490 // It's an ICE whether or not the definition we found is 1491 // out-of-line. See DR 721 and the discussion in Clang PR 1492 // 6206 for details. 1493 1494 if (Eval->CheckingICE) 1495 return false; 1496 Eval->CheckingICE = true; 1497 1498 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext()); 1499 Eval->CheckingICE = false; 1500 Eval->CheckedICE = true; 1501 return Eval->IsICE; 1502 } 1503 1504 bool VarDecl::extendsLifetimeOfTemporary() const { 1505 assert(getType()->isReferenceType() &&"Non-references never extend lifetime"); 1506 1507 const Expr *E = getInit(); 1508 if (!E) 1509 return false; 1510 1511 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E)) 1512 E = Cleanups->getSubExpr(); 1513 1514 return isa<MaterializeTemporaryExpr>(E); 1515 } 1516 1517 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 1518 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 1519 return cast<VarDecl>(MSI->getInstantiatedFrom()); 1520 1521 return 0; 1522 } 1523 1524 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 1525 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 1526 return MSI->getTemplateSpecializationKind(); 1527 1528 return TSK_Undeclared; 1529 } 1530 1531 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 1532 return getASTContext().getInstantiatedFromStaticDataMember(this); 1533 } 1534 1535 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1536 SourceLocation PointOfInstantiation) { 1537 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 1538 assert(MSI && "Not an instantiated static data member?"); 1539 MSI->setTemplateSpecializationKind(TSK); 1540 if (TSK != TSK_ExplicitSpecialization && 1541 PointOfInstantiation.isValid() && 1542 MSI->getPointOfInstantiation().isInvalid()) 1543 MSI->setPointOfInstantiation(PointOfInstantiation); 1544 } 1545 1546 //===----------------------------------------------------------------------===// 1547 // ParmVarDecl Implementation 1548 //===----------------------------------------------------------------------===// 1549 1550 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 1551 SourceLocation StartLoc, 1552 SourceLocation IdLoc, IdentifierInfo *Id, 1553 QualType T, TypeSourceInfo *TInfo, 1554 StorageClass S, StorageClass SCAsWritten, 1555 Expr *DefArg) { 1556 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo, 1557 S, SCAsWritten, DefArg); 1558 } 1559 1560 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1561 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl)); 1562 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(), 1563 0, QualType(), 0, SC_None, SC_None, 0); 1564 } 1565 1566 SourceRange ParmVarDecl::getSourceRange() const { 1567 if (!hasInheritedDefaultArg()) { 1568 SourceRange ArgRange = getDefaultArgRange(); 1569 if (ArgRange.isValid()) 1570 return SourceRange(getOuterLocStart(), ArgRange.getEnd()); 1571 } 1572 1573 return DeclaratorDecl::getSourceRange(); 1574 } 1575 1576 Expr *ParmVarDecl::getDefaultArg() { 1577 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 1578 assert(!hasUninstantiatedDefaultArg() && 1579 "Default argument is not yet instantiated!"); 1580 1581 Expr *Arg = getInit(); 1582 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg)) 1583 return E->getSubExpr(); 1584 1585 return Arg; 1586 } 1587 1588 SourceRange ParmVarDecl::getDefaultArgRange() const { 1589 if (const Expr *E = getInit()) 1590 return E->getSourceRange(); 1591 1592 if (hasUninstantiatedDefaultArg()) 1593 return getUninstantiatedDefaultArg()->getSourceRange(); 1594 1595 return SourceRange(); 1596 } 1597 1598 bool ParmVarDecl::isParameterPack() const { 1599 return isa<PackExpansionType>(getType()); 1600 } 1601 1602 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) { 1603 getASTContext().setParameterIndex(this, parameterIndex); 1604 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel; 1605 } 1606 1607 unsigned ParmVarDecl::getParameterIndexLarge() const { 1608 return getASTContext().getParameterIndex(this); 1609 } 1610 1611 //===----------------------------------------------------------------------===// 1612 // FunctionDecl Implementation 1613 //===----------------------------------------------------------------------===// 1614 1615 void FunctionDecl::getNameForDiagnostic(std::string &S, 1616 const PrintingPolicy &Policy, 1617 bool Qualified) const { 1618 NamedDecl::getNameForDiagnostic(S, Policy, Qualified); 1619 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 1620 if (TemplateArgs) 1621 S += TemplateSpecializationType::PrintTemplateArgumentList( 1622 TemplateArgs->data(), 1623 TemplateArgs->size(), 1624 Policy); 1625 1626 } 1627 1628 bool FunctionDecl::isVariadic() const { 1629 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>()) 1630 return FT->isVariadic(); 1631 return false; 1632 } 1633 1634 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 1635 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1636 if (I->Body || I->IsLateTemplateParsed) { 1637 Definition = *I; 1638 return true; 1639 } 1640 } 1641 1642 return false; 1643 } 1644 1645 bool FunctionDecl::hasTrivialBody() const 1646 { 1647 Stmt *S = getBody(); 1648 if (!S) { 1649 // Since we don't have a body for this function, we don't know if it's 1650 // trivial or not. 1651 return false; 1652 } 1653 1654 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty()) 1655 return true; 1656 return false; 1657 } 1658 1659 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const { 1660 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1661 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) { 1662 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I; 1663 return true; 1664 } 1665 } 1666 1667 return false; 1668 } 1669 1670 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 1671 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1672 if (I->Body) { 1673 Definition = *I; 1674 return I->Body.get(getASTContext().getExternalSource()); 1675 } else if (I->IsLateTemplateParsed) { 1676 Definition = *I; 1677 return 0; 1678 } 1679 } 1680 1681 return 0; 1682 } 1683 1684 void FunctionDecl::setBody(Stmt *B) { 1685 Body = B; 1686 if (B) 1687 EndRangeLoc = B->getLocEnd(); 1688 for (redecl_iterator R = redecls_begin(), REnd = redecls_end(); R != REnd; 1689 ++R) 1690 R->ClearLVCache(); 1691 } 1692 1693 void FunctionDecl::setPure(bool P) { 1694 IsPure = P; 1695 if (P) 1696 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 1697 Parent->markedVirtualFunctionPure(); 1698 } 1699 1700 bool FunctionDecl::isMain() const { 1701 const TranslationUnitDecl *tunit = 1702 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 1703 return tunit && 1704 !tunit->getASTContext().getLangOpts().Freestanding && 1705 getIdentifier() && 1706 getIdentifier()->isStr("main"); 1707 } 1708 1709 bool FunctionDecl::isReservedGlobalPlacementOperator() const { 1710 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName); 1711 assert(getDeclName().getCXXOverloadedOperator() == OO_New || 1712 getDeclName().getCXXOverloadedOperator() == OO_Delete || 1713 getDeclName().getCXXOverloadedOperator() == OO_Array_New || 1714 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete); 1715 1716 if (isa<CXXRecordDecl>(getDeclContext())) return false; 1717 assert(getDeclContext()->getRedeclContext()->isTranslationUnit()); 1718 1719 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>(); 1720 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false; 1721 1722 ASTContext &Context = 1723 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()) 1724 ->getASTContext(); 1725 1726 // The result type and first argument type are constant across all 1727 // these operators. The second argument must be exactly void*. 1728 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy); 1729 } 1730 1731 bool FunctionDecl::hasCLanguageLinkage() const { 1732 return hasCLanguageLinkageTemplate(*this); 1733 } 1734 1735 bool FunctionDecl::isExternC() const { 1736 if (getLinkage() != ExternalLinkage) 1737 return false; 1738 1739 if (getAttr<OverloadableAttr>()) 1740 return false; 1741 1742 const DeclContext *DC = getDeclContext(); 1743 if (DC->isRecord()) 1744 return false; 1745 1746 ASTContext &Context = getASTContext(); 1747 if (!Context.getLangOpts().CPlusPlus) 1748 return true; 1749 1750 return isMain() || DC->isExternCContext(); 1751 } 1752 1753 bool FunctionDecl::isGlobal() const { 1754 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this)) 1755 return Method->isStatic(); 1756 1757 if (getStorageClass() == SC_Static) 1758 return false; 1759 1760 for (const DeclContext *DC = getDeclContext(); 1761 DC->isNamespace(); 1762 DC = DC->getParent()) { 1763 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) { 1764 if (!Namespace->getDeclName()) 1765 return false; 1766 break; 1767 } 1768 } 1769 1770 return true; 1771 } 1772 1773 void 1774 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 1775 redeclarable_base::setPreviousDeclaration(PrevDecl); 1776 1777 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 1778 FunctionTemplateDecl *PrevFunTmpl 1779 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0; 1780 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 1781 FunTmpl->setPreviousDeclaration(PrevFunTmpl); 1782 } 1783 1784 if (PrevDecl && PrevDecl->IsInline) 1785 IsInline = true; 1786 } 1787 1788 const FunctionDecl *FunctionDecl::getCanonicalDecl() const { 1789 return getFirstDeclaration(); 1790 } 1791 1792 FunctionDecl *FunctionDecl::getCanonicalDecl() { 1793 return getFirstDeclaration(); 1794 } 1795 1796 void FunctionDecl::setStorageClass(StorageClass SC) { 1797 assert(isLegalForFunction(SC)); 1798 if (getStorageClass() != SC) 1799 ClearLVCache(); 1800 1801 SClass = SC; 1802 } 1803 1804 /// \brief Returns a value indicating whether this function 1805 /// corresponds to a builtin function. 1806 /// 1807 /// The function corresponds to a built-in function if it is 1808 /// declared at translation scope or within an extern "C" block and 1809 /// its name matches with the name of a builtin. The returned value 1810 /// will be 0 for functions that do not correspond to a builtin, a 1811 /// value of type \c Builtin::ID if in the target-independent range 1812 /// \c [1,Builtin::First), or a target-specific builtin value. 1813 unsigned FunctionDecl::getBuiltinID() const { 1814 if (!getIdentifier()) 1815 return 0; 1816 1817 unsigned BuiltinID = getIdentifier()->getBuiltinID(); 1818 if (!BuiltinID) 1819 return 0; 1820 1821 ASTContext &Context = getASTContext(); 1822 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 1823 return BuiltinID; 1824 1825 // This function has the name of a known C library 1826 // function. Determine whether it actually refers to the C library 1827 // function or whether it just has the same name. 1828 1829 // If this is a static function, it's not a builtin. 1830 if (getStorageClass() == SC_Static) 1831 return 0; 1832 1833 // If this function is at translation-unit scope and we're not in 1834 // C++, it refers to the C library function. 1835 if (!Context.getLangOpts().CPlusPlus && 1836 getDeclContext()->isTranslationUnit()) 1837 return BuiltinID; 1838 1839 // If the function is in an extern "C" linkage specification and is 1840 // not marked "overloadable", it's the real function. 1841 if (isa<LinkageSpecDecl>(getDeclContext()) && 1842 cast<LinkageSpecDecl>(getDeclContext())->getLanguage() 1843 == LinkageSpecDecl::lang_c && 1844 !getAttr<OverloadableAttr>()) 1845 return BuiltinID; 1846 1847 // Not a builtin 1848 return 0; 1849 } 1850 1851 1852 /// getNumParams - Return the number of parameters this function must have 1853 /// based on its FunctionType. This is the length of the ParamInfo array 1854 /// after it has been created. 1855 unsigned FunctionDecl::getNumParams() const { 1856 const FunctionType *FT = getType()->castAs<FunctionType>(); 1857 if (isa<FunctionNoProtoType>(FT)) 1858 return 0; 1859 return cast<FunctionProtoType>(FT)->getNumArgs(); 1860 1861 } 1862 1863 void FunctionDecl::setParams(ASTContext &C, 1864 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) { 1865 assert(ParamInfo == 0 && "Already has param info!"); 1866 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"); 1867 1868 // Zero params -> null pointer. 1869 if (!NewParamInfo.empty()) { 1870 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; 1871 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 1872 } 1873 } 1874 1875 void FunctionDecl::setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls) { 1876 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!"); 1877 1878 if (!NewDecls.empty()) { 1879 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()]; 1880 std::copy(NewDecls.begin(), NewDecls.end(), A); 1881 DeclsInPrototypeScope = llvm::ArrayRef<NamedDecl*>(A, NewDecls.size()); 1882 } 1883 } 1884 1885 /// getMinRequiredArguments - Returns the minimum number of arguments 1886 /// needed to call this function. This may be fewer than the number of 1887 /// function parameters, if some of the parameters have default 1888 /// arguments (in C++) or the last parameter is a parameter pack. 1889 unsigned FunctionDecl::getMinRequiredArguments() const { 1890 if (!getASTContext().getLangOpts().CPlusPlus) 1891 return getNumParams(); 1892 1893 unsigned NumRequiredArgs = getNumParams(); 1894 1895 // If the last parameter is a parameter pack, we don't need an argument for 1896 // it. 1897 if (NumRequiredArgs > 0 && 1898 getParamDecl(NumRequiredArgs - 1)->isParameterPack()) 1899 --NumRequiredArgs; 1900 1901 // If this parameter has a default argument, we don't need an argument for 1902 // it. 1903 while (NumRequiredArgs > 0 && 1904 getParamDecl(NumRequiredArgs-1)->hasDefaultArg()) 1905 --NumRequiredArgs; 1906 1907 // We might have parameter packs before the end. These can't be deduced, 1908 // but they can still handle multiple arguments. 1909 unsigned ArgIdx = NumRequiredArgs; 1910 while (ArgIdx > 0) { 1911 if (getParamDecl(ArgIdx - 1)->isParameterPack()) 1912 NumRequiredArgs = ArgIdx; 1913 1914 --ArgIdx; 1915 } 1916 1917 return NumRequiredArgs; 1918 } 1919 1920 bool FunctionDecl::isInlined() const { 1921 if (IsInline) 1922 return true; 1923 1924 if (isa<CXXMethodDecl>(this)) { 1925 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified()) 1926 return true; 1927 } 1928 1929 switch (getTemplateSpecializationKind()) { 1930 case TSK_Undeclared: 1931 case TSK_ExplicitSpecialization: 1932 return false; 1933 1934 case TSK_ImplicitInstantiation: 1935 case TSK_ExplicitInstantiationDeclaration: 1936 case TSK_ExplicitInstantiationDefinition: 1937 // Handle below. 1938 break; 1939 } 1940 1941 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1942 bool HasPattern = false; 1943 if (PatternDecl) 1944 HasPattern = PatternDecl->hasBody(PatternDecl); 1945 1946 if (HasPattern && PatternDecl) 1947 return PatternDecl->isInlined(); 1948 1949 return false; 1950 } 1951 1952 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { 1953 // Only consider file-scope declarations in this test. 1954 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 1955 return false; 1956 1957 // Only consider explicit declarations; the presence of a builtin for a 1958 // libcall shouldn't affect whether a definition is externally visible. 1959 if (Redecl->isImplicit()) 1960 return false; 1961 1962 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 1963 return true; // Not an inline definition 1964 1965 return false; 1966 } 1967 1968 /// \brief For a function declaration in C or C++, determine whether this 1969 /// declaration causes the definition to be externally visible. 1970 /// 1971 /// Specifically, this determines if adding the current declaration to the set 1972 /// of redeclarations of the given functions causes 1973 /// isInlineDefinitionExternallyVisible to change from false to true. 1974 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { 1975 assert(!doesThisDeclarationHaveABody() && 1976 "Must have a declaration without a body."); 1977 1978 ASTContext &Context = getASTContext(); 1979 1980 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 1981 // With GNU inlining, a declaration with 'inline' but not 'extern', forces 1982 // an externally visible definition. 1983 // 1984 // FIXME: What happens if gnu_inline gets added on after the first 1985 // declaration? 1986 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern) 1987 return false; 1988 1989 const FunctionDecl *Prev = this; 1990 bool FoundBody = false; 1991 while ((Prev = Prev->getPreviousDecl())) { 1992 FoundBody |= Prev->Body; 1993 1994 if (Prev->Body) { 1995 // If it's not the case that both 'inline' and 'extern' are 1996 // specified on the definition, then it is always externally visible. 1997 if (!Prev->isInlineSpecified() || 1998 Prev->getStorageClassAsWritten() != SC_Extern) 1999 return false; 2000 } else if (Prev->isInlineSpecified() && 2001 Prev->getStorageClassAsWritten() != SC_Extern) { 2002 return false; 2003 } 2004 } 2005 return FoundBody; 2006 } 2007 2008 if (Context.getLangOpts().CPlusPlus) 2009 return false; 2010 2011 // C99 6.7.4p6: 2012 // [...] If all of the file scope declarations for a function in a 2013 // translation unit include the inline function specifier without extern, 2014 // then the definition in that translation unit is an inline definition. 2015 if (isInlineSpecified() && getStorageClass() != SC_Extern) 2016 return false; 2017 const FunctionDecl *Prev = this; 2018 bool FoundBody = false; 2019 while ((Prev = Prev->getPreviousDecl())) { 2020 FoundBody |= Prev->Body; 2021 if (RedeclForcesDefC99(Prev)) 2022 return false; 2023 } 2024 return FoundBody; 2025 } 2026 2027 /// \brief For an inline function definition in C or C++, determine whether the 2028 /// definition will be externally visible. 2029 /// 2030 /// Inline function definitions are always available for inlining optimizations. 2031 /// However, depending on the language dialect, declaration specifiers, and 2032 /// attributes, the definition of an inline function may or may not be 2033 /// "externally" visible to other translation units in the program. 2034 /// 2035 /// In C99, inline definitions are not externally visible by default. However, 2036 /// if even one of the global-scope declarations is marked "extern inline", the 2037 /// inline definition becomes externally visible (C99 6.7.4p6). 2038 /// 2039 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function 2040 /// definition, we use the GNU semantics for inline, which are nearly the 2041 /// opposite of C99 semantics. In particular, "inline" by itself will create 2042 /// an externally visible symbol, but "extern inline" will not create an 2043 /// externally visible symbol. 2044 bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 2045 assert(doesThisDeclarationHaveABody() && "Must have the function definition"); 2046 assert(isInlined() && "Function must be inline"); 2047 ASTContext &Context = getASTContext(); 2048 2049 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 2050 // Note: If you change the logic here, please change 2051 // doesDeclarationForceExternallyVisibleDefinition as well. 2052 // 2053 // If it's not the case that both 'inline' and 'extern' are 2054 // specified on the definition, then this inline definition is 2055 // externally visible. 2056 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern)) 2057 return true; 2058 2059 // If any declaration is 'inline' but not 'extern', then this definition 2060 // is externally visible. 2061 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 2062 Redecl != RedeclEnd; 2063 ++Redecl) { 2064 if (Redecl->isInlineSpecified() && 2065 Redecl->getStorageClassAsWritten() != SC_Extern) 2066 return true; 2067 } 2068 2069 return false; 2070 } 2071 2072 // C99 6.7.4p6: 2073 // [...] If all of the file scope declarations for a function in a 2074 // translation unit include the inline function specifier without extern, 2075 // then the definition in that translation unit is an inline definition. 2076 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 2077 Redecl != RedeclEnd; 2078 ++Redecl) { 2079 if (RedeclForcesDefC99(*Redecl)) 2080 return true; 2081 } 2082 2083 // C99 6.7.4p6: 2084 // An inline definition does not provide an external definition for the 2085 // function, and does not forbid an external definition in another 2086 // translation unit. 2087 return false; 2088 } 2089 2090 /// getOverloadedOperator - Which C++ overloaded operator this 2091 /// function represents, if any. 2092 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 2093 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 2094 return getDeclName().getCXXOverloadedOperator(); 2095 else 2096 return OO_None; 2097 } 2098 2099 /// getLiteralIdentifier - The literal suffix identifier this function 2100 /// represents, if any. 2101 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 2102 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 2103 return getDeclName().getCXXLiteralIdentifier(); 2104 else 2105 return 0; 2106 } 2107 2108 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 2109 if (TemplateOrSpecialization.isNull()) 2110 return TK_NonTemplate; 2111 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>()) 2112 return TK_FunctionTemplate; 2113 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 2114 return TK_MemberSpecialization; 2115 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 2116 return TK_FunctionTemplateSpecialization; 2117 if (TemplateOrSpecialization.is 2118 <DependentFunctionTemplateSpecializationInfo*>()) 2119 return TK_DependentFunctionTemplateSpecialization; 2120 2121 llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); 2122 } 2123 2124 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 2125 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 2126 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 2127 2128 return 0; 2129 } 2130 2131 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 2132 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 2133 } 2134 2135 void 2136 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 2137 FunctionDecl *FD, 2138 TemplateSpecializationKind TSK) { 2139 assert(TemplateOrSpecialization.isNull() && 2140 "Member function is already a specialization"); 2141 MemberSpecializationInfo *Info 2142 = new (C) MemberSpecializationInfo(FD, TSK); 2143 TemplateOrSpecialization = Info; 2144 } 2145 2146 bool FunctionDecl::isImplicitlyInstantiable() const { 2147 // If the function is invalid, it can't be implicitly instantiated. 2148 if (isInvalidDecl()) 2149 return false; 2150 2151 switch (getTemplateSpecializationKind()) { 2152 case TSK_Undeclared: 2153 case TSK_ExplicitInstantiationDefinition: 2154 return false; 2155 2156 case TSK_ImplicitInstantiation: 2157 return true; 2158 2159 // It is possible to instantiate TSK_ExplicitSpecialization kind 2160 // if the FunctionDecl has a class scope specialization pattern. 2161 case TSK_ExplicitSpecialization: 2162 return getClassScopeSpecializationPattern() != 0; 2163 2164 case TSK_ExplicitInstantiationDeclaration: 2165 // Handled below. 2166 break; 2167 } 2168 2169 // Find the actual template from which we will instantiate. 2170 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 2171 bool HasPattern = false; 2172 if (PatternDecl) 2173 HasPattern = PatternDecl->hasBody(PatternDecl); 2174 2175 // C++0x [temp.explicit]p9: 2176 // Except for inline functions, other explicit instantiation declarations 2177 // have the effect of suppressing the implicit instantiation of the entity 2178 // to which they refer. 2179 if (!HasPattern || !PatternDecl) 2180 return true; 2181 2182 return PatternDecl->isInlined(); 2183 } 2184 2185 bool FunctionDecl::isTemplateInstantiation() const { 2186 switch (getTemplateSpecializationKind()) { 2187 case TSK_Undeclared: 2188 case TSK_ExplicitSpecialization: 2189 return false; 2190 case TSK_ImplicitInstantiation: 2191 case TSK_ExplicitInstantiationDeclaration: 2192 case TSK_ExplicitInstantiationDefinition: 2193 return true; 2194 } 2195 llvm_unreachable("All TSK values handled."); 2196 } 2197 2198 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { 2199 // Handle class scope explicit specialization special case. 2200 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 2201 return getClassScopeSpecializationPattern(); 2202 2203 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 2204 while (Primary->getInstantiatedFromMemberTemplate()) { 2205 // If we have hit a point where the user provided a specialization of 2206 // this template, we're done looking. 2207 if (Primary->isMemberSpecialization()) 2208 break; 2209 2210 Primary = Primary->getInstantiatedFromMemberTemplate(); 2211 } 2212 2213 return Primary->getTemplatedDecl(); 2214 } 2215 2216 return getInstantiatedFromMemberFunction(); 2217 } 2218 2219 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 2220 if (FunctionTemplateSpecializationInfo *Info 2221 = TemplateOrSpecialization 2222 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 2223 return Info->Template.getPointer(); 2224 } 2225 return 0; 2226 } 2227 2228 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const { 2229 return getASTContext().getClassScopeSpecializationPattern(this); 2230 } 2231 2232 const TemplateArgumentList * 2233 FunctionDecl::getTemplateSpecializationArgs() const { 2234 if (FunctionTemplateSpecializationInfo *Info 2235 = TemplateOrSpecialization 2236 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 2237 return Info->TemplateArguments; 2238 } 2239 return 0; 2240 } 2241 2242 const ASTTemplateArgumentListInfo * 2243 FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 2244 if (FunctionTemplateSpecializationInfo *Info 2245 = TemplateOrSpecialization 2246 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 2247 return Info->TemplateArgumentsAsWritten; 2248 } 2249 return 0; 2250 } 2251 2252 void 2253 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 2254 FunctionTemplateDecl *Template, 2255 const TemplateArgumentList *TemplateArgs, 2256 void *InsertPos, 2257 TemplateSpecializationKind TSK, 2258 const TemplateArgumentListInfo *TemplateArgsAsWritten, 2259 SourceLocation PointOfInstantiation) { 2260 assert(TSK != TSK_Undeclared && 2261 "Must specify the type of function template specialization"); 2262 FunctionTemplateSpecializationInfo *Info 2263 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 2264 if (!Info) 2265 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK, 2266 TemplateArgs, 2267 TemplateArgsAsWritten, 2268 PointOfInstantiation); 2269 TemplateOrSpecialization = Info; 2270 Template->addSpecialization(Info, InsertPos); 2271 } 2272 2273 void 2274 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 2275 const UnresolvedSetImpl &Templates, 2276 const TemplateArgumentListInfo &TemplateArgs) { 2277 assert(TemplateOrSpecialization.isNull()); 2278 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo); 2279 Size += Templates.size() * sizeof(FunctionTemplateDecl*); 2280 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc); 2281 void *Buffer = Context.Allocate(Size); 2282 DependentFunctionTemplateSpecializationInfo *Info = 2283 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates, 2284 TemplateArgs); 2285 TemplateOrSpecialization = Info; 2286 } 2287 2288 DependentFunctionTemplateSpecializationInfo:: 2289 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 2290 const TemplateArgumentListInfo &TArgs) 2291 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 2292 2293 d.NumTemplates = Ts.size(); 2294 d.NumArgs = TArgs.size(); 2295 2296 FunctionTemplateDecl **TsArray = 2297 const_cast<FunctionTemplateDecl**>(getTemplates()); 2298 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 2299 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 2300 2301 TemplateArgumentLoc *ArgsArray = 2302 const_cast<TemplateArgumentLoc*>(getTemplateArgs()); 2303 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 2304 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 2305 } 2306 2307 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 2308 // For a function template specialization, query the specialization 2309 // information object. 2310 FunctionTemplateSpecializationInfo *FTSInfo 2311 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 2312 if (FTSInfo) 2313 return FTSInfo->getTemplateSpecializationKind(); 2314 2315 MemberSpecializationInfo *MSInfo 2316 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 2317 if (MSInfo) 2318 return MSInfo->getTemplateSpecializationKind(); 2319 2320 return TSK_Undeclared; 2321 } 2322 2323 void 2324 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2325 SourceLocation PointOfInstantiation) { 2326 if (FunctionTemplateSpecializationInfo *FTSInfo 2327 = TemplateOrSpecialization.dyn_cast< 2328 FunctionTemplateSpecializationInfo*>()) { 2329 FTSInfo->setTemplateSpecializationKind(TSK); 2330 if (TSK != TSK_ExplicitSpecialization && 2331 PointOfInstantiation.isValid() && 2332 FTSInfo->getPointOfInstantiation().isInvalid()) 2333 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 2334 } else if (MemberSpecializationInfo *MSInfo 2335 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 2336 MSInfo->setTemplateSpecializationKind(TSK); 2337 if (TSK != TSK_ExplicitSpecialization && 2338 PointOfInstantiation.isValid() && 2339 MSInfo->getPointOfInstantiation().isInvalid()) 2340 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2341 } else 2342 llvm_unreachable("Function cannot have a template specialization kind"); 2343 } 2344 2345 SourceLocation FunctionDecl::getPointOfInstantiation() const { 2346 if (FunctionTemplateSpecializationInfo *FTSInfo 2347 = TemplateOrSpecialization.dyn_cast< 2348 FunctionTemplateSpecializationInfo*>()) 2349 return FTSInfo->getPointOfInstantiation(); 2350 else if (MemberSpecializationInfo *MSInfo 2351 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) 2352 return MSInfo->getPointOfInstantiation(); 2353 2354 return SourceLocation(); 2355 } 2356 2357 bool FunctionDecl::isOutOfLine() const { 2358 if (Decl::isOutOfLine()) 2359 return true; 2360 2361 // If this function was instantiated from a member function of a 2362 // class template, check whether that member function was defined out-of-line. 2363 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 2364 const FunctionDecl *Definition; 2365 if (FD->hasBody(Definition)) 2366 return Definition->isOutOfLine(); 2367 } 2368 2369 // If this function was instantiated from a function template, 2370 // check whether that function template was defined out-of-line. 2371 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 2372 const FunctionDecl *Definition; 2373 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 2374 return Definition->isOutOfLine(); 2375 } 2376 2377 return false; 2378 } 2379 2380 SourceRange FunctionDecl::getSourceRange() const { 2381 return SourceRange(getOuterLocStart(), EndRangeLoc); 2382 } 2383 2384 unsigned FunctionDecl::getMemoryFunctionKind() const { 2385 IdentifierInfo *FnInfo = getIdentifier(); 2386 2387 if (!FnInfo) 2388 return 0; 2389 2390 // Builtin handling. 2391 switch (getBuiltinID()) { 2392 case Builtin::BI__builtin_memset: 2393 case Builtin::BI__builtin___memset_chk: 2394 case Builtin::BImemset: 2395 return Builtin::BImemset; 2396 2397 case Builtin::BI__builtin_memcpy: 2398 case Builtin::BI__builtin___memcpy_chk: 2399 case Builtin::BImemcpy: 2400 return Builtin::BImemcpy; 2401 2402 case Builtin::BI__builtin_memmove: 2403 case Builtin::BI__builtin___memmove_chk: 2404 case Builtin::BImemmove: 2405 return Builtin::BImemmove; 2406 2407 case Builtin::BIstrlcpy: 2408 return Builtin::BIstrlcpy; 2409 case Builtin::BIstrlcat: 2410 return Builtin::BIstrlcat; 2411 2412 case Builtin::BI__builtin_memcmp: 2413 case Builtin::BImemcmp: 2414 return Builtin::BImemcmp; 2415 2416 case Builtin::BI__builtin_strncpy: 2417 case Builtin::BI__builtin___strncpy_chk: 2418 case Builtin::BIstrncpy: 2419 return Builtin::BIstrncpy; 2420 2421 case Builtin::BI__builtin_strncmp: 2422 case Builtin::BIstrncmp: 2423 return Builtin::BIstrncmp; 2424 2425 case Builtin::BI__builtin_strncasecmp: 2426 case Builtin::BIstrncasecmp: 2427 return Builtin::BIstrncasecmp; 2428 2429 case Builtin::BI__builtin_strncat: 2430 case Builtin::BI__builtin___strncat_chk: 2431 case Builtin::BIstrncat: 2432 return Builtin::BIstrncat; 2433 2434 case Builtin::BI__builtin_strndup: 2435 case Builtin::BIstrndup: 2436 return Builtin::BIstrndup; 2437 2438 case Builtin::BI__builtin_strlen: 2439 case Builtin::BIstrlen: 2440 return Builtin::BIstrlen; 2441 2442 default: 2443 if (hasCLanguageLinkage()) { 2444 if (FnInfo->isStr("memset")) 2445 return Builtin::BImemset; 2446 else if (FnInfo->isStr("memcpy")) 2447 return Builtin::BImemcpy; 2448 else if (FnInfo->isStr("memmove")) 2449 return Builtin::BImemmove; 2450 else if (FnInfo->isStr("memcmp")) 2451 return Builtin::BImemcmp; 2452 else if (FnInfo->isStr("strncpy")) 2453 return Builtin::BIstrncpy; 2454 else if (FnInfo->isStr("strncmp")) 2455 return Builtin::BIstrncmp; 2456 else if (FnInfo->isStr("strncasecmp")) 2457 return Builtin::BIstrncasecmp; 2458 else if (FnInfo->isStr("strncat")) 2459 return Builtin::BIstrncat; 2460 else if (FnInfo->isStr("strndup")) 2461 return Builtin::BIstrndup; 2462 else if (FnInfo->isStr("strlen")) 2463 return Builtin::BIstrlen; 2464 } 2465 break; 2466 } 2467 return 0; 2468 } 2469 2470 //===----------------------------------------------------------------------===// 2471 // FieldDecl Implementation 2472 //===----------------------------------------------------------------------===// 2473 2474 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 2475 SourceLocation StartLoc, SourceLocation IdLoc, 2476 IdentifierInfo *Id, QualType T, 2477 TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 2478 InClassInitStyle InitStyle) { 2479 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, 2480 BW, Mutable, InitStyle); 2481 } 2482 2483 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2484 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl)); 2485 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(), 2486 0, QualType(), 0, 0, false, ICIS_NoInit); 2487 } 2488 2489 bool FieldDecl::isAnonymousStructOrUnion() const { 2490 if (!isImplicit() || getDeclName()) 2491 return false; 2492 2493 if (const RecordType *Record = getType()->getAs<RecordType>()) 2494 return Record->getDecl()->isAnonymousStructOrUnion(); 2495 2496 return false; 2497 } 2498 2499 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const { 2500 assert(isBitField() && "not a bitfield"); 2501 Expr *BitWidth = InitializerOrBitWidth.getPointer(); 2502 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue(); 2503 } 2504 2505 unsigned FieldDecl::getFieldIndex() const { 2506 if (CachedFieldIndex) return CachedFieldIndex - 1; 2507 2508 unsigned Index = 0; 2509 const RecordDecl *RD = getParent(); 2510 const FieldDecl *LastFD = 0; 2511 bool IsMsStruct = RD->isMsStruct(getASTContext()); 2512 2513 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 2514 I != E; ++I, ++Index) { 2515 I->CachedFieldIndex = Index + 1; 2516 2517 if (IsMsStruct) { 2518 // Zero-length bitfields following non-bitfield members are ignored. 2519 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) { 2520 --Index; 2521 continue; 2522 } 2523 LastFD = *I; 2524 } 2525 } 2526 2527 assert(CachedFieldIndex && "failed to find field in parent"); 2528 return CachedFieldIndex - 1; 2529 } 2530 2531 SourceRange FieldDecl::getSourceRange() const { 2532 if (const Expr *E = InitializerOrBitWidth.getPointer()) 2533 return SourceRange(getInnerLocStart(), E->getLocEnd()); 2534 return DeclaratorDecl::getSourceRange(); 2535 } 2536 2537 void FieldDecl::setBitWidth(Expr *Width) { 2538 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() && 2539 "bit width or initializer already set"); 2540 InitializerOrBitWidth.setPointer(Width); 2541 } 2542 2543 void FieldDecl::setInClassInitializer(Expr *Init) { 2544 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() && 2545 "bit width or initializer already set"); 2546 InitializerOrBitWidth.setPointer(Init); 2547 } 2548 2549 //===----------------------------------------------------------------------===// 2550 // TagDecl Implementation 2551 //===----------------------------------------------------------------------===// 2552 2553 SourceLocation TagDecl::getOuterLocStart() const { 2554 return getTemplateOrInnerLocStart(this); 2555 } 2556 2557 SourceRange TagDecl::getSourceRange() const { 2558 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 2559 return SourceRange(getOuterLocStart(), E); 2560 } 2561 2562 TagDecl* TagDecl::getCanonicalDecl() { 2563 return getFirstDeclaration(); 2564 } 2565 2566 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { 2567 TypedefNameDeclOrQualifier = TDD; 2568 if (TypeForDecl) 2569 const_cast<Type*>(TypeForDecl)->ClearLVCache(); 2570 ClearLVCache(); 2571 } 2572 2573 void TagDecl::startDefinition() { 2574 IsBeingDefined = true; 2575 2576 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) { 2577 struct CXXRecordDecl::DefinitionData *Data = 2578 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 2579 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) 2580 cast<CXXRecordDecl>(*I)->DefinitionData = Data; 2581 } 2582 } 2583 2584 void TagDecl::completeDefinition() { 2585 assert((!isa<CXXRecordDecl>(this) || 2586 cast<CXXRecordDecl>(this)->hasDefinition()) && 2587 "definition completed but not started"); 2588 2589 IsCompleteDefinition = true; 2590 IsBeingDefined = false; 2591 2592 if (ASTMutationListener *L = getASTMutationListener()) 2593 L->CompletedTagDefinition(this); 2594 } 2595 2596 TagDecl *TagDecl::getDefinition() const { 2597 if (isCompleteDefinition()) 2598 return const_cast<TagDecl *>(this); 2599 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this)) 2600 return CXXRD->getDefinition(); 2601 2602 for (redecl_iterator R = redecls_begin(), REnd = redecls_end(); 2603 R != REnd; ++R) 2604 if (R->isCompleteDefinition()) 2605 return *R; 2606 2607 return 0; 2608 } 2609 2610 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 2611 if (QualifierLoc) { 2612 // Make sure the extended qualifier info is allocated. 2613 if (!hasExtInfo()) 2614 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 2615 // Set qualifier info. 2616 getExtInfo()->QualifierLoc = QualifierLoc; 2617 } else { 2618 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 2619 if (hasExtInfo()) { 2620 if (getExtInfo()->NumTemplParamLists == 0) { 2621 getASTContext().Deallocate(getExtInfo()); 2622 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0; 2623 } 2624 else 2625 getExtInfo()->QualifierLoc = QualifierLoc; 2626 } 2627 } 2628 } 2629 2630 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context, 2631 unsigned NumTPLists, 2632 TemplateParameterList **TPLists) { 2633 assert(NumTPLists > 0); 2634 // Make sure the extended decl info is allocated. 2635 if (!hasExtInfo()) 2636 // Allocate external info struct. 2637 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 2638 // Set the template parameter lists info. 2639 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists); 2640 } 2641 2642 //===----------------------------------------------------------------------===// 2643 // EnumDecl Implementation 2644 //===----------------------------------------------------------------------===// 2645 2646 void EnumDecl::anchor() { } 2647 2648 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, 2649 SourceLocation StartLoc, SourceLocation IdLoc, 2650 IdentifierInfo *Id, 2651 EnumDecl *PrevDecl, bool IsScoped, 2652 bool IsScopedUsingClassTag, bool IsFixed) { 2653 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl, 2654 IsScoped, IsScopedUsingClassTag, IsFixed); 2655 C.getTypeDeclType(Enum, PrevDecl); 2656 return Enum; 2657 } 2658 2659 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2660 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl)); 2661 return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0, 2662 false, false, false); 2663 } 2664 2665 void EnumDecl::completeDefinition(QualType NewType, 2666 QualType NewPromotionType, 2667 unsigned NumPositiveBits, 2668 unsigned NumNegativeBits) { 2669 assert(!isCompleteDefinition() && "Cannot redefine enums!"); 2670 if (!IntegerType) 2671 IntegerType = NewType.getTypePtr(); 2672 PromotionType = NewPromotionType; 2673 setNumPositiveBits(NumPositiveBits); 2674 setNumNegativeBits(NumNegativeBits); 2675 TagDecl::completeDefinition(); 2676 } 2677 2678 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const { 2679 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2680 return MSI->getTemplateSpecializationKind(); 2681 2682 return TSK_Undeclared; 2683 } 2684 2685 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2686 SourceLocation PointOfInstantiation) { 2687 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 2688 assert(MSI && "Not an instantiated member enumeration?"); 2689 MSI->setTemplateSpecializationKind(TSK); 2690 if (TSK != TSK_ExplicitSpecialization && 2691 PointOfInstantiation.isValid() && 2692 MSI->getPointOfInstantiation().isInvalid()) 2693 MSI->setPointOfInstantiation(PointOfInstantiation); 2694 } 2695 2696 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const { 2697 if (SpecializationInfo) 2698 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom()); 2699 2700 return 0; 2701 } 2702 2703 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, 2704 TemplateSpecializationKind TSK) { 2705 assert(!SpecializationInfo && "Member enum is already a specialization"); 2706 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK); 2707 } 2708 2709 //===----------------------------------------------------------------------===// 2710 // RecordDecl Implementation 2711 //===----------------------------------------------------------------------===// 2712 2713 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, 2714 SourceLocation StartLoc, SourceLocation IdLoc, 2715 IdentifierInfo *Id, RecordDecl *PrevDecl) 2716 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) { 2717 HasFlexibleArrayMember = false; 2718 AnonymousStructOrUnion = false; 2719 HasObjectMember = false; 2720 LoadedFieldsFromExternalStorage = false; 2721 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); 2722 } 2723 2724 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 2725 SourceLocation StartLoc, SourceLocation IdLoc, 2726 IdentifierInfo *Id, RecordDecl* PrevDecl) { 2727 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id, 2728 PrevDecl); 2729 C.getTypeDeclType(R, PrevDecl); 2730 return R; 2731 } 2732 2733 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { 2734 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl)); 2735 return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(), 2736 SourceLocation(), 0, 0); 2737 } 2738 2739 bool RecordDecl::isInjectedClassName() const { 2740 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 2741 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 2742 } 2743 2744 RecordDecl::field_iterator RecordDecl::field_begin() const { 2745 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage) 2746 LoadFieldsFromExternalStorage(); 2747 2748 return field_iterator(decl_iterator(FirstDecl)); 2749 } 2750 2751 /// completeDefinition - Notes that the definition of this type is now 2752 /// complete. 2753 void RecordDecl::completeDefinition() { 2754 assert(!isCompleteDefinition() && "Cannot redefine record!"); 2755 TagDecl::completeDefinition(); 2756 } 2757 2758 /// isMsStruct - Get whether or not this record uses ms_struct layout. 2759 /// This which can be turned on with an attribute, pragma, or the 2760 /// -mms-bitfields command-line option. 2761 bool RecordDecl::isMsStruct(const ASTContext &C) const { 2762 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1; 2763 } 2764 2765 static bool isFieldOrIndirectField(Decl::Kind K) { 2766 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); 2767 } 2768 2769 void RecordDecl::LoadFieldsFromExternalStorage() const { 2770 ExternalASTSource *Source = getASTContext().getExternalSource(); 2771 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 2772 2773 // Notify that we have a RecordDecl doing some initialization. 2774 ExternalASTSource::Deserializing TheFields(Source); 2775 2776 SmallVector<Decl*, 64> Decls; 2777 LoadedFieldsFromExternalStorage = true; 2778 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField, 2779 Decls)) { 2780 case ELR_Success: 2781 break; 2782 2783 case ELR_AlreadyLoaded: 2784 case ELR_Failure: 2785 return; 2786 } 2787 2788 #ifndef NDEBUG 2789 // Check that all decls we got were FieldDecls. 2790 for (unsigned i=0, e=Decls.size(); i != e; ++i) 2791 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])); 2792 #endif 2793 2794 if (Decls.empty()) 2795 return; 2796 2797 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls, 2798 /*FieldsAlreadyLoaded=*/false); 2799 } 2800 2801 //===----------------------------------------------------------------------===// 2802 // BlockDecl Implementation 2803 //===----------------------------------------------------------------------===// 2804 2805 void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) { 2806 assert(ParamInfo == 0 && "Already has param info!"); 2807 2808 // Zero params -> null pointer. 2809 if (!NewParamInfo.empty()) { 2810 NumParams = NewParamInfo.size(); 2811 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; 2812 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 2813 } 2814 } 2815 2816 void BlockDecl::setCaptures(ASTContext &Context, 2817 const Capture *begin, 2818 const Capture *end, 2819 bool capturesCXXThis) { 2820 CapturesCXXThis = capturesCXXThis; 2821 2822 if (begin == end) { 2823 NumCaptures = 0; 2824 Captures = 0; 2825 return; 2826 } 2827 2828 NumCaptures = end - begin; 2829 2830 // Avoid new Capture[] because we don't want to provide a default 2831 // constructor. 2832 size_t allocationSize = NumCaptures * sizeof(Capture); 2833 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*)); 2834 memcpy(buffer, begin, allocationSize); 2835 Captures = static_cast<Capture*>(buffer); 2836 } 2837 2838 bool BlockDecl::capturesVariable(const VarDecl *variable) const { 2839 for (capture_const_iterator 2840 i = capture_begin(), e = capture_end(); i != e; ++i) 2841 // Only auto vars can be captured, so no redeclaration worries. 2842 if (i->getVariable() == variable) 2843 return true; 2844 2845 return false; 2846 } 2847 2848 SourceRange BlockDecl::getSourceRange() const { 2849 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation()); 2850 } 2851 2852 //===----------------------------------------------------------------------===// 2853 // Other Decl Allocation/Deallocation Method Implementations 2854 //===----------------------------------------------------------------------===// 2855 2856 void TranslationUnitDecl::anchor() { } 2857 2858 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 2859 return new (C) TranslationUnitDecl(C); 2860 } 2861 2862 void LabelDecl::anchor() { } 2863 2864 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 2865 SourceLocation IdentL, IdentifierInfo *II) { 2866 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL); 2867 } 2868 2869 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 2870 SourceLocation IdentL, IdentifierInfo *II, 2871 SourceLocation GnuLabelL) { 2872 assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); 2873 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL); 2874 } 2875 2876 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2877 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl)); 2878 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation()); 2879 } 2880 2881 void ValueDecl::anchor() { } 2882 2883 bool ValueDecl::isWeak() const { 2884 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I) 2885 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I)) 2886 return true; 2887 2888 return isWeakImported(); 2889 } 2890 2891 void ImplicitParamDecl::anchor() { } 2892 2893 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 2894 SourceLocation IdLoc, 2895 IdentifierInfo *Id, 2896 QualType Type) { 2897 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type); 2898 } 2899 2900 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, 2901 unsigned ID) { 2902 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl)); 2903 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType()); 2904 } 2905 2906 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, 2907 SourceLocation StartLoc, 2908 const DeclarationNameInfo &NameInfo, 2909 QualType T, TypeSourceInfo *TInfo, 2910 StorageClass SC, StorageClass SCAsWritten, 2911 bool isInlineSpecified, 2912 bool hasWrittenPrototype, 2913 bool isConstexprSpecified) { 2914 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo, 2915 T, TInfo, SC, SCAsWritten, 2916 isInlineSpecified, 2917 isConstexprSpecified); 2918 New->HasWrittenPrototype = hasWrittenPrototype; 2919 return New; 2920 } 2921 2922 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2923 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl)); 2924 return new (Mem) FunctionDecl(Function, 0, SourceLocation(), 2925 DeclarationNameInfo(), QualType(), 0, 2926 SC_None, SC_None, false, false); 2927 } 2928 2929 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 2930 return new (C) BlockDecl(DC, L); 2931 } 2932 2933 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2934 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl)); 2935 return new (Mem) BlockDecl(0, SourceLocation()); 2936 } 2937 2938 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 2939 SourceLocation L, 2940 IdentifierInfo *Id, QualType T, 2941 Expr *E, const llvm::APSInt &V) { 2942 return new (C) EnumConstantDecl(CD, L, Id, T, E, V); 2943 } 2944 2945 EnumConstantDecl * 2946 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2947 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl)); 2948 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0, 2949 llvm::APSInt()); 2950 } 2951 2952 void IndirectFieldDecl::anchor() { } 2953 2954 IndirectFieldDecl * 2955 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 2956 IdentifierInfo *Id, QualType T, NamedDecl **CH, 2957 unsigned CHS) { 2958 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS); 2959 } 2960 2961 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C, 2962 unsigned ID) { 2963 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl)); 2964 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(), 2965 QualType(), 0, 0); 2966 } 2967 2968 SourceRange EnumConstantDecl::getSourceRange() const { 2969 SourceLocation End = getLocation(); 2970 if (Init) 2971 End = Init->getLocEnd(); 2972 return SourceRange(getLocation(), End); 2973 } 2974 2975 void TypeDecl::anchor() { } 2976 2977 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 2978 SourceLocation StartLoc, SourceLocation IdLoc, 2979 IdentifierInfo *Id, TypeSourceInfo *TInfo) { 2980 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo); 2981 } 2982 2983 void TypedefNameDecl::anchor() { } 2984 2985 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2986 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl)); 2987 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0); 2988 } 2989 2990 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC, 2991 SourceLocation StartLoc, 2992 SourceLocation IdLoc, IdentifierInfo *Id, 2993 TypeSourceInfo *TInfo) { 2994 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo); 2995 } 2996 2997 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2998 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl)); 2999 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0); 3000 } 3001 3002 SourceRange TypedefDecl::getSourceRange() const { 3003 SourceLocation RangeEnd = getLocation(); 3004 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 3005 if (typeIsPostfix(TInfo->getType())) 3006 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 3007 } 3008 return SourceRange(getLocStart(), RangeEnd); 3009 } 3010 3011 SourceRange TypeAliasDecl::getSourceRange() const { 3012 SourceLocation RangeEnd = getLocStart(); 3013 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) 3014 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 3015 return SourceRange(getLocStart(), RangeEnd); 3016 } 3017 3018 void FileScopeAsmDecl::anchor() { } 3019 3020 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 3021 StringLiteral *Str, 3022 SourceLocation AsmLoc, 3023 SourceLocation RParenLoc) { 3024 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); 3025 } 3026 3027 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, 3028 unsigned ID) { 3029 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl)); 3030 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation()); 3031 } 3032 3033 //===----------------------------------------------------------------------===// 3034 // ImportDecl Implementation 3035 //===----------------------------------------------------------------------===// 3036 3037 /// \brief Retrieve the number of module identifiers needed to name the given 3038 /// module. 3039 static unsigned getNumModuleIdentifiers(Module *Mod) { 3040 unsigned Result = 1; 3041 while (Mod->Parent) { 3042 Mod = Mod->Parent; 3043 ++Result; 3044 } 3045 return Result; 3046 } 3047 3048 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 3049 Module *Imported, 3050 ArrayRef<SourceLocation> IdentifierLocs) 3051 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true), 3052 NextLocalImport() 3053 { 3054 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size()); 3055 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1); 3056 memcpy(StoredLocs, IdentifierLocs.data(), 3057 IdentifierLocs.size() * sizeof(SourceLocation)); 3058 } 3059 3060 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 3061 Module *Imported, SourceLocation EndLoc) 3062 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false), 3063 NextLocalImport() 3064 { 3065 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc; 3066 } 3067 3068 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, 3069 SourceLocation StartLoc, Module *Imported, 3070 ArrayRef<SourceLocation> IdentifierLocs) { 3071 void *Mem = C.Allocate(sizeof(ImportDecl) + 3072 IdentifierLocs.size() * sizeof(SourceLocation)); 3073 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs); 3074 } 3075 3076 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, 3077 SourceLocation StartLoc, 3078 Module *Imported, 3079 SourceLocation EndLoc) { 3080 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation)); 3081 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc); 3082 Import->setImplicit(); 3083 return Import; 3084 } 3085 3086 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID, 3087 unsigned NumLocations) { 3088 void *Mem = AllocateDeserializedDecl(C, ID, 3089 (sizeof(ImportDecl) + 3090 NumLocations * sizeof(SourceLocation))); 3091 return new (Mem) ImportDecl(EmptyShell()); 3092 } 3093 3094 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const { 3095 if (!ImportedAndComplete.getInt()) 3096 return ArrayRef<SourceLocation>(); 3097 3098 const SourceLocation *StoredLocs 3099 = reinterpret_cast<const SourceLocation *>(this + 1); 3100 return ArrayRef<SourceLocation>(StoredLocs, 3101 getNumModuleIdentifiers(getImportedModule())); 3102 } 3103 3104 SourceRange ImportDecl::getSourceRange() const { 3105 if (!ImportedAndComplete.getInt()) 3106 return SourceRange(getLocation(), 3107 *reinterpret_cast<const SourceLocation *>(this + 1)); 3108 3109 return SourceRange(getLocation(), getIdentifierLocs().back()); 3110 } 3111