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