1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===// 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 ASTContext interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTContext.h" 15 #include "CXXABI.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Comment.h" 20 #include "clang/AST/CommentCommandTraits.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExternalASTSource.h" 27 #include "clang/AST/Mangle.h" 28 #include "clang/AST/MangleNumberingContext.h" 29 #include "clang/AST/RecordLayout.h" 30 #include "clang/AST/RecursiveASTVisitor.h" 31 #include "clang/AST/TypeLoc.h" 32 #include "clang/AST/VTableBuilder.h" 33 #include "clang/Basic/Builtins.h" 34 #include "clang/Basic/SourceManager.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "llvm/ADT/SmallString.h" 37 #include "llvm/ADT/StringExtras.h" 38 #include "llvm/ADT/Triple.h" 39 #include "llvm/Support/Capacity.h" 40 #include "llvm/Support/MathExtras.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <map> 43 44 using namespace clang; 45 46 unsigned ASTContext::NumImplicitDefaultConstructors; 47 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared; 48 unsigned ASTContext::NumImplicitCopyConstructors; 49 unsigned ASTContext::NumImplicitCopyConstructorsDeclared; 50 unsigned ASTContext::NumImplicitMoveConstructors; 51 unsigned ASTContext::NumImplicitMoveConstructorsDeclared; 52 unsigned ASTContext::NumImplicitCopyAssignmentOperators; 53 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 54 unsigned ASTContext::NumImplicitMoveAssignmentOperators; 55 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 56 unsigned ASTContext::NumImplicitDestructors; 57 unsigned ASTContext::NumImplicitDestructorsDeclared; 58 59 enum FloatingRank { 60 HalfRank, FloatRank, DoubleRank, LongDoubleRank 61 }; 62 63 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 64 if (!CommentsLoaded && ExternalSource) { 65 ExternalSource->ReadComments(); 66 67 #ifndef NDEBUG 68 ArrayRef<RawComment *> RawComments = Comments.getComments(); 69 assert(std::is_sorted(RawComments.begin(), RawComments.end(), 70 BeforeThanCompare<RawComment>(SourceMgr))); 71 #endif 72 73 CommentsLoaded = true; 74 } 75 76 assert(D); 77 78 // User can not attach documentation to implicit declarations. 79 if (D->isImplicit()) 80 return nullptr; 81 82 // User can not attach documentation to implicit instantiations. 83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 85 return nullptr; 86 } 87 88 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 89 if (VD->isStaticDataMember() && 90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 91 return nullptr; 92 } 93 94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) { 95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 96 return nullptr; 97 } 98 99 if (const ClassTemplateSpecializationDecl *CTSD = 100 dyn_cast<ClassTemplateSpecializationDecl>(D)) { 101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 102 if (TSK == TSK_ImplicitInstantiation || 103 TSK == TSK_Undeclared) 104 return nullptr; 105 } 106 107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 109 return nullptr; 110 } 111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) { 112 // When tag declaration (but not definition!) is part of the 113 // decl-specifier-seq of some other declaration, it doesn't get comment 114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 115 return nullptr; 116 } 117 // TODO: handle comments for function parameters properly. 118 if (isa<ParmVarDecl>(D)) 119 return nullptr; 120 121 // TODO: we could look up template parameter documentation in the template 122 // documentation. 123 if (isa<TemplateTypeParmDecl>(D) || 124 isa<NonTypeTemplateParmDecl>(D) || 125 isa<TemplateTemplateParmDecl>(D)) 126 return nullptr; 127 128 ArrayRef<RawComment *> RawComments = Comments.getComments(); 129 130 // If there are no comments anywhere, we won't find anything. 131 if (RawComments.empty()) 132 return nullptr; 133 134 // Find declaration location. 135 // For Objective-C declarations we generally don't expect to have multiple 136 // declarators, thus use declaration starting location as the "declaration 137 // location". 138 // For all other declarations multiple declarators are used quite frequently, 139 // so we use the location of the identifier as the "declaration location". 140 SourceLocation DeclLoc; 141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 142 isa<ObjCPropertyDecl>(D) || 143 isa<RedeclarableTemplateDecl>(D) || 144 isa<ClassTemplateSpecializationDecl>(D)) 145 DeclLoc = D->getLocStart(); 146 else { 147 DeclLoc = D->getLocation(); 148 if (DeclLoc.isMacroID()) { 149 if (isa<TypedefDecl>(D)) { 150 // If location of the typedef name is in a macro, it is because being 151 // declared via a macro. Try using declaration's starting location as 152 // the "declaration location". 153 DeclLoc = D->getLocStart(); 154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) { 155 // If location of the tag decl is inside a macro, but the spelling of 156 // the tag name comes from a macro argument, it looks like a special 157 // macro like NS_ENUM is being used to define the tag decl. In that 158 // case, adjust the source location to the expansion loc so that we can 159 // attach the comment to the tag decl. 160 if (SourceMgr.isMacroArgExpansion(DeclLoc) && 161 TD->isCompleteDefinition()) 162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc); 163 } 164 } 165 } 166 167 // If the declaration doesn't map directly to a location in a file, we 168 // can't find the comment. 169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 170 return nullptr; 171 172 // Find the comment that occurs just after this declaration. 173 ArrayRef<RawComment *>::iterator Comment; 174 { 175 // When searching for comments during parsing, the comment we are looking 176 // for is usually among the last two comments we parsed -- check them 177 // first. 178 RawComment CommentAtDeclLoc( 179 SourceMgr, SourceRange(DeclLoc), false, 180 LangOpts.CommentOpts.ParseAllComments); 181 BeforeThanCompare<RawComment> Compare(SourceMgr); 182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1; 183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 184 if (!Found && RawComments.size() >= 2) { 185 MaybeBeforeDecl--; 186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 187 } 188 189 if (Found) { 190 Comment = MaybeBeforeDecl + 1; 191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(), 192 &CommentAtDeclLoc, Compare)); 193 } else { 194 // Slow path. 195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(), 196 &CommentAtDeclLoc, Compare); 197 } 198 } 199 200 // Decompose the location for the declaration and find the beginning of the 201 // file buffer. 202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc); 203 204 // First check whether we have a trailing comment. 205 if (Comment != RawComments.end() && 206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() && 207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 209 std::pair<FileID, unsigned> CommentBeginDecomp 210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin()); 211 // Check that Doxygen trailing comment comes after the declaration, starts 212 // on the same line and in the same file as the declaration. 213 if (DeclLocDecomp.first == CommentBeginDecomp.first && 214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) 215 == SourceMgr.getLineNumber(CommentBeginDecomp.first, 216 CommentBeginDecomp.second)) { 217 return *Comment; 218 } 219 } 220 221 // The comment just after the declaration was not a trailing comment. 222 // Let's look at the previous comment. 223 if (Comment == RawComments.begin()) 224 return nullptr; 225 --Comment; 226 227 // Check that we actually have a non-member Doxygen comment. 228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment()) 229 return nullptr; 230 231 // Decompose the end of the comment. 232 std::pair<FileID, unsigned> CommentEndDecomp 233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd()); 234 235 // If the comment and the declaration aren't in the same file, then they 236 // aren't related. 237 if (DeclLocDecomp.first != CommentEndDecomp.first) 238 return nullptr; 239 240 // Get the corresponding buffer. 241 bool Invalid = false; 242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 243 &Invalid).data(); 244 if (Invalid) 245 return nullptr; 246 247 // Extract text between the comment and declaration. 248 StringRef Text(Buffer + CommentEndDecomp.second, 249 DeclLocDecomp.second - CommentEndDecomp.second); 250 251 // There should be no other declarations or preprocessor directives between 252 // comment and declaration. 253 if (Text.find_first_of(";{}#@") != StringRef::npos) 254 return nullptr; 255 256 return *Comment; 257 } 258 259 namespace { 260 /// If we have a 'templated' declaration for a template, adjust 'D' to 261 /// refer to the actual template. 262 /// If we have an implicit instantiation, adjust 'D' to refer to template. 263 const Decl *adjustDeclToTemplate(const Decl *D) { 264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 265 // Is this function declaration part of a function template? 266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 267 return FTD; 268 269 // Nothing to do if function is not an implicit instantiation. 270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 271 return D; 272 273 // Function is an implicit instantiation of a function template? 274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 275 return FTD; 276 277 // Function is instantiated from a member definition of a class template? 278 if (const FunctionDecl *MemberDecl = 279 FD->getInstantiatedFromMemberFunction()) 280 return MemberDecl; 281 282 return D; 283 } 284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 285 // Static data member is instantiated from a member definition of a class 286 // template? 287 if (VD->isStaticDataMember()) 288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 289 return MemberDecl; 290 291 return D; 292 } 293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) { 294 // Is this class declaration part of a class template? 295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 296 return CTD; 297 298 // Class is an implicit instantiation of a class template or partial 299 // specialization? 300 if (const ClassTemplateSpecializationDecl *CTSD = 301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 303 return D; 304 llvm::PointerUnion<ClassTemplateDecl *, 305 ClassTemplatePartialSpecializationDecl *> 306 PU = CTSD->getSpecializedTemplateOrPartial(); 307 return PU.is<ClassTemplateDecl*>() ? 308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) : 309 static_cast<const Decl*>( 310 PU.get<ClassTemplatePartialSpecializationDecl *>()); 311 } 312 313 // Class is instantiated from a member definition of a class template? 314 if (const MemberSpecializationInfo *Info = 315 CRD->getMemberSpecializationInfo()) 316 return Info->getInstantiatedFrom(); 317 318 return D; 319 } 320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 321 // Enum is instantiated from a member definition of a class template? 322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 323 return MemberDecl; 324 325 return D; 326 } 327 // FIXME: Adjust alias templates? 328 return D; 329 } 330 } // unnamed namespace 331 332 const RawComment *ASTContext::getRawCommentForAnyRedecl( 333 const Decl *D, 334 const Decl **OriginalDecl) const { 335 D = adjustDeclToTemplate(D); 336 337 // Check whether we have cached a comment for this declaration already. 338 { 339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 340 RedeclComments.find(D); 341 if (Pos != RedeclComments.end()) { 342 const RawCommentAndCacheFlags &Raw = Pos->second; 343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 344 if (OriginalDecl) 345 *OriginalDecl = Raw.getOriginalDecl(); 346 return Raw.getRaw(); 347 } 348 } 349 } 350 351 // Search for comments attached to declarations in the redeclaration chain. 352 const RawComment *RC = nullptr; 353 const Decl *OriginalDeclForRC = nullptr; 354 for (auto I : D->redecls()) { 355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 356 RedeclComments.find(I); 357 if (Pos != RedeclComments.end()) { 358 const RawCommentAndCacheFlags &Raw = Pos->second; 359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 360 RC = Raw.getRaw(); 361 OriginalDeclForRC = Raw.getOriginalDecl(); 362 break; 363 } 364 } else { 365 RC = getRawCommentForDeclNoCache(I); 366 OriginalDeclForRC = I; 367 RawCommentAndCacheFlags Raw; 368 if (RC) { 369 Raw.setRaw(RC); 370 Raw.setKind(RawCommentAndCacheFlags::FromDecl); 371 } else 372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl); 373 Raw.setOriginalDecl(I); 374 RedeclComments[I] = Raw; 375 if (RC) 376 break; 377 } 378 } 379 380 // If we found a comment, it should be a documentation comment. 381 assert(!RC || RC->isDocumentation()); 382 383 if (OriginalDecl) 384 *OriginalDecl = OriginalDeclForRC; 385 386 // Update cache for every declaration in the redeclaration chain. 387 RawCommentAndCacheFlags Raw; 388 Raw.setRaw(RC); 389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl); 390 Raw.setOriginalDecl(OriginalDeclForRC); 391 392 for (auto I : D->redecls()) { 393 RawCommentAndCacheFlags &R = RedeclComments[I]; 394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl) 395 R = Raw; 396 } 397 398 return RC; 399 } 400 401 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 402 SmallVectorImpl<const NamedDecl *> &Redeclared) { 403 const DeclContext *DC = ObjCMethod->getDeclContext(); 404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) { 405 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 406 if (!ID) 407 return; 408 // Add redeclared method here. 409 for (const auto *Ext : ID->known_extensions()) { 410 if (ObjCMethodDecl *RedeclaredMethod = 411 Ext->getMethod(ObjCMethod->getSelector(), 412 ObjCMethod->isInstanceMethod())) 413 Redeclared.push_back(RedeclaredMethod); 414 } 415 } 416 } 417 418 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 419 const Decl *D) const { 420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo; 421 ThisDeclInfo->CommentDecl = D; 422 ThisDeclInfo->IsFilled = false; 423 ThisDeclInfo->fill(); 424 ThisDeclInfo->CommentDecl = FC->getDecl(); 425 if (!ThisDeclInfo->TemplateParameters) 426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 427 comments::FullComment *CFC = 428 new (*this) comments::FullComment(FC->getBlocks(), 429 ThisDeclInfo); 430 return CFC; 431 432 } 433 434 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 435 const RawComment *RC = getRawCommentForDeclNoCache(D); 436 return RC ? RC->parse(*this, nullptr, D) : nullptr; 437 } 438 439 comments::FullComment *ASTContext::getCommentForDecl( 440 const Decl *D, 441 const Preprocessor *PP) const { 442 if (D->isInvalidDecl()) 443 return nullptr; 444 D = adjustDeclToTemplate(D); 445 446 const Decl *Canonical = D->getCanonicalDecl(); 447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 448 ParsedComments.find(Canonical); 449 450 if (Pos != ParsedComments.end()) { 451 if (Canonical != D) { 452 comments::FullComment *FC = Pos->second; 453 comments::FullComment *CFC = cloneFullComment(FC, D); 454 return CFC; 455 } 456 return Pos->second; 457 } 458 459 const Decl *OriginalDecl; 460 461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 462 if (!RC) { 463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 464 SmallVector<const NamedDecl*, 8> Overridden; 465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D); 466 if (OMD && OMD->isPropertyAccessor()) 467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 469 return cloneFullComment(FC, D); 470 if (OMD) 471 addRedeclaredMethods(OMD, Overridden); 472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 473 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 475 return cloneFullComment(FC, D); 476 } 477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 478 // Attach any tag type's documentation to its typedef if latter 479 // does not have one of its own. 480 QualType QT = TD->getUnderlyingType(); 481 if (const TagType *TT = QT->getAs<TagType>()) 482 if (const Decl *TD = TT->getDecl()) 483 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 484 return cloneFullComment(FC, D); 485 } 486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 487 while (IC->getSuperClass()) { 488 IC = IC->getSuperClass(); 489 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 490 return cloneFullComment(FC, D); 491 } 492 } 493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) { 494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 495 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 496 return cloneFullComment(FC, D); 497 } 498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 499 if (!(RD = RD->getDefinition())) 500 return nullptr; 501 // Check non-virtual bases. 502 for (const auto &I : RD->bases()) { 503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 504 continue; 505 QualType Ty = I.getType(); 506 if (Ty.isNull()) 507 continue; 508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 509 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 510 continue; 511 512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 513 return cloneFullComment(FC, D); 514 } 515 } 516 // Check virtual bases. 517 for (const auto &I : RD->vbases()) { 518 if (I.getAccessSpecifier() != AS_public) 519 continue; 520 QualType Ty = I.getType(); 521 if (Ty.isNull()) 522 continue; 523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 524 if (!(VirtualBase= VirtualBase->getDefinition())) 525 continue; 526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 527 return cloneFullComment(FC, D); 528 } 529 } 530 } 531 return nullptr; 532 } 533 534 // If the RawComment was attached to other redeclaration of this Decl, we 535 // should parse the comment in context of that other Decl. This is important 536 // because comments can contain references to parameter names which can be 537 // different across redeclarations. 538 if (D != OriginalDecl) 539 return getCommentForDecl(OriginalDecl, PP); 540 541 comments::FullComment *FC = RC->parse(*this, PP, D); 542 ParsedComments[Canonical] = FC; 543 return FC; 544 } 545 546 void 547 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 548 TemplateTemplateParmDecl *Parm) { 549 ID.AddInteger(Parm->getDepth()); 550 ID.AddInteger(Parm->getPosition()); 551 ID.AddBoolean(Parm->isParameterPack()); 552 553 TemplateParameterList *Params = Parm->getTemplateParameters(); 554 ID.AddInteger(Params->size()); 555 for (TemplateParameterList::const_iterator P = Params->begin(), 556 PEnd = Params->end(); 557 P != PEnd; ++P) { 558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 559 ID.AddInteger(0); 560 ID.AddBoolean(TTP->isParameterPack()); 561 continue; 562 } 563 564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 565 ID.AddInteger(1); 566 ID.AddBoolean(NTTP->isParameterPack()); 567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 568 if (NTTP->isExpandedParameterPack()) { 569 ID.AddBoolean(true); 570 ID.AddInteger(NTTP->getNumExpansionTypes()); 571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 572 QualType T = NTTP->getExpansionType(I); 573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 574 } 575 } else 576 ID.AddBoolean(false); 577 continue; 578 } 579 580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 581 ID.AddInteger(2); 582 Profile(ID, TTP); 583 } 584 } 585 586 TemplateTemplateParmDecl * 587 ASTContext::getCanonicalTemplateTemplateParmDecl( 588 TemplateTemplateParmDecl *TTP) const { 589 // Check if we already have a canonical template template parameter. 590 llvm::FoldingSetNodeID ID; 591 CanonicalTemplateTemplateParm::Profile(ID, TTP); 592 void *InsertPos = nullptr; 593 CanonicalTemplateTemplateParm *Canonical 594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 595 if (Canonical) 596 return Canonical->getParam(); 597 598 // Build a canonical template parameter list. 599 TemplateParameterList *Params = TTP->getTemplateParameters(); 600 SmallVector<NamedDecl *, 4> CanonParams; 601 CanonParams.reserve(Params->size()); 602 for (TemplateParameterList::const_iterator P = Params->begin(), 603 PEnd = Params->end(); 604 P != PEnd; ++P) { 605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 606 CanonParams.push_back( 607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 608 SourceLocation(), 609 SourceLocation(), 610 TTP->getDepth(), 611 TTP->getIndex(), nullptr, false, 612 TTP->isParameterPack())); 613 else if (NonTypeTemplateParmDecl *NTTP 614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 615 QualType T = getCanonicalType(NTTP->getType()); 616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 617 NonTypeTemplateParmDecl *Param; 618 if (NTTP->isExpandedParameterPack()) { 619 SmallVector<QualType, 2> ExpandedTypes; 620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 623 ExpandedTInfos.push_back( 624 getTrivialTypeSourceInfo(ExpandedTypes.back())); 625 } 626 627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 628 SourceLocation(), 629 SourceLocation(), 630 NTTP->getDepth(), 631 NTTP->getPosition(), nullptr, 632 T, 633 TInfo, 634 ExpandedTypes.data(), 635 ExpandedTypes.size(), 636 ExpandedTInfos.data()); 637 } else { 638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 639 SourceLocation(), 640 SourceLocation(), 641 NTTP->getDepth(), 642 NTTP->getPosition(), nullptr, 643 T, 644 NTTP->isParameterPack(), 645 TInfo); 646 } 647 CanonParams.push_back(Param); 648 649 } else 650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 651 cast<TemplateTemplateParmDecl>(*P))); 652 } 653 654 TemplateTemplateParmDecl *CanonTTP 655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 656 SourceLocation(), TTP->getDepth(), 657 TTP->getPosition(), 658 TTP->isParameterPack(), 659 nullptr, 660 TemplateParameterList::Create(*this, SourceLocation(), 661 SourceLocation(), 662 CanonParams.data(), 663 CanonParams.size(), 664 SourceLocation())); 665 666 // Get the new insert position for the node we care about. 667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 668 assert(!Canonical && "Shouldn't be in the map!"); 669 (void)Canonical; 670 671 // Create the canonical template template parameter entry. 672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 674 return CanonTTP; 675 } 676 677 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 678 if (!LangOpts.CPlusPlus) return nullptr; 679 680 switch (T.getCXXABI().getKind()) { 681 case TargetCXXABI::GenericARM: // Same as Itanium at this level 682 case TargetCXXABI::iOS: 683 case TargetCXXABI::iOS64: 684 case TargetCXXABI::GenericAArch64: 685 case TargetCXXABI::GenericItanium: 686 return CreateItaniumCXXABI(*this); 687 case TargetCXXABI::Microsoft: 688 return CreateMicrosoftCXXABI(*this); 689 } 690 llvm_unreachable("Invalid CXXABI type!"); 691 } 692 693 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T, 694 const LangOptions &LOpts) { 695 if (LOpts.FakeAddressSpaceMap) { 696 // The fake address space map must have a distinct entry for each 697 // language-specific address space. 698 static const unsigned FakeAddrSpaceMap[] = { 699 1, // opencl_global 700 2, // opencl_local 701 3, // opencl_constant 702 4, // cuda_device 703 5, // cuda_constant 704 6 // cuda_shared 705 }; 706 return &FakeAddrSpaceMap; 707 } else { 708 return &T.getAddressSpaceMap(); 709 } 710 } 711 712 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 713 const LangOptions &LangOpts) { 714 switch (LangOpts.getAddressSpaceMapMangling()) { 715 case LangOptions::ASMM_Target: 716 return TI.useAddressSpaceMapMangling(); 717 case LangOptions::ASMM_On: 718 return true; 719 case LangOptions::ASMM_Off: 720 return false; 721 } 722 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 723 } 724 725 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM, 726 IdentifierTable &idents, SelectorTable &sels, 727 Builtin::Context &builtins) 728 : FunctionProtoTypes(this_()), 729 TemplateSpecializationTypes(this_()), 730 DependentTemplateSpecializationTypes(this_()), 731 SubstTemplateTemplateParmPacks(this_()), 732 GlobalNestedNameSpecifier(nullptr), 733 Int128Decl(nullptr), UInt128Decl(nullptr), Float128StubDecl(nullptr), 734 BuiltinVaListDecl(nullptr), 735 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr), 736 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr), 737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr), 738 FILEDecl(nullptr), 739 jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr), 740 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr), 741 cudaConfigureCallDecl(nullptr), 742 NullTypeSourceInfo(QualType()), 743 FirstLocalImport(), LastLocalImport(), 744 SourceMgr(SM), LangOpts(LOpts), 745 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts), 746 Idents(idents), Selectors(sels), 747 BuiltinInfo(builtins), 748 DeclarationNames(*this), 749 ExternalSource(nullptr), Listener(nullptr), 750 Comments(SM), CommentsLoaded(false), 751 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 752 LastSDM(nullptr, 0) 753 { 754 TUDecl = TranslationUnitDecl::Create(*this); 755 } 756 757 ASTContext::~ASTContext() { 758 ReleaseParentMapEntries(); 759 760 // Release the DenseMaps associated with DeclContext objects. 761 // FIXME: Is this the ideal solution? 762 ReleaseDeclContextMaps(); 763 764 // Call all of the deallocation functions on all of their targets. 765 for (DeallocationMap::const_iterator I = Deallocations.begin(), 766 E = Deallocations.end(); I != E; ++I) 767 for (unsigned J = 0, N = I->second.size(); J != N; ++J) 768 (I->first)((I->second)[J]); 769 770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 771 // because they can contain DenseMaps. 772 for (llvm::DenseMap<const ObjCContainerDecl*, 773 const ASTRecordLayout*>::iterator 774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 775 // Increment in loop to prevent using deallocated memory. 776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 777 R->Destroy(*this); 778 779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 781 // Increment in loop to prevent using deallocated memory. 782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 783 R->Destroy(*this); 784 } 785 786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 787 AEnd = DeclAttrs.end(); 788 A != AEnd; ++A) 789 A->second->~AttrVec(); 790 791 llvm::DeleteContainerSeconds(MangleNumberingContexts); 792 } 793 794 void ASTContext::ReleaseParentMapEntries() { 795 if (!AllParents) return; 796 for (const auto &Entry : *AllParents) { 797 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { 798 delete Entry.second.get<ast_type_traits::DynTypedNode *>(); 799 } else { 800 assert(Entry.second.is<ParentVector *>()); 801 delete Entry.second.get<ParentVector *>(); 802 } 803 } 804 } 805 806 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 807 Deallocations[Callback].push_back(Data); 808 } 809 810 void 811 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 812 ExternalSource = Source; 813 } 814 815 void ASTContext::PrintStats() const { 816 llvm::errs() << "\n*** AST Context Stats:\n"; 817 llvm::errs() << " " << Types.size() << " types total.\n"; 818 819 unsigned counts[] = { 820 #define TYPE(Name, Parent) 0, 821 #define ABSTRACT_TYPE(Name, Parent) 822 #include "clang/AST/TypeNodes.def" 823 0 // Extra 824 }; 825 826 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 827 Type *T = Types[i]; 828 counts[(unsigned)T->getTypeClass()]++; 829 } 830 831 unsigned Idx = 0; 832 unsigned TotalBytes = 0; 833 #define TYPE(Name, Parent) \ 834 if (counts[Idx]) \ 835 llvm::errs() << " " << counts[Idx] << " " << #Name \ 836 << " types\n"; \ 837 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 838 ++Idx; 839 #define ABSTRACT_TYPE(Name, Parent) 840 #include "clang/AST/TypeNodes.def" 841 842 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 843 844 // Implicit special member functions. 845 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 846 << NumImplicitDefaultConstructors 847 << " implicit default constructors created\n"; 848 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 849 << NumImplicitCopyConstructors 850 << " implicit copy constructors created\n"; 851 if (getLangOpts().CPlusPlus) 852 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 853 << NumImplicitMoveConstructors 854 << " implicit move constructors created\n"; 855 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 856 << NumImplicitCopyAssignmentOperators 857 << " implicit copy assignment operators created\n"; 858 if (getLangOpts().CPlusPlus) 859 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 860 << NumImplicitMoveAssignmentOperators 861 << " implicit move assignment operators created\n"; 862 llvm::errs() << NumImplicitDestructorsDeclared << "/" 863 << NumImplicitDestructors 864 << " implicit destructors created\n"; 865 866 if (ExternalSource) { 867 llvm::errs() << "\n"; 868 ExternalSource->PrintStats(); 869 } 870 871 BumpAlloc.PrintStats(); 872 } 873 874 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 875 RecordDecl::TagKind TK) const { 876 SourceLocation Loc; 877 RecordDecl *NewDecl; 878 if (getLangOpts().CPlusPlus) 879 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 880 Loc, &Idents.get(Name)); 881 else 882 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 883 &Idents.get(Name)); 884 NewDecl->setImplicit(); 885 return NewDecl; 886 } 887 888 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 889 StringRef Name) const { 890 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 891 TypedefDecl *NewDecl = TypedefDecl::Create( 892 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 893 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 894 NewDecl->setImplicit(); 895 return NewDecl; 896 } 897 898 TypedefDecl *ASTContext::getInt128Decl() const { 899 if (!Int128Decl) 900 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 901 return Int128Decl; 902 } 903 904 TypedefDecl *ASTContext::getUInt128Decl() const { 905 if (!UInt128Decl) 906 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 907 return UInt128Decl; 908 } 909 910 TypeDecl *ASTContext::getFloat128StubType() const { 911 assert(LangOpts.CPlusPlus && "should only be called for c++"); 912 if (!Float128StubDecl) 913 Float128StubDecl = buildImplicitRecord("__float128"); 914 915 return Float128StubDecl; 916 } 917 918 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 919 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 920 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 921 Types.push_back(Ty); 922 } 923 924 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) { 925 assert((!this->Target || this->Target == &Target) && 926 "Incorrect target reinitialization"); 927 assert(VoidTy.isNull() && "Context reinitialized?"); 928 929 this->Target = &Target; 930 931 ABI.reset(createCXXABI(Target)); 932 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 933 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 934 935 // C99 6.2.5p19. 936 InitBuiltinType(VoidTy, BuiltinType::Void); 937 938 // C99 6.2.5p2. 939 InitBuiltinType(BoolTy, BuiltinType::Bool); 940 // C99 6.2.5p3. 941 if (LangOpts.CharIsSigned) 942 InitBuiltinType(CharTy, BuiltinType::Char_S); 943 else 944 InitBuiltinType(CharTy, BuiltinType::Char_U); 945 // C99 6.2.5p4. 946 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 947 InitBuiltinType(ShortTy, BuiltinType::Short); 948 InitBuiltinType(IntTy, BuiltinType::Int); 949 InitBuiltinType(LongTy, BuiltinType::Long); 950 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 951 952 // C99 6.2.5p6. 953 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 954 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 955 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 956 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 957 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 958 959 // C99 6.2.5p10. 960 InitBuiltinType(FloatTy, BuiltinType::Float); 961 InitBuiltinType(DoubleTy, BuiltinType::Double); 962 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 963 964 // GNU extension, 128-bit integers. 965 InitBuiltinType(Int128Ty, BuiltinType::Int128); 966 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 967 968 // C++ 3.9.1p5 969 if (TargetInfo::isTypeSigned(Target.getWCharType())) 970 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 971 else // -fshort-wchar makes wchar_t be unsigned. 972 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 973 if (LangOpts.CPlusPlus && LangOpts.WChar) 974 WideCharTy = WCharTy; 975 else { 976 // C99 (or C++ using -fno-wchar). 977 WideCharTy = getFromTargetType(Target.getWCharType()); 978 } 979 980 WIntTy = getFromTargetType(Target.getWIntType()); 981 982 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 983 InitBuiltinType(Char16Ty, BuiltinType::Char16); 984 else // C99 985 Char16Ty = getFromTargetType(Target.getChar16Type()); 986 987 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 988 InitBuiltinType(Char32Ty, BuiltinType::Char32); 989 else // C99 990 Char32Ty = getFromTargetType(Target.getChar32Type()); 991 992 // Placeholder type for type-dependent expressions whose type is 993 // completely unknown. No code should ever check a type against 994 // DependentTy and users should never see it; however, it is here to 995 // help diagnose failures to properly check for type-dependent 996 // expressions. 997 InitBuiltinType(DependentTy, BuiltinType::Dependent); 998 999 // Placeholder type for functions. 1000 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1001 1002 // Placeholder type for bound members. 1003 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1004 1005 // Placeholder type for pseudo-objects. 1006 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1007 1008 // "any" type; useful for debugger-like clients. 1009 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1010 1011 // Placeholder type for unbridged ARC casts. 1012 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1013 1014 // Placeholder type for builtin functions. 1015 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1016 1017 // C99 6.2.5p11. 1018 FloatComplexTy = getComplexType(FloatTy); 1019 DoubleComplexTy = getComplexType(DoubleTy); 1020 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1021 1022 // Builtin types for 'id', 'Class', and 'SEL'. 1023 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1024 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1025 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1026 1027 if (LangOpts.OpenCL) { 1028 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d); 1029 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray); 1030 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer); 1031 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d); 1032 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray); 1033 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d); 1034 1035 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1036 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1037 } 1038 1039 // Builtin type for __objc_yes and __objc_no 1040 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1041 SignedCharTy : BoolTy); 1042 1043 ObjCConstantStringType = QualType(); 1044 1045 ObjCSuperType = QualType(); 1046 1047 // void * type 1048 VoidPtrTy = getPointerType(VoidTy); 1049 1050 // nullptr type (C++0x 2.14.7) 1051 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1052 1053 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1054 InitBuiltinType(HalfTy, BuiltinType::Half); 1055 1056 // Builtin type used to help define __builtin_va_list. 1057 VaListTagTy = QualType(); 1058 } 1059 1060 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1061 return SourceMgr.getDiagnostics(); 1062 } 1063 1064 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1065 AttrVec *&Result = DeclAttrs[D]; 1066 if (!Result) { 1067 void *Mem = Allocate(sizeof(AttrVec)); 1068 Result = new (Mem) AttrVec; 1069 } 1070 1071 return *Result; 1072 } 1073 1074 /// \brief Erase the attributes corresponding to the given declaration. 1075 void ASTContext::eraseDeclAttrs(const Decl *D) { 1076 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1077 if (Pos != DeclAttrs.end()) { 1078 Pos->second->~AttrVec(); 1079 DeclAttrs.erase(Pos); 1080 } 1081 } 1082 1083 // FIXME: Remove ? 1084 MemberSpecializationInfo * 1085 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1086 assert(Var->isStaticDataMember() && "Not a static data member"); 1087 return getTemplateOrSpecializationInfo(Var) 1088 .dyn_cast<MemberSpecializationInfo *>(); 1089 } 1090 1091 ASTContext::TemplateOrSpecializationInfo 1092 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1093 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1094 TemplateOrInstantiation.find(Var); 1095 if (Pos == TemplateOrInstantiation.end()) 1096 return TemplateOrSpecializationInfo(); 1097 1098 return Pos->second; 1099 } 1100 1101 void 1102 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1103 TemplateSpecializationKind TSK, 1104 SourceLocation PointOfInstantiation) { 1105 assert(Inst->isStaticDataMember() && "Not a static data member"); 1106 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1107 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1108 Tmpl, TSK, PointOfInstantiation)); 1109 } 1110 1111 void 1112 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1113 TemplateOrSpecializationInfo TSI) { 1114 assert(!TemplateOrInstantiation[Inst] && 1115 "Already noted what the variable was instantiated from"); 1116 TemplateOrInstantiation[Inst] = TSI; 1117 } 1118 1119 FunctionDecl *ASTContext::getClassScopeSpecializationPattern( 1120 const FunctionDecl *FD){ 1121 assert(FD && "Specialization is 0"); 1122 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos 1123 = ClassScopeSpecializationPattern.find(FD); 1124 if (Pos == ClassScopeSpecializationPattern.end()) 1125 return nullptr; 1126 1127 return Pos->second; 1128 } 1129 1130 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD, 1131 FunctionDecl *Pattern) { 1132 assert(FD && "Specialization is 0"); 1133 assert(Pattern && "Class scope specialization pattern is 0"); 1134 ClassScopeSpecializationPattern[FD] = Pattern; 1135 } 1136 1137 NamedDecl * 1138 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 1139 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 1140 = InstantiatedFromUsingDecl.find(UUD); 1141 if (Pos == InstantiatedFromUsingDecl.end()) 1142 return nullptr; 1143 1144 return Pos->second; 1145 } 1146 1147 void 1148 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 1149 assert((isa<UsingDecl>(Pattern) || 1150 isa<UnresolvedUsingValueDecl>(Pattern) || 1151 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1152 "pattern decl is not a using decl"); 1153 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1154 InstantiatedFromUsingDecl[Inst] = Pattern; 1155 } 1156 1157 UsingShadowDecl * 1158 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1159 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1160 = InstantiatedFromUsingShadowDecl.find(Inst); 1161 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1162 return nullptr; 1163 1164 return Pos->second; 1165 } 1166 1167 void 1168 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1169 UsingShadowDecl *Pattern) { 1170 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1171 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1172 } 1173 1174 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1175 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1176 = InstantiatedFromUnnamedFieldDecl.find(Field); 1177 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1178 return nullptr; 1179 1180 return Pos->second; 1181 } 1182 1183 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1184 FieldDecl *Tmpl) { 1185 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1186 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1187 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1188 "Already noted what unnamed field was instantiated from"); 1189 1190 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1191 } 1192 1193 ASTContext::overridden_cxx_method_iterator 1194 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1195 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1196 = OverriddenMethods.find(Method->getCanonicalDecl()); 1197 if (Pos == OverriddenMethods.end()) 1198 return nullptr; 1199 1200 return Pos->second.begin(); 1201 } 1202 1203 ASTContext::overridden_cxx_method_iterator 1204 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1205 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1206 = OverriddenMethods.find(Method->getCanonicalDecl()); 1207 if (Pos == OverriddenMethods.end()) 1208 return nullptr; 1209 1210 return Pos->second.end(); 1211 } 1212 1213 unsigned 1214 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1215 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1216 = OverriddenMethods.find(Method->getCanonicalDecl()); 1217 if (Pos == OverriddenMethods.end()) 1218 return 0; 1219 1220 return Pos->second.size(); 1221 } 1222 1223 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1224 const CXXMethodDecl *Overridden) { 1225 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1226 OverriddenMethods[Method].push_back(Overridden); 1227 } 1228 1229 void ASTContext::getOverriddenMethods( 1230 const NamedDecl *D, 1231 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1232 assert(D); 1233 1234 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1235 Overridden.append(overridden_methods_begin(CXXMethod), 1236 overridden_methods_end(CXXMethod)); 1237 return; 1238 } 1239 1240 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 1241 if (!Method) 1242 return; 1243 1244 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1245 Method->getOverriddenMethods(OverDecls); 1246 Overridden.append(OverDecls.begin(), OverDecls.end()); 1247 } 1248 1249 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1250 assert(!Import->NextLocalImport && "Import declaration already in the chain"); 1251 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1252 if (!FirstLocalImport) { 1253 FirstLocalImport = Import; 1254 LastLocalImport = Import; 1255 return; 1256 } 1257 1258 LastLocalImport->NextLocalImport = Import; 1259 LastLocalImport = Import; 1260 } 1261 1262 //===----------------------------------------------------------------------===// 1263 // Type Sizing and Analysis 1264 //===----------------------------------------------------------------------===// 1265 1266 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1267 /// scalar floating point type. 1268 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1269 const BuiltinType *BT = T->getAs<BuiltinType>(); 1270 assert(BT && "Not a floating point type!"); 1271 switch (BT->getKind()) { 1272 default: llvm_unreachable("Not a floating point type!"); 1273 case BuiltinType::Half: return Target->getHalfFormat(); 1274 case BuiltinType::Float: return Target->getFloatFormat(); 1275 case BuiltinType::Double: return Target->getDoubleFormat(); 1276 case BuiltinType::LongDouble: return Target->getLongDoubleFormat(); 1277 } 1278 } 1279 1280 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1281 unsigned Align = Target->getCharWidth(); 1282 1283 bool UseAlignAttrOnly = false; 1284 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1285 Align = AlignFromAttr; 1286 1287 // __attribute__((aligned)) can increase or decrease alignment 1288 // *except* on a struct or struct member, where it only increases 1289 // alignment unless 'packed' is also specified. 1290 // 1291 // It is an error for alignas to decrease alignment, so we can 1292 // ignore that possibility; Sema should diagnose it. 1293 if (isa<FieldDecl>(D)) { 1294 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1295 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1296 } else { 1297 UseAlignAttrOnly = true; 1298 } 1299 } 1300 else if (isa<FieldDecl>(D)) 1301 UseAlignAttrOnly = 1302 D->hasAttr<PackedAttr>() || 1303 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1304 1305 // If we're using the align attribute only, just ignore everything 1306 // else about the declaration and its type. 1307 if (UseAlignAttrOnly) { 1308 // do nothing 1309 1310 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1311 QualType T = VD->getType(); 1312 if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 1313 if (ForAlignof) 1314 T = RT->getPointeeType(); 1315 else 1316 T = getPointerType(RT->getPointeeType()); 1317 } 1318 QualType BaseT = getBaseElementType(T); 1319 if (!BaseT->isIncompleteType() && !T->isFunctionType()) { 1320 // Adjust alignments of declarations with array type by the 1321 // large-array alignment on the target. 1322 if (const ArrayType *arrayType = getAsArrayType(T)) { 1323 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1324 if (!ForAlignof && MinWidth) { 1325 if (isa<VariableArrayType>(arrayType)) 1326 Align = std::max(Align, Target->getLargeArrayAlign()); 1327 else if (isa<ConstantArrayType>(arrayType) && 1328 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1329 Align = std::max(Align, Target->getLargeArrayAlign()); 1330 } 1331 } 1332 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1333 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1334 if (VD->hasGlobalStorage()) 1335 Align = std::max(Align, getTargetInfo().getMinGlobalAlign()); 1336 } 1337 } 1338 1339 // Fields can be subject to extra alignment constraints, like if 1340 // the field is packed, the struct is packed, or the struct has a 1341 // a max-field-alignment constraint (#pragma pack). So calculate 1342 // the actual alignment of the field within the struct, and then 1343 // (as we're expected to) constrain that by the alignment of the type. 1344 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 1345 const RecordDecl *Parent = Field->getParent(); 1346 // We can only produce a sensible answer if the record is valid. 1347 if (!Parent->isInvalidDecl()) { 1348 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1349 1350 // Start with the record's overall alignment. 1351 unsigned FieldAlign = toBits(Layout.getAlignment()); 1352 1353 // Use the GCD of that and the offset within the record. 1354 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1355 if (Offset > 0) { 1356 // Alignment is always a power of 2, so the GCD will be a power of 2, 1357 // which means we get to do this crazy thing instead of Euclid's. 1358 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1359 if (LowBitOfOffset < FieldAlign) 1360 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1361 } 1362 1363 Align = std::min(Align, FieldAlign); 1364 } 1365 } 1366 } 1367 1368 return toCharUnitsFromBits(Align); 1369 } 1370 1371 // getTypeInfoDataSizeInChars - Return the size of a type, in 1372 // chars. If the type is a record, its data size is returned. This is 1373 // the size of the memcpy that's performed when assigning this type 1374 // using a trivial copy/move assignment operator. 1375 std::pair<CharUnits, CharUnits> 1376 ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1377 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T); 1378 1379 // In C++, objects can sometimes be allocated into the tail padding 1380 // of a base-class subobject. We decide whether that's possible 1381 // during class layout, so here we can just trust the layout results. 1382 if (getLangOpts().CPlusPlus) { 1383 if (const RecordType *RT = T->getAs<RecordType>()) { 1384 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1385 sizeAndAlign.first = layout.getDataSize(); 1386 } 1387 } 1388 1389 return sizeAndAlign; 1390 } 1391 1392 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1393 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1394 std::pair<CharUnits, CharUnits> 1395 static getConstantArrayInfoInChars(const ASTContext &Context, 1396 const ConstantArrayType *CAT) { 1397 std::pair<CharUnits, CharUnits> EltInfo = 1398 Context.getTypeInfoInChars(CAT->getElementType()); 1399 uint64_t Size = CAT->getSize().getZExtValue(); 1400 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= 1401 (uint64_t)(-1)/Size) && 1402 "Overflow in array type char size evaluation"); 1403 uint64_t Width = EltInfo.first.getQuantity() * Size; 1404 unsigned Align = EltInfo.second.getQuantity(); 1405 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1406 Context.getTargetInfo().getPointerWidth(0) == 64) 1407 Width = llvm::RoundUpToAlignment(Width, Align); 1408 return std::make_pair(CharUnits::fromQuantity(Width), 1409 CharUnits::fromQuantity(Align)); 1410 } 1411 1412 std::pair<CharUnits, CharUnits> 1413 ASTContext::getTypeInfoInChars(const Type *T) const { 1414 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) 1415 return getConstantArrayInfoInChars(*this, CAT); 1416 TypeInfo Info = getTypeInfo(T); 1417 return std::make_pair(toCharUnitsFromBits(Info.Width), 1418 toCharUnitsFromBits(Info.Align)); 1419 } 1420 1421 std::pair<CharUnits, CharUnits> 1422 ASTContext::getTypeInfoInChars(QualType T) const { 1423 return getTypeInfoInChars(T.getTypePtr()); 1424 } 1425 1426 bool ASTContext::isAlignmentRequired(const Type *T) const { 1427 return getTypeInfo(T).AlignIsRequired; 1428 } 1429 1430 bool ASTContext::isAlignmentRequired(QualType T) const { 1431 return isAlignmentRequired(T.getTypePtr()); 1432 } 1433 1434 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1435 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1436 if (I != MemoizedTypeInfo.end()) 1437 return I->second; 1438 1439 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1440 TypeInfo TI = getTypeInfoImpl(T); 1441 MemoizedTypeInfo[T] = TI; 1442 return TI; 1443 } 1444 1445 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1446 /// method does not work on incomplete types. 1447 /// 1448 /// FIXME: Pointers into different addr spaces could have different sizes and 1449 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1450 /// should take a QualType, &c. 1451 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1452 uint64_t Width = 0; 1453 unsigned Align = 8; 1454 bool AlignIsRequired = false; 1455 switch (T->getTypeClass()) { 1456 #define TYPE(Class, Base) 1457 #define ABSTRACT_TYPE(Class, Base) 1458 #define NON_CANONICAL_TYPE(Class, Base) 1459 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1460 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1461 case Type::Class: \ 1462 assert(!T->isDependentType() && "should not see dependent types here"); \ 1463 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1464 #include "clang/AST/TypeNodes.def" 1465 llvm_unreachable("Should not see dependent types"); 1466 1467 case Type::FunctionNoProto: 1468 case Type::FunctionProto: 1469 // GCC extension: alignof(function) = 32 bits 1470 Width = 0; 1471 Align = 32; 1472 break; 1473 1474 case Type::IncompleteArray: 1475 case Type::VariableArray: 1476 Width = 0; 1477 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 1478 break; 1479 1480 case Type::ConstantArray: { 1481 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 1482 1483 TypeInfo EltInfo = getTypeInfo(CAT->getElementType()); 1484 uint64_t Size = CAT->getSize().getZExtValue(); 1485 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1486 "Overflow in array type bit size evaluation"); 1487 Width = EltInfo.Width * Size; 1488 Align = EltInfo.Align; 1489 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1490 getTargetInfo().getPointerWidth(0) == 64) 1491 Width = llvm::RoundUpToAlignment(Width, Align); 1492 break; 1493 } 1494 case Type::ExtVector: 1495 case Type::Vector: { 1496 const VectorType *VT = cast<VectorType>(T); 1497 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1498 Width = EltInfo.Width * VT->getNumElements(); 1499 Align = Width; 1500 // If the alignment is not a power of 2, round up to the next power of 2. 1501 // This happens for non-power-of-2 length vectors. 1502 if (Align & (Align-1)) { 1503 Align = llvm::NextPowerOf2(Align); 1504 Width = llvm::RoundUpToAlignment(Width, Align); 1505 } 1506 // Adjust the alignment based on the target max. 1507 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1508 if (TargetVectorAlign && TargetVectorAlign < Align) 1509 Align = TargetVectorAlign; 1510 break; 1511 } 1512 1513 case Type::Builtin: 1514 switch (cast<BuiltinType>(T)->getKind()) { 1515 default: llvm_unreachable("Unknown builtin type!"); 1516 case BuiltinType::Void: 1517 // GCC extension: alignof(void) = 8 bits. 1518 Width = 0; 1519 Align = 8; 1520 break; 1521 1522 case BuiltinType::Bool: 1523 Width = Target->getBoolWidth(); 1524 Align = Target->getBoolAlign(); 1525 break; 1526 case BuiltinType::Char_S: 1527 case BuiltinType::Char_U: 1528 case BuiltinType::UChar: 1529 case BuiltinType::SChar: 1530 Width = Target->getCharWidth(); 1531 Align = Target->getCharAlign(); 1532 break; 1533 case BuiltinType::WChar_S: 1534 case BuiltinType::WChar_U: 1535 Width = Target->getWCharWidth(); 1536 Align = Target->getWCharAlign(); 1537 break; 1538 case BuiltinType::Char16: 1539 Width = Target->getChar16Width(); 1540 Align = Target->getChar16Align(); 1541 break; 1542 case BuiltinType::Char32: 1543 Width = Target->getChar32Width(); 1544 Align = Target->getChar32Align(); 1545 break; 1546 case BuiltinType::UShort: 1547 case BuiltinType::Short: 1548 Width = Target->getShortWidth(); 1549 Align = Target->getShortAlign(); 1550 break; 1551 case BuiltinType::UInt: 1552 case BuiltinType::Int: 1553 Width = Target->getIntWidth(); 1554 Align = Target->getIntAlign(); 1555 break; 1556 case BuiltinType::ULong: 1557 case BuiltinType::Long: 1558 Width = Target->getLongWidth(); 1559 Align = Target->getLongAlign(); 1560 break; 1561 case BuiltinType::ULongLong: 1562 case BuiltinType::LongLong: 1563 Width = Target->getLongLongWidth(); 1564 Align = Target->getLongLongAlign(); 1565 break; 1566 case BuiltinType::Int128: 1567 case BuiltinType::UInt128: 1568 Width = 128; 1569 Align = 128; // int128_t is 128-bit aligned on all targets. 1570 break; 1571 case BuiltinType::Half: 1572 Width = Target->getHalfWidth(); 1573 Align = Target->getHalfAlign(); 1574 break; 1575 case BuiltinType::Float: 1576 Width = Target->getFloatWidth(); 1577 Align = Target->getFloatAlign(); 1578 break; 1579 case BuiltinType::Double: 1580 Width = Target->getDoubleWidth(); 1581 Align = Target->getDoubleAlign(); 1582 break; 1583 case BuiltinType::LongDouble: 1584 Width = Target->getLongDoubleWidth(); 1585 Align = Target->getLongDoubleAlign(); 1586 break; 1587 case BuiltinType::NullPtr: 1588 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 1589 Align = Target->getPointerAlign(0); // == sizeof(void*) 1590 break; 1591 case BuiltinType::ObjCId: 1592 case BuiltinType::ObjCClass: 1593 case BuiltinType::ObjCSel: 1594 Width = Target->getPointerWidth(0); 1595 Align = Target->getPointerAlign(0); 1596 break; 1597 case BuiltinType::OCLSampler: 1598 // Samplers are modeled as integers. 1599 Width = Target->getIntWidth(); 1600 Align = Target->getIntAlign(); 1601 break; 1602 case BuiltinType::OCLEvent: 1603 case BuiltinType::OCLImage1d: 1604 case BuiltinType::OCLImage1dArray: 1605 case BuiltinType::OCLImage1dBuffer: 1606 case BuiltinType::OCLImage2d: 1607 case BuiltinType::OCLImage2dArray: 1608 case BuiltinType::OCLImage3d: 1609 // Currently these types are pointers to opaque types. 1610 Width = Target->getPointerWidth(0); 1611 Align = Target->getPointerAlign(0); 1612 break; 1613 } 1614 break; 1615 case Type::ObjCObjectPointer: 1616 Width = Target->getPointerWidth(0); 1617 Align = Target->getPointerAlign(0); 1618 break; 1619 case Type::BlockPointer: { 1620 unsigned AS = getTargetAddressSpace( 1621 cast<BlockPointerType>(T)->getPointeeType()); 1622 Width = Target->getPointerWidth(AS); 1623 Align = Target->getPointerAlign(AS); 1624 break; 1625 } 1626 case Type::LValueReference: 1627 case Type::RValueReference: { 1628 // alignof and sizeof should never enter this code path here, so we go 1629 // the pointer route. 1630 unsigned AS = getTargetAddressSpace( 1631 cast<ReferenceType>(T)->getPointeeType()); 1632 Width = Target->getPointerWidth(AS); 1633 Align = Target->getPointerAlign(AS); 1634 break; 1635 } 1636 case Type::Pointer: { 1637 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 1638 Width = Target->getPointerWidth(AS); 1639 Align = Target->getPointerAlign(AS); 1640 break; 1641 } 1642 case Type::MemberPointer: { 1643 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1644 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT); 1645 break; 1646 } 1647 case Type::Complex: { 1648 // Complex types have the same alignment as their elements, but twice the 1649 // size. 1650 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 1651 Width = EltInfo.Width * 2; 1652 Align = EltInfo.Align; 1653 break; 1654 } 1655 case Type::ObjCObject: 1656 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 1657 case Type::Adjusted: 1658 case Type::Decayed: 1659 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 1660 case Type::ObjCInterface: { 1661 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 1662 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 1663 Width = toBits(Layout.getSize()); 1664 Align = toBits(Layout.getAlignment()); 1665 break; 1666 } 1667 case Type::Record: 1668 case Type::Enum: { 1669 const TagType *TT = cast<TagType>(T); 1670 1671 if (TT->getDecl()->isInvalidDecl()) { 1672 Width = 8; 1673 Align = 8; 1674 break; 1675 } 1676 1677 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 1678 return getTypeInfo(ET->getDecl()->getIntegerType()); 1679 1680 const RecordType *RT = cast<RecordType>(TT); 1681 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 1682 Width = toBits(Layout.getSize()); 1683 Align = toBits(Layout.getAlignment()); 1684 break; 1685 } 1686 1687 case Type::SubstTemplateTypeParm: 1688 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 1689 getReplacementType().getTypePtr()); 1690 1691 case Type::Auto: { 1692 const AutoType *A = cast<AutoType>(T); 1693 assert(!A->getDeducedType().isNull() && 1694 "cannot request the size of an undeduced or dependent auto type"); 1695 return getTypeInfo(A->getDeducedType().getTypePtr()); 1696 } 1697 1698 case Type::Paren: 1699 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 1700 1701 case Type::Typedef: { 1702 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 1703 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 1704 // If the typedef has an aligned attribute on it, it overrides any computed 1705 // alignment we have. This violates the GCC documentation (which says that 1706 // attribute(aligned) can only round up) but matches its implementation. 1707 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 1708 Align = AttrAlign; 1709 AlignIsRequired = true; 1710 } else { 1711 Align = Info.Align; 1712 AlignIsRequired = Info.AlignIsRequired; 1713 } 1714 Width = Info.Width; 1715 break; 1716 } 1717 1718 case Type::Elaborated: 1719 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 1720 1721 case Type::Attributed: 1722 return getTypeInfo( 1723 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 1724 1725 case Type::Atomic: { 1726 // Start with the base type information. 1727 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 1728 Width = Info.Width; 1729 Align = Info.Align; 1730 1731 // If the size of the type doesn't exceed the platform's max 1732 // atomic promotion width, make the size and alignment more 1733 // favorable to atomic operations: 1734 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) { 1735 // Round the size up to a power of 2. 1736 if (!llvm::isPowerOf2_64(Width)) 1737 Width = llvm::NextPowerOf2(Width); 1738 1739 // Set the alignment equal to the size. 1740 Align = static_cast<unsigned>(Width); 1741 } 1742 } 1743 1744 } 1745 1746 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 1747 return TypeInfo(Width, Align, AlignIsRequired); 1748 } 1749 1750 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 1751 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 1752 return CharUnits::fromQuantity(BitSize / getCharWidth()); 1753 } 1754 1755 /// toBits - Convert a size in characters to a size in characters. 1756 int64_t ASTContext::toBits(CharUnits CharSize) const { 1757 return CharSize.getQuantity() * getCharWidth(); 1758 } 1759 1760 /// getTypeSizeInChars - Return the size of the specified type, in characters. 1761 /// This method does not work on incomplete types. 1762 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 1763 return getTypeInfoInChars(T).first; 1764 } 1765 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 1766 return getTypeInfoInChars(T).first; 1767 } 1768 1769 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 1770 /// characters. This method does not work on incomplete types. 1771 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 1772 return toCharUnitsFromBits(getTypeAlign(T)); 1773 } 1774 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 1775 return toCharUnitsFromBits(getTypeAlign(T)); 1776 } 1777 1778 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 1779 /// type for the current target in bits. This can be different than the ABI 1780 /// alignment in cases where it is beneficial for performance to overalign 1781 /// a data type. 1782 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 1783 TypeInfo TI = getTypeInfo(T); 1784 unsigned ABIAlign = TI.Align; 1785 1786 if (Target->getTriple().getArch() == llvm::Triple::xcore) 1787 return ABIAlign; // Never overalign on XCore. 1788 1789 // Double and long long should be naturally aligned if possible. 1790 T = T->getBaseElementTypeUnsafe(); 1791 if (const ComplexType *CT = T->getAs<ComplexType>()) 1792 T = CT->getElementType().getTypePtr(); 1793 if (T->isSpecificBuiltinType(BuiltinType::Double) || 1794 T->isSpecificBuiltinType(BuiltinType::LongLong) || 1795 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 1796 // Don't increase the alignment if an alignment attribute was specified on a 1797 // typedef declaration. 1798 if (!TI.AlignIsRequired) 1799 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 1800 1801 return ABIAlign; 1802 } 1803 1804 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 1805 /// to a global variable of the specified type. 1806 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 1807 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign()); 1808 } 1809 1810 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 1811 /// should be given to a global variable of the specified type. 1812 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 1813 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 1814 } 1815 1816 /// DeepCollectObjCIvars - 1817 /// This routine first collects all declared, but not synthesized, ivars in 1818 /// super class and then collects all ivars, including those synthesized for 1819 /// current class. This routine is used for implementation of current class 1820 /// when all ivars, declared and synthesized are known. 1821 /// 1822 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 1823 bool leafClass, 1824 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 1825 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 1826 DeepCollectObjCIvars(SuperClass, false, Ivars); 1827 if (!leafClass) { 1828 for (const auto *I : OI->ivars()) 1829 Ivars.push_back(I); 1830 } else { 1831 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 1832 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 1833 Iv= Iv->getNextIvar()) 1834 Ivars.push_back(Iv); 1835 } 1836 } 1837 1838 /// CollectInheritedProtocols - Collect all protocols in current class and 1839 /// those inherited by it. 1840 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 1841 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 1842 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1843 // We can use protocol_iterator here instead of 1844 // all_referenced_protocol_iterator since we are walking all categories. 1845 for (auto *Proto : OI->all_referenced_protocols()) { 1846 Protocols.insert(Proto->getCanonicalDecl()); 1847 for (auto *P : Proto->protocols()) { 1848 Protocols.insert(P->getCanonicalDecl()); 1849 CollectInheritedProtocols(P, Protocols); 1850 } 1851 } 1852 1853 // Categories of this Interface. 1854 for (const auto *Cat : OI->visible_categories()) 1855 CollectInheritedProtocols(Cat, Protocols); 1856 1857 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 1858 while (SD) { 1859 CollectInheritedProtocols(SD, Protocols); 1860 SD = SD->getSuperClass(); 1861 } 1862 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1863 for (auto *Proto : OC->protocols()) { 1864 Protocols.insert(Proto->getCanonicalDecl()); 1865 for (const auto *P : Proto->protocols()) 1866 CollectInheritedProtocols(P, Protocols); 1867 } 1868 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 1869 for (auto *Proto : OP->protocols()) { 1870 Protocols.insert(Proto->getCanonicalDecl()); 1871 for (const auto *P : Proto->protocols()) 1872 CollectInheritedProtocols(P, Protocols); 1873 } 1874 } 1875 } 1876 1877 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 1878 unsigned count = 0; 1879 // Count ivars declared in class extension. 1880 for (const auto *Ext : OI->known_extensions()) 1881 count += Ext->ivar_size(); 1882 1883 // Count ivar defined in this class's implementation. This 1884 // includes synthesized ivars. 1885 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 1886 count += ImplDecl->ivar_size(); 1887 1888 return count; 1889 } 1890 1891 bool ASTContext::isSentinelNullExpr(const Expr *E) { 1892 if (!E) 1893 return false; 1894 1895 // nullptr_t is always treated as null. 1896 if (E->getType()->isNullPtrType()) return true; 1897 1898 if (E->getType()->isAnyPointerType() && 1899 E->IgnoreParenCasts()->isNullPointerConstant(*this, 1900 Expr::NPC_ValueDependentIsNull)) 1901 return true; 1902 1903 // Unfortunately, __null has type 'int'. 1904 if (isa<GNUNullExpr>(E)) return true; 1905 1906 return false; 1907 } 1908 1909 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 1910 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 1911 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1912 I = ObjCImpls.find(D); 1913 if (I != ObjCImpls.end()) 1914 return cast<ObjCImplementationDecl>(I->second); 1915 return nullptr; 1916 } 1917 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 1918 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 1919 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1920 I = ObjCImpls.find(D); 1921 if (I != ObjCImpls.end()) 1922 return cast<ObjCCategoryImplDecl>(I->second); 1923 return nullptr; 1924 } 1925 1926 /// \brief Set the implementation of ObjCInterfaceDecl. 1927 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 1928 ObjCImplementationDecl *ImplD) { 1929 assert(IFaceD && ImplD && "Passed null params"); 1930 ObjCImpls[IFaceD] = ImplD; 1931 } 1932 /// \brief Set the implementation of ObjCCategoryDecl. 1933 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 1934 ObjCCategoryImplDecl *ImplD) { 1935 assert(CatD && ImplD && "Passed null params"); 1936 ObjCImpls[CatD] = ImplD; 1937 } 1938 1939 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 1940 const NamedDecl *ND) const { 1941 if (const ObjCInterfaceDecl *ID = 1942 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 1943 return ID; 1944 if (const ObjCCategoryDecl *CD = 1945 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 1946 return CD->getClassInterface(); 1947 if (const ObjCImplDecl *IMD = 1948 dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 1949 return IMD->getClassInterface(); 1950 1951 return nullptr; 1952 } 1953 1954 /// \brief Get the copy initialization expression of VarDecl,or NULL if 1955 /// none exists. 1956 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 1957 assert(VD && "Passed null params"); 1958 assert(VD->hasAttr<BlocksAttr>() && 1959 "getBlockVarCopyInits - not __block var"); 1960 llvm::DenseMap<const VarDecl*, Expr*>::iterator 1961 I = BlockVarCopyInits.find(VD); 1962 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr; 1963 } 1964 1965 /// \brief Set the copy inialization expression of a block var decl. 1966 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 1967 assert(VD && Init && "Passed null params"); 1968 assert(VD->hasAttr<BlocksAttr>() && 1969 "setBlockVarCopyInits - not __block var"); 1970 BlockVarCopyInits[VD] = Init; 1971 } 1972 1973 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 1974 unsigned DataSize) const { 1975 if (!DataSize) 1976 DataSize = TypeLoc::getFullDataSizeForType(T); 1977 else 1978 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1979 "incorrect data size provided to CreateTypeSourceInfo!"); 1980 1981 TypeSourceInfo *TInfo = 1982 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1983 new (TInfo) TypeSourceInfo(T); 1984 return TInfo; 1985 } 1986 1987 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1988 SourceLocation L) const { 1989 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1990 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 1991 return DI; 1992 } 1993 1994 const ASTRecordLayout & 1995 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 1996 return getObjCLayout(D, nullptr); 1997 } 1998 1999 const ASTRecordLayout & 2000 ASTContext::getASTObjCImplementationLayout( 2001 const ObjCImplementationDecl *D) const { 2002 return getObjCLayout(D->getClassInterface(), D); 2003 } 2004 2005 //===----------------------------------------------------------------------===// 2006 // Type creation/memoization methods 2007 //===----------------------------------------------------------------------===// 2008 2009 QualType 2010 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2011 unsigned fastQuals = quals.getFastQualifiers(); 2012 quals.removeFastQualifiers(); 2013 2014 // Check if we've already instantiated this type. 2015 llvm::FoldingSetNodeID ID; 2016 ExtQuals::Profile(ID, baseType, quals); 2017 void *insertPos = nullptr; 2018 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2019 assert(eq->getQualifiers() == quals); 2020 return QualType(eq, fastQuals); 2021 } 2022 2023 // If the base type is not canonical, make the appropriate canonical type. 2024 QualType canon; 2025 if (!baseType->isCanonicalUnqualified()) { 2026 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2027 canonSplit.Quals.addConsistentQualifiers(quals); 2028 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2029 2030 // Re-find the insert position. 2031 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2032 } 2033 2034 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2035 ExtQualNodes.InsertNode(eq, insertPos); 2036 return QualType(eq, fastQuals); 2037 } 2038 2039 QualType 2040 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const { 2041 QualType CanT = getCanonicalType(T); 2042 if (CanT.getAddressSpace() == AddressSpace) 2043 return T; 2044 2045 // If we are composing extended qualifiers together, merge together 2046 // into one ExtQuals node. 2047 QualifierCollector Quals; 2048 const Type *TypeNode = Quals.strip(T); 2049 2050 // If this type already has an address space specified, it cannot get 2051 // another one. 2052 assert(!Quals.hasAddressSpace() && 2053 "Type cannot be in multiple addr spaces!"); 2054 Quals.addAddressSpace(AddressSpace); 2055 2056 return getExtQualType(TypeNode, Quals); 2057 } 2058 2059 QualType ASTContext::getObjCGCQualType(QualType T, 2060 Qualifiers::GC GCAttr) const { 2061 QualType CanT = getCanonicalType(T); 2062 if (CanT.getObjCGCAttr() == GCAttr) 2063 return T; 2064 2065 if (const PointerType *ptr = T->getAs<PointerType>()) { 2066 QualType Pointee = ptr->getPointeeType(); 2067 if (Pointee->isAnyPointerType()) { 2068 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 2069 return getPointerType(ResultType); 2070 } 2071 } 2072 2073 // If we are composing extended qualifiers together, merge together 2074 // into one ExtQuals node. 2075 QualifierCollector Quals; 2076 const Type *TypeNode = Quals.strip(T); 2077 2078 // If this type already has an ObjCGC specified, it cannot get 2079 // another one. 2080 assert(!Quals.hasObjCGCAttr() && 2081 "Type cannot have multiple ObjCGCs!"); 2082 Quals.addObjCGCAttr(GCAttr); 2083 2084 return getExtQualType(TypeNode, Quals); 2085 } 2086 2087 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 2088 FunctionType::ExtInfo Info) { 2089 if (T->getExtInfo() == Info) 2090 return T; 2091 2092 QualType Result; 2093 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 2094 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 2095 } else { 2096 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 2097 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2098 EPI.ExtInfo = Info; 2099 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 2100 } 2101 2102 return cast<FunctionType>(Result.getTypePtr()); 2103 } 2104 2105 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 2106 QualType ResultType) { 2107 FD = FD->getMostRecentDecl(); 2108 while (true) { 2109 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 2110 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2111 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 2112 if (FunctionDecl *Next = FD->getPreviousDecl()) 2113 FD = Next; 2114 else 2115 break; 2116 } 2117 if (ASTMutationListener *L = getASTMutationListener()) 2118 L->DeducedReturnType(FD, ResultType); 2119 } 2120 2121 /// getComplexType - Return the uniqued reference to the type for a complex 2122 /// number with the specified element type. 2123 QualType ASTContext::getComplexType(QualType T) const { 2124 // Unique pointers, to guarantee there is only one pointer of a particular 2125 // structure. 2126 llvm::FoldingSetNodeID ID; 2127 ComplexType::Profile(ID, T); 2128 2129 void *InsertPos = nullptr; 2130 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 2131 return QualType(CT, 0); 2132 2133 // If the pointee type isn't canonical, this won't be a canonical type either, 2134 // so fill in the canonical type field. 2135 QualType Canonical; 2136 if (!T.isCanonical()) { 2137 Canonical = getComplexType(getCanonicalType(T)); 2138 2139 // Get the new insert position for the node we care about. 2140 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 2141 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2142 } 2143 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 2144 Types.push_back(New); 2145 ComplexTypes.InsertNode(New, InsertPos); 2146 return QualType(New, 0); 2147 } 2148 2149 /// getPointerType - Return the uniqued reference to the type for a pointer to 2150 /// the specified type. 2151 QualType ASTContext::getPointerType(QualType T) const { 2152 // Unique pointers, to guarantee there is only one pointer of a particular 2153 // structure. 2154 llvm::FoldingSetNodeID ID; 2155 PointerType::Profile(ID, T); 2156 2157 void *InsertPos = nullptr; 2158 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2159 return QualType(PT, 0); 2160 2161 // If the pointee type isn't canonical, this won't be a canonical type either, 2162 // so fill in the canonical type field. 2163 QualType Canonical; 2164 if (!T.isCanonical()) { 2165 Canonical = getPointerType(getCanonicalType(T)); 2166 2167 // Get the new insert position for the node we care about. 2168 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2169 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2170 } 2171 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 2172 Types.push_back(New); 2173 PointerTypes.InsertNode(New, InsertPos); 2174 return QualType(New, 0); 2175 } 2176 2177 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 2178 llvm::FoldingSetNodeID ID; 2179 AdjustedType::Profile(ID, Orig, New); 2180 void *InsertPos = nullptr; 2181 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2182 if (AT) 2183 return QualType(AT, 0); 2184 2185 QualType Canonical = getCanonicalType(New); 2186 2187 // Get the new insert position for the node we care about. 2188 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2189 assert(!AT && "Shouldn't be in the map!"); 2190 2191 AT = new (*this, TypeAlignment) 2192 AdjustedType(Type::Adjusted, Orig, New, Canonical); 2193 Types.push_back(AT); 2194 AdjustedTypes.InsertNode(AT, InsertPos); 2195 return QualType(AT, 0); 2196 } 2197 2198 QualType ASTContext::getDecayedType(QualType T) const { 2199 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 2200 2201 QualType Decayed; 2202 2203 // C99 6.7.5.3p7: 2204 // A declaration of a parameter as "array of type" shall be 2205 // adjusted to "qualified pointer to type", where the type 2206 // qualifiers (if any) are those specified within the [ and ] of 2207 // the array type derivation. 2208 if (T->isArrayType()) 2209 Decayed = getArrayDecayedType(T); 2210 2211 // C99 6.7.5.3p8: 2212 // A declaration of a parameter as "function returning type" 2213 // shall be adjusted to "pointer to function returning type", as 2214 // in 6.3.2.1. 2215 if (T->isFunctionType()) 2216 Decayed = getPointerType(T); 2217 2218 llvm::FoldingSetNodeID ID; 2219 AdjustedType::Profile(ID, T, Decayed); 2220 void *InsertPos = nullptr; 2221 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2222 if (AT) 2223 return QualType(AT, 0); 2224 2225 QualType Canonical = getCanonicalType(Decayed); 2226 2227 // Get the new insert position for the node we care about. 2228 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2229 assert(!AT && "Shouldn't be in the map!"); 2230 2231 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 2232 Types.push_back(AT); 2233 AdjustedTypes.InsertNode(AT, InsertPos); 2234 return QualType(AT, 0); 2235 } 2236 2237 /// getBlockPointerType - Return the uniqued reference to the type for 2238 /// a pointer to the specified block. 2239 QualType ASTContext::getBlockPointerType(QualType T) const { 2240 assert(T->isFunctionType() && "block of function types only"); 2241 // Unique pointers, to guarantee there is only one block of a particular 2242 // structure. 2243 llvm::FoldingSetNodeID ID; 2244 BlockPointerType::Profile(ID, T); 2245 2246 void *InsertPos = nullptr; 2247 if (BlockPointerType *PT = 2248 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2249 return QualType(PT, 0); 2250 2251 // If the block pointee type isn't canonical, this won't be a canonical 2252 // type either so fill in the canonical type field. 2253 QualType Canonical; 2254 if (!T.isCanonical()) { 2255 Canonical = getBlockPointerType(getCanonicalType(T)); 2256 2257 // Get the new insert position for the node we care about. 2258 BlockPointerType *NewIP = 2259 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2260 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2261 } 2262 BlockPointerType *New 2263 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 2264 Types.push_back(New); 2265 BlockPointerTypes.InsertNode(New, InsertPos); 2266 return QualType(New, 0); 2267 } 2268 2269 /// getLValueReferenceType - Return the uniqued reference to the type for an 2270 /// lvalue reference to the specified type. 2271 QualType 2272 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 2273 assert(getCanonicalType(T) != OverloadTy && 2274 "Unresolved overloaded function type"); 2275 2276 // Unique pointers, to guarantee there is only one pointer of a particular 2277 // structure. 2278 llvm::FoldingSetNodeID ID; 2279 ReferenceType::Profile(ID, T, SpelledAsLValue); 2280 2281 void *InsertPos = nullptr; 2282 if (LValueReferenceType *RT = 2283 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2284 return QualType(RT, 0); 2285 2286 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 2287 2288 // If the referencee type isn't canonical, this won't be a canonical type 2289 // either, so fill in the canonical type field. 2290 QualType Canonical; 2291 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 2292 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2293 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 2294 2295 // Get the new insert position for the node we care about. 2296 LValueReferenceType *NewIP = 2297 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2298 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2299 } 2300 2301 LValueReferenceType *New 2302 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 2303 SpelledAsLValue); 2304 Types.push_back(New); 2305 LValueReferenceTypes.InsertNode(New, InsertPos); 2306 2307 return QualType(New, 0); 2308 } 2309 2310 /// getRValueReferenceType - Return the uniqued reference to the type for an 2311 /// rvalue reference to the specified type. 2312 QualType ASTContext::getRValueReferenceType(QualType T) const { 2313 // Unique pointers, to guarantee there is only one pointer of a particular 2314 // structure. 2315 llvm::FoldingSetNodeID ID; 2316 ReferenceType::Profile(ID, T, false); 2317 2318 void *InsertPos = nullptr; 2319 if (RValueReferenceType *RT = 2320 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2321 return QualType(RT, 0); 2322 2323 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 2324 2325 // If the referencee type isn't canonical, this won't be a canonical type 2326 // either, so fill in the canonical type field. 2327 QualType Canonical; 2328 if (InnerRef || !T.isCanonical()) { 2329 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2330 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 2331 2332 // Get the new insert position for the node we care about. 2333 RValueReferenceType *NewIP = 2334 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2335 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2336 } 2337 2338 RValueReferenceType *New 2339 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 2340 Types.push_back(New); 2341 RValueReferenceTypes.InsertNode(New, InsertPos); 2342 return QualType(New, 0); 2343 } 2344 2345 /// getMemberPointerType - Return the uniqued reference to the type for a 2346 /// member pointer to the specified type, in the specified class. 2347 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 2348 // Unique pointers, to guarantee there is only one pointer of a particular 2349 // structure. 2350 llvm::FoldingSetNodeID ID; 2351 MemberPointerType::Profile(ID, T, Cls); 2352 2353 void *InsertPos = nullptr; 2354 if (MemberPointerType *PT = 2355 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2356 return QualType(PT, 0); 2357 2358 // If the pointee or class type isn't canonical, this won't be a canonical 2359 // type either, so fill in the canonical type field. 2360 QualType Canonical; 2361 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 2362 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 2363 2364 // Get the new insert position for the node we care about. 2365 MemberPointerType *NewIP = 2366 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2367 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2368 } 2369 MemberPointerType *New 2370 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 2371 Types.push_back(New); 2372 MemberPointerTypes.InsertNode(New, InsertPos); 2373 return QualType(New, 0); 2374 } 2375 2376 /// getConstantArrayType - Return the unique reference to the type for an 2377 /// array of the specified element type. 2378 QualType ASTContext::getConstantArrayType(QualType EltTy, 2379 const llvm::APInt &ArySizeIn, 2380 ArrayType::ArraySizeModifier ASM, 2381 unsigned IndexTypeQuals) const { 2382 assert((EltTy->isDependentType() || 2383 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 2384 "Constant array of VLAs is illegal!"); 2385 2386 // Convert the array size into a canonical width matching the pointer size for 2387 // the target. 2388 llvm::APInt ArySize(ArySizeIn); 2389 ArySize = 2390 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy))); 2391 2392 llvm::FoldingSetNodeID ID; 2393 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 2394 2395 void *InsertPos = nullptr; 2396 if (ConstantArrayType *ATP = 2397 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 2398 return QualType(ATP, 0); 2399 2400 // If the element type isn't canonical or has qualifiers, this won't 2401 // be a canonical type either, so fill in the canonical type field. 2402 QualType Canon; 2403 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2404 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2405 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 2406 ASM, IndexTypeQuals); 2407 Canon = getQualifiedType(Canon, canonSplit.Quals); 2408 2409 // Get the new insert position for the node we care about. 2410 ConstantArrayType *NewIP = 2411 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 2412 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2413 } 2414 2415 ConstantArrayType *New = new(*this,TypeAlignment) 2416 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 2417 ConstantArrayTypes.InsertNode(New, InsertPos); 2418 Types.push_back(New); 2419 return QualType(New, 0); 2420 } 2421 2422 /// getVariableArrayDecayedType - Turns the given type, which may be 2423 /// variably-modified, into the corresponding type with all the known 2424 /// sizes replaced with [*]. 2425 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 2426 // Vastly most common case. 2427 if (!type->isVariablyModifiedType()) return type; 2428 2429 QualType result; 2430 2431 SplitQualType split = type.getSplitDesugaredType(); 2432 const Type *ty = split.Ty; 2433 switch (ty->getTypeClass()) { 2434 #define TYPE(Class, Base) 2435 #define ABSTRACT_TYPE(Class, Base) 2436 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2437 #include "clang/AST/TypeNodes.def" 2438 llvm_unreachable("didn't desugar past all non-canonical types?"); 2439 2440 // These types should never be variably-modified. 2441 case Type::Builtin: 2442 case Type::Complex: 2443 case Type::Vector: 2444 case Type::ExtVector: 2445 case Type::DependentSizedExtVector: 2446 case Type::ObjCObject: 2447 case Type::ObjCInterface: 2448 case Type::ObjCObjectPointer: 2449 case Type::Record: 2450 case Type::Enum: 2451 case Type::UnresolvedUsing: 2452 case Type::TypeOfExpr: 2453 case Type::TypeOf: 2454 case Type::Decltype: 2455 case Type::UnaryTransform: 2456 case Type::DependentName: 2457 case Type::InjectedClassName: 2458 case Type::TemplateSpecialization: 2459 case Type::DependentTemplateSpecialization: 2460 case Type::TemplateTypeParm: 2461 case Type::SubstTemplateTypeParmPack: 2462 case Type::Auto: 2463 case Type::PackExpansion: 2464 llvm_unreachable("type should never be variably-modified"); 2465 2466 // These types can be variably-modified but should never need to 2467 // further decay. 2468 case Type::FunctionNoProto: 2469 case Type::FunctionProto: 2470 case Type::BlockPointer: 2471 case Type::MemberPointer: 2472 return type; 2473 2474 // These types can be variably-modified. All these modifications 2475 // preserve structure except as noted by comments. 2476 // TODO: if we ever care about optimizing VLAs, there are no-op 2477 // optimizations available here. 2478 case Type::Pointer: 2479 result = getPointerType(getVariableArrayDecayedType( 2480 cast<PointerType>(ty)->getPointeeType())); 2481 break; 2482 2483 case Type::LValueReference: { 2484 const LValueReferenceType *lv = cast<LValueReferenceType>(ty); 2485 result = getLValueReferenceType( 2486 getVariableArrayDecayedType(lv->getPointeeType()), 2487 lv->isSpelledAsLValue()); 2488 break; 2489 } 2490 2491 case Type::RValueReference: { 2492 const RValueReferenceType *lv = cast<RValueReferenceType>(ty); 2493 result = getRValueReferenceType( 2494 getVariableArrayDecayedType(lv->getPointeeType())); 2495 break; 2496 } 2497 2498 case Type::Atomic: { 2499 const AtomicType *at = cast<AtomicType>(ty); 2500 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 2501 break; 2502 } 2503 2504 case Type::ConstantArray: { 2505 const ConstantArrayType *cat = cast<ConstantArrayType>(ty); 2506 result = getConstantArrayType( 2507 getVariableArrayDecayedType(cat->getElementType()), 2508 cat->getSize(), 2509 cat->getSizeModifier(), 2510 cat->getIndexTypeCVRQualifiers()); 2511 break; 2512 } 2513 2514 case Type::DependentSizedArray: { 2515 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty); 2516 result = getDependentSizedArrayType( 2517 getVariableArrayDecayedType(dat->getElementType()), 2518 dat->getSizeExpr(), 2519 dat->getSizeModifier(), 2520 dat->getIndexTypeCVRQualifiers(), 2521 dat->getBracketsRange()); 2522 break; 2523 } 2524 2525 // Turn incomplete types into [*] types. 2526 case Type::IncompleteArray: { 2527 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty); 2528 result = getVariableArrayType( 2529 getVariableArrayDecayedType(iat->getElementType()), 2530 /*size*/ nullptr, 2531 ArrayType::Normal, 2532 iat->getIndexTypeCVRQualifiers(), 2533 SourceRange()); 2534 break; 2535 } 2536 2537 // Turn VLA types into [*] types. 2538 case Type::VariableArray: { 2539 const VariableArrayType *vat = cast<VariableArrayType>(ty); 2540 result = getVariableArrayType( 2541 getVariableArrayDecayedType(vat->getElementType()), 2542 /*size*/ nullptr, 2543 ArrayType::Star, 2544 vat->getIndexTypeCVRQualifiers(), 2545 vat->getBracketsRange()); 2546 break; 2547 } 2548 } 2549 2550 // Apply the top-level qualifiers from the original. 2551 return getQualifiedType(result, split.Quals); 2552 } 2553 2554 /// getVariableArrayType - Returns a non-unique reference to the type for a 2555 /// variable array of the specified element type. 2556 QualType ASTContext::getVariableArrayType(QualType EltTy, 2557 Expr *NumElts, 2558 ArrayType::ArraySizeModifier ASM, 2559 unsigned IndexTypeQuals, 2560 SourceRange Brackets) const { 2561 // Since we don't unique expressions, it isn't possible to unique VLA's 2562 // that have an expression provided for their size. 2563 QualType Canon; 2564 2565 // Be sure to pull qualifiers off the element type. 2566 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2567 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2568 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 2569 IndexTypeQuals, Brackets); 2570 Canon = getQualifiedType(Canon, canonSplit.Quals); 2571 } 2572 2573 VariableArrayType *New = new(*this, TypeAlignment) 2574 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 2575 2576 VariableArrayTypes.push_back(New); 2577 Types.push_back(New); 2578 return QualType(New, 0); 2579 } 2580 2581 /// getDependentSizedArrayType - Returns a non-unique reference to 2582 /// the type for a dependently-sized array of the specified element 2583 /// type. 2584 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 2585 Expr *numElements, 2586 ArrayType::ArraySizeModifier ASM, 2587 unsigned elementTypeQuals, 2588 SourceRange brackets) const { 2589 assert((!numElements || numElements->isTypeDependent() || 2590 numElements->isValueDependent()) && 2591 "Size must be type- or value-dependent!"); 2592 2593 // Dependently-sized array types that do not have a specified number 2594 // of elements will have their sizes deduced from a dependent 2595 // initializer. We do no canonicalization here at all, which is okay 2596 // because they can't be used in most locations. 2597 if (!numElements) { 2598 DependentSizedArrayType *newType 2599 = new (*this, TypeAlignment) 2600 DependentSizedArrayType(*this, elementType, QualType(), 2601 numElements, ASM, elementTypeQuals, 2602 brackets); 2603 Types.push_back(newType); 2604 return QualType(newType, 0); 2605 } 2606 2607 // Otherwise, we actually build a new type every time, but we 2608 // also build a canonical type. 2609 2610 SplitQualType canonElementType = getCanonicalType(elementType).split(); 2611 2612 void *insertPos = nullptr; 2613 llvm::FoldingSetNodeID ID; 2614 DependentSizedArrayType::Profile(ID, *this, 2615 QualType(canonElementType.Ty, 0), 2616 ASM, elementTypeQuals, numElements); 2617 2618 // Look for an existing type with these properties. 2619 DependentSizedArrayType *canonTy = 2620 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2621 2622 // If we don't have one, build one. 2623 if (!canonTy) { 2624 canonTy = new (*this, TypeAlignment) 2625 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 2626 QualType(), numElements, ASM, elementTypeQuals, 2627 brackets); 2628 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 2629 Types.push_back(canonTy); 2630 } 2631 2632 // Apply qualifiers from the element type to the array. 2633 QualType canon = getQualifiedType(QualType(canonTy,0), 2634 canonElementType.Quals); 2635 2636 // If we didn't need extra canonicalization for the element type, 2637 // then just use that as our result. 2638 if (QualType(canonElementType.Ty, 0) == elementType) 2639 return canon; 2640 2641 // Otherwise, we need to build a type which follows the spelling 2642 // of the element type. 2643 DependentSizedArrayType *sugaredType 2644 = new (*this, TypeAlignment) 2645 DependentSizedArrayType(*this, elementType, canon, numElements, 2646 ASM, elementTypeQuals, brackets); 2647 Types.push_back(sugaredType); 2648 return QualType(sugaredType, 0); 2649 } 2650 2651 QualType ASTContext::getIncompleteArrayType(QualType elementType, 2652 ArrayType::ArraySizeModifier ASM, 2653 unsigned elementTypeQuals) const { 2654 llvm::FoldingSetNodeID ID; 2655 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 2656 2657 void *insertPos = nullptr; 2658 if (IncompleteArrayType *iat = 2659 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 2660 return QualType(iat, 0); 2661 2662 // If the element type isn't canonical, this won't be a canonical type 2663 // either, so fill in the canonical type field. We also have to pull 2664 // qualifiers off the element type. 2665 QualType canon; 2666 2667 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 2668 SplitQualType canonSplit = getCanonicalType(elementType).split(); 2669 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 2670 ASM, elementTypeQuals); 2671 canon = getQualifiedType(canon, canonSplit.Quals); 2672 2673 // Get the new insert position for the node we care about. 2674 IncompleteArrayType *existing = 2675 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2676 assert(!existing && "Shouldn't be in the map!"); (void) existing; 2677 } 2678 2679 IncompleteArrayType *newType = new (*this, TypeAlignment) 2680 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 2681 2682 IncompleteArrayTypes.InsertNode(newType, insertPos); 2683 Types.push_back(newType); 2684 return QualType(newType, 0); 2685 } 2686 2687 /// getVectorType - Return the unique reference to a vector type of 2688 /// the specified element type and size. VectorType must be a built-in type. 2689 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 2690 VectorType::VectorKind VecKind) const { 2691 assert(vecType->isBuiltinType()); 2692 2693 // Check if we've already instantiated a vector of this type. 2694 llvm::FoldingSetNodeID ID; 2695 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 2696 2697 void *InsertPos = nullptr; 2698 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2699 return QualType(VTP, 0); 2700 2701 // If the element type isn't canonical, this won't be a canonical type either, 2702 // so fill in the canonical type field. 2703 QualType Canonical; 2704 if (!vecType.isCanonical()) { 2705 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 2706 2707 // Get the new insert position for the node we care about. 2708 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2709 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2710 } 2711 VectorType *New = new (*this, TypeAlignment) 2712 VectorType(vecType, NumElts, Canonical, VecKind); 2713 VectorTypes.InsertNode(New, InsertPos); 2714 Types.push_back(New); 2715 return QualType(New, 0); 2716 } 2717 2718 /// getExtVectorType - Return the unique reference to an extended vector type of 2719 /// the specified element type and size. VectorType must be a built-in type. 2720 QualType 2721 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 2722 assert(vecType->isBuiltinType() || vecType->isDependentType()); 2723 2724 // Check if we've already instantiated a vector of this type. 2725 llvm::FoldingSetNodeID ID; 2726 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 2727 VectorType::GenericVector); 2728 void *InsertPos = nullptr; 2729 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2730 return QualType(VTP, 0); 2731 2732 // If the element type isn't canonical, this won't be a canonical type either, 2733 // so fill in the canonical type field. 2734 QualType Canonical; 2735 if (!vecType.isCanonical()) { 2736 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 2737 2738 // Get the new insert position for the node we care about. 2739 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2740 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2741 } 2742 ExtVectorType *New = new (*this, TypeAlignment) 2743 ExtVectorType(vecType, NumElts, Canonical); 2744 VectorTypes.InsertNode(New, InsertPos); 2745 Types.push_back(New); 2746 return QualType(New, 0); 2747 } 2748 2749 QualType 2750 ASTContext::getDependentSizedExtVectorType(QualType vecType, 2751 Expr *SizeExpr, 2752 SourceLocation AttrLoc) const { 2753 llvm::FoldingSetNodeID ID; 2754 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 2755 SizeExpr); 2756 2757 void *InsertPos = nullptr; 2758 DependentSizedExtVectorType *Canon 2759 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2760 DependentSizedExtVectorType *New; 2761 if (Canon) { 2762 // We already have a canonical version of this array type; use it as 2763 // the canonical type for a newly-built type. 2764 New = new (*this, TypeAlignment) 2765 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 2766 SizeExpr, AttrLoc); 2767 } else { 2768 QualType CanonVecTy = getCanonicalType(vecType); 2769 if (CanonVecTy == vecType) { 2770 New = new (*this, TypeAlignment) 2771 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 2772 AttrLoc); 2773 2774 DependentSizedExtVectorType *CanonCheck 2775 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2776 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 2777 (void)CanonCheck; 2778 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 2779 } else { 2780 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 2781 SourceLocation()); 2782 New = new (*this, TypeAlignment) 2783 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 2784 } 2785 } 2786 2787 Types.push_back(New); 2788 return QualType(New, 0); 2789 } 2790 2791 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 2792 /// 2793 QualType 2794 ASTContext::getFunctionNoProtoType(QualType ResultTy, 2795 const FunctionType::ExtInfo &Info) const { 2796 const CallingConv CallConv = Info.getCC(); 2797 2798 // Unique functions, to guarantee there is only one function of a particular 2799 // structure. 2800 llvm::FoldingSetNodeID ID; 2801 FunctionNoProtoType::Profile(ID, ResultTy, Info); 2802 2803 void *InsertPos = nullptr; 2804 if (FunctionNoProtoType *FT = 2805 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2806 return QualType(FT, 0); 2807 2808 QualType Canonical; 2809 if (!ResultTy.isCanonical()) { 2810 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info); 2811 2812 // Get the new insert position for the node we care about. 2813 FunctionNoProtoType *NewIP = 2814 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2815 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2816 } 2817 2818 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv); 2819 FunctionNoProtoType *New = new (*this, TypeAlignment) 2820 FunctionNoProtoType(ResultTy, Canonical, newInfo); 2821 Types.push_back(New); 2822 FunctionNoProtoTypes.InsertNode(New, InsertPos); 2823 return QualType(New, 0); 2824 } 2825 2826 /// \brief Determine whether \p T is canonical as the result type of a function. 2827 static bool isCanonicalResultType(QualType T) { 2828 return T.isCanonical() && 2829 (T.getObjCLifetime() == Qualifiers::OCL_None || 2830 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 2831 } 2832 2833 QualType 2834 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray, 2835 const FunctionProtoType::ExtProtoInfo &EPI) const { 2836 size_t NumArgs = ArgArray.size(); 2837 2838 // Unique functions, to guarantee there is only one function of a particular 2839 // structure. 2840 llvm::FoldingSetNodeID ID; 2841 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 2842 *this); 2843 2844 void *InsertPos = nullptr; 2845 if (FunctionProtoType *FTP = 2846 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2847 return QualType(FTP, 0); 2848 2849 // Determine whether the type being created is already canonical or not. 2850 bool isCanonical = 2851 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) && 2852 !EPI.HasTrailingReturn; 2853 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 2854 if (!ArgArray[i].isCanonicalAsParam()) 2855 isCanonical = false; 2856 2857 // If this type isn't canonical, get the canonical version of it. 2858 // The exception spec is not part of the canonical type. 2859 QualType Canonical; 2860 if (!isCanonical) { 2861 SmallVector<QualType, 16> CanonicalArgs; 2862 CanonicalArgs.reserve(NumArgs); 2863 for (unsigned i = 0; i != NumArgs; ++i) 2864 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 2865 2866 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 2867 CanonicalEPI.HasTrailingReturn = false; 2868 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 2869 2870 // Result types do not have ARC lifetime qualifiers. 2871 QualType CanResultTy = getCanonicalType(ResultTy); 2872 if (ResultTy.getQualifiers().hasObjCLifetime()) { 2873 Qualifiers Qs = CanResultTy.getQualifiers(); 2874 Qs.removeObjCLifetime(); 2875 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs); 2876 } 2877 2878 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI); 2879 2880 // Get the new insert position for the node we care about. 2881 FunctionProtoType *NewIP = 2882 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2883 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2884 } 2885 2886 // FunctionProtoType objects are allocated with extra bytes after 2887 // them for three variable size arrays at the end: 2888 // - parameter types 2889 // - exception types 2890 // - consumed-arguments flags 2891 // Instead of the exception types, there could be a noexcept 2892 // expression, or information used to resolve the exception 2893 // specification. 2894 size_t Size = sizeof(FunctionProtoType) + 2895 NumArgs * sizeof(QualType); 2896 if (EPI.ExceptionSpec.Type == EST_Dynamic) { 2897 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType); 2898 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) { 2899 Size += sizeof(Expr*); 2900 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) { 2901 Size += 2 * sizeof(FunctionDecl*); 2902 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) { 2903 Size += sizeof(FunctionDecl*); 2904 } 2905 if (EPI.ConsumedParameters) 2906 Size += NumArgs * sizeof(bool); 2907 2908 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment); 2909 FunctionProtoType::ExtProtoInfo newEPI = EPI; 2910 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 2911 Types.push_back(FTP); 2912 FunctionProtoTypes.InsertNode(FTP, InsertPos); 2913 return QualType(FTP, 0); 2914 } 2915 2916 #ifndef NDEBUG 2917 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 2918 if (!isa<CXXRecordDecl>(D)) return false; 2919 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 2920 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 2921 return true; 2922 if (RD->getDescribedClassTemplate() && 2923 !isa<ClassTemplateSpecializationDecl>(RD)) 2924 return true; 2925 return false; 2926 } 2927 #endif 2928 2929 /// getInjectedClassNameType - Return the unique reference to the 2930 /// injected class name type for the specified templated declaration. 2931 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 2932 QualType TST) const { 2933 assert(NeedsInjectedClassNameType(Decl)); 2934 if (Decl->TypeForDecl) { 2935 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2936 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 2937 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 2938 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2939 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2940 } else { 2941 Type *newType = 2942 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 2943 Decl->TypeForDecl = newType; 2944 Types.push_back(newType); 2945 } 2946 return QualType(Decl->TypeForDecl, 0); 2947 } 2948 2949 /// getTypeDeclType - Return the unique reference to the type for the 2950 /// specified type declaration. 2951 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 2952 assert(Decl && "Passed null for Decl param"); 2953 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 2954 2955 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 2956 return getTypedefType(Typedef); 2957 2958 assert(!isa<TemplateTypeParmDecl>(Decl) && 2959 "Template type parameter types are always available."); 2960 2961 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 2962 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 2963 assert(!NeedsInjectedClassNameType(Record)); 2964 return getRecordType(Record); 2965 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 2966 assert(Enum->isFirstDecl() && "enum has previous declaration"); 2967 return getEnumType(Enum); 2968 } else if (const UnresolvedUsingTypenameDecl *Using = 2969 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 2970 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 2971 Decl->TypeForDecl = newType; 2972 Types.push_back(newType); 2973 } else 2974 llvm_unreachable("TypeDecl without a type?"); 2975 2976 return QualType(Decl->TypeForDecl, 0); 2977 } 2978 2979 /// getTypedefType - Return the unique reference to the type for the 2980 /// specified typedef name decl. 2981 QualType 2982 ASTContext::getTypedefType(const TypedefNameDecl *Decl, 2983 QualType Canonical) const { 2984 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2985 2986 if (Canonical.isNull()) 2987 Canonical = getCanonicalType(Decl->getUnderlyingType()); 2988 TypedefType *newType = new(*this, TypeAlignment) 2989 TypedefType(Type::Typedef, Decl, Canonical); 2990 Decl->TypeForDecl = newType; 2991 Types.push_back(newType); 2992 return QualType(newType, 0); 2993 } 2994 2995 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 2996 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2997 2998 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 2999 if (PrevDecl->TypeForDecl) 3000 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3001 3002 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl); 3003 Decl->TypeForDecl = newType; 3004 Types.push_back(newType); 3005 return QualType(newType, 0); 3006 } 3007 3008 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 3009 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3010 3011 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 3012 if (PrevDecl->TypeForDecl) 3013 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3014 3015 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl); 3016 Decl->TypeForDecl = newType; 3017 Types.push_back(newType); 3018 return QualType(newType, 0); 3019 } 3020 3021 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 3022 QualType modifiedType, 3023 QualType equivalentType) { 3024 llvm::FoldingSetNodeID id; 3025 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 3026 3027 void *insertPos = nullptr; 3028 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 3029 if (type) return QualType(type, 0); 3030 3031 QualType canon = getCanonicalType(equivalentType); 3032 type = new (*this, TypeAlignment) 3033 AttributedType(canon, attrKind, modifiedType, equivalentType); 3034 3035 Types.push_back(type); 3036 AttributedTypes.InsertNode(type, insertPos); 3037 3038 return QualType(type, 0); 3039 } 3040 3041 3042 /// \brief Retrieve a substitution-result type. 3043 QualType 3044 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 3045 QualType Replacement) const { 3046 assert(Replacement.isCanonical() 3047 && "replacement types must always be canonical"); 3048 3049 llvm::FoldingSetNodeID ID; 3050 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 3051 void *InsertPos = nullptr; 3052 SubstTemplateTypeParmType *SubstParm 3053 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3054 3055 if (!SubstParm) { 3056 SubstParm = new (*this, TypeAlignment) 3057 SubstTemplateTypeParmType(Parm, Replacement); 3058 Types.push_back(SubstParm); 3059 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3060 } 3061 3062 return QualType(SubstParm, 0); 3063 } 3064 3065 /// \brief Retrieve a 3066 QualType ASTContext::getSubstTemplateTypeParmPackType( 3067 const TemplateTypeParmType *Parm, 3068 const TemplateArgument &ArgPack) { 3069 #ifndef NDEBUG 3070 for (const auto &P : ArgPack.pack_elements()) { 3071 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 3072 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 3073 } 3074 #endif 3075 3076 llvm::FoldingSetNodeID ID; 3077 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 3078 void *InsertPos = nullptr; 3079 if (SubstTemplateTypeParmPackType *SubstParm 3080 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 3081 return QualType(SubstParm, 0); 3082 3083 QualType Canon; 3084 if (!Parm->isCanonicalUnqualified()) { 3085 Canon = getCanonicalType(QualType(Parm, 0)); 3086 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 3087 ArgPack); 3088 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 3089 } 3090 3091 SubstTemplateTypeParmPackType *SubstParm 3092 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 3093 ArgPack); 3094 Types.push_back(SubstParm); 3095 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3096 return QualType(SubstParm, 0); 3097 } 3098 3099 /// \brief Retrieve the template type parameter type for a template 3100 /// parameter or parameter pack with the given depth, index, and (optionally) 3101 /// name. 3102 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 3103 bool ParameterPack, 3104 TemplateTypeParmDecl *TTPDecl) const { 3105 llvm::FoldingSetNodeID ID; 3106 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 3107 void *InsertPos = nullptr; 3108 TemplateTypeParmType *TypeParm 3109 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3110 3111 if (TypeParm) 3112 return QualType(TypeParm, 0); 3113 3114 if (TTPDecl) { 3115 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 3116 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 3117 3118 TemplateTypeParmType *TypeCheck 3119 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3120 assert(!TypeCheck && "Template type parameter canonical type broken"); 3121 (void)TypeCheck; 3122 } else 3123 TypeParm = new (*this, TypeAlignment) 3124 TemplateTypeParmType(Depth, Index, ParameterPack); 3125 3126 Types.push_back(TypeParm); 3127 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 3128 3129 return QualType(TypeParm, 0); 3130 } 3131 3132 TypeSourceInfo * 3133 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 3134 SourceLocation NameLoc, 3135 const TemplateArgumentListInfo &Args, 3136 QualType Underlying) const { 3137 assert(!Name.getAsDependentTemplateName() && 3138 "No dependent template names here!"); 3139 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 3140 3141 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 3142 TemplateSpecializationTypeLoc TL = 3143 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 3144 TL.setTemplateKeywordLoc(SourceLocation()); 3145 TL.setTemplateNameLoc(NameLoc); 3146 TL.setLAngleLoc(Args.getLAngleLoc()); 3147 TL.setRAngleLoc(Args.getRAngleLoc()); 3148 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 3149 TL.setArgLocInfo(i, Args[i].getLocInfo()); 3150 return DI; 3151 } 3152 3153 QualType 3154 ASTContext::getTemplateSpecializationType(TemplateName Template, 3155 const TemplateArgumentListInfo &Args, 3156 QualType Underlying) const { 3157 assert(!Template.getAsDependentTemplateName() && 3158 "No dependent template names here!"); 3159 3160 unsigned NumArgs = Args.size(); 3161 3162 SmallVector<TemplateArgument, 4> ArgVec; 3163 ArgVec.reserve(NumArgs); 3164 for (unsigned i = 0; i != NumArgs; ++i) 3165 ArgVec.push_back(Args[i].getArgument()); 3166 3167 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 3168 Underlying); 3169 } 3170 3171 #ifndef NDEBUG 3172 static bool hasAnyPackExpansions(const TemplateArgument *Args, 3173 unsigned NumArgs) { 3174 for (unsigned I = 0; I != NumArgs; ++I) 3175 if (Args[I].isPackExpansion()) 3176 return true; 3177 3178 return true; 3179 } 3180 #endif 3181 3182 QualType 3183 ASTContext::getTemplateSpecializationType(TemplateName Template, 3184 const TemplateArgument *Args, 3185 unsigned NumArgs, 3186 QualType Underlying) const { 3187 assert(!Template.getAsDependentTemplateName() && 3188 "No dependent template names here!"); 3189 // Look through qualified template names. 3190 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 3191 Template = TemplateName(QTN->getTemplateDecl()); 3192 3193 bool IsTypeAlias = 3194 Template.getAsTemplateDecl() && 3195 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 3196 QualType CanonType; 3197 if (!Underlying.isNull()) 3198 CanonType = getCanonicalType(Underlying); 3199 else { 3200 // We can get here with an alias template when the specialization contains 3201 // a pack expansion that does not match up with a parameter pack. 3202 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) && 3203 "Caller must compute aliased type"); 3204 IsTypeAlias = false; 3205 CanonType = getCanonicalTemplateSpecializationType(Template, Args, 3206 NumArgs); 3207 } 3208 3209 // Allocate the (non-canonical) template specialization type, but don't 3210 // try to unique it: these types typically have location information that 3211 // we don't unique and don't want to lose. 3212 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 3213 sizeof(TemplateArgument) * NumArgs + 3214 (IsTypeAlias? sizeof(QualType) : 0), 3215 TypeAlignment); 3216 TemplateSpecializationType *Spec 3217 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType, 3218 IsTypeAlias ? Underlying : QualType()); 3219 3220 Types.push_back(Spec); 3221 return QualType(Spec, 0); 3222 } 3223 3224 QualType 3225 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 3226 const TemplateArgument *Args, 3227 unsigned NumArgs) const { 3228 assert(!Template.getAsDependentTemplateName() && 3229 "No dependent template names here!"); 3230 3231 // Look through qualified template names. 3232 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 3233 Template = TemplateName(QTN->getTemplateDecl()); 3234 3235 // Build the canonical template specialization type. 3236 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 3237 SmallVector<TemplateArgument, 4> CanonArgs; 3238 CanonArgs.reserve(NumArgs); 3239 for (unsigned I = 0; I != NumArgs; ++I) 3240 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 3241 3242 // Determine whether this canonical template specialization type already 3243 // exists. 3244 llvm::FoldingSetNodeID ID; 3245 TemplateSpecializationType::Profile(ID, CanonTemplate, 3246 CanonArgs.data(), NumArgs, *this); 3247 3248 void *InsertPos = nullptr; 3249 TemplateSpecializationType *Spec 3250 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3251 3252 if (!Spec) { 3253 // Allocate a new canonical template specialization type. 3254 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 3255 sizeof(TemplateArgument) * NumArgs), 3256 TypeAlignment); 3257 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 3258 CanonArgs.data(), NumArgs, 3259 QualType(), QualType()); 3260 Types.push_back(Spec); 3261 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 3262 } 3263 3264 assert(Spec->isDependentType() && 3265 "Non-dependent template-id type must have a canonical type"); 3266 return QualType(Spec, 0); 3267 } 3268 3269 QualType 3270 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 3271 NestedNameSpecifier *NNS, 3272 QualType NamedType) const { 3273 llvm::FoldingSetNodeID ID; 3274 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 3275 3276 void *InsertPos = nullptr; 3277 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 3278 if (T) 3279 return QualType(T, 0); 3280 3281 QualType Canon = NamedType; 3282 if (!Canon.isCanonical()) { 3283 Canon = getCanonicalType(NamedType); 3284 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 3285 assert(!CheckT && "Elaborated canonical type broken"); 3286 (void)CheckT; 3287 } 3288 3289 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 3290 Types.push_back(T); 3291 ElaboratedTypes.InsertNode(T, InsertPos); 3292 return QualType(T, 0); 3293 } 3294 3295 QualType 3296 ASTContext::getParenType(QualType InnerType) const { 3297 llvm::FoldingSetNodeID ID; 3298 ParenType::Profile(ID, InnerType); 3299 3300 void *InsertPos = nullptr; 3301 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 3302 if (T) 3303 return QualType(T, 0); 3304 3305 QualType Canon = InnerType; 3306 if (!Canon.isCanonical()) { 3307 Canon = getCanonicalType(InnerType); 3308 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 3309 assert(!CheckT && "Paren canonical type broken"); 3310 (void)CheckT; 3311 } 3312 3313 T = new (*this) ParenType(InnerType, Canon); 3314 Types.push_back(T); 3315 ParenTypes.InsertNode(T, InsertPos); 3316 return QualType(T, 0); 3317 } 3318 3319 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 3320 NestedNameSpecifier *NNS, 3321 const IdentifierInfo *Name, 3322 QualType Canon) const { 3323 if (Canon.isNull()) { 3324 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 3325 ElaboratedTypeKeyword CanonKeyword = Keyword; 3326 if (Keyword == ETK_None) 3327 CanonKeyword = ETK_Typename; 3328 3329 if (CanonNNS != NNS || CanonKeyword != Keyword) 3330 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 3331 } 3332 3333 llvm::FoldingSetNodeID ID; 3334 DependentNameType::Profile(ID, Keyword, NNS, Name); 3335 3336 void *InsertPos = nullptr; 3337 DependentNameType *T 3338 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 3339 if (T) 3340 return QualType(T, 0); 3341 3342 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 3343 Types.push_back(T); 3344 DependentNameTypes.InsertNode(T, InsertPos); 3345 return QualType(T, 0); 3346 } 3347 3348 QualType 3349 ASTContext::getDependentTemplateSpecializationType( 3350 ElaboratedTypeKeyword Keyword, 3351 NestedNameSpecifier *NNS, 3352 const IdentifierInfo *Name, 3353 const TemplateArgumentListInfo &Args) const { 3354 // TODO: avoid this copy 3355 SmallVector<TemplateArgument, 16> ArgCopy; 3356 for (unsigned I = 0, E = Args.size(); I != E; ++I) 3357 ArgCopy.push_back(Args[I].getArgument()); 3358 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 3359 ArgCopy.size(), 3360 ArgCopy.data()); 3361 } 3362 3363 QualType 3364 ASTContext::getDependentTemplateSpecializationType( 3365 ElaboratedTypeKeyword Keyword, 3366 NestedNameSpecifier *NNS, 3367 const IdentifierInfo *Name, 3368 unsigned NumArgs, 3369 const TemplateArgument *Args) const { 3370 assert((!NNS || NNS->isDependent()) && 3371 "nested-name-specifier must be dependent"); 3372 3373 llvm::FoldingSetNodeID ID; 3374 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 3375 Name, NumArgs, Args); 3376 3377 void *InsertPos = nullptr; 3378 DependentTemplateSpecializationType *T 3379 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3380 if (T) 3381 return QualType(T, 0); 3382 3383 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 3384 3385 ElaboratedTypeKeyword CanonKeyword = Keyword; 3386 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 3387 3388 bool AnyNonCanonArgs = false; 3389 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 3390 for (unsigned I = 0; I != NumArgs; ++I) { 3391 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 3392 if (!CanonArgs[I].structurallyEquals(Args[I])) 3393 AnyNonCanonArgs = true; 3394 } 3395 3396 QualType Canon; 3397 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 3398 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 3399 Name, NumArgs, 3400 CanonArgs.data()); 3401 3402 // Find the insert position again. 3403 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3404 } 3405 3406 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 3407 sizeof(TemplateArgument) * NumArgs), 3408 TypeAlignment); 3409 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 3410 Name, NumArgs, Args, Canon); 3411 Types.push_back(T); 3412 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 3413 return QualType(T, 0); 3414 } 3415 3416 QualType ASTContext::getPackExpansionType(QualType Pattern, 3417 Optional<unsigned> NumExpansions) { 3418 llvm::FoldingSetNodeID ID; 3419 PackExpansionType::Profile(ID, Pattern, NumExpansions); 3420 3421 assert(Pattern->containsUnexpandedParameterPack() && 3422 "Pack expansions must expand one or more parameter packs"); 3423 void *InsertPos = nullptr; 3424 PackExpansionType *T 3425 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3426 if (T) 3427 return QualType(T, 0); 3428 3429 QualType Canon; 3430 if (!Pattern.isCanonical()) { 3431 Canon = getCanonicalType(Pattern); 3432 // The canonical type might not contain an unexpanded parameter pack, if it 3433 // contains an alias template specialization which ignores one of its 3434 // parameters. 3435 if (Canon->containsUnexpandedParameterPack()) { 3436 Canon = getPackExpansionType(Canon, NumExpansions); 3437 3438 // Find the insert position again, in case we inserted an element into 3439 // PackExpansionTypes and invalidated our insert position. 3440 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3441 } 3442 } 3443 3444 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions); 3445 Types.push_back(T); 3446 PackExpansionTypes.InsertNode(T, InsertPos); 3447 return QualType(T, 0); 3448 } 3449 3450 /// CmpProtocolNames - Comparison predicate for sorting protocols 3451 /// alphabetically. 3452 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 3453 const ObjCProtocolDecl *RHS) { 3454 return LHS->getDeclName() < RHS->getDeclName(); 3455 } 3456 3457 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 3458 unsigned NumProtocols) { 3459 if (NumProtocols == 0) return true; 3460 3461 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 3462 return false; 3463 3464 for (unsigned i = 1; i != NumProtocols; ++i) 3465 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) || 3466 Protocols[i]->getCanonicalDecl() != Protocols[i]) 3467 return false; 3468 return true; 3469 } 3470 3471 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 3472 unsigned &NumProtocols) { 3473 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 3474 3475 // Sort protocols, keyed by name. 3476 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 3477 3478 // Canonicalize. 3479 for (unsigned I = 0, N = NumProtocols; I != N; ++I) 3480 Protocols[I] = Protocols[I]->getCanonicalDecl(); 3481 3482 // Remove duplicates. 3483 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 3484 NumProtocols = ProtocolsEnd-Protocols; 3485 } 3486 3487 QualType ASTContext::getObjCObjectType(QualType BaseType, 3488 ObjCProtocolDecl * const *Protocols, 3489 unsigned NumProtocols) const { 3490 // If the base type is an interface and there aren't any protocols 3491 // to add, then the interface type will do just fine. 3492 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 3493 return BaseType; 3494 3495 // Look in the folding set for an existing type. 3496 llvm::FoldingSetNodeID ID; 3497 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 3498 void *InsertPos = nullptr; 3499 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 3500 return QualType(QT, 0); 3501 3502 // Build the canonical type, which has the canonical base type and 3503 // a sorted-and-uniqued list of protocols. 3504 QualType Canonical; 3505 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 3506 if (!ProtocolsSorted || !BaseType.isCanonical()) { 3507 if (!ProtocolsSorted) { 3508 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 3509 Protocols + NumProtocols); 3510 unsigned UniqueCount = NumProtocols; 3511 3512 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 3513 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3514 &Sorted[0], UniqueCount); 3515 } else { 3516 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3517 Protocols, NumProtocols); 3518 } 3519 3520 // Regenerate InsertPos. 3521 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 3522 } 3523 3524 unsigned Size = sizeof(ObjCObjectTypeImpl); 3525 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 3526 void *Mem = Allocate(Size, TypeAlignment); 3527 ObjCObjectTypeImpl *T = 3528 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 3529 3530 Types.push_back(T); 3531 ObjCObjectTypes.InsertNode(T, InsertPos); 3532 return QualType(T, 0); 3533 } 3534 3535 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 3536 /// protocol list adopt all protocols in QT's qualified-id protocol 3537 /// list. 3538 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 3539 ObjCInterfaceDecl *IC) { 3540 if (!QT->isObjCQualifiedIdType()) 3541 return false; 3542 3543 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) { 3544 // If both the right and left sides have qualifiers. 3545 for (auto *Proto : OPT->quals()) { 3546 if (!IC->ClassImplementsProtocol(Proto, false)) 3547 return false; 3548 } 3549 return true; 3550 } 3551 return false; 3552 } 3553 3554 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 3555 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 3556 /// of protocols. 3557 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 3558 ObjCInterfaceDecl *IDecl) { 3559 if (!QT->isObjCQualifiedIdType()) 3560 return false; 3561 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>(); 3562 if (!OPT) 3563 return false; 3564 if (!IDecl->hasDefinition()) 3565 return false; 3566 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 3567 CollectInheritedProtocols(IDecl, InheritedProtocols); 3568 if (InheritedProtocols.empty()) 3569 return false; 3570 // Check that if every protocol in list of id<plist> conforms to a protcol 3571 // of IDecl's, then bridge casting is ok. 3572 bool Conforms = false; 3573 for (auto *Proto : OPT->quals()) { 3574 Conforms = false; 3575 for (auto *PI : InheritedProtocols) { 3576 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 3577 Conforms = true; 3578 break; 3579 } 3580 } 3581 if (!Conforms) 3582 break; 3583 } 3584 if (Conforms) 3585 return true; 3586 3587 for (auto *PI : InheritedProtocols) { 3588 // If both the right and left sides have qualifiers. 3589 bool Adopts = false; 3590 for (auto *Proto : OPT->quals()) { 3591 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 3592 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 3593 break; 3594 } 3595 if (!Adopts) 3596 return false; 3597 } 3598 return true; 3599 } 3600 3601 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 3602 /// the given object type. 3603 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 3604 llvm::FoldingSetNodeID ID; 3605 ObjCObjectPointerType::Profile(ID, ObjectT); 3606 3607 void *InsertPos = nullptr; 3608 if (ObjCObjectPointerType *QT = 3609 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3610 return QualType(QT, 0); 3611 3612 // Find the canonical object type. 3613 QualType Canonical; 3614 if (!ObjectT.isCanonical()) { 3615 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 3616 3617 // Regenerate InsertPos. 3618 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3619 } 3620 3621 // No match. 3622 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 3623 ObjCObjectPointerType *QType = 3624 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 3625 3626 Types.push_back(QType); 3627 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 3628 return QualType(QType, 0); 3629 } 3630 3631 /// getObjCInterfaceType - Return the unique reference to the type for the 3632 /// specified ObjC interface decl. The list of protocols is optional. 3633 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 3634 ObjCInterfaceDecl *PrevDecl) const { 3635 if (Decl->TypeForDecl) 3636 return QualType(Decl->TypeForDecl, 0); 3637 3638 if (PrevDecl) { 3639 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 3640 Decl->TypeForDecl = PrevDecl->TypeForDecl; 3641 return QualType(PrevDecl->TypeForDecl, 0); 3642 } 3643 3644 // Prefer the definition, if there is one. 3645 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 3646 Decl = Def; 3647 3648 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 3649 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 3650 Decl->TypeForDecl = T; 3651 Types.push_back(T); 3652 return QualType(T, 0); 3653 } 3654 3655 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 3656 /// TypeOfExprType AST's (since expression's are never shared). For example, 3657 /// multiple declarations that refer to "typeof(x)" all contain different 3658 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 3659 /// on canonical type's (which are always unique). 3660 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 3661 TypeOfExprType *toe; 3662 if (tofExpr->isTypeDependent()) { 3663 llvm::FoldingSetNodeID ID; 3664 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 3665 3666 void *InsertPos = nullptr; 3667 DependentTypeOfExprType *Canon 3668 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 3669 if (Canon) { 3670 // We already have a "canonical" version of an identical, dependent 3671 // typeof(expr) type. Use that as our canonical type. 3672 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 3673 QualType((TypeOfExprType*)Canon, 0)); 3674 } else { 3675 // Build a new, canonical typeof(expr) type. 3676 Canon 3677 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 3678 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 3679 toe = Canon; 3680 } 3681 } else { 3682 QualType Canonical = getCanonicalType(tofExpr->getType()); 3683 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 3684 } 3685 Types.push_back(toe); 3686 return QualType(toe, 0); 3687 } 3688 3689 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 3690 /// TypeOfType nodes. The only motivation to unique these nodes would be 3691 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 3692 /// an issue. This doesn't affect the type checker, since it operates 3693 /// on canonical types (which are always unique). 3694 QualType ASTContext::getTypeOfType(QualType tofType) const { 3695 QualType Canonical = getCanonicalType(tofType); 3696 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 3697 Types.push_back(tot); 3698 return QualType(tot, 0); 3699 } 3700 3701 3702 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType 3703 /// nodes. This would never be helpful, since each such type has its own 3704 /// expression, and would not give a significant memory saving, since there 3705 /// is an Expr tree under each such type. 3706 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 3707 DecltypeType *dt; 3708 3709 // C++11 [temp.type]p2: 3710 // If an expression e involves a template parameter, decltype(e) denotes a 3711 // unique dependent type. Two such decltype-specifiers refer to the same 3712 // type only if their expressions are equivalent (14.5.6.1). 3713 if (e->isInstantiationDependent()) { 3714 llvm::FoldingSetNodeID ID; 3715 DependentDecltypeType::Profile(ID, *this, e); 3716 3717 void *InsertPos = nullptr; 3718 DependentDecltypeType *Canon 3719 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 3720 if (!Canon) { 3721 // Build a new, canonical typeof(expr) type. 3722 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 3723 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 3724 } 3725 dt = new (*this, TypeAlignment) 3726 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 3727 } else { 3728 dt = new (*this, TypeAlignment) 3729 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 3730 } 3731 Types.push_back(dt); 3732 return QualType(dt, 0); 3733 } 3734 3735 /// getUnaryTransformationType - We don't unique these, since the memory 3736 /// savings are minimal and these are rare. 3737 QualType ASTContext::getUnaryTransformType(QualType BaseType, 3738 QualType UnderlyingType, 3739 UnaryTransformType::UTTKind Kind) 3740 const { 3741 UnaryTransformType *Ty = 3742 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 3743 Kind, 3744 UnderlyingType->isDependentType() ? 3745 QualType() : getCanonicalType(UnderlyingType)); 3746 Types.push_back(Ty); 3747 return QualType(Ty, 0); 3748 } 3749 3750 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 3751 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 3752 /// canonical deduced-but-dependent 'auto' type. 3753 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto, 3754 bool IsDependent) const { 3755 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent) 3756 return getAutoDeductType(); 3757 3758 // Look in the folding set for an existing type. 3759 void *InsertPos = nullptr; 3760 llvm::FoldingSetNodeID ID; 3761 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent); 3762 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3763 return QualType(AT, 0); 3764 3765 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType, 3766 IsDecltypeAuto, 3767 IsDependent); 3768 Types.push_back(AT); 3769 if (InsertPos) 3770 AutoTypes.InsertNode(AT, InsertPos); 3771 return QualType(AT, 0); 3772 } 3773 3774 /// getAtomicType - Return the uniqued reference to the atomic type for 3775 /// the given value type. 3776 QualType ASTContext::getAtomicType(QualType T) const { 3777 // Unique pointers, to guarantee there is only one pointer of a particular 3778 // structure. 3779 llvm::FoldingSetNodeID ID; 3780 AtomicType::Profile(ID, T); 3781 3782 void *InsertPos = nullptr; 3783 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 3784 return QualType(AT, 0); 3785 3786 // If the atomic value type isn't canonical, this won't be a canonical type 3787 // either, so fill in the canonical type field. 3788 QualType Canonical; 3789 if (!T.isCanonical()) { 3790 Canonical = getAtomicType(getCanonicalType(T)); 3791 3792 // Get the new insert position for the node we care about. 3793 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 3794 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3795 } 3796 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 3797 Types.push_back(New); 3798 AtomicTypes.InsertNode(New, InsertPos); 3799 return QualType(New, 0); 3800 } 3801 3802 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 3803 QualType ASTContext::getAutoDeductType() const { 3804 if (AutoDeductTy.isNull()) 3805 AutoDeductTy = QualType( 3806 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false, 3807 /*dependent*/false), 3808 0); 3809 return AutoDeductTy; 3810 } 3811 3812 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 3813 QualType ASTContext::getAutoRRefDeductType() const { 3814 if (AutoRRefDeductTy.isNull()) 3815 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 3816 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 3817 return AutoRRefDeductTy; 3818 } 3819 3820 /// getTagDeclType - Return the unique reference to the type for the 3821 /// specified TagDecl (struct/union/class/enum) decl. 3822 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 3823 assert (Decl); 3824 // FIXME: What is the design on getTagDeclType when it requires casting 3825 // away const? mutable? 3826 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 3827 } 3828 3829 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 3830 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 3831 /// needs to agree with the definition in <stddef.h>. 3832 CanQualType ASTContext::getSizeType() const { 3833 return getFromTargetType(Target->getSizeType()); 3834 } 3835 3836 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 3837 CanQualType ASTContext::getIntMaxType() const { 3838 return getFromTargetType(Target->getIntMaxType()); 3839 } 3840 3841 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 3842 CanQualType ASTContext::getUIntMaxType() const { 3843 return getFromTargetType(Target->getUIntMaxType()); 3844 } 3845 3846 /// getSignedWCharType - Return the type of "signed wchar_t". 3847 /// Used when in C++, as a GCC extension. 3848 QualType ASTContext::getSignedWCharType() const { 3849 // FIXME: derive from "Target" ? 3850 return WCharTy; 3851 } 3852 3853 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 3854 /// Used when in C++, as a GCC extension. 3855 QualType ASTContext::getUnsignedWCharType() const { 3856 // FIXME: derive from "Target" ? 3857 return UnsignedIntTy; 3858 } 3859 3860 QualType ASTContext::getIntPtrType() const { 3861 return getFromTargetType(Target->getIntPtrType()); 3862 } 3863 3864 QualType ASTContext::getUIntPtrType() const { 3865 return getCorrespondingUnsignedType(getIntPtrType()); 3866 } 3867 3868 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 3869 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 3870 QualType ASTContext::getPointerDiffType() const { 3871 return getFromTargetType(Target->getPtrDiffType(0)); 3872 } 3873 3874 /// \brief Return the unique type for "pid_t" defined in 3875 /// <sys/types.h>. We need this to compute the correct type for vfork(). 3876 QualType ASTContext::getProcessIDType() const { 3877 return getFromTargetType(Target->getProcessIDType()); 3878 } 3879 3880 //===----------------------------------------------------------------------===// 3881 // Type Operators 3882 //===----------------------------------------------------------------------===// 3883 3884 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 3885 // Push qualifiers into arrays, and then discard any remaining 3886 // qualifiers. 3887 T = getCanonicalType(T); 3888 T = getVariableArrayDecayedType(T); 3889 const Type *Ty = T.getTypePtr(); 3890 QualType Result; 3891 if (isa<ArrayType>(Ty)) { 3892 Result = getArrayDecayedType(QualType(Ty,0)); 3893 } else if (isa<FunctionType>(Ty)) { 3894 Result = getPointerType(QualType(Ty, 0)); 3895 } else { 3896 Result = QualType(Ty, 0); 3897 } 3898 3899 return CanQualType::CreateUnsafe(Result); 3900 } 3901 3902 QualType ASTContext::getUnqualifiedArrayType(QualType type, 3903 Qualifiers &quals) { 3904 SplitQualType splitType = type.getSplitUnqualifiedType(); 3905 3906 // FIXME: getSplitUnqualifiedType() actually walks all the way to 3907 // the unqualified desugared type and then drops it on the floor. 3908 // We then have to strip that sugar back off with 3909 // getUnqualifiedDesugaredType(), which is silly. 3910 const ArrayType *AT = 3911 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 3912 3913 // If we don't have an array, just use the results in splitType. 3914 if (!AT) { 3915 quals = splitType.Quals; 3916 return QualType(splitType.Ty, 0); 3917 } 3918 3919 // Otherwise, recurse on the array's element type. 3920 QualType elementType = AT->getElementType(); 3921 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 3922 3923 // If that didn't change the element type, AT has no qualifiers, so we 3924 // can just use the results in splitType. 3925 if (elementType == unqualElementType) { 3926 assert(quals.empty()); // from the recursive call 3927 quals = splitType.Quals; 3928 return QualType(splitType.Ty, 0); 3929 } 3930 3931 // Otherwise, add in the qualifiers from the outermost type, then 3932 // build the type back up. 3933 quals.addConsistentQualifiers(splitType.Quals); 3934 3935 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 3936 return getConstantArrayType(unqualElementType, CAT->getSize(), 3937 CAT->getSizeModifier(), 0); 3938 } 3939 3940 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 3941 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 3942 } 3943 3944 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 3945 return getVariableArrayType(unqualElementType, 3946 VAT->getSizeExpr(), 3947 VAT->getSizeModifier(), 3948 VAT->getIndexTypeCVRQualifiers(), 3949 VAT->getBracketsRange()); 3950 } 3951 3952 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 3953 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 3954 DSAT->getSizeModifier(), 0, 3955 SourceRange()); 3956 } 3957 3958 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 3959 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that 3960 /// they point to and return true. If T1 and T2 aren't pointer types 3961 /// or pointer-to-member types, or if they are not similar at this 3962 /// level, returns false and leaves T1 and T2 unchanged. Top-level 3963 /// qualifiers on T1 and T2 are ignored. This function will typically 3964 /// be called in a loop that successively "unwraps" pointer and 3965 /// pointer-to-member types to compare them at each level. 3966 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 3967 const PointerType *T1PtrType = T1->getAs<PointerType>(), 3968 *T2PtrType = T2->getAs<PointerType>(); 3969 if (T1PtrType && T2PtrType) { 3970 T1 = T1PtrType->getPointeeType(); 3971 T2 = T2PtrType->getPointeeType(); 3972 return true; 3973 } 3974 3975 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 3976 *T2MPType = T2->getAs<MemberPointerType>(); 3977 if (T1MPType && T2MPType && 3978 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 3979 QualType(T2MPType->getClass(), 0))) { 3980 T1 = T1MPType->getPointeeType(); 3981 T2 = T2MPType->getPointeeType(); 3982 return true; 3983 } 3984 3985 if (getLangOpts().ObjC1) { 3986 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 3987 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 3988 if (T1OPType && T2OPType) { 3989 T1 = T1OPType->getPointeeType(); 3990 T2 = T2OPType->getPointeeType(); 3991 return true; 3992 } 3993 } 3994 3995 // FIXME: Block pointers, too? 3996 3997 return false; 3998 } 3999 4000 DeclarationNameInfo 4001 ASTContext::getNameForTemplate(TemplateName Name, 4002 SourceLocation NameLoc) const { 4003 switch (Name.getKind()) { 4004 case TemplateName::QualifiedTemplate: 4005 case TemplateName::Template: 4006 // DNInfo work in progress: CHECKME: what about DNLoc? 4007 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 4008 NameLoc); 4009 4010 case TemplateName::OverloadedTemplate: { 4011 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 4012 // DNInfo work in progress: CHECKME: what about DNLoc? 4013 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 4014 } 4015 4016 case TemplateName::DependentTemplate: { 4017 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 4018 DeclarationName DName; 4019 if (DTN->isIdentifier()) { 4020 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 4021 return DeclarationNameInfo(DName, NameLoc); 4022 } else { 4023 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 4024 // DNInfo work in progress: FIXME: source locations? 4025 DeclarationNameLoc DNLoc; 4026 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 4027 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 4028 return DeclarationNameInfo(DName, NameLoc, DNLoc); 4029 } 4030 } 4031 4032 case TemplateName::SubstTemplateTemplateParm: { 4033 SubstTemplateTemplateParmStorage *subst 4034 = Name.getAsSubstTemplateTemplateParm(); 4035 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 4036 NameLoc); 4037 } 4038 4039 case TemplateName::SubstTemplateTemplateParmPack: { 4040 SubstTemplateTemplateParmPackStorage *subst 4041 = Name.getAsSubstTemplateTemplateParmPack(); 4042 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 4043 NameLoc); 4044 } 4045 } 4046 4047 llvm_unreachable("bad template name kind!"); 4048 } 4049 4050 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 4051 switch (Name.getKind()) { 4052 case TemplateName::QualifiedTemplate: 4053 case TemplateName::Template: { 4054 TemplateDecl *Template = Name.getAsTemplateDecl(); 4055 if (TemplateTemplateParmDecl *TTP 4056 = dyn_cast<TemplateTemplateParmDecl>(Template)) 4057 Template = getCanonicalTemplateTemplateParmDecl(TTP); 4058 4059 // The canonical template name is the canonical template declaration. 4060 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 4061 } 4062 4063 case TemplateName::OverloadedTemplate: 4064 llvm_unreachable("cannot canonicalize overloaded template"); 4065 4066 case TemplateName::DependentTemplate: { 4067 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 4068 assert(DTN && "Non-dependent template names must refer to template decls."); 4069 return DTN->CanonicalTemplateName; 4070 } 4071 4072 case TemplateName::SubstTemplateTemplateParm: { 4073 SubstTemplateTemplateParmStorage *subst 4074 = Name.getAsSubstTemplateTemplateParm(); 4075 return getCanonicalTemplateName(subst->getReplacement()); 4076 } 4077 4078 case TemplateName::SubstTemplateTemplateParmPack: { 4079 SubstTemplateTemplateParmPackStorage *subst 4080 = Name.getAsSubstTemplateTemplateParmPack(); 4081 TemplateTemplateParmDecl *canonParameter 4082 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 4083 TemplateArgument canonArgPack 4084 = getCanonicalTemplateArgument(subst->getArgumentPack()); 4085 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 4086 } 4087 } 4088 4089 llvm_unreachable("bad template name!"); 4090 } 4091 4092 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 4093 X = getCanonicalTemplateName(X); 4094 Y = getCanonicalTemplateName(Y); 4095 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 4096 } 4097 4098 TemplateArgument 4099 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 4100 switch (Arg.getKind()) { 4101 case TemplateArgument::Null: 4102 return Arg; 4103 4104 case TemplateArgument::Expression: 4105 return Arg; 4106 4107 case TemplateArgument::Declaration: { 4108 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 4109 return TemplateArgument(D, Arg.isDeclForReferenceParam()); 4110 } 4111 4112 case TemplateArgument::NullPtr: 4113 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 4114 /*isNullPtr*/true); 4115 4116 case TemplateArgument::Template: 4117 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 4118 4119 case TemplateArgument::TemplateExpansion: 4120 return TemplateArgument(getCanonicalTemplateName( 4121 Arg.getAsTemplateOrTemplatePattern()), 4122 Arg.getNumTemplateExpansions()); 4123 4124 case TemplateArgument::Integral: 4125 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 4126 4127 case TemplateArgument::Type: 4128 return TemplateArgument(getCanonicalType(Arg.getAsType())); 4129 4130 case TemplateArgument::Pack: { 4131 if (Arg.pack_size() == 0) 4132 return Arg; 4133 4134 TemplateArgument *CanonArgs 4135 = new (*this) TemplateArgument[Arg.pack_size()]; 4136 unsigned Idx = 0; 4137 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 4138 AEnd = Arg.pack_end(); 4139 A != AEnd; (void)++A, ++Idx) 4140 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 4141 4142 return TemplateArgument(CanonArgs, Arg.pack_size()); 4143 } 4144 } 4145 4146 // Silence GCC warning 4147 llvm_unreachable("Unhandled template argument kind"); 4148 } 4149 4150 NestedNameSpecifier * 4151 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 4152 if (!NNS) 4153 return nullptr; 4154 4155 switch (NNS->getKind()) { 4156 case NestedNameSpecifier::Identifier: 4157 // Canonicalize the prefix but keep the identifier the same. 4158 return NestedNameSpecifier::Create(*this, 4159 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 4160 NNS->getAsIdentifier()); 4161 4162 case NestedNameSpecifier::Namespace: 4163 // A namespace is canonical; build a nested-name-specifier with 4164 // this namespace and no prefix. 4165 return NestedNameSpecifier::Create(*this, nullptr, 4166 NNS->getAsNamespace()->getOriginalNamespace()); 4167 4168 case NestedNameSpecifier::NamespaceAlias: 4169 // A namespace is canonical; build a nested-name-specifier with 4170 // this namespace and no prefix. 4171 return NestedNameSpecifier::Create(*this, nullptr, 4172 NNS->getAsNamespaceAlias()->getNamespace() 4173 ->getOriginalNamespace()); 4174 4175 case NestedNameSpecifier::TypeSpec: 4176 case NestedNameSpecifier::TypeSpecWithTemplate: { 4177 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 4178 4179 // If we have some kind of dependent-named type (e.g., "typename T::type"), 4180 // break it apart into its prefix and identifier, then reconsititute those 4181 // as the canonical nested-name-specifier. This is required to canonicalize 4182 // a dependent nested-name-specifier involving typedefs of dependent-name 4183 // types, e.g., 4184 // typedef typename T::type T1; 4185 // typedef typename T1::type T2; 4186 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) 4187 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 4188 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 4189 4190 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 4191 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 4192 // first place? 4193 return NestedNameSpecifier::Create(*this, nullptr, false, 4194 const_cast<Type *>(T.getTypePtr())); 4195 } 4196 4197 case NestedNameSpecifier::Global: 4198 case NestedNameSpecifier::Super: 4199 // The global specifier and __super specifer are canonical and unique. 4200 return NNS; 4201 } 4202 4203 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 4204 } 4205 4206 4207 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 4208 // Handle the non-qualified case efficiently. 4209 if (!T.hasLocalQualifiers()) { 4210 // Handle the common positive case fast. 4211 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 4212 return AT; 4213 } 4214 4215 // Handle the common negative case fast. 4216 if (!isa<ArrayType>(T.getCanonicalType())) 4217 return nullptr; 4218 4219 // Apply any qualifiers from the array type to the element type. This 4220 // implements C99 6.7.3p8: "If the specification of an array type includes 4221 // any type qualifiers, the element type is so qualified, not the array type." 4222 4223 // If we get here, we either have type qualifiers on the type, or we have 4224 // sugar such as a typedef in the way. If we have type qualifiers on the type 4225 // we must propagate them down into the element type. 4226 4227 SplitQualType split = T.getSplitDesugaredType(); 4228 Qualifiers qs = split.Quals; 4229 4230 // If we have a simple case, just return now. 4231 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty); 4232 if (!ATy || qs.empty()) 4233 return ATy; 4234 4235 // Otherwise, we have an array and we have qualifiers on it. Push the 4236 // qualifiers into the array element type and return a new array type. 4237 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 4238 4239 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 4240 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 4241 CAT->getSizeModifier(), 4242 CAT->getIndexTypeCVRQualifiers())); 4243 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 4244 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 4245 IAT->getSizeModifier(), 4246 IAT->getIndexTypeCVRQualifiers())); 4247 4248 if (const DependentSizedArrayType *DSAT 4249 = dyn_cast<DependentSizedArrayType>(ATy)) 4250 return cast<ArrayType>( 4251 getDependentSizedArrayType(NewEltTy, 4252 DSAT->getSizeExpr(), 4253 DSAT->getSizeModifier(), 4254 DSAT->getIndexTypeCVRQualifiers(), 4255 DSAT->getBracketsRange())); 4256 4257 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 4258 return cast<ArrayType>(getVariableArrayType(NewEltTy, 4259 VAT->getSizeExpr(), 4260 VAT->getSizeModifier(), 4261 VAT->getIndexTypeCVRQualifiers(), 4262 VAT->getBracketsRange())); 4263 } 4264 4265 QualType ASTContext::getAdjustedParameterType(QualType T) const { 4266 if (T->isArrayType() || T->isFunctionType()) 4267 return getDecayedType(T); 4268 return T; 4269 } 4270 4271 QualType ASTContext::getSignatureParameterType(QualType T) const { 4272 T = getVariableArrayDecayedType(T); 4273 T = getAdjustedParameterType(T); 4274 return T.getUnqualifiedType(); 4275 } 4276 4277 /// getArrayDecayedType - Return the properly qualified result of decaying the 4278 /// specified array type to a pointer. This operation is non-trivial when 4279 /// handling typedefs etc. The canonical type of "T" must be an array type, 4280 /// this returns a pointer to a properly qualified element of the array. 4281 /// 4282 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 4283 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 4284 // Get the element type with 'getAsArrayType' so that we don't lose any 4285 // typedefs in the element type of the array. This also handles propagation 4286 // of type qualifiers from the array type into the element type if present 4287 // (C99 6.7.3p8). 4288 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 4289 assert(PrettyArrayType && "Not an array type!"); 4290 4291 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 4292 4293 // int x[restrict 4] -> int *restrict 4294 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 4295 } 4296 4297 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 4298 return getBaseElementType(array->getElementType()); 4299 } 4300 4301 QualType ASTContext::getBaseElementType(QualType type) const { 4302 Qualifiers qs; 4303 while (true) { 4304 SplitQualType split = type.getSplitDesugaredType(); 4305 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 4306 if (!array) break; 4307 4308 type = array->getElementType(); 4309 qs.addConsistentQualifiers(split.Quals); 4310 } 4311 4312 return getQualifiedType(type, qs); 4313 } 4314 4315 /// getConstantArrayElementCount - Returns number of constant array elements. 4316 uint64_t 4317 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 4318 uint64_t ElementCount = 1; 4319 do { 4320 ElementCount *= CA->getSize().getZExtValue(); 4321 CA = dyn_cast_or_null<ConstantArrayType>( 4322 CA->getElementType()->getAsArrayTypeUnsafe()); 4323 } while (CA); 4324 return ElementCount; 4325 } 4326 4327 /// getFloatingRank - Return a relative rank for floating point types. 4328 /// This routine will assert if passed a built-in type that isn't a float. 4329 static FloatingRank getFloatingRank(QualType T) { 4330 if (const ComplexType *CT = T->getAs<ComplexType>()) 4331 return getFloatingRank(CT->getElementType()); 4332 4333 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 4334 switch (T->getAs<BuiltinType>()->getKind()) { 4335 default: llvm_unreachable("getFloatingRank(): not a floating type"); 4336 case BuiltinType::Half: return HalfRank; 4337 case BuiltinType::Float: return FloatRank; 4338 case BuiltinType::Double: return DoubleRank; 4339 case BuiltinType::LongDouble: return LongDoubleRank; 4340 } 4341 } 4342 4343 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 4344 /// point or a complex type (based on typeDomain/typeSize). 4345 /// 'typeDomain' is a real floating point or complex type. 4346 /// 'typeSize' is a real floating point or complex type. 4347 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 4348 QualType Domain) const { 4349 FloatingRank EltRank = getFloatingRank(Size); 4350 if (Domain->isComplexType()) { 4351 switch (EltRank) { 4352 case HalfRank: llvm_unreachable("Complex half is not supported"); 4353 case FloatRank: return FloatComplexTy; 4354 case DoubleRank: return DoubleComplexTy; 4355 case LongDoubleRank: return LongDoubleComplexTy; 4356 } 4357 } 4358 4359 assert(Domain->isRealFloatingType() && "Unknown domain!"); 4360 switch (EltRank) { 4361 case HalfRank: return HalfTy; 4362 case FloatRank: return FloatTy; 4363 case DoubleRank: return DoubleTy; 4364 case LongDoubleRank: return LongDoubleTy; 4365 } 4366 llvm_unreachable("getFloatingRank(): illegal value for rank"); 4367 } 4368 4369 /// getFloatingTypeOrder - Compare the rank of the two specified floating 4370 /// point types, ignoring the domain of the type (i.e. 'double' == 4371 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 4372 /// LHS < RHS, return -1. 4373 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 4374 FloatingRank LHSR = getFloatingRank(LHS); 4375 FloatingRank RHSR = getFloatingRank(RHS); 4376 4377 if (LHSR == RHSR) 4378 return 0; 4379 if (LHSR > RHSR) 4380 return 1; 4381 return -1; 4382 } 4383 4384 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 4385 /// routine will assert if passed a built-in type that isn't an integer or enum, 4386 /// or if it is not canonicalized. 4387 unsigned ASTContext::getIntegerRank(const Type *T) const { 4388 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 4389 4390 switch (cast<BuiltinType>(T)->getKind()) { 4391 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 4392 case BuiltinType::Bool: 4393 return 1 + (getIntWidth(BoolTy) << 3); 4394 case BuiltinType::Char_S: 4395 case BuiltinType::Char_U: 4396 case BuiltinType::SChar: 4397 case BuiltinType::UChar: 4398 return 2 + (getIntWidth(CharTy) << 3); 4399 case BuiltinType::Short: 4400 case BuiltinType::UShort: 4401 return 3 + (getIntWidth(ShortTy) << 3); 4402 case BuiltinType::Int: 4403 case BuiltinType::UInt: 4404 return 4 + (getIntWidth(IntTy) << 3); 4405 case BuiltinType::Long: 4406 case BuiltinType::ULong: 4407 return 5 + (getIntWidth(LongTy) << 3); 4408 case BuiltinType::LongLong: 4409 case BuiltinType::ULongLong: 4410 return 6 + (getIntWidth(LongLongTy) << 3); 4411 case BuiltinType::Int128: 4412 case BuiltinType::UInt128: 4413 return 7 + (getIntWidth(Int128Ty) << 3); 4414 } 4415 } 4416 4417 /// \brief Whether this is a promotable bitfield reference according 4418 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 4419 /// 4420 /// \returns the type this bit-field will promote to, or NULL if no 4421 /// promotion occurs. 4422 QualType ASTContext::isPromotableBitField(Expr *E) const { 4423 if (E->isTypeDependent() || E->isValueDependent()) 4424 return QualType(); 4425 4426 // FIXME: We should not do this unless E->refersToBitField() is true. This 4427 // matters in C where getSourceBitField() will find bit-fields for various 4428 // cases where the source expression is not a bit-field designator. 4429 4430 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 4431 if (!Field) 4432 return QualType(); 4433 4434 QualType FT = Field->getType(); 4435 4436 uint64_t BitWidth = Field->getBitWidthValue(*this); 4437 uint64_t IntSize = getTypeSize(IntTy); 4438 // C++ [conv.prom]p5: 4439 // A prvalue for an integral bit-field can be converted to a prvalue of type 4440 // int if int can represent all the values of the bit-field; otherwise, it 4441 // can be converted to unsigned int if unsigned int can represent all the 4442 // values of the bit-field. If the bit-field is larger yet, no integral 4443 // promotion applies to it. 4444 // C11 6.3.1.1/2: 4445 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 4446 // If an int can represent all values of the original type (as restricted by 4447 // the width, for a bit-field), the value is converted to an int; otherwise, 4448 // it is converted to an unsigned int. 4449 // 4450 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 4451 // We perform that promotion here to match GCC and C++. 4452 if (BitWidth < IntSize) 4453 return IntTy; 4454 4455 if (BitWidth == IntSize) 4456 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 4457 4458 // Types bigger than int are not subject to promotions, and therefore act 4459 // like the base type. GCC has some weird bugs in this area that we 4460 // deliberately do not follow (GCC follows a pre-standard resolution to 4461 // C's DR315 which treats bit-width as being part of the type, and this leaks 4462 // into their semantics in some cases). 4463 return QualType(); 4464 } 4465 4466 /// getPromotedIntegerType - Returns the type that Promotable will 4467 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 4468 /// integer type. 4469 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 4470 assert(!Promotable.isNull()); 4471 assert(Promotable->isPromotableIntegerType()); 4472 if (const EnumType *ET = Promotable->getAs<EnumType>()) 4473 return ET->getDecl()->getPromotionType(); 4474 4475 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 4476 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 4477 // (3.9.1) can be converted to a prvalue of the first of the following 4478 // types that can represent all the values of its underlying type: 4479 // int, unsigned int, long int, unsigned long int, long long int, or 4480 // unsigned long long int [...] 4481 // FIXME: Is there some better way to compute this? 4482 if (BT->getKind() == BuiltinType::WChar_S || 4483 BT->getKind() == BuiltinType::WChar_U || 4484 BT->getKind() == BuiltinType::Char16 || 4485 BT->getKind() == BuiltinType::Char32) { 4486 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 4487 uint64_t FromSize = getTypeSize(BT); 4488 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 4489 LongLongTy, UnsignedLongLongTy }; 4490 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 4491 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 4492 if (FromSize < ToSize || 4493 (FromSize == ToSize && 4494 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 4495 return PromoteTypes[Idx]; 4496 } 4497 llvm_unreachable("char type should fit into long long"); 4498 } 4499 } 4500 4501 // At this point, we should have a signed or unsigned integer type. 4502 if (Promotable->isSignedIntegerType()) 4503 return IntTy; 4504 uint64_t PromotableSize = getIntWidth(Promotable); 4505 uint64_t IntSize = getIntWidth(IntTy); 4506 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 4507 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 4508 } 4509 4510 /// \brief Recurses in pointer/array types until it finds an objc retainable 4511 /// type and returns its ownership. 4512 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 4513 while (!T.isNull()) { 4514 if (T.getObjCLifetime() != Qualifiers::OCL_None) 4515 return T.getObjCLifetime(); 4516 if (T->isArrayType()) 4517 T = getBaseElementType(T); 4518 else if (const PointerType *PT = T->getAs<PointerType>()) 4519 T = PT->getPointeeType(); 4520 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 4521 T = RT->getPointeeType(); 4522 else 4523 break; 4524 } 4525 4526 return Qualifiers::OCL_None; 4527 } 4528 4529 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 4530 // Incomplete enum types are not treated as integer types. 4531 // FIXME: In C++, enum types are never integer types. 4532 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 4533 return ET->getDecl()->getIntegerType().getTypePtr(); 4534 return nullptr; 4535 } 4536 4537 /// getIntegerTypeOrder - Returns the highest ranked integer type: 4538 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 4539 /// LHS < RHS, return -1. 4540 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 4541 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 4542 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 4543 4544 // Unwrap enums to their underlying type. 4545 if (const EnumType *ET = dyn_cast<EnumType>(LHSC)) 4546 LHSC = getIntegerTypeForEnum(ET); 4547 if (const EnumType *ET = dyn_cast<EnumType>(RHSC)) 4548 RHSC = getIntegerTypeForEnum(ET); 4549 4550 if (LHSC == RHSC) return 0; 4551 4552 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 4553 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 4554 4555 unsigned LHSRank = getIntegerRank(LHSC); 4556 unsigned RHSRank = getIntegerRank(RHSC); 4557 4558 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 4559 if (LHSRank == RHSRank) return 0; 4560 return LHSRank > RHSRank ? 1 : -1; 4561 } 4562 4563 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 4564 if (LHSUnsigned) { 4565 // If the unsigned [LHS] type is larger, return it. 4566 if (LHSRank >= RHSRank) 4567 return 1; 4568 4569 // If the signed type can represent all values of the unsigned type, it 4570 // wins. Because we are dealing with 2's complement and types that are 4571 // powers of two larger than each other, this is always safe. 4572 return -1; 4573 } 4574 4575 // If the unsigned [RHS] type is larger, return it. 4576 if (RHSRank >= LHSRank) 4577 return -1; 4578 4579 // If the signed type can represent all values of the unsigned type, it 4580 // wins. Because we are dealing with 2's complement and types that are 4581 // powers of two larger than each other, this is always safe. 4582 return 1; 4583 } 4584 4585 // getCFConstantStringType - Return the type used for constant CFStrings. 4586 QualType ASTContext::getCFConstantStringType() const { 4587 if (!CFConstantStringTypeDecl) { 4588 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString"); 4589 CFConstantStringTypeDecl->startDefinition(); 4590 4591 QualType FieldTypes[4]; 4592 4593 // const int *isa; 4594 FieldTypes[0] = getPointerType(IntTy.withConst()); 4595 // int flags; 4596 FieldTypes[1] = IntTy; 4597 // const char *str; 4598 FieldTypes[2] = getPointerType(CharTy.withConst()); 4599 // long length; 4600 FieldTypes[3] = LongTy; 4601 4602 // Create fields 4603 for (unsigned i = 0; i < 4; ++i) { 4604 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 4605 SourceLocation(), 4606 SourceLocation(), nullptr, 4607 FieldTypes[i], /*TInfo=*/nullptr, 4608 /*BitWidth=*/nullptr, 4609 /*Mutable=*/false, 4610 ICIS_NoInit); 4611 Field->setAccess(AS_public); 4612 CFConstantStringTypeDecl->addDecl(Field); 4613 } 4614 4615 CFConstantStringTypeDecl->completeDefinition(); 4616 } 4617 4618 return getTagDeclType(CFConstantStringTypeDecl); 4619 } 4620 4621 QualType ASTContext::getObjCSuperType() const { 4622 if (ObjCSuperType.isNull()) { 4623 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 4624 TUDecl->addDecl(ObjCSuperTypeDecl); 4625 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 4626 } 4627 return ObjCSuperType; 4628 } 4629 4630 void ASTContext::setCFConstantStringType(QualType T) { 4631 const RecordType *Rec = T->getAs<RecordType>(); 4632 assert(Rec && "Invalid CFConstantStringType"); 4633 CFConstantStringTypeDecl = Rec->getDecl(); 4634 } 4635 4636 QualType ASTContext::getBlockDescriptorType() const { 4637 if (BlockDescriptorType) 4638 return getTagDeclType(BlockDescriptorType); 4639 4640 RecordDecl *RD; 4641 // FIXME: Needs the FlagAppleBlock bit. 4642 RD = buildImplicitRecord("__block_descriptor"); 4643 RD->startDefinition(); 4644 4645 QualType FieldTypes[] = { 4646 UnsignedLongTy, 4647 UnsignedLongTy, 4648 }; 4649 4650 static const char *const FieldNames[] = { 4651 "reserved", 4652 "Size" 4653 }; 4654 4655 for (size_t i = 0; i < 2; ++i) { 4656 FieldDecl *Field = FieldDecl::Create( 4657 *this, RD, SourceLocation(), SourceLocation(), 4658 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 4659 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 4660 Field->setAccess(AS_public); 4661 RD->addDecl(Field); 4662 } 4663 4664 RD->completeDefinition(); 4665 4666 BlockDescriptorType = RD; 4667 4668 return getTagDeclType(BlockDescriptorType); 4669 } 4670 4671 QualType ASTContext::getBlockDescriptorExtendedType() const { 4672 if (BlockDescriptorExtendedType) 4673 return getTagDeclType(BlockDescriptorExtendedType); 4674 4675 RecordDecl *RD; 4676 // FIXME: Needs the FlagAppleBlock bit. 4677 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 4678 RD->startDefinition(); 4679 4680 QualType FieldTypes[] = { 4681 UnsignedLongTy, 4682 UnsignedLongTy, 4683 getPointerType(VoidPtrTy), 4684 getPointerType(VoidPtrTy) 4685 }; 4686 4687 static const char *const FieldNames[] = { 4688 "reserved", 4689 "Size", 4690 "CopyFuncPtr", 4691 "DestroyFuncPtr" 4692 }; 4693 4694 for (size_t i = 0; i < 4; ++i) { 4695 FieldDecl *Field = FieldDecl::Create( 4696 *this, RD, SourceLocation(), SourceLocation(), 4697 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 4698 /*BitWidth=*/nullptr, 4699 /*Mutable=*/false, ICIS_NoInit); 4700 Field->setAccess(AS_public); 4701 RD->addDecl(Field); 4702 } 4703 4704 RD->completeDefinition(); 4705 4706 BlockDescriptorExtendedType = RD; 4707 return getTagDeclType(BlockDescriptorExtendedType); 4708 } 4709 4710 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 4711 /// requires copy/dispose. Note that this must match the logic 4712 /// in buildByrefHelpers. 4713 bool ASTContext::BlockRequiresCopying(QualType Ty, 4714 const VarDecl *D) { 4715 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 4716 const Expr *copyExpr = getBlockVarCopyInits(D); 4717 if (!copyExpr && record->hasTrivialDestructor()) return false; 4718 4719 return true; 4720 } 4721 4722 if (!Ty->isObjCRetainableType()) return false; 4723 4724 Qualifiers qs = Ty.getQualifiers(); 4725 4726 // If we have lifetime, that dominates. 4727 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 4728 assert(getLangOpts().ObjCAutoRefCount); 4729 4730 switch (lifetime) { 4731 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 4732 4733 // These are just bits as far as the runtime is concerned. 4734 case Qualifiers::OCL_ExplicitNone: 4735 case Qualifiers::OCL_Autoreleasing: 4736 return false; 4737 4738 // Tell the runtime that this is ARC __weak, called by the 4739 // byref routines. 4740 case Qualifiers::OCL_Weak: 4741 // ARC __strong __block variables need to be retained. 4742 case Qualifiers::OCL_Strong: 4743 return true; 4744 } 4745 llvm_unreachable("fell out of lifetime switch!"); 4746 } 4747 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 4748 Ty->isObjCObjectPointerType()); 4749 } 4750 4751 bool ASTContext::getByrefLifetime(QualType Ty, 4752 Qualifiers::ObjCLifetime &LifeTime, 4753 bool &HasByrefExtendedLayout) const { 4754 4755 if (!getLangOpts().ObjC1 || 4756 getLangOpts().getGC() != LangOptions::NonGC) 4757 return false; 4758 4759 HasByrefExtendedLayout = false; 4760 if (Ty->isRecordType()) { 4761 HasByrefExtendedLayout = true; 4762 LifeTime = Qualifiers::OCL_None; 4763 } 4764 else if (getLangOpts().ObjCAutoRefCount) 4765 LifeTime = Ty.getObjCLifetime(); 4766 // MRR. 4767 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 4768 LifeTime = Qualifiers::OCL_ExplicitNone; 4769 else 4770 LifeTime = Qualifiers::OCL_None; 4771 return true; 4772 } 4773 4774 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 4775 if (!ObjCInstanceTypeDecl) 4776 ObjCInstanceTypeDecl = 4777 buildImplicitTypedef(getObjCIdType(), "instancetype"); 4778 return ObjCInstanceTypeDecl; 4779 } 4780 4781 // This returns true if a type has been typedefed to BOOL: 4782 // typedef <type> BOOL; 4783 static bool isTypeTypedefedAsBOOL(QualType T) { 4784 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 4785 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 4786 return II->isStr("BOOL"); 4787 4788 return false; 4789 } 4790 4791 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 4792 /// purpose. 4793 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 4794 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 4795 return CharUnits::Zero(); 4796 4797 CharUnits sz = getTypeSizeInChars(type); 4798 4799 // Make all integer and enum types at least as large as an int 4800 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 4801 sz = std::max(sz, getTypeSizeInChars(IntTy)); 4802 // Treat arrays as pointers, since that's how they're passed in. 4803 else if (type->isArrayType()) 4804 sz = getTypeSizeInChars(VoidPtrTy); 4805 return sz; 4806 } 4807 4808 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 4809 return getLangOpts().MSVCCompat && VD->isStaticDataMember() && 4810 VD->getType()->isIntegralOrEnumerationType() && 4811 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 4812 } 4813 4814 static inline 4815 std::string charUnitsToString(const CharUnits &CU) { 4816 return llvm::itostr(CU.getQuantity()); 4817 } 4818 4819 /// getObjCEncodingForBlock - Return the encoded type for this block 4820 /// declaration. 4821 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 4822 std::string S; 4823 4824 const BlockDecl *Decl = Expr->getBlockDecl(); 4825 QualType BlockTy = 4826 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 4827 // Encode result type. 4828 if (getLangOpts().EncodeExtendedBlockSig) 4829 getObjCEncodingForMethodParameter( 4830 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S, 4831 true /*Extended*/); 4832 else 4833 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S); 4834 // Compute size of all parameters. 4835 // Start with computing size of a pointer in number of bytes. 4836 // FIXME: There might(should) be a better way of doing this computation! 4837 SourceLocation Loc; 4838 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4839 CharUnits ParmOffset = PtrSize; 4840 for (auto PI : Decl->params()) { 4841 QualType PType = PI->getType(); 4842 CharUnits sz = getObjCEncodingTypeSize(PType); 4843 if (sz.isZero()) 4844 continue; 4845 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 4846 ParmOffset += sz; 4847 } 4848 // Size of the argument frame 4849 S += charUnitsToString(ParmOffset); 4850 // Block pointer and offset. 4851 S += "@?0"; 4852 4853 // Argument types. 4854 ParmOffset = PtrSize; 4855 for (auto PVDecl : Decl->params()) { 4856 QualType PType = PVDecl->getOriginalType(); 4857 if (const ArrayType *AT = 4858 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4859 // Use array's original type only if it has known number of 4860 // elements. 4861 if (!isa<ConstantArrayType>(AT)) 4862 PType = PVDecl->getType(); 4863 } else if (PType->isFunctionType()) 4864 PType = PVDecl->getType(); 4865 if (getLangOpts().EncodeExtendedBlockSig) 4866 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 4867 S, true /*Extended*/); 4868 else 4869 getObjCEncodingForType(PType, S); 4870 S += charUnitsToString(ParmOffset); 4871 ParmOffset += getObjCEncodingTypeSize(PType); 4872 } 4873 4874 return S; 4875 } 4876 4877 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, 4878 std::string& S) { 4879 // Encode result type. 4880 getObjCEncodingForType(Decl->getReturnType(), S); 4881 CharUnits ParmOffset; 4882 // Compute size of all parameters. 4883 for (auto PI : Decl->params()) { 4884 QualType PType = PI->getType(); 4885 CharUnits sz = getObjCEncodingTypeSize(PType); 4886 if (sz.isZero()) 4887 continue; 4888 4889 assert (sz.isPositive() && 4890 "getObjCEncodingForFunctionDecl - Incomplete param type"); 4891 ParmOffset += sz; 4892 } 4893 S += charUnitsToString(ParmOffset); 4894 ParmOffset = CharUnits::Zero(); 4895 4896 // Argument types. 4897 for (auto PVDecl : Decl->params()) { 4898 QualType PType = PVDecl->getOriginalType(); 4899 if (const ArrayType *AT = 4900 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4901 // Use array's original type only if it has known number of 4902 // elements. 4903 if (!isa<ConstantArrayType>(AT)) 4904 PType = PVDecl->getType(); 4905 } else if (PType->isFunctionType()) 4906 PType = PVDecl->getType(); 4907 getObjCEncodingForType(PType, S); 4908 S += charUnitsToString(ParmOffset); 4909 ParmOffset += getObjCEncodingTypeSize(PType); 4910 } 4911 4912 return false; 4913 } 4914 4915 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 4916 /// method parameter or return type. If Extended, include class names and 4917 /// block object types. 4918 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 4919 QualType T, std::string& S, 4920 bool Extended) const { 4921 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 4922 getObjCEncodingForTypeQualifier(QT, S); 4923 // Encode parameter type. 4924 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 4925 true /*OutermostType*/, 4926 false /*EncodingProperty*/, 4927 false /*StructField*/, 4928 Extended /*EncodeBlockParameters*/, 4929 Extended /*EncodeClassNames*/); 4930 } 4931 4932 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 4933 /// declaration. 4934 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 4935 std::string& S, 4936 bool Extended) const { 4937 // FIXME: This is not very efficient. 4938 // Encode return type. 4939 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 4940 Decl->getReturnType(), S, Extended); 4941 // Compute size of all parameters. 4942 // Start with computing size of a pointer in number of bytes. 4943 // FIXME: There might(should) be a better way of doing this computation! 4944 SourceLocation Loc; 4945 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4946 // The first two arguments (self and _cmd) are pointers; account for 4947 // their size. 4948 CharUnits ParmOffset = 2 * PtrSize; 4949 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4950 E = Decl->sel_param_end(); PI != E; ++PI) { 4951 QualType PType = (*PI)->getType(); 4952 CharUnits sz = getObjCEncodingTypeSize(PType); 4953 if (sz.isZero()) 4954 continue; 4955 4956 assert (sz.isPositive() && 4957 "getObjCEncodingForMethodDecl - Incomplete param type"); 4958 ParmOffset += sz; 4959 } 4960 S += charUnitsToString(ParmOffset); 4961 S += "@0:"; 4962 S += charUnitsToString(PtrSize); 4963 4964 // Argument types. 4965 ParmOffset = 2 * PtrSize; 4966 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4967 E = Decl->sel_param_end(); PI != E; ++PI) { 4968 const ParmVarDecl *PVDecl = *PI; 4969 QualType PType = PVDecl->getOriginalType(); 4970 if (const ArrayType *AT = 4971 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4972 // Use array's original type only if it has known number of 4973 // elements. 4974 if (!isa<ConstantArrayType>(AT)) 4975 PType = PVDecl->getType(); 4976 } else if (PType->isFunctionType()) 4977 PType = PVDecl->getType(); 4978 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 4979 PType, S, Extended); 4980 S += charUnitsToString(ParmOffset); 4981 ParmOffset += getObjCEncodingTypeSize(PType); 4982 } 4983 4984 return false; 4985 } 4986 4987 ObjCPropertyImplDecl * 4988 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 4989 const ObjCPropertyDecl *PD, 4990 const Decl *Container) const { 4991 if (!Container) 4992 return nullptr; 4993 if (const ObjCCategoryImplDecl *CID = 4994 dyn_cast<ObjCCategoryImplDecl>(Container)) { 4995 for (auto *PID : CID->property_impls()) 4996 if (PID->getPropertyDecl() == PD) 4997 return PID; 4998 } else { 4999 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 5000 for (auto *PID : OID->property_impls()) 5001 if (PID->getPropertyDecl() == PD) 5002 return PID; 5003 } 5004 return nullptr; 5005 } 5006 5007 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 5008 /// property declaration. If non-NULL, Container must be either an 5009 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 5010 /// NULL when getting encodings for protocol properties. 5011 /// Property attributes are stored as a comma-delimited C string. The simple 5012 /// attributes readonly and bycopy are encoded as single characters. The 5013 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 5014 /// encoded as single characters, followed by an identifier. Property types 5015 /// are also encoded as a parametrized attribute. The characters used to encode 5016 /// these attributes are defined by the following enumeration: 5017 /// @code 5018 /// enum PropertyAttributes { 5019 /// kPropertyReadOnly = 'R', // property is read-only. 5020 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 5021 /// kPropertyByref = '&', // property is a reference to the value last assigned 5022 /// kPropertyDynamic = 'D', // property is dynamic 5023 /// kPropertyGetter = 'G', // followed by getter selector name 5024 /// kPropertySetter = 'S', // followed by setter selector name 5025 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 5026 /// kPropertyType = 'T' // followed by old-style type encoding. 5027 /// kPropertyWeak = 'W' // 'weak' property 5028 /// kPropertyStrong = 'P' // property GC'able 5029 /// kPropertyNonAtomic = 'N' // property non-atomic 5030 /// }; 5031 /// @endcode 5032 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 5033 const Decl *Container, 5034 std::string& S) const { 5035 // Collect information from the property implementation decl(s). 5036 bool Dynamic = false; 5037 ObjCPropertyImplDecl *SynthesizePID = nullptr; 5038 5039 if (ObjCPropertyImplDecl *PropertyImpDecl = 5040 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 5041 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 5042 Dynamic = true; 5043 else 5044 SynthesizePID = PropertyImpDecl; 5045 } 5046 5047 // FIXME: This is not very efficient. 5048 S = "T"; 5049 5050 // Encode result type. 5051 // GCC has some special rules regarding encoding of properties which 5052 // closely resembles encoding of ivars. 5053 getObjCEncodingForPropertyType(PD->getType(), S); 5054 5055 if (PD->isReadOnly()) { 5056 S += ",R"; 5057 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) 5058 S += ",C"; 5059 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) 5060 S += ",&"; 5061 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) 5062 S += ",W"; 5063 } else { 5064 switch (PD->getSetterKind()) { 5065 case ObjCPropertyDecl::Assign: break; 5066 case ObjCPropertyDecl::Copy: S += ",C"; break; 5067 case ObjCPropertyDecl::Retain: S += ",&"; break; 5068 case ObjCPropertyDecl::Weak: S += ",W"; break; 5069 } 5070 } 5071 5072 // It really isn't clear at all what this means, since properties 5073 // are "dynamic by default". 5074 if (Dynamic) 5075 S += ",D"; 5076 5077 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 5078 S += ",N"; 5079 5080 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 5081 S += ",G"; 5082 S += PD->getGetterName().getAsString(); 5083 } 5084 5085 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 5086 S += ",S"; 5087 S += PD->getSetterName().getAsString(); 5088 } 5089 5090 if (SynthesizePID) { 5091 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 5092 S += ",V"; 5093 S += OID->getNameAsString(); 5094 } 5095 5096 // FIXME: OBJCGC: weak & strong 5097 } 5098 5099 /// getLegacyIntegralTypeEncoding - 5100 /// Another legacy compatibility encoding: 32-bit longs are encoded as 5101 /// 'l' or 'L' , but not always. For typedefs, we need to use 5102 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 5103 /// 5104 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 5105 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 5106 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 5107 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 5108 PointeeTy = UnsignedIntTy; 5109 else 5110 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 5111 PointeeTy = IntTy; 5112 } 5113 } 5114 } 5115 5116 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 5117 const FieldDecl *Field, 5118 QualType *NotEncodedT) const { 5119 // We follow the behavior of gcc, expanding structures which are 5120 // directly pointed to, and expanding embedded structures. Note that 5121 // these rules are sufficient to prevent recursive encoding of the 5122 // same type. 5123 getObjCEncodingForTypeImpl(T, S, true, true, Field, 5124 true /* outermost type */, false, false, 5125 false, false, false, NotEncodedT); 5126 } 5127 5128 void ASTContext::getObjCEncodingForPropertyType(QualType T, 5129 std::string& S) const { 5130 // Encode result type. 5131 // GCC has some special rules regarding encoding of properties which 5132 // closely resembles encoding of ivars. 5133 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 5134 true /* outermost type */, 5135 true /* encoding property */); 5136 } 5137 5138 static char getObjCEncodingForPrimitiveKind(const ASTContext *C, 5139 BuiltinType::Kind kind) { 5140 switch (kind) { 5141 case BuiltinType::Void: return 'v'; 5142 case BuiltinType::Bool: return 'B'; 5143 case BuiltinType::Char_U: 5144 case BuiltinType::UChar: return 'C'; 5145 case BuiltinType::Char16: 5146 case BuiltinType::UShort: return 'S'; 5147 case BuiltinType::Char32: 5148 case BuiltinType::UInt: return 'I'; 5149 case BuiltinType::ULong: 5150 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 5151 case BuiltinType::UInt128: return 'T'; 5152 case BuiltinType::ULongLong: return 'Q'; 5153 case BuiltinType::Char_S: 5154 case BuiltinType::SChar: return 'c'; 5155 case BuiltinType::Short: return 's'; 5156 case BuiltinType::WChar_S: 5157 case BuiltinType::WChar_U: 5158 case BuiltinType::Int: return 'i'; 5159 case BuiltinType::Long: 5160 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 5161 case BuiltinType::LongLong: return 'q'; 5162 case BuiltinType::Int128: return 't'; 5163 case BuiltinType::Float: return 'f'; 5164 case BuiltinType::Double: return 'd'; 5165 case BuiltinType::LongDouble: return 'D'; 5166 case BuiltinType::NullPtr: return '*'; // like char* 5167 5168 case BuiltinType::Half: 5169 // FIXME: potentially need @encodes for these! 5170 return ' '; 5171 5172 case BuiltinType::ObjCId: 5173 case BuiltinType::ObjCClass: 5174 case BuiltinType::ObjCSel: 5175 llvm_unreachable("@encoding ObjC primitive type"); 5176 5177 // OpenCL and placeholder types don't need @encodings. 5178 case BuiltinType::OCLImage1d: 5179 case BuiltinType::OCLImage1dArray: 5180 case BuiltinType::OCLImage1dBuffer: 5181 case BuiltinType::OCLImage2d: 5182 case BuiltinType::OCLImage2dArray: 5183 case BuiltinType::OCLImage3d: 5184 case BuiltinType::OCLEvent: 5185 case BuiltinType::OCLSampler: 5186 case BuiltinType::Dependent: 5187 #define BUILTIN_TYPE(KIND, ID) 5188 #define PLACEHOLDER_TYPE(KIND, ID) \ 5189 case BuiltinType::KIND: 5190 #include "clang/AST/BuiltinTypes.def" 5191 llvm_unreachable("invalid builtin type for @encode"); 5192 } 5193 llvm_unreachable("invalid BuiltinType::Kind value"); 5194 } 5195 5196 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 5197 EnumDecl *Enum = ET->getDecl(); 5198 5199 // The encoding of an non-fixed enum type is always 'i', regardless of size. 5200 if (!Enum->isFixed()) 5201 return 'i'; 5202 5203 // The encoding of a fixed enum type matches its fixed underlying type. 5204 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 5205 return getObjCEncodingForPrimitiveKind(C, BT->getKind()); 5206 } 5207 5208 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 5209 QualType T, const FieldDecl *FD) { 5210 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 5211 S += 'b'; 5212 // The NeXT runtime encodes bit fields as b followed by the number of bits. 5213 // The GNU runtime requires more information; bitfields are encoded as b, 5214 // then the offset (in bits) of the first element, then the type of the 5215 // bitfield, then the size in bits. For example, in this structure: 5216 // 5217 // struct 5218 // { 5219 // int integer; 5220 // int flags:2; 5221 // }; 5222 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 5223 // runtime, but b32i2 for the GNU runtime. The reason for this extra 5224 // information is not especially sensible, but we're stuck with it for 5225 // compatibility with GCC, although providing it breaks anything that 5226 // actually uses runtime introspection and wants to work on both runtimes... 5227 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 5228 const RecordDecl *RD = FD->getParent(); 5229 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 5230 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); 5231 if (const EnumType *ET = T->getAs<EnumType>()) 5232 S += ObjCEncodingForEnumType(Ctx, ET); 5233 else { 5234 const BuiltinType *BT = T->castAs<BuiltinType>(); 5235 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind()); 5236 } 5237 } 5238 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 5239 } 5240 5241 // FIXME: Use SmallString for accumulating string. 5242 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 5243 bool ExpandPointedToStructures, 5244 bool ExpandStructures, 5245 const FieldDecl *FD, 5246 bool OutermostType, 5247 bool EncodingProperty, 5248 bool StructField, 5249 bool EncodeBlockParameters, 5250 bool EncodeClassNames, 5251 bool EncodePointerToObjCTypedef, 5252 QualType *NotEncodedT) const { 5253 CanQualType CT = getCanonicalType(T); 5254 switch (CT->getTypeClass()) { 5255 case Type::Builtin: 5256 case Type::Enum: 5257 if (FD && FD->isBitField()) 5258 return EncodeBitField(this, S, T, FD); 5259 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT)) 5260 S += getObjCEncodingForPrimitiveKind(this, BT->getKind()); 5261 else 5262 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 5263 return; 5264 5265 case Type::Complex: { 5266 const ComplexType *CT = T->castAs<ComplexType>(); 5267 S += 'j'; 5268 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr); 5269 return; 5270 } 5271 5272 case Type::Atomic: { 5273 const AtomicType *AT = T->castAs<AtomicType>(); 5274 S += 'A'; 5275 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr); 5276 return; 5277 } 5278 5279 // encoding for pointer or reference types. 5280 case Type::Pointer: 5281 case Type::LValueReference: 5282 case Type::RValueReference: { 5283 QualType PointeeTy; 5284 if (isa<PointerType>(CT)) { 5285 const PointerType *PT = T->castAs<PointerType>(); 5286 if (PT->isObjCSelType()) { 5287 S += ':'; 5288 return; 5289 } 5290 PointeeTy = PT->getPointeeType(); 5291 } else { 5292 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 5293 } 5294 5295 bool isReadOnly = false; 5296 // For historical/compatibility reasons, the read-only qualifier of the 5297 // pointee gets emitted _before_ the '^'. The read-only qualifier of 5298 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 5299 // Also, do not emit the 'r' for anything but the outermost type! 5300 if (isa<TypedefType>(T.getTypePtr())) { 5301 if (OutermostType && T.isConstQualified()) { 5302 isReadOnly = true; 5303 S += 'r'; 5304 } 5305 } else if (OutermostType) { 5306 QualType P = PointeeTy; 5307 while (P->getAs<PointerType>()) 5308 P = P->getAs<PointerType>()->getPointeeType(); 5309 if (P.isConstQualified()) { 5310 isReadOnly = true; 5311 S += 'r'; 5312 } 5313 } 5314 if (isReadOnly) { 5315 // Another legacy compatibility encoding. Some ObjC qualifier and type 5316 // combinations need to be rearranged. 5317 // Rewrite "in const" from "nr" to "rn" 5318 if (StringRef(S).endswith("nr")) 5319 S.replace(S.end()-2, S.end(), "rn"); 5320 } 5321 5322 if (PointeeTy->isCharType()) { 5323 // char pointer types should be encoded as '*' unless it is a 5324 // type that has been typedef'd to 'BOOL'. 5325 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 5326 S += '*'; 5327 return; 5328 } 5329 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 5330 // GCC binary compat: Need to convert "struct objc_class *" to "#". 5331 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 5332 S += '#'; 5333 return; 5334 } 5335 // GCC binary compat: Need to convert "struct objc_object *" to "@". 5336 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 5337 S += '@'; 5338 return; 5339 } 5340 // fall through... 5341 } 5342 S += '^'; 5343 getLegacyIntegralTypeEncoding(PointeeTy); 5344 5345 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 5346 nullptr, false, false, false, false, false, false, 5347 NotEncodedT); 5348 return; 5349 } 5350 5351 case Type::ConstantArray: 5352 case Type::IncompleteArray: 5353 case Type::VariableArray: { 5354 const ArrayType *AT = cast<ArrayType>(CT); 5355 5356 if (isa<IncompleteArrayType>(AT) && !StructField) { 5357 // Incomplete arrays are encoded as a pointer to the array element. 5358 S += '^'; 5359 5360 getObjCEncodingForTypeImpl(AT->getElementType(), S, 5361 false, ExpandStructures, FD); 5362 } else { 5363 S += '['; 5364 5365 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 5366 S += llvm::utostr(CAT->getSize().getZExtValue()); 5367 else { 5368 //Variable length arrays are encoded as a regular array with 0 elements. 5369 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 5370 "Unknown array type!"); 5371 S += '0'; 5372 } 5373 5374 getObjCEncodingForTypeImpl(AT->getElementType(), S, 5375 false, ExpandStructures, FD, 5376 false, false, false, false, false, false, 5377 NotEncodedT); 5378 S += ']'; 5379 } 5380 return; 5381 } 5382 5383 case Type::FunctionNoProto: 5384 case Type::FunctionProto: 5385 S += '?'; 5386 return; 5387 5388 case Type::Record: { 5389 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 5390 S += RDecl->isUnion() ? '(' : '{'; 5391 // Anonymous structures print as '?' 5392 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 5393 S += II->getName(); 5394 if (ClassTemplateSpecializationDecl *Spec 5395 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 5396 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 5397 llvm::raw_string_ostream OS(S); 5398 TemplateSpecializationType::PrintTemplateArgumentList(OS, 5399 TemplateArgs.data(), 5400 TemplateArgs.size(), 5401 (*this).getPrintingPolicy()); 5402 } 5403 } else { 5404 S += '?'; 5405 } 5406 if (ExpandStructures) { 5407 S += '='; 5408 if (!RDecl->isUnion()) { 5409 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 5410 } else { 5411 for (const auto *Field : RDecl->fields()) { 5412 if (FD) { 5413 S += '"'; 5414 S += Field->getNameAsString(); 5415 S += '"'; 5416 } 5417 5418 // Special case bit-fields. 5419 if (Field->isBitField()) { 5420 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 5421 Field); 5422 } else { 5423 QualType qt = Field->getType(); 5424 getLegacyIntegralTypeEncoding(qt); 5425 getObjCEncodingForTypeImpl(qt, S, false, true, 5426 FD, /*OutermostType*/false, 5427 /*EncodingProperty*/false, 5428 /*StructField*/true, 5429 false, false, false, NotEncodedT); 5430 } 5431 } 5432 } 5433 } 5434 S += RDecl->isUnion() ? ')' : '}'; 5435 return; 5436 } 5437 5438 case Type::BlockPointer: { 5439 const BlockPointerType *BT = T->castAs<BlockPointerType>(); 5440 S += "@?"; // Unlike a pointer-to-function, which is "^?". 5441 if (EncodeBlockParameters) { 5442 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>(); 5443 5444 S += '<'; 5445 // Block return type 5446 getObjCEncodingForTypeImpl( 5447 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures, 5448 FD, false /* OutermostType */, EncodingProperty, 5449 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false, 5450 NotEncodedT); 5451 // Block self 5452 S += "@?"; 5453 // Block parameters 5454 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 5455 for (const auto &I : FPT->param_types()) 5456 getObjCEncodingForTypeImpl( 5457 I, S, ExpandPointedToStructures, ExpandStructures, FD, 5458 false /* OutermostType */, EncodingProperty, 5459 false /* StructField */, EncodeBlockParameters, EncodeClassNames, 5460 false, NotEncodedT); 5461 } 5462 S += '>'; 5463 } 5464 return; 5465 } 5466 5467 case Type::ObjCObject: { 5468 // hack to match legacy encoding of *id and *Class 5469 QualType Ty = getObjCObjectPointerType(CT); 5470 if (Ty->isObjCIdType()) { 5471 S += "{objc_object=}"; 5472 return; 5473 } 5474 else if (Ty->isObjCClassType()) { 5475 S += "{objc_class=}"; 5476 return; 5477 } 5478 } 5479 5480 case Type::ObjCInterface: { 5481 // Ignore protocol qualifiers when mangling at this level. 5482 T = T->castAs<ObjCObjectType>()->getBaseType(); 5483 5484 // The assumption seems to be that this assert will succeed 5485 // because nested levels will have filtered out 'id' and 'Class'. 5486 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>(); 5487 // @encode(class_name) 5488 ObjCInterfaceDecl *OI = OIT->getDecl(); 5489 S += '{'; 5490 const IdentifierInfo *II = OI->getIdentifier(); 5491 S += II->getName(); 5492 S += '='; 5493 SmallVector<const ObjCIvarDecl*, 32> Ivars; 5494 DeepCollectObjCIvars(OI, true, Ivars); 5495 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 5496 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 5497 if (Field->isBitField()) 5498 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 5499 else 5500 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD, 5501 false, false, false, false, false, 5502 EncodePointerToObjCTypedef, 5503 NotEncodedT); 5504 } 5505 S += '}'; 5506 return; 5507 } 5508 5509 case Type::ObjCObjectPointer: { 5510 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>(); 5511 if (OPT->isObjCIdType()) { 5512 S += '@'; 5513 return; 5514 } 5515 5516 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 5517 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 5518 // Since this is a binary compatibility issue, need to consult with runtime 5519 // folks. Fortunately, this is a *very* obsure construct. 5520 S += '#'; 5521 return; 5522 } 5523 5524 if (OPT->isObjCQualifiedIdType()) { 5525 getObjCEncodingForTypeImpl(getObjCIdType(), S, 5526 ExpandPointedToStructures, 5527 ExpandStructures, FD); 5528 if (FD || EncodingProperty || EncodeClassNames) { 5529 // Note that we do extended encoding of protocol qualifer list 5530 // Only when doing ivar or property encoding. 5531 S += '"'; 5532 for (const auto *I : OPT->quals()) { 5533 S += '<'; 5534 S += I->getNameAsString(); 5535 S += '>'; 5536 } 5537 S += '"'; 5538 } 5539 return; 5540 } 5541 5542 QualType PointeeTy = OPT->getPointeeType(); 5543 if (!EncodingProperty && 5544 isa<TypedefType>(PointeeTy.getTypePtr()) && 5545 !EncodePointerToObjCTypedef) { 5546 // Another historical/compatibility reason. 5547 // We encode the underlying type which comes out as 5548 // {...}; 5549 S += '^'; 5550 if (FD && OPT->getInterfaceDecl()) { 5551 // Prevent recursive encoding of fields in some rare cases. 5552 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl(); 5553 SmallVector<const ObjCIvarDecl*, 32> Ivars; 5554 DeepCollectObjCIvars(OI, true, Ivars); 5555 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 5556 if (cast<FieldDecl>(Ivars[i]) == FD) { 5557 S += '{'; 5558 S += OI->getIdentifier()->getName(); 5559 S += '}'; 5560 return; 5561 } 5562 } 5563 } 5564 getObjCEncodingForTypeImpl(PointeeTy, S, 5565 false, ExpandPointedToStructures, 5566 nullptr, 5567 false, false, false, false, false, 5568 /*EncodePointerToObjCTypedef*/true); 5569 return; 5570 } 5571 5572 S += '@'; 5573 if (OPT->getInterfaceDecl() && 5574 (FD || EncodingProperty || EncodeClassNames)) { 5575 S += '"'; 5576 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 5577 for (const auto *I : OPT->quals()) { 5578 S += '<'; 5579 S += I->getNameAsString(); 5580 S += '>'; 5581 } 5582 S += '"'; 5583 } 5584 return; 5585 } 5586 5587 // gcc just blithely ignores member pointers. 5588 // FIXME: we shoul do better than that. 'M' is available. 5589 case Type::MemberPointer: 5590 // This matches gcc's encoding, even though technically it is insufficient. 5591 //FIXME. We should do a better job than gcc. 5592 case Type::Vector: 5593 case Type::ExtVector: 5594 // Until we have a coherent encoding of these three types, issue warning. 5595 { if (NotEncodedT) 5596 *NotEncodedT = T; 5597 return; 5598 } 5599 5600 // We could see an undeduced auto type here during error recovery. 5601 // Just ignore it. 5602 case Type::Auto: 5603 return; 5604 5605 5606 #define ABSTRACT_TYPE(KIND, BASE) 5607 #define TYPE(KIND, BASE) 5608 #define DEPENDENT_TYPE(KIND, BASE) \ 5609 case Type::KIND: 5610 #define NON_CANONICAL_TYPE(KIND, BASE) \ 5611 case Type::KIND: 5612 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 5613 case Type::KIND: 5614 #include "clang/AST/TypeNodes.def" 5615 llvm_unreachable("@encode for dependent type!"); 5616 } 5617 llvm_unreachable("bad type kind!"); 5618 } 5619 5620 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 5621 std::string &S, 5622 const FieldDecl *FD, 5623 bool includeVBases, 5624 QualType *NotEncodedT) const { 5625 assert(RDecl && "Expected non-null RecordDecl"); 5626 assert(!RDecl->isUnion() && "Should not be called for unions"); 5627 if (!RDecl->getDefinition()) 5628 return; 5629 5630 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 5631 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 5632 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 5633 5634 if (CXXRec) { 5635 for (const auto &BI : CXXRec->bases()) { 5636 if (!BI.isVirtual()) { 5637 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 5638 if (base->isEmpty()) 5639 continue; 5640 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 5641 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5642 std::make_pair(offs, base)); 5643 } 5644 } 5645 } 5646 5647 unsigned i = 0; 5648 for (auto *Field : RDecl->fields()) { 5649 uint64_t offs = layout.getFieldOffset(i); 5650 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5651 std::make_pair(offs, Field)); 5652 ++i; 5653 } 5654 5655 if (CXXRec && includeVBases) { 5656 for (const auto &BI : CXXRec->vbases()) { 5657 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 5658 if (base->isEmpty()) 5659 continue; 5660 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 5661 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 5662 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 5663 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 5664 std::make_pair(offs, base)); 5665 } 5666 } 5667 5668 CharUnits size; 5669 if (CXXRec) { 5670 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 5671 } else { 5672 size = layout.getSize(); 5673 } 5674 5675 #ifndef NDEBUG 5676 uint64_t CurOffs = 0; 5677 #endif 5678 std::multimap<uint64_t, NamedDecl *>::iterator 5679 CurLayObj = FieldOrBaseOffsets.begin(); 5680 5681 if (CXXRec && CXXRec->isDynamicClass() && 5682 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 5683 if (FD) { 5684 S += "\"_vptr$"; 5685 std::string recname = CXXRec->getNameAsString(); 5686 if (recname.empty()) recname = "?"; 5687 S += recname; 5688 S += '"'; 5689 } 5690 S += "^^?"; 5691 #ifndef NDEBUG 5692 CurOffs += getTypeSize(VoidPtrTy); 5693 #endif 5694 } 5695 5696 if (!RDecl->hasFlexibleArrayMember()) { 5697 // Mark the end of the structure. 5698 uint64_t offs = toBits(size); 5699 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5700 std::make_pair(offs, nullptr)); 5701 } 5702 5703 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 5704 #ifndef NDEBUG 5705 assert(CurOffs <= CurLayObj->first); 5706 if (CurOffs < CurLayObj->first) { 5707 uint64_t padding = CurLayObj->first - CurOffs; 5708 // FIXME: There doesn't seem to be a way to indicate in the encoding that 5709 // packing/alignment of members is different that normal, in which case 5710 // the encoding will be out-of-sync with the real layout. 5711 // If the runtime switches to just consider the size of types without 5712 // taking into account alignment, we could make padding explicit in the 5713 // encoding (e.g. using arrays of chars). The encoding strings would be 5714 // longer then though. 5715 CurOffs += padding; 5716 } 5717 #endif 5718 5719 NamedDecl *dcl = CurLayObj->second; 5720 if (!dcl) 5721 break; // reached end of structure. 5722 5723 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) { 5724 // We expand the bases without their virtual bases since those are going 5725 // in the initial structure. Note that this differs from gcc which 5726 // expands virtual bases each time one is encountered in the hierarchy, 5727 // making the encoding type bigger than it really is. 5728 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 5729 NotEncodedT); 5730 assert(!base->isEmpty()); 5731 #ifndef NDEBUG 5732 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 5733 #endif 5734 } else { 5735 FieldDecl *field = cast<FieldDecl>(dcl); 5736 if (FD) { 5737 S += '"'; 5738 S += field->getNameAsString(); 5739 S += '"'; 5740 } 5741 5742 if (field->isBitField()) { 5743 EncodeBitField(this, S, field->getType(), field); 5744 #ifndef NDEBUG 5745 CurOffs += field->getBitWidthValue(*this); 5746 #endif 5747 } else { 5748 QualType qt = field->getType(); 5749 getLegacyIntegralTypeEncoding(qt); 5750 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 5751 /*OutermostType*/false, 5752 /*EncodingProperty*/false, 5753 /*StructField*/true, 5754 false, false, false, NotEncodedT); 5755 #ifndef NDEBUG 5756 CurOffs += getTypeSize(field->getType()); 5757 #endif 5758 } 5759 } 5760 } 5761 } 5762 5763 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 5764 std::string& S) const { 5765 if (QT & Decl::OBJC_TQ_In) 5766 S += 'n'; 5767 if (QT & Decl::OBJC_TQ_Inout) 5768 S += 'N'; 5769 if (QT & Decl::OBJC_TQ_Out) 5770 S += 'o'; 5771 if (QT & Decl::OBJC_TQ_Bycopy) 5772 S += 'O'; 5773 if (QT & Decl::OBJC_TQ_Byref) 5774 S += 'R'; 5775 if (QT & Decl::OBJC_TQ_Oneway) 5776 S += 'V'; 5777 } 5778 5779 TypedefDecl *ASTContext::getObjCIdDecl() const { 5780 if (!ObjCIdDecl) { 5781 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0); 5782 T = getObjCObjectPointerType(T); 5783 ObjCIdDecl = buildImplicitTypedef(T, "id"); 5784 } 5785 return ObjCIdDecl; 5786 } 5787 5788 TypedefDecl *ASTContext::getObjCSelDecl() const { 5789 if (!ObjCSelDecl) { 5790 QualType T = getPointerType(ObjCBuiltinSelTy); 5791 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 5792 } 5793 return ObjCSelDecl; 5794 } 5795 5796 TypedefDecl *ASTContext::getObjCClassDecl() const { 5797 if (!ObjCClassDecl) { 5798 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0); 5799 T = getObjCObjectPointerType(T); 5800 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 5801 } 5802 return ObjCClassDecl; 5803 } 5804 5805 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 5806 if (!ObjCProtocolClassDecl) { 5807 ObjCProtocolClassDecl 5808 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 5809 SourceLocation(), 5810 &Idents.get("Protocol"), 5811 /*PrevDecl=*/nullptr, 5812 SourceLocation(), true); 5813 } 5814 5815 return ObjCProtocolClassDecl; 5816 } 5817 5818 //===----------------------------------------------------------------------===// 5819 // __builtin_va_list Construction Functions 5820 //===----------------------------------------------------------------------===// 5821 5822 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 5823 // typedef char* __builtin_va_list; 5824 QualType T = Context->getPointerType(Context->CharTy); 5825 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 5826 } 5827 5828 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 5829 // typedef void* __builtin_va_list; 5830 QualType T = Context->getPointerType(Context->VoidTy); 5831 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 5832 } 5833 5834 static TypedefDecl * 5835 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 5836 // struct __va_list 5837 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 5838 if (Context->getLangOpts().CPlusPlus) { 5839 // namespace std { struct __va_list { 5840 NamespaceDecl *NS; 5841 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 5842 Context->getTranslationUnitDecl(), 5843 /*Inline*/ false, SourceLocation(), 5844 SourceLocation(), &Context->Idents.get("std"), 5845 /*PrevDecl*/ nullptr); 5846 NS->setImplicit(); 5847 VaListTagDecl->setDeclContext(NS); 5848 } 5849 5850 VaListTagDecl->startDefinition(); 5851 5852 const size_t NumFields = 5; 5853 QualType FieldTypes[NumFields]; 5854 const char *FieldNames[NumFields]; 5855 5856 // void *__stack; 5857 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 5858 FieldNames[0] = "__stack"; 5859 5860 // void *__gr_top; 5861 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 5862 FieldNames[1] = "__gr_top"; 5863 5864 // void *__vr_top; 5865 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 5866 FieldNames[2] = "__vr_top"; 5867 5868 // int __gr_offs; 5869 FieldTypes[3] = Context->IntTy; 5870 FieldNames[3] = "__gr_offs"; 5871 5872 // int __vr_offs; 5873 FieldTypes[4] = Context->IntTy; 5874 FieldNames[4] = "__vr_offs"; 5875 5876 // Create fields 5877 for (unsigned i = 0; i < NumFields; ++i) { 5878 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 5879 VaListTagDecl, 5880 SourceLocation(), 5881 SourceLocation(), 5882 &Context->Idents.get(FieldNames[i]), 5883 FieldTypes[i], /*TInfo=*/nullptr, 5884 /*BitWidth=*/nullptr, 5885 /*Mutable=*/false, 5886 ICIS_NoInit); 5887 Field->setAccess(AS_public); 5888 VaListTagDecl->addDecl(Field); 5889 } 5890 VaListTagDecl->completeDefinition(); 5891 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5892 Context->VaListTagTy = VaListTagType; 5893 5894 // } __builtin_va_list; 5895 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 5896 } 5897 5898 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 5899 // typedef struct __va_list_tag { 5900 RecordDecl *VaListTagDecl; 5901 5902 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 5903 VaListTagDecl->startDefinition(); 5904 5905 const size_t NumFields = 5; 5906 QualType FieldTypes[NumFields]; 5907 const char *FieldNames[NumFields]; 5908 5909 // unsigned char gpr; 5910 FieldTypes[0] = Context->UnsignedCharTy; 5911 FieldNames[0] = "gpr"; 5912 5913 // unsigned char fpr; 5914 FieldTypes[1] = Context->UnsignedCharTy; 5915 FieldNames[1] = "fpr"; 5916 5917 // unsigned short reserved; 5918 FieldTypes[2] = Context->UnsignedShortTy; 5919 FieldNames[2] = "reserved"; 5920 5921 // void* overflow_arg_area; 5922 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5923 FieldNames[3] = "overflow_arg_area"; 5924 5925 // void* reg_save_area; 5926 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 5927 FieldNames[4] = "reg_save_area"; 5928 5929 // Create fields 5930 for (unsigned i = 0; i < NumFields; ++i) { 5931 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 5932 SourceLocation(), 5933 SourceLocation(), 5934 &Context->Idents.get(FieldNames[i]), 5935 FieldTypes[i], /*TInfo=*/nullptr, 5936 /*BitWidth=*/nullptr, 5937 /*Mutable=*/false, 5938 ICIS_NoInit); 5939 Field->setAccess(AS_public); 5940 VaListTagDecl->addDecl(Field); 5941 } 5942 VaListTagDecl->completeDefinition(); 5943 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5944 Context->VaListTagTy = VaListTagType; 5945 5946 // } __va_list_tag; 5947 TypedefDecl *VaListTagTypedefDecl = 5948 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 5949 5950 QualType VaListTagTypedefType = 5951 Context->getTypedefType(VaListTagTypedefDecl); 5952 5953 // typedef __va_list_tag __builtin_va_list[1]; 5954 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 5955 QualType VaListTagArrayType 5956 = Context->getConstantArrayType(VaListTagTypedefType, 5957 Size, ArrayType::Normal, 0); 5958 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 5959 } 5960 5961 static TypedefDecl * 5962 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 5963 // typedef struct __va_list_tag { 5964 RecordDecl *VaListTagDecl; 5965 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 5966 VaListTagDecl->startDefinition(); 5967 5968 const size_t NumFields = 4; 5969 QualType FieldTypes[NumFields]; 5970 const char *FieldNames[NumFields]; 5971 5972 // unsigned gp_offset; 5973 FieldTypes[0] = Context->UnsignedIntTy; 5974 FieldNames[0] = "gp_offset"; 5975 5976 // unsigned fp_offset; 5977 FieldTypes[1] = Context->UnsignedIntTy; 5978 FieldNames[1] = "fp_offset"; 5979 5980 // void* overflow_arg_area; 5981 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 5982 FieldNames[2] = "overflow_arg_area"; 5983 5984 // void* reg_save_area; 5985 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5986 FieldNames[3] = "reg_save_area"; 5987 5988 // Create fields 5989 for (unsigned i = 0; i < NumFields; ++i) { 5990 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 5991 VaListTagDecl, 5992 SourceLocation(), 5993 SourceLocation(), 5994 &Context->Idents.get(FieldNames[i]), 5995 FieldTypes[i], /*TInfo=*/nullptr, 5996 /*BitWidth=*/nullptr, 5997 /*Mutable=*/false, 5998 ICIS_NoInit); 5999 Field->setAccess(AS_public); 6000 VaListTagDecl->addDecl(Field); 6001 } 6002 VaListTagDecl->completeDefinition(); 6003 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6004 Context->VaListTagTy = VaListTagType; 6005 6006 // } __va_list_tag; 6007 TypedefDecl *VaListTagTypedefDecl = 6008 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 6009 6010 QualType VaListTagTypedefType = 6011 Context->getTypedefType(VaListTagTypedefDecl); 6012 6013 // typedef __va_list_tag __builtin_va_list[1]; 6014 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6015 QualType VaListTagArrayType 6016 = Context->getConstantArrayType(VaListTagTypedefType, 6017 Size, ArrayType::Normal,0); 6018 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6019 } 6020 6021 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 6022 // typedef int __builtin_va_list[4]; 6023 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 6024 QualType IntArrayType 6025 = Context->getConstantArrayType(Context->IntTy, 6026 Size, ArrayType::Normal, 0); 6027 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 6028 } 6029 6030 static TypedefDecl * 6031 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 6032 // struct __va_list 6033 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 6034 if (Context->getLangOpts().CPlusPlus) { 6035 // namespace std { struct __va_list { 6036 NamespaceDecl *NS; 6037 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 6038 Context->getTranslationUnitDecl(), 6039 /*Inline*/false, SourceLocation(), 6040 SourceLocation(), &Context->Idents.get("std"), 6041 /*PrevDecl*/ nullptr); 6042 NS->setImplicit(); 6043 VaListDecl->setDeclContext(NS); 6044 } 6045 6046 VaListDecl->startDefinition(); 6047 6048 // void * __ap; 6049 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6050 VaListDecl, 6051 SourceLocation(), 6052 SourceLocation(), 6053 &Context->Idents.get("__ap"), 6054 Context->getPointerType(Context->VoidTy), 6055 /*TInfo=*/nullptr, 6056 /*BitWidth=*/nullptr, 6057 /*Mutable=*/false, 6058 ICIS_NoInit); 6059 Field->setAccess(AS_public); 6060 VaListDecl->addDecl(Field); 6061 6062 // }; 6063 VaListDecl->completeDefinition(); 6064 6065 // typedef struct __va_list __builtin_va_list; 6066 QualType T = Context->getRecordType(VaListDecl); 6067 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 6068 } 6069 6070 static TypedefDecl * 6071 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 6072 // typedef struct __va_list_tag { 6073 RecordDecl *VaListTagDecl; 6074 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6075 VaListTagDecl->startDefinition(); 6076 6077 const size_t NumFields = 4; 6078 QualType FieldTypes[NumFields]; 6079 const char *FieldNames[NumFields]; 6080 6081 // long __gpr; 6082 FieldTypes[0] = Context->LongTy; 6083 FieldNames[0] = "__gpr"; 6084 6085 // long __fpr; 6086 FieldTypes[1] = Context->LongTy; 6087 FieldNames[1] = "__fpr"; 6088 6089 // void *__overflow_arg_area; 6090 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6091 FieldNames[2] = "__overflow_arg_area"; 6092 6093 // void *__reg_save_area; 6094 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6095 FieldNames[3] = "__reg_save_area"; 6096 6097 // Create fields 6098 for (unsigned i = 0; i < NumFields; ++i) { 6099 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6100 VaListTagDecl, 6101 SourceLocation(), 6102 SourceLocation(), 6103 &Context->Idents.get(FieldNames[i]), 6104 FieldTypes[i], /*TInfo=*/nullptr, 6105 /*BitWidth=*/nullptr, 6106 /*Mutable=*/false, 6107 ICIS_NoInit); 6108 Field->setAccess(AS_public); 6109 VaListTagDecl->addDecl(Field); 6110 } 6111 VaListTagDecl->completeDefinition(); 6112 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6113 Context->VaListTagTy = VaListTagType; 6114 6115 // } __va_list_tag; 6116 TypedefDecl *VaListTagTypedefDecl = 6117 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 6118 QualType VaListTagTypedefType = 6119 Context->getTypedefType(VaListTagTypedefDecl); 6120 6121 // typedef __va_list_tag __builtin_va_list[1]; 6122 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6123 QualType VaListTagArrayType 6124 = Context->getConstantArrayType(VaListTagTypedefType, 6125 Size, ArrayType::Normal,0); 6126 6127 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6128 } 6129 6130 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 6131 TargetInfo::BuiltinVaListKind Kind) { 6132 switch (Kind) { 6133 case TargetInfo::CharPtrBuiltinVaList: 6134 return CreateCharPtrBuiltinVaListDecl(Context); 6135 case TargetInfo::VoidPtrBuiltinVaList: 6136 return CreateVoidPtrBuiltinVaListDecl(Context); 6137 case TargetInfo::AArch64ABIBuiltinVaList: 6138 return CreateAArch64ABIBuiltinVaListDecl(Context); 6139 case TargetInfo::PowerABIBuiltinVaList: 6140 return CreatePowerABIBuiltinVaListDecl(Context); 6141 case TargetInfo::X86_64ABIBuiltinVaList: 6142 return CreateX86_64ABIBuiltinVaListDecl(Context); 6143 case TargetInfo::PNaClABIBuiltinVaList: 6144 return CreatePNaClABIBuiltinVaListDecl(Context); 6145 case TargetInfo::AAPCSABIBuiltinVaList: 6146 return CreateAAPCSABIBuiltinVaListDecl(Context); 6147 case TargetInfo::SystemZBuiltinVaList: 6148 return CreateSystemZBuiltinVaListDecl(Context); 6149 } 6150 6151 llvm_unreachable("Unhandled __builtin_va_list type kind"); 6152 } 6153 6154 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 6155 if (!BuiltinVaListDecl) { 6156 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 6157 assert(BuiltinVaListDecl->isImplicit()); 6158 } 6159 6160 return BuiltinVaListDecl; 6161 } 6162 6163 QualType ASTContext::getVaListTagType() const { 6164 // Force the creation of VaListTagTy by building the __builtin_va_list 6165 // declaration. 6166 if (VaListTagTy.isNull()) 6167 (void) getBuiltinVaListDecl(); 6168 6169 return VaListTagTy; 6170 } 6171 6172 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 6173 assert(ObjCConstantStringType.isNull() && 6174 "'NSConstantString' type already set!"); 6175 6176 ObjCConstantStringType = getObjCInterfaceType(Decl); 6177 } 6178 6179 /// \brief Retrieve the template name that corresponds to a non-empty 6180 /// lookup. 6181 TemplateName 6182 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 6183 UnresolvedSetIterator End) const { 6184 unsigned size = End - Begin; 6185 assert(size > 1 && "set is not overloaded!"); 6186 6187 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 6188 size * sizeof(FunctionTemplateDecl*)); 6189 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 6190 6191 NamedDecl **Storage = OT->getStorage(); 6192 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 6193 NamedDecl *D = *I; 6194 assert(isa<FunctionTemplateDecl>(D) || 6195 (isa<UsingShadowDecl>(D) && 6196 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 6197 *Storage++ = D; 6198 } 6199 6200 return TemplateName(OT); 6201 } 6202 6203 /// \brief Retrieve the template name that represents a qualified 6204 /// template name such as \c std::vector. 6205 TemplateName 6206 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 6207 bool TemplateKeyword, 6208 TemplateDecl *Template) const { 6209 assert(NNS && "Missing nested-name-specifier in qualified template name"); 6210 6211 // FIXME: Canonicalization? 6212 llvm::FoldingSetNodeID ID; 6213 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 6214 6215 void *InsertPos = nullptr; 6216 QualifiedTemplateName *QTN = 6217 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6218 if (!QTN) { 6219 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>()) 6220 QualifiedTemplateName(NNS, TemplateKeyword, Template); 6221 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 6222 } 6223 6224 return TemplateName(QTN); 6225 } 6226 6227 /// \brief Retrieve the template name that represents a dependent 6228 /// template name such as \c MetaFun::template apply. 6229 TemplateName 6230 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 6231 const IdentifierInfo *Name) const { 6232 assert((!NNS || NNS->isDependent()) && 6233 "Nested name specifier must be dependent"); 6234 6235 llvm::FoldingSetNodeID ID; 6236 DependentTemplateName::Profile(ID, NNS, Name); 6237 6238 void *InsertPos = nullptr; 6239 DependentTemplateName *QTN = 6240 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6241 6242 if (QTN) 6243 return TemplateName(QTN); 6244 6245 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 6246 if (CanonNNS == NNS) { 6247 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6248 DependentTemplateName(NNS, Name); 6249 } else { 6250 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 6251 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6252 DependentTemplateName(NNS, Name, Canon); 6253 DependentTemplateName *CheckQTN = 6254 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6255 assert(!CheckQTN && "Dependent type name canonicalization broken"); 6256 (void)CheckQTN; 6257 } 6258 6259 DependentTemplateNames.InsertNode(QTN, InsertPos); 6260 return TemplateName(QTN); 6261 } 6262 6263 /// \brief Retrieve the template name that represents a dependent 6264 /// template name such as \c MetaFun::template operator+. 6265 TemplateName 6266 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 6267 OverloadedOperatorKind Operator) const { 6268 assert((!NNS || NNS->isDependent()) && 6269 "Nested name specifier must be dependent"); 6270 6271 llvm::FoldingSetNodeID ID; 6272 DependentTemplateName::Profile(ID, NNS, Operator); 6273 6274 void *InsertPos = nullptr; 6275 DependentTemplateName *QTN 6276 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6277 6278 if (QTN) 6279 return TemplateName(QTN); 6280 6281 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 6282 if (CanonNNS == NNS) { 6283 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6284 DependentTemplateName(NNS, Operator); 6285 } else { 6286 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 6287 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6288 DependentTemplateName(NNS, Operator, Canon); 6289 6290 DependentTemplateName *CheckQTN 6291 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6292 assert(!CheckQTN && "Dependent template name canonicalization broken"); 6293 (void)CheckQTN; 6294 } 6295 6296 DependentTemplateNames.InsertNode(QTN, InsertPos); 6297 return TemplateName(QTN); 6298 } 6299 6300 TemplateName 6301 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 6302 TemplateName replacement) const { 6303 llvm::FoldingSetNodeID ID; 6304 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 6305 6306 void *insertPos = nullptr; 6307 SubstTemplateTemplateParmStorage *subst 6308 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 6309 6310 if (!subst) { 6311 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 6312 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 6313 } 6314 6315 return TemplateName(subst); 6316 } 6317 6318 TemplateName 6319 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 6320 const TemplateArgument &ArgPack) const { 6321 ASTContext &Self = const_cast<ASTContext &>(*this); 6322 llvm::FoldingSetNodeID ID; 6323 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 6324 6325 void *InsertPos = nullptr; 6326 SubstTemplateTemplateParmPackStorage *Subst 6327 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 6328 6329 if (!Subst) { 6330 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 6331 ArgPack.pack_size(), 6332 ArgPack.pack_begin()); 6333 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 6334 } 6335 6336 return TemplateName(Subst); 6337 } 6338 6339 /// getFromTargetType - Given one of the integer types provided by 6340 /// TargetInfo, produce the corresponding type. The unsigned @p Type 6341 /// is actually a value of type @c TargetInfo::IntType. 6342 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 6343 switch (Type) { 6344 case TargetInfo::NoInt: return CanQualType(); 6345 case TargetInfo::SignedChar: return SignedCharTy; 6346 case TargetInfo::UnsignedChar: return UnsignedCharTy; 6347 case TargetInfo::SignedShort: return ShortTy; 6348 case TargetInfo::UnsignedShort: return UnsignedShortTy; 6349 case TargetInfo::SignedInt: return IntTy; 6350 case TargetInfo::UnsignedInt: return UnsignedIntTy; 6351 case TargetInfo::SignedLong: return LongTy; 6352 case TargetInfo::UnsignedLong: return UnsignedLongTy; 6353 case TargetInfo::SignedLongLong: return LongLongTy; 6354 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 6355 } 6356 6357 llvm_unreachable("Unhandled TargetInfo::IntType value"); 6358 } 6359 6360 //===----------------------------------------------------------------------===// 6361 // Type Predicates. 6362 //===----------------------------------------------------------------------===// 6363 6364 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 6365 /// garbage collection attribute. 6366 /// 6367 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 6368 if (getLangOpts().getGC() == LangOptions::NonGC) 6369 return Qualifiers::GCNone; 6370 6371 assert(getLangOpts().ObjC1); 6372 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 6373 6374 // Default behaviour under objective-C's gc is for ObjC pointers 6375 // (or pointers to them) be treated as though they were declared 6376 // as __strong. 6377 if (GCAttrs == Qualifiers::GCNone) { 6378 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 6379 return Qualifiers::Strong; 6380 else if (Ty->isPointerType()) 6381 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 6382 } else { 6383 // It's not valid to set GC attributes on anything that isn't a 6384 // pointer. 6385 #ifndef NDEBUG 6386 QualType CT = Ty->getCanonicalTypeInternal(); 6387 while (const ArrayType *AT = dyn_cast<ArrayType>(CT)) 6388 CT = AT->getElementType(); 6389 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 6390 #endif 6391 } 6392 return GCAttrs; 6393 } 6394 6395 //===----------------------------------------------------------------------===// 6396 // Type Compatibility Testing 6397 //===----------------------------------------------------------------------===// 6398 6399 /// areCompatVectorTypes - Return true if the two specified vector types are 6400 /// compatible. 6401 static bool areCompatVectorTypes(const VectorType *LHS, 6402 const VectorType *RHS) { 6403 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 6404 return LHS->getElementType() == RHS->getElementType() && 6405 LHS->getNumElements() == RHS->getNumElements(); 6406 } 6407 6408 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 6409 QualType SecondVec) { 6410 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 6411 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 6412 6413 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 6414 return true; 6415 6416 // Treat Neon vector types and most AltiVec vector types as if they are the 6417 // equivalent GCC vector types. 6418 const VectorType *First = FirstVec->getAs<VectorType>(); 6419 const VectorType *Second = SecondVec->getAs<VectorType>(); 6420 if (First->getNumElements() == Second->getNumElements() && 6421 hasSameType(First->getElementType(), Second->getElementType()) && 6422 First->getVectorKind() != VectorType::AltiVecPixel && 6423 First->getVectorKind() != VectorType::AltiVecBool && 6424 Second->getVectorKind() != VectorType::AltiVecPixel && 6425 Second->getVectorKind() != VectorType::AltiVecBool) 6426 return true; 6427 6428 return false; 6429 } 6430 6431 //===----------------------------------------------------------------------===// 6432 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 6433 //===----------------------------------------------------------------------===// 6434 6435 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 6436 /// inheritance hierarchy of 'rProto'. 6437 bool 6438 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 6439 ObjCProtocolDecl *rProto) const { 6440 if (declaresSameEntity(lProto, rProto)) 6441 return true; 6442 for (auto *PI : rProto->protocols()) 6443 if (ProtocolCompatibleWithProtocol(lProto, PI)) 6444 return true; 6445 return false; 6446 } 6447 6448 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 6449 /// Class<pr1, ...>. 6450 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 6451 QualType rhs) { 6452 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 6453 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 6454 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 6455 6456 for (auto *lhsProto : lhsQID->quals()) { 6457 bool match = false; 6458 for (auto *rhsProto : rhsOPT->quals()) { 6459 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 6460 match = true; 6461 break; 6462 } 6463 } 6464 if (!match) 6465 return false; 6466 } 6467 return true; 6468 } 6469 6470 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 6471 /// ObjCQualifiedIDType. 6472 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 6473 bool compare) { 6474 // Allow id<P..> and an 'id' or void* type in all cases. 6475 if (lhs->isVoidPointerType() || 6476 lhs->isObjCIdType() || lhs->isObjCClassType()) 6477 return true; 6478 else if (rhs->isVoidPointerType() || 6479 rhs->isObjCIdType() || rhs->isObjCClassType()) 6480 return true; 6481 6482 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 6483 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 6484 6485 if (!rhsOPT) return false; 6486 6487 if (rhsOPT->qual_empty()) { 6488 // If the RHS is a unqualified interface pointer "NSString*", 6489 // make sure we check the class hierarchy. 6490 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 6491 for (auto *I : lhsQID->quals()) { 6492 // when comparing an id<P> on lhs with a static type on rhs, 6493 // see if static class implements all of id's protocols, directly or 6494 // through its super class and categories. 6495 if (!rhsID->ClassImplementsProtocol(I, true)) 6496 return false; 6497 } 6498 } 6499 // If there are no qualifiers and no interface, we have an 'id'. 6500 return true; 6501 } 6502 // Both the right and left sides have qualifiers. 6503 for (auto *lhsProto : lhsQID->quals()) { 6504 bool match = false; 6505 6506 // when comparing an id<P> on lhs with a static type on rhs, 6507 // see if static class implements all of id's protocols, directly or 6508 // through its super class and categories. 6509 for (auto *rhsProto : rhsOPT->quals()) { 6510 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 6511 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 6512 match = true; 6513 break; 6514 } 6515 } 6516 // If the RHS is a qualified interface pointer "NSString<P>*", 6517 // make sure we check the class hierarchy. 6518 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 6519 for (auto *I : lhsQID->quals()) { 6520 // when comparing an id<P> on lhs with a static type on rhs, 6521 // see if static class implements all of id's protocols, directly or 6522 // through its super class and categories. 6523 if (rhsID->ClassImplementsProtocol(I, true)) { 6524 match = true; 6525 break; 6526 } 6527 } 6528 } 6529 if (!match) 6530 return false; 6531 } 6532 6533 return true; 6534 } 6535 6536 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 6537 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 6538 6539 if (const ObjCObjectPointerType *lhsOPT = 6540 lhs->getAsObjCInterfacePointerType()) { 6541 // If both the right and left sides have qualifiers. 6542 for (auto *lhsProto : lhsOPT->quals()) { 6543 bool match = false; 6544 6545 // when comparing an id<P> on rhs with a static type on lhs, 6546 // see if static class implements all of id's protocols, directly or 6547 // through its super class and categories. 6548 // First, lhs protocols in the qualifier list must be found, direct 6549 // or indirect in rhs's qualifier list or it is a mismatch. 6550 for (auto *rhsProto : rhsQID->quals()) { 6551 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 6552 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 6553 match = true; 6554 break; 6555 } 6556 } 6557 if (!match) 6558 return false; 6559 } 6560 6561 // Static class's protocols, or its super class or category protocols 6562 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 6563 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 6564 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 6565 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 6566 // This is rather dubious but matches gcc's behavior. If lhs has 6567 // no type qualifier and its class has no static protocol(s) 6568 // assume that it is mismatch. 6569 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 6570 return false; 6571 for (auto *lhsProto : LHSInheritedProtocols) { 6572 bool match = false; 6573 for (auto *rhsProto : rhsQID->quals()) { 6574 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 6575 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 6576 match = true; 6577 break; 6578 } 6579 } 6580 if (!match) 6581 return false; 6582 } 6583 } 6584 return true; 6585 } 6586 return false; 6587 } 6588 6589 /// canAssignObjCInterfaces - Return true if the two interface types are 6590 /// compatible for assignment from RHS to LHS. This handles validation of any 6591 /// protocol qualifiers on the LHS or RHS. 6592 /// 6593 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 6594 const ObjCObjectPointerType *RHSOPT) { 6595 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 6596 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 6597 6598 // If either type represents the built-in 'id' or 'Class' types, return true. 6599 if (LHS->isObjCUnqualifiedIdOrClass() || 6600 RHS->isObjCUnqualifiedIdOrClass()) 6601 return true; 6602 6603 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 6604 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 6605 QualType(RHSOPT,0), 6606 false); 6607 6608 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) 6609 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 6610 QualType(RHSOPT,0)); 6611 6612 // If we have 2 user-defined types, fall into that path. 6613 if (LHS->getInterface() && RHS->getInterface()) 6614 return canAssignObjCInterfaces(LHS, RHS); 6615 6616 return false; 6617 } 6618 6619 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 6620 /// for providing type-safety for objective-c pointers used to pass/return 6621 /// arguments in block literals. When passed as arguments, passing 'A*' where 6622 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 6623 /// not OK. For the return type, the opposite is not OK. 6624 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 6625 const ObjCObjectPointerType *LHSOPT, 6626 const ObjCObjectPointerType *RHSOPT, 6627 bool BlockReturnType) { 6628 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 6629 return true; 6630 6631 if (LHSOPT->isObjCBuiltinType()) { 6632 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 6633 } 6634 6635 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 6636 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 6637 QualType(RHSOPT,0), 6638 false); 6639 6640 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 6641 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 6642 if (LHS && RHS) { // We have 2 user-defined types. 6643 if (LHS != RHS) { 6644 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 6645 return BlockReturnType; 6646 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 6647 return !BlockReturnType; 6648 } 6649 else 6650 return true; 6651 } 6652 return false; 6653 } 6654 6655 /// getIntersectionOfProtocols - This routine finds the intersection of set 6656 /// of protocols inherited from two distinct objective-c pointer objects. 6657 /// It is used to build composite qualifier list of the composite type of 6658 /// the conditional expression involving two objective-c pointer objects. 6659 static 6660 void getIntersectionOfProtocols(ASTContext &Context, 6661 const ObjCObjectPointerType *LHSOPT, 6662 const ObjCObjectPointerType *RHSOPT, 6663 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 6664 6665 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 6666 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 6667 assert(LHS->getInterface() && "LHS must have an interface base"); 6668 assert(RHS->getInterface() && "RHS must have an interface base"); 6669 6670 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 6671 unsigned LHSNumProtocols = LHS->getNumProtocols(); 6672 if (LHSNumProtocols > 0) 6673 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 6674 else { 6675 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 6676 Context.CollectInheritedProtocols(LHS->getInterface(), 6677 LHSInheritedProtocols); 6678 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 6679 LHSInheritedProtocols.end()); 6680 } 6681 6682 unsigned RHSNumProtocols = RHS->getNumProtocols(); 6683 if (RHSNumProtocols > 0) { 6684 ObjCProtocolDecl **RHSProtocols = 6685 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 6686 for (unsigned i = 0; i < RHSNumProtocols; ++i) 6687 if (InheritedProtocolSet.count(RHSProtocols[i])) 6688 IntersectionOfProtocols.push_back(RHSProtocols[i]); 6689 } else { 6690 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 6691 Context.CollectInheritedProtocols(RHS->getInterface(), 6692 RHSInheritedProtocols); 6693 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols) 6694 if (InheritedProtocolSet.count(ProtDecl)) 6695 IntersectionOfProtocols.push_back(ProtDecl); 6696 } 6697 } 6698 6699 /// areCommonBaseCompatible - Returns common base class of the two classes if 6700 /// one found. Note that this is O'2 algorithm. But it will be called as the 6701 /// last type comparison in a ?-exp of ObjC pointer types before a 6702 /// warning is issued. So, its invokation is extremely rare. 6703 QualType ASTContext::areCommonBaseCompatible( 6704 const ObjCObjectPointerType *Lptr, 6705 const ObjCObjectPointerType *Rptr) { 6706 const ObjCObjectType *LHS = Lptr->getObjectType(); 6707 const ObjCObjectType *RHS = Rptr->getObjectType(); 6708 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 6709 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 6710 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl))) 6711 return QualType(); 6712 6713 do { 6714 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 6715 if (canAssignObjCInterfaces(LHS, RHS)) { 6716 SmallVector<ObjCProtocolDecl *, 8> Protocols; 6717 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 6718 6719 QualType Result = QualType(LHS, 0); 6720 if (!Protocols.empty()) 6721 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 6722 Result = getObjCObjectPointerType(Result); 6723 return Result; 6724 } 6725 } while ((LDecl = LDecl->getSuperClass())); 6726 6727 return QualType(); 6728 } 6729 6730 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 6731 const ObjCObjectType *RHS) { 6732 assert(LHS->getInterface() && "LHS is not an interface type"); 6733 assert(RHS->getInterface() && "RHS is not an interface type"); 6734 6735 // Verify that the base decls are compatible: the RHS must be a subclass of 6736 // the LHS. 6737 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 6738 return false; 6739 6740 // RHS must have a superset of the protocols in the LHS. If the LHS is not 6741 // protocol qualified at all, then we are good. 6742 if (LHS->getNumProtocols() == 0) 6743 return true; 6744 6745 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, 6746 // more detailed analysis is required. 6747 if (RHS->getNumProtocols() == 0) { 6748 // OK, if LHS is a superclass of RHS *and* 6749 // this superclass is assignment compatible with LHS. 6750 // false otherwise. 6751 bool IsSuperClass = 6752 LHS->getInterface()->isSuperClassOf(RHS->getInterface()); 6753 if (IsSuperClass) { 6754 // OK if conversion of LHS to SuperClass results in narrowing of types 6755 // ; i.e., SuperClass may implement at least one of the protocols 6756 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 6757 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 6758 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 6759 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 6760 // If super class has no protocols, it is not a match. 6761 if (SuperClassInheritedProtocols.empty()) 6762 return false; 6763 6764 for (const auto *LHSProto : LHS->quals()) { 6765 bool SuperImplementsProtocol = false; 6766 for (auto *SuperClassProto : SuperClassInheritedProtocols) { 6767 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 6768 SuperImplementsProtocol = true; 6769 break; 6770 } 6771 } 6772 if (!SuperImplementsProtocol) 6773 return false; 6774 } 6775 return true; 6776 } 6777 return false; 6778 } 6779 6780 for (const auto *LHSPI : LHS->quals()) { 6781 bool RHSImplementsProtocol = false; 6782 6783 // If the RHS doesn't implement the protocol on the left, the types 6784 // are incompatible. 6785 for (auto *RHSPI : RHS->quals()) { 6786 if (RHSPI->lookupProtocolNamed(LHSPI->getIdentifier())) { 6787 RHSImplementsProtocol = true; 6788 break; 6789 } 6790 } 6791 // FIXME: For better diagnostics, consider passing back the protocol name. 6792 if (!RHSImplementsProtocol) 6793 return false; 6794 } 6795 // The RHS implements all protocols listed on the LHS. 6796 return true; 6797 } 6798 6799 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 6800 // get the "pointed to" types 6801 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 6802 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 6803 6804 if (!LHSOPT || !RHSOPT) 6805 return false; 6806 6807 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 6808 canAssignObjCInterfaces(RHSOPT, LHSOPT); 6809 } 6810 6811 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 6812 return canAssignObjCInterfaces( 6813 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 6814 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 6815 } 6816 6817 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 6818 /// both shall have the identically qualified version of a compatible type. 6819 /// C99 6.2.7p1: Two types have compatible types if their types are the 6820 /// same. See 6.7.[2,3,5] for additional rules. 6821 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 6822 bool CompareUnqualified) { 6823 if (getLangOpts().CPlusPlus) 6824 return hasSameType(LHS, RHS); 6825 6826 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 6827 } 6828 6829 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 6830 return typesAreCompatible(LHS, RHS); 6831 } 6832 6833 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 6834 return !mergeTypes(LHS, RHS, true).isNull(); 6835 } 6836 6837 /// mergeTransparentUnionType - if T is a transparent union type and a member 6838 /// of T is compatible with SubType, return the merged type, else return 6839 /// QualType() 6840 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 6841 bool OfBlockPointer, 6842 bool Unqualified) { 6843 if (const RecordType *UT = T->getAsUnionType()) { 6844 RecordDecl *UD = UT->getDecl(); 6845 if (UD->hasAttr<TransparentUnionAttr>()) { 6846 for (const auto *I : UD->fields()) { 6847 QualType ET = I->getType().getUnqualifiedType(); 6848 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 6849 if (!MT.isNull()) 6850 return MT; 6851 } 6852 } 6853 } 6854 6855 return QualType(); 6856 } 6857 6858 /// mergeFunctionParameterTypes - merge two types which appear as function 6859 /// parameter types 6860 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 6861 bool OfBlockPointer, 6862 bool Unqualified) { 6863 // GNU extension: two types are compatible if they appear as a function 6864 // argument, one of the types is a transparent union type and the other 6865 // type is compatible with a union member 6866 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 6867 Unqualified); 6868 if (!lmerge.isNull()) 6869 return lmerge; 6870 6871 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 6872 Unqualified); 6873 if (!rmerge.isNull()) 6874 return rmerge; 6875 6876 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 6877 } 6878 6879 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 6880 bool OfBlockPointer, 6881 bool Unqualified) { 6882 const FunctionType *lbase = lhs->getAs<FunctionType>(); 6883 const FunctionType *rbase = rhs->getAs<FunctionType>(); 6884 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 6885 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 6886 bool allLTypes = true; 6887 bool allRTypes = true; 6888 6889 // Check return type 6890 QualType retType; 6891 if (OfBlockPointer) { 6892 QualType RHS = rbase->getReturnType(); 6893 QualType LHS = lbase->getReturnType(); 6894 bool UnqualifiedResult = Unqualified; 6895 if (!UnqualifiedResult) 6896 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 6897 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 6898 } 6899 else 6900 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 6901 Unqualified); 6902 if (retType.isNull()) return QualType(); 6903 6904 if (Unqualified) 6905 retType = retType.getUnqualifiedType(); 6906 6907 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 6908 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 6909 if (Unqualified) { 6910 LRetType = LRetType.getUnqualifiedType(); 6911 RRetType = RRetType.getUnqualifiedType(); 6912 } 6913 6914 if (getCanonicalType(retType) != LRetType) 6915 allLTypes = false; 6916 if (getCanonicalType(retType) != RRetType) 6917 allRTypes = false; 6918 6919 // FIXME: double check this 6920 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 6921 // rbase->getRegParmAttr() != 0 && 6922 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 6923 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 6924 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 6925 6926 // Compatible functions must have compatible calling conventions 6927 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 6928 return QualType(); 6929 6930 // Regparm is part of the calling convention. 6931 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 6932 return QualType(); 6933 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 6934 return QualType(); 6935 6936 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 6937 return QualType(); 6938 6939 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 6940 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 6941 6942 if (lbaseInfo.getNoReturn() != NoReturn) 6943 allLTypes = false; 6944 if (rbaseInfo.getNoReturn() != NoReturn) 6945 allRTypes = false; 6946 6947 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 6948 6949 if (lproto && rproto) { // two C99 style function prototypes 6950 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 6951 "C++ shouldn't be here"); 6952 // Compatible functions must have the same number of parameters 6953 if (lproto->getNumParams() != rproto->getNumParams()) 6954 return QualType(); 6955 6956 // Variadic and non-variadic functions aren't compatible 6957 if (lproto->isVariadic() != rproto->isVariadic()) 6958 return QualType(); 6959 6960 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 6961 return QualType(); 6962 6963 if (LangOpts.ObjCAutoRefCount && 6964 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto)) 6965 return QualType(); 6966 6967 // Check parameter type compatibility 6968 SmallVector<QualType, 10> types; 6969 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 6970 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 6971 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 6972 QualType paramType = mergeFunctionParameterTypes( 6973 lParamType, rParamType, OfBlockPointer, Unqualified); 6974 if (paramType.isNull()) 6975 return QualType(); 6976 6977 if (Unqualified) 6978 paramType = paramType.getUnqualifiedType(); 6979 6980 types.push_back(paramType); 6981 if (Unqualified) { 6982 lParamType = lParamType.getUnqualifiedType(); 6983 rParamType = rParamType.getUnqualifiedType(); 6984 } 6985 6986 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 6987 allLTypes = false; 6988 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 6989 allRTypes = false; 6990 } 6991 6992 if (allLTypes) return lhs; 6993 if (allRTypes) return rhs; 6994 6995 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 6996 EPI.ExtInfo = einfo; 6997 return getFunctionType(retType, types, EPI); 6998 } 6999 7000 if (lproto) allRTypes = false; 7001 if (rproto) allLTypes = false; 7002 7003 const FunctionProtoType *proto = lproto ? lproto : rproto; 7004 if (proto) { 7005 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 7006 if (proto->isVariadic()) return QualType(); 7007 // Check that the types are compatible with the types that 7008 // would result from default argument promotions (C99 6.7.5.3p15). 7009 // The only types actually affected are promotable integer 7010 // types and floats, which would be passed as a different 7011 // type depending on whether the prototype is visible. 7012 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 7013 QualType paramTy = proto->getParamType(i); 7014 7015 // Look at the converted type of enum types, since that is the type used 7016 // to pass enum values. 7017 if (const EnumType *Enum = paramTy->getAs<EnumType>()) { 7018 paramTy = Enum->getDecl()->getIntegerType(); 7019 if (paramTy.isNull()) 7020 return QualType(); 7021 } 7022 7023 if (paramTy->isPromotableIntegerType() || 7024 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 7025 return QualType(); 7026 } 7027 7028 if (allLTypes) return lhs; 7029 if (allRTypes) return rhs; 7030 7031 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 7032 EPI.ExtInfo = einfo; 7033 return getFunctionType(retType, proto->getParamTypes(), EPI); 7034 } 7035 7036 if (allLTypes) return lhs; 7037 if (allRTypes) return rhs; 7038 return getFunctionNoProtoType(retType, einfo); 7039 } 7040 7041 /// Given that we have an enum type and a non-enum type, try to merge them. 7042 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 7043 QualType other, bool isBlockReturnType) { 7044 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 7045 // a signed integer type, or an unsigned integer type. 7046 // Compatibility is based on the underlying type, not the promotion 7047 // type. 7048 QualType underlyingType = ET->getDecl()->getIntegerType(); 7049 if (underlyingType.isNull()) return QualType(); 7050 if (Context.hasSameType(underlyingType, other)) 7051 return other; 7052 7053 // In block return types, we're more permissive and accept any 7054 // integral type of the same size. 7055 if (isBlockReturnType && other->isIntegerType() && 7056 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 7057 return other; 7058 7059 return QualType(); 7060 } 7061 7062 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 7063 bool OfBlockPointer, 7064 bool Unqualified, bool BlockReturnType) { 7065 // C++ [expr]: If an expression initially has the type "reference to T", the 7066 // type is adjusted to "T" prior to any further analysis, the expression 7067 // designates the object or function denoted by the reference, and the 7068 // expression is an lvalue unless the reference is an rvalue reference and 7069 // the expression is a function call (possibly inside parentheses). 7070 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 7071 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 7072 7073 if (Unqualified) { 7074 LHS = LHS.getUnqualifiedType(); 7075 RHS = RHS.getUnqualifiedType(); 7076 } 7077 7078 QualType LHSCan = getCanonicalType(LHS), 7079 RHSCan = getCanonicalType(RHS); 7080 7081 // If two types are identical, they are compatible. 7082 if (LHSCan == RHSCan) 7083 return LHS; 7084 7085 // If the qualifiers are different, the types aren't compatible... mostly. 7086 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 7087 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 7088 if (LQuals != RQuals) { 7089 // If any of these qualifiers are different, we have a type 7090 // mismatch. 7091 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 7092 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 7093 LQuals.getObjCLifetime() != RQuals.getObjCLifetime()) 7094 return QualType(); 7095 7096 // Exactly one GC qualifier difference is allowed: __strong is 7097 // okay if the other type has no GC qualifier but is an Objective 7098 // C object pointer (i.e. implicitly strong by default). We fix 7099 // this by pretending that the unqualified type was actually 7100 // qualified __strong. 7101 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 7102 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 7103 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 7104 7105 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 7106 return QualType(); 7107 7108 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 7109 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 7110 } 7111 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 7112 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 7113 } 7114 return QualType(); 7115 } 7116 7117 // Okay, qualifiers are equal. 7118 7119 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 7120 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 7121 7122 // We want to consider the two function types to be the same for these 7123 // comparisons, just force one to the other. 7124 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 7125 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 7126 7127 // Same as above for arrays 7128 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 7129 LHSClass = Type::ConstantArray; 7130 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 7131 RHSClass = Type::ConstantArray; 7132 7133 // ObjCInterfaces are just specialized ObjCObjects. 7134 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 7135 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 7136 7137 // Canonicalize ExtVector -> Vector. 7138 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 7139 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 7140 7141 // If the canonical type classes don't match. 7142 if (LHSClass != RHSClass) { 7143 // Note that we only have special rules for turning block enum 7144 // returns into block int returns, not vice-versa. 7145 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 7146 return mergeEnumWithInteger(*this, ETy, RHS, false); 7147 } 7148 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 7149 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 7150 } 7151 // allow block pointer type to match an 'id' type. 7152 if (OfBlockPointer && !BlockReturnType) { 7153 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 7154 return LHS; 7155 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 7156 return RHS; 7157 } 7158 7159 return QualType(); 7160 } 7161 7162 // The canonical type classes match. 7163 switch (LHSClass) { 7164 #define TYPE(Class, Base) 7165 #define ABSTRACT_TYPE(Class, Base) 7166 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 7167 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 7168 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 7169 #include "clang/AST/TypeNodes.def" 7170 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 7171 7172 case Type::Auto: 7173 case Type::LValueReference: 7174 case Type::RValueReference: 7175 case Type::MemberPointer: 7176 llvm_unreachable("C++ should never be in mergeTypes"); 7177 7178 case Type::ObjCInterface: 7179 case Type::IncompleteArray: 7180 case Type::VariableArray: 7181 case Type::FunctionProto: 7182 case Type::ExtVector: 7183 llvm_unreachable("Types are eliminated above"); 7184 7185 case Type::Pointer: 7186 { 7187 // Merge two pointer types, while trying to preserve typedef info 7188 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 7189 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 7190 if (Unqualified) { 7191 LHSPointee = LHSPointee.getUnqualifiedType(); 7192 RHSPointee = RHSPointee.getUnqualifiedType(); 7193 } 7194 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 7195 Unqualified); 7196 if (ResultType.isNull()) return QualType(); 7197 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 7198 return LHS; 7199 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 7200 return RHS; 7201 return getPointerType(ResultType); 7202 } 7203 case Type::BlockPointer: 7204 { 7205 // Merge two block pointer types, while trying to preserve typedef info 7206 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 7207 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 7208 if (Unqualified) { 7209 LHSPointee = LHSPointee.getUnqualifiedType(); 7210 RHSPointee = RHSPointee.getUnqualifiedType(); 7211 } 7212 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 7213 Unqualified); 7214 if (ResultType.isNull()) return QualType(); 7215 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 7216 return LHS; 7217 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 7218 return RHS; 7219 return getBlockPointerType(ResultType); 7220 } 7221 case Type::Atomic: 7222 { 7223 // Merge two pointer types, while trying to preserve typedef info 7224 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 7225 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 7226 if (Unqualified) { 7227 LHSValue = LHSValue.getUnqualifiedType(); 7228 RHSValue = RHSValue.getUnqualifiedType(); 7229 } 7230 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 7231 Unqualified); 7232 if (ResultType.isNull()) return QualType(); 7233 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 7234 return LHS; 7235 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 7236 return RHS; 7237 return getAtomicType(ResultType); 7238 } 7239 case Type::ConstantArray: 7240 { 7241 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 7242 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 7243 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 7244 return QualType(); 7245 7246 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 7247 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 7248 if (Unqualified) { 7249 LHSElem = LHSElem.getUnqualifiedType(); 7250 RHSElem = RHSElem.getUnqualifiedType(); 7251 } 7252 7253 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 7254 if (ResultType.isNull()) return QualType(); 7255 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 7256 return LHS; 7257 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 7258 return RHS; 7259 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 7260 ArrayType::ArraySizeModifier(), 0); 7261 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 7262 ArrayType::ArraySizeModifier(), 0); 7263 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 7264 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 7265 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 7266 return LHS; 7267 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 7268 return RHS; 7269 if (LVAT) { 7270 // FIXME: This isn't correct! But tricky to implement because 7271 // the array's size has to be the size of LHS, but the type 7272 // has to be different. 7273 return LHS; 7274 } 7275 if (RVAT) { 7276 // FIXME: This isn't correct! But tricky to implement because 7277 // the array's size has to be the size of RHS, but the type 7278 // has to be different. 7279 return RHS; 7280 } 7281 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 7282 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 7283 return getIncompleteArrayType(ResultType, 7284 ArrayType::ArraySizeModifier(), 0); 7285 } 7286 case Type::FunctionNoProto: 7287 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 7288 case Type::Record: 7289 case Type::Enum: 7290 return QualType(); 7291 case Type::Builtin: 7292 // Only exactly equal builtin types are compatible, which is tested above. 7293 return QualType(); 7294 case Type::Complex: 7295 // Distinct complex types are incompatible. 7296 return QualType(); 7297 case Type::Vector: 7298 // FIXME: The merged type should be an ExtVector! 7299 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 7300 RHSCan->getAs<VectorType>())) 7301 return LHS; 7302 return QualType(); 7303 case Type::ObjCObject: { 7304 // Check if the types are assignment compatible. 7305 // FIXME: This should be type compatibility, e.g. whether 7306 // "LHS x; RHS x;" at global scope is legal. 7307 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 7308 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 7309 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 7310 return LHS; 7311 7312 return QualType(); 7313 } 7314 case Type::ObjCObjectPointer: { 7315 if (OfBlockPointer) { 7316 if (canAssignObjCInterfacesInBlockPointer( 7317 LHS->getAs<ObjCObjectPointerType>(), 7318 RHS->getAs<ObjCObjectPointerType>(), 7319 BlockReturnType)) 7320 return LHS; 7321 return QualType(); 7322 } 7323 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 7324 RHS->getAs<ObjCObjectPointerType>())) 7325 return LHS; 7326 7327 return QualType(); 7328 } 7329 } 7330 7331 llvm_unreachable("Invalid Type::Class!"); 7332 } 7333 7334 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs( 7335 const FunctionProtoType *FromFunctionType, 7336 const FunctionProtoType *ToFunctionType) { 7337 if (FromFunctionType->hasAnyConsumedParams() != 7338 ToFunctionType->hasAnyConsumedParams()) 7339 return false; 7340 FunctionProtoType::ExtProtoInfo FromEPI = 7341 FromFunctionType->getExtProtoInfo(); 7342 FunctionProtoType::ExtProtoInfo ToEPI = 7343 ToFunctionType->getExtProtoInfo(); 7344 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters) 7345 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) { 7346 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i]) 7347 return false; 7348 } 7349 return true; 7350 } 7351 7352 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 7353 /// 'RHS' attributes and returns the merged version; including for function 7354 /// return types. 7355 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 7356 QualType LHSCan = getCanonicalType(LHS), 7357 RHSCan = getCanonicalType(RHS); 7358 // If two types are identical, they are compatible. 7359 if (LHSCan == RHSCan) 7360 return LHS; 7361 if (RHSCan->isFunctionType()) { 7362 if (!LHSCan->isFunctionType()) 7363 return QualType(); 7364 QualType OldReturnType = 7365 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 7366 QualType NewReturnType = 7367 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 7368 QualType ResReturnType = 7369 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 7370 if (ResReturnType.isNull()) 7371 return QualType(); 7372 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 7373 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 7374 // In either case, use OldReturnType to build the new function type. 7375 const FunctionType *F = LHS->getAs<FunctionType>(); 7376 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 7377 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7378 EPI.ExtInfo = getFunctionExtInfo(LHS); 7379 QualType ResultType = 7380 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 7381 return ResultType; 7382 } 7383 } 7384 return QualType(); 7385 } 7386 7387 // If the qualifiers are different, the types can still be merged. 7388 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 7389 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 7390 if (LQuals != RQuals) { 7391 // If any of these qualifiers are different, we have a type mismatch. 7392 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 7393 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 7394 return QualType(); 7395 7396 // Exactly one GC qualifier difference is allowed: __strong is 7397 // okay if the other type has no GC qualifier but is an Objective 7398 // C object pointer (i.e. implicitly strong by default). We fix 7399 // this by pretending that the unqualified type was actually 7400 // qualified __strong. 7401 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 7402 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 7403 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 7404 7405 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 7406 return QualType(); 7407 7408 if (GC_L == Qualifiers::Strong) 7409 return LHS; 7410 if (GC_R == Qualifiers::Strong) 7411 return RHS; 7412 return QualType(); 7413 } 7414 7415 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 7416 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 7417 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 7418 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 7419 if (ResQT == LHSBaseQT) 7420 return LHS; 7421 if (ResQT == RHSBaseQT) 7422 return RHS; 7423 } 7424 return QualType(); 7425 } 7426 7427 //===----------------------------------------------------------------------===// 7428 // Integer Predicates 7429 //===----------------------------------------------------------------------===// 7430 7431 unsigned ASTContext::getIntWidth(QualType T) const { 7432 if (const EnumType *ET = T->getAs<EnumType>()) 7433 T = ET->getDecl()->getIntegerType(); 7434 if (T->isBooleanType()) 7435 return 1; 7436 // For builtin types, just use the standard type sizing method 7437 return (unsigned)getTypeSize(T); 7438 } 7439 7440 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 7441 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 7442 7443 // Turn <4 x signed int> -> <4 x unsigned int> 7444 if (const VectorType *VTy = T->getAs<VectorType>()) 7445 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 7446 VTy->getNumElements(), VTy->getVectorKind()); 7447 7448 // For enums, we return the unsigned version of the base type. 7449 if (const EnumType *ETy = T->getAs<EnumType>()) 7450 T = ETy->getDecl()->getIntegerType(); 7451 7452 const BuiltinType *BTy = T->getAs<BuiltinType>(); 7453 assert(BTy && "Unexpected signed integer type"); 7454 switch (BTy->getKind()) { 7455 case BuiltinType::Char_S: 7456 case BuiltinType::SChar: 7457 return UnsignedCharTy; 7458 case BuiltinType::Short: 7459 return UnsignedShortTy; 7460 case BuiltinType::Int: 7461 return UnsignedIntTy; 7462 case BuiltinType::Long: 7463 return UnsignedLongTy; 7464 case BuiltinType::LongLong: 7465 return UnsignedLongLongTy; 7466 case BuiltinType::Int128: 7467 return UnsignedInt128Ty; 7468 default: 7469 llvm_unreachable("Unexpected signed integer type"); 7470 } 7471 } 7472 7473 ASTMutationListener::~ASTMutationListener() { } 7474 7475 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 7476 QualType ReturnType) {} 7477 7478 //===----------------------------------------------------------------------===// 7479 // Builtin Type Computation 7480 //===----------------------------------------------------------------------===// 7481 7482 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 7483 /// pointer over the consumed characters. This returns the resultant type. If 7484 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 7485 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 7486 /// a vector of "i*". 7487 /// 7488 /// RequiresICE is filled in on return to indicate whether the value is required 7489 /// to be an Integer Constant Expression. 7490 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 7491 ASTContext::GetBuiltinTypeError &Error, 7492 bool &RequiresICE, 7493 bool AllowTypeModifiers) { 7494 // Modifiers. 7495 int HowLong = 0; 7496 bool Signed = false, Unsigned = false; 7497 RequiresICE = false; 7498 7499 // Read the prefixed modifiers first. 7500 bool Done = false; 7501 while (!Done) { 7502 switch (*Str++) { 7503 default: Done = true; --Str; break; 7504 case 'I': 7505 RequiresICE = true; 7506 break; 7507 case 'S': 7508 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 7509 assert(!Signed && "Can't use 'S' modifier multiple times!"); 7510 Signed = true; 7511 break; 7512 case 'U': 7513 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 7514 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 7515 Unsigned = true; 7516 break; 7517 case 'L': 7518 assert(HowLong <= 2 && "Can't have LLLL modifier"); 7519 ++HowLong; 7520 break; 7521 case 'W': 7522 // This modifier represents int64 type. 7523 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 7524 switch (Context.getTargetInfo().getInt64Type()) { 7525 default: 7526 llvm_unreachable("Unexpected integer type"); 7527 case TargetInfo::SignedLong: 7528 HowLong = 1; 7529 break; 7530 case TargetInfo::SignedLongLong: 7531 HowLong = 2; 7532 break; 7533 } 7534 } 7535 } 7536 7537 QualType Type; 7538 7539 // Read the base type. 7540 switch (*Str++) { 7541 default: llvm_unreachable("Unknown builtin type letter!"); 7542 case 'v': 7543 assert(HowLong == 0 && !Signed && !Unsigned && 7544 "Bad modifiers used with 'v'!"); 7545 Type = Context.VoidTy; 7546 break; 7547 case 'h': 7548 assert(HowLong == 0 && !Signed && !Unsigned && 7549 "Bad modifiers used with 'f'!"); 7550 Type = Context.HalfTy; 7551 break; 7552 case 'f': 7553 assert(HowLong == 0 && !Signed && !Unsigned && 7554 "Bad modifiers used with 'f'!"); 7555 Type = Context.FloatTy; 7556 break; 7557 case 'd': 7558 assert(HowLong < 2 && !Signed && !Unsigned && 7559 "Bad modifiers used with 'd'!"); 7560 if (HowLong) 7561 Type = Context.LongDoubleTy; 7562 else 7563 Type = Context.DoubleTy; 7564 break; 7565 case 's': 7566 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 7567 if (Unsigned) 7568 Type = Context.UnsignedShortTy; 7569 else 7570 Type = Context.ShortTy; 7571 break; 7572 case 'i': 7573 if (HowLong == 3) 7574 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 7575 else if (HowLong == 2) 7576 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 7577 else if (HowLong == 1) 7578 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 7579 else 7580 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 7581 break; 7582 case 'c': 7583 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 7584 if (Signed) 7585 Type = Context.SignedCharTy; 7586 else if (Unsigned) 7587 Type = Context.UnsignedCharTy; 7588 else 7589 Type = Context.CharTy; 7590 break; 7591 case 'b': // boolean 7592 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 7593 Type = Context.BoolTy; 7594 break; 7595 case 'z': // size_t. 7596 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 7597 Type = Context.getSizeType(); 7598 break; 7599 case 'F': 7600 Type = Context.getCFConstantStringType(); 7601 break; 7602 case 'G': 7603 Type = Context.getObjCIdType(); 7604 break; 7605 case 'H': 7606 Type = Context.getObjCSelType(); 7607 break; 7608 case 'M': 7609 Type = Context.getObjCSuperType(); 7610 break; 7611 case 'a': 7612 Type = Context.getBuiltinVaListType(); 7613 assert(!Type.isNull() && "builtin va list type not initialized!"); 7614 break; 7615 case 'A': 7616 // This is a "reference" to a va_list; however, what exactly 7617 // this means depends on how va_list is defined. There are two 7618 // different kinds of va_list: ones passed by value, and ones 7619 // passed by reference. An example of a by-value va_list is 7620 // x86, where va_list is a char*. An example of by-ref va_list 7621 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 7622 // we want this argument to be a char*&; for x86-64, we want 7623 // it to be a __va_list_tag*. 7624 Type = Context.getBuiltinVaListType(); 7625 assert(!Type.isNull() && "builtin va list type not initialized!"); 7626 if (Type->isArrayType()) 7627 Type = Context.getArrayDecayedType(Type); 7628 else 7629 Type = Context.getLValueReferenceType(Type); 7630 break; 7631 case 'V': { 7632 char *End; 7633 unsigned NumElements = strtoul(Str, &End, 10); 7634 assert(End != Str && "Missing vector size"); 7635 Str = End; 7636 7637 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 7638 RequiresICE, false); 7639 assert(!RequiresICE && "Can't require vector ICE"); 7640 7641 // TODO: No way to make AltiVec vectors in builtins yet. 7642 Type = Context.getVectorType(ElementType, NumElements, 7643 VectorType::GenericVector); 7644 break; 7645 } 7646 case 'E': { 7647 char *End; 7648 7649 unsigned NumElements = strtoul(Str, &End, 10); 7650 assert(End != Str && "Missing vector size"); 7651 7652 Str = End; 7653 7654 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 7655 false); 7656 Type = Context.getExtVectorType(ElementType, NumElements); 7657 break; 7658 } 7659 case 'X': { 7660 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 7661 false); 7662 assert(!RequiresICE && "Can't require complex ICE"); 7663 Type = Context.getComplexType(ElementType); 7664 break; 7665 } 7666 case 'Y' : { 7667 Type = Context.getPointerDiffType(); 7668 break; 7669 } 7670 case 'P': 7671 Type = Context.getFILEType(); 7672 if (Type.isNull()) { 7673 Error = ASTContext::GE_Missing_stdio; 7674 return QualType(); 7675 } 7676 break; 7677 case 'J': 7678 if (Signed) 7679 Type = Context.getsigjmp_bufType(); 7680 else 7681 Type = Context.getjmp_bufType(); 7682 7683 if (Type.isNull()) { 7684 Error = ASTContext::GE_Missing_setjmp; 7685 return QualType(); 7686 } 7687 break; 7688 case 'K': 7689 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 7690 Type = Context.getucontext_tType(); 7691 7692 if (Type.isNull()) { 7693 Error = ASTContext::GE_Missing_ucontext; 7694 return QualType(); 7695 } 7696 break; 7697 case 'p': 7698 Type = Context.getProcessIDType(); 7699 break; 7700 } 7701 7702 // If there are modifiers and if we're allowed to parse them, go for it. 7703 Done = !AllowTypeModifiers; 7704 while (!Done) { 7705 switch (char c = *Str++) { 7706 default: Done = true; --Str; break; 7707 case '*': 7708 case '&': { 7709 // Both pointers and references can have their pointee types 7710 // qualified with an address space. 7711 char *End; 7712 unsigned AddrSpace = strtoul(Str, &End, 10); 7713 if (End != Str && AddrSpace != 0) { 7714 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 7715 Str = End; 7716 } 7717 if (c == '*') 7718 Type = Context.getPointerType(Type); 7719 else 7720 Type = Context.getLValueReferenceType(Type); 7721 break; 7722 } 7723 // FIXME: There's no way to have a built-in with an rvalue ref arg. 7724 case 'C': 7725 Type = Type.withConst(); 7726 break; 7727 case 'D': 7728 Type = Context.getVolatileType(Type); 7729 break; 7730 case 'R': 7731 Type = Type.withRestrict(); 7732 break; 7733 } 7734 } 7735 7736 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 7737 "Integer constant 'I' type must be an integer"); 7738 7739 return Type; 7740 } 7741 7742 /// GetBuiltinType - Return the type for the specified builtin. 7743 QualType ASTContext::GetBuiltinType(unsigned Id, 7744 GetBuiltinTypeError &Error, 7745 unsigned *IntegerConstantArgs) const { 7746 const char *TypeStr = BuiltinInfo.GetTypeString(Id); 7747 7748 SmallVector<QualType, 8> ArgTypes; 7749 7750 bool RequiresICE = false; 7751 Error = GE_None; 7752 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 7753 RequiresICE, true); 7754 if (Error != GE_None) 7755 return QualType(); 7756 7757 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 7758 7759 while (TypeStr[0] && TypeStr[0] != '.') { 7760 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 7761 if (Error != GE_None) 7762 return QualType(); 7763 7764 // If this argument is required to be an IntegerConstantExpression and the 7765 // caller cares, fill in the bitmask we return. 7766 if (RequiresICE && IntegerConstantArgs) 7767 *IntegerConstantArgs |= 1 << ArgTypes.size(); 7768 7769 // Do array -> pointer decay. The builtin should use the decayed type. 7770 if (Ty->isArrayType()) 7771 Ty = getArrayDecayedType(Ty); 7772 7773 ArgTypes.push_back(Ty); 7774 } 7775 7776 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 7777 "'.' should only occur at end of builtin type list!"); 7778 7779 FunctionType::ExtInfo EI(CC_C); 7780 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 7781 7782 bool Variadic = (TypeStr[0] == '.'); 7783 7784 // We really shouldn't be making a no-proto type here, especially in C++. 7785 if (ArgTypes.empty() && Variadic) 7786 return getFunctionNoProtoType(ResType, EI); 7787 7788 FunctionProtoType::ExtProtoInfo EPI; 7789 EPI.ExtInfo = EI; 7790 EPI.Variadic = Variadic; 7791 7792 return getFunctionType(ResType, ArgTypes, EPI); 7793 } 7794 7795 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 7796 const FunctionDecl *FD) { 7797 if (!FD->isExternallyVisible()) 7798 return GVA_Internal; 7799 7800 GVALinkage External = GVA_StrongExternal; 7801 switch (FD->getTemplateSpecializationKind()) { 7802 case TSK_Undeclared: 7803 case TSK_ExplicitSpecialization: 7804 External = GVA_StrongExternal; 7805 break; 7806 7807 case TSK_ExplicitInstantiationDefinition: 7808 return GVA_StrongODR; 7809 7810 // C++11 [temp.explicit]p10: 7811 // [ Note: The intent is that an inline function that is the subject of 7812 // an explicit instantiation declaration will still be implicitly 7813 // instantiated when used so that the body can be considered for 7814 // inlining, but that no out-of-line copy of the inline function would be 7815 // generated in the translation unit. -- end note ] 7816 case TSK_ExplicitInstantiationDeclaration: 7817 return GVA_AvailableExternally; 7818 7819 case TSK_ImplicitInstantiation: 7820 External = GVA_DiscardableODR; 7821 break; 7822 } 7823 7824 if (!FD->isInlined()) 7825 return External; 7826 7827 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat && 7828 !FD->hasAttr<DLLExportAttr>()) || 7829 FD->hasAttr<GNUInlineAttr>()) { 7830 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 7831 7832 // GNU or C99 inline semantics. Determine whether this symbol should be 7833 // externally visible. 7834 if (FD->isInlineDefinitionExternallyVisible()) 7835 return External; 7836 7837 // C99 inline semantics, where the symbol is not externally visible. 7838 return GVA_AvailableExternally; 7839 } 7840 7841 // Functions specified with extern and inline in -fms-compatibility mode 7842 // forcibly get emitted. While the body of the function cannot be later 7843 // replaced, the function definition cannot be discarded. 7844 if (FD->getMostRecentDecl()->isMSExternInline()) 7845 return GVA_StrongODR; 7846 7847 return GVA_DiscardableODR; 7848 } 7849 7850 static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) { 7851 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 7852 // dllexport/dllimport on inline functions. 7853 if (D->hasAttr<DLLImportAttr>()) { 7854 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 7855 return GVA_AvailableExternally; 7856 } else if (D->hasAttr<DLLExportAttr>()) { 7857 if (L == GVA_DiscardableODR) 7858 return GVA_StrongODR; 7859 } 7860 return L; 7861 } 7862 7863 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 7864 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD), 7865 FD); 7866 } 7867 7868 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 7869 const VarDecl *VD) { 7870 if (!VD->isExternallyVisible()) 7871 return GVA_Internal; 7872 7873 if (VD->isStaticLocal()) { 7874 GVALinkage StaticLocalLinkage = GVA_DiscardableODR; 7875 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 7876 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 7877 LexicalContext = LexicalContext->getLexicalParent(); 7878 7879 // Let the static local variable inherit it's linkage from the nearest 7880 // enclosing function. 7881 if (LexicalContext) 7882 StaticLocalLinkage = 7883 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 7884 7885 // GVA_StrongODR function linkage is stronger than what we need, 7886 // downgrade to GVA_DiscardableODR. 7887 // This allows us to discard the variable if we never end up needing it. 7888 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR 7889 : StaticLocalLinkage; 7890 } 7891 7892 // MSVC treats in-class initialized static data members as definitions. 7893 // By giving them non-strong linkage, out-of-line definitions won't 7894 // cause link errors. 7895 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 7896 return GVA_DiscardableODR; 7897 7898 switch (VD->getTemplateSpecializationKind()) { 7899 case TSK_Undeclared: 7900 case TSK_ExplicitSpecialization: 7901 return GVA_StrongExternal; 7902 7903 case TSK_ExplicitInstantiationDefinition: 7904 return GVA_StrongODR; 7905 7906 case TSK_ExplicitInstantiationDeclaration: 7907 return GVA_AvailableExternally; 7908 7909 case TSK_ImplicitInstantiation: 7910 return GVA_DiscardableODR; 7911 } 7912 7913 llvm_unreachable("Invalid Linkage!"); 7914 } 7915 7916 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 7917 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD), 7918 VD); 7919 } 7920 7921 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 7922 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 7923 if (!VD->isFileVarDecl()) 7924 return false; 7925 // Global named register variables (GNU extension) are never emitted. 7926 if (VD->getStorageClass() == SC_Register) 7927 return false; 7928 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7929 // We never need to emit an uninstantiated function template. 7930 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 7931 return false; 7932 } else 7933 return false; 7934 7935 // If this is a member of a class template, we do not need to emit it. 7936 if (D->getDeclContext()->isDependentContext()) 7937 return false; 7938 7939 // Weak references don't produce any output by themselves. 7940 if (D->hasAttr<WeakRefAttr>()) 7941 return false; 7942 7943 // Aliases and used decls are required. 7944 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 7945 return true; 7946 7947 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7948 // Forward declarations aren't required. 7949 if (!FD->doesThisDeclarationHaveABody()) 7950 return FD->doesDeclarationForceExternallyVisibleDefinition(); 7951 7952 // Constructors and destructors are required. 7953 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 7954 return true; 7955 7956 // The key function for a class is required. This rule only comes 7957 // into play when inline functions can be key functions, though. 7958 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7959 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7960 const CXXRecordDecl *RD = MD->getParent(); 7961 if (MD->isOutOfLine() && RD->isDynamicClass()) { 7962 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 7963 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 7964 return true; 7965 } 7966 } 7967 } 7968 7969 GVALinkage Linkage = GetGVALinkageForFunction(FD); 7970 7971 // static, static inline, always_inline, and extern inline functions can 7972 // always be deferred. Normal inline functions can be deferred in C99/C++. 7973 // Implicit template instantiations can also be deferred in C++. 7974 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally || 7975 Linkage == GVA_DiscardableODR) 7976 return false; 7977 return true; 7978 } 7979 7980 const VarDecl *VD = cast<VarDecl>(D); 7981 assert(VD->isFileVarDecl() && "Expected file scoped var"); 7982 7983 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 7984 !isMSStaticDataMemberInlineDefinition(VD)) 7985 return false; 7986 7987 // Variables that can be needed in other TUs are required. 7988 GVALinkage L = GetGVALinkageForVariable(VD); 7989 if (L != GVA_Internal && L != GVA_AvailableExternally && 7990 L != GVA_DiscardableODR) 7991 return true; 7992 7993 // Variables that have destruction with side-effects are required. 7994 if (VD->getType().isDestructedType()) 7995 return true; 7996 7997 // Variables that have initialization with side-effects are required. 7998 if (VD->getInit() && VD->getInit()->HasSideEffects(*this)) 7999 return true; 8000 8001 return false; 8002 } 8003 8004 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 8005 bool IsCXXMethod) const { 8006 // Pass through to the C++ ABI object 8007 if (IsCXXMethod) 8008 return ABI->getDefaultMethodCallConv(IsVariadic); 8009 8010 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C; 8011 } 8012 8013 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 8014 // Pass through to the C++ ABI object 8015 return ABI->isNearlyEmpty(RD); 8016 } 8017 8018 VTableContextBase *ASTContext::getVTableContext() { 8019 if (!VTContext.get()) { 8020 if (Target->getCXXABI().isMicrosoft()) 8021 VTContext.reset(new MicrosoftVTableContext(*this)); 8022 else 8023 VTContext.reset(new ItaniumVTableContext(*this)); 8024 } 8025 return VTContext.get(); 8026 } 8027 8028 MangleContext *ASTContext::createMangleContext() { 8029 switch (Target->getCXXABI().getKind()) { 8030 case TargetCXXABI::GenericAArch64: 8031 case TargetCXXABI::GenericItanium: 8032 case TargetCXXABI::GenericARM: 8033 case TargetCXXABI::iOS: 8034 case TargetCXXABI::iOS64: 8035 return ItaniumMangleContext::create(*this, getDiagnostics()); 8036 case TargetCXXABI::Microsoft: 8037 return MicrosoftMangleContext::create(*this, getDiagnostics()); 8038 } 8039 llvm_unreachable("Unsupported ABI"); 8040 } 8041 8042 CXXABI::~CXXABI() {} 8043 8044 size_t ASTContext::getSideTableAllocatedMemory() const { 8045 return ASTRecordLayouts.getMemorySize() + 8046 llvm::capacity_in_bytes(ObjCLayouts) + 8047 llvm::capacity_in_bytes(KeyFunctions) + 8048 llvm::capacity_in_bytes(ObjCImpls) + 8049 llvm::capacity_in_bytes(BlockVarCopyInits) + 8050 llvm::capacity_in_bytes(DeclAttrs) + 8051 llvm::capacity_in_bytes(TemplateOrInstantiation) + 8052 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 8053 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 8054 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 8055 llvm::capacity_in_bytes(OverriddenMethods) + 8056 llvm::capacity_in_bytes(Types) + 8057 llvm::capacity_in_bytes(VariableArrayTypes) + 8058 llvm::capacity_in_bytes(ClassScopeSpecializationPattern); 8059 } 8060 8061 /// getIntTypeForBitwidth - 8062 /// sets integer QualTy according to specified details: 8063 /// bitwidth, signed/unsigned. 8064 /// Returns empty type if there is no appropriate target types. 8065 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 8066 unsigned Signed) const { 8067 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 8068 CanQualType QualTy = getFromTargetType(Ty); 8069 if (!QualTy && DestWidth == 128) 8070 return Signed ? Int128Ty : UnsignedInt128Ty; 8071 return QualTy; 8072 } 8073 8074 /// getRealTypeForBitwidth - 8075 /// sets floating point QualTy according to specified bitwidth. 8076 /// Returns empty type if there is no appropriate target types. 8077 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const { 8078 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth); 8079 switch (Ty) { 8080 case TargetInfo::Float: 8081 return FloatTy; 8082 case TargetInfo::Double: 8083 return DoubleTy; 8084 case TargetInfo::LongDouble: 8085 return LongDoubleTy; 8086 case TargetInfo::NoFloat: 8087 return QualType(); 8088 } 8089 8090 llvm_unreachable("Unhandled TargetInfo::RealType value"); 8091 } 8092 8093 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 8094 if (Number > 1) 8095 MangleNumbers[ND] = Number; 8096 } 8097 8098 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 8099 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I = 8100 MangleNumbers.find(ND); 8101 return I != MangleNumbers.end() ? I->second : 1; 8102 } 8103 8104 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 8105 if (Number > 1) 8106 StaticLocalNumbers[VD] = Number; 8107 } 8108 8109 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 8110 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I = 8111 StaticLocalNumbers.find(VD); 8112 return I != StaticLocalNumbers.end() ? I->second : 1; 8113 } 8114 8115 MangleNumberingContext & 8116 ASTContext::getManglingNumberContext(const DeclContext *DC) { 8117 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 8118 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC]; 8119 if (!MCtx) 8120 MCtx = createMangleNumberingContext(); 8121 return *MCtx; 8122 } 8123 8124 MangleNumberingContext *ASTContext::createMangleNumberingContext() const { 8125 return ABI->createMangleNumberingContext(); 8126 } 8127 8128 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 8129 ParamIndices[D] = index; 8130 } 8131 8132 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 8133 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 8134 assert(I != ParamIndices.end() && 8135 "ParmIndices lacks entry set by ParmVarDecl"); 8136 return I->second; 8137 } 8138 8139 APValue * 8140 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, 8141 bool MayCreate) { 8142 assert(E && E->getStorageDuration() == SD_Static && 8143 "don't need to cache the computed value for this temporary"); 8144 if (MayCreate) 8145 return &MaterializedTemporaryValues[E]; 8146 8147 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I = 8148 MaterializedTemporaryValues.find(E); 8149 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second; 8150 } 8151 8152 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 8153 const llvm::Triple &T = getTargetInfo().getTriple(); 8154 if (!T.isOSDarwin()) 8155 return false; 8156 8157 if (!(T.isiOS() && T.isOSVersionLT(7)) && 8158 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 8159 return false; 8160 8161 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 8162 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 8163 uint64_t Size = sizeChars.getQuantity(); 8164 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 8165 unsigned Align = alignChars.getQuantity(); 8166 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 8167 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 8168 } 8169 8170 namespace { 8171 8172 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their 8173 /// parents as defined by the \c RecursiveASTVisitor. 8174 /// 8175 /// Note that the relationship described here is purely in terms of AST 8176 /// traversal - there are other relationships (for example declaration context) 8177 /// in the AST that are better modeled by special matchers. 8178 /// 8179 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes. 8180 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> { 8181 8182 public: 8183 /// \brief Builds and returns the translation unit's parent map. 8184 /// 8185 /// The caller takes ownership of the returned \c ParentMap. 8186 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) { 8187 ParentMapASTVisitor Visitor(new ASTContext::ParentMap); 8188 Visitor.TraverseDecl(&TU); 8189 return Visitor.Parents; 8190 } 8191 8192 private: 8193 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase; 8194 8195 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) { 8196 } 8197 8198 bool shouldVisitTemplateInstantiations() const { 8199 return true; 8200 } 8201 bool shouldVisitImplicitCode() const { 8202 return true; 8203 } 8204 // Disables data recursion. We intercept Traverse* methods in the RAV, which 8205 // are not triggered during data recursion. 8206 bool shouldUseDataRecursionFor(clang::Stmt *S) const { 8207 return false; 8208 } 8209 8210 template <typename T> 8211 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) { 8212 if (!Node) 8213 return true; 8214 if (ParentStack.size() > 0) { 8215 // FIXME: Currently we add the same parent multiple times, but only 8216 // when no memoization data is available for the type. 8217 // For example when we visit all subexpressions of template 8218 // instantiations; this is suboptimal, but benign: the only way to 8219 // visit those is with hasAncestor / hasParent, and those do not create 8220 // new matches. 8221 // The plan is to enable DynTypedNode to be storable in a map or hash 8222 // map. The main problem there is to implement hash functions / 8223 // comparison operators for all types that DynTypedNode supports that 8224 // do not have pointer identity. 8225 auto &NodeOrVector = (*Parents)[Node]; 8226 if (NodeOrVector.isNull()) { 8227 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back()); 8228 } else { 8229 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) { 8230 auto *Node = 8231 NodeOrVector.template get<ast_type_traits::DynTypedNode *>(); 8232 auto *Vector = new ASTContext::ParentVector(1, *Node); 8233 NodeOrVector = Vector; 8234 delete Node; 8235 } 8236 assert(NodeOrVector.template is<ASTContext::ParentVector *>()); 8237 8238 auto *Vector = 8239 NodeOrVector.template get<ASTContext::ParentVector *>(); 8240 // Skip duplicates for types that have memoization data. 8241 // We must check that the type has memoization data before calling 8242 // std::find() because DynTypedNode::operator== can't compare all 8243 // types. 8244 bool Found = ParentStack.back().getMemoizationData() && 8245 std::find(Vector->begin(), Vector->end(), 8246 ParentStack.back()) != Vector->end(); 8247 if (!Found) 8248 Vector->push_back(ParentStack.back()); 8249 } 8250 } 8251 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node)); 8252 bool Result = (this ->* traverse) (Node); 8253 ParentStack.pop_back(); 8254 return Result; 8255 } 8256 8257 bool TraverseDecl(Decl *DeclNode) { 8258 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl); 8259 } 8260 8261 bool TraverseStmt(Stmt *StmtNode) { 8262 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt); 8263 } 8264 8265 ASTContext::ParentMap *Parents; 8266 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack; 8267 8268 friend class RecursiveASTVisitor<ParentMapASTVisitor>; 8269 }; 8270 8271 } // end namespace 8272 8273 ASTContext::ParentVector 8274 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) { 8275 assert(Node.getMemoizationData() && 8276 "Invariant broken: only nodes that support memoization may be " 8277 "used in the parent map."); 8278 if (!AllParents) { 8279 // We always need to run over the whole translation unit, as 8280 // hasAncestor can escape any subtree. 8281 AllParents.reset( 8282 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl())); 8283 } 8284 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData()); 8285 if (I == AllParents->end()) { 8286 return ParentVector(); 8287 } 8288 if (I->second.is<ast_type_traits::DynTypedNode *>()) { 8289 return ParentVector(1, *I->second.get<ast_type_traits::DynTypedNode *>()); 8290 } 8291 const auto &Parents = *I->second.get<ParentVector *>(); 8292 return ParentVector(Parents.begin(), Parents.end()); 8293 } 8294 8295 bool 8296 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 8297 const ObjCMethodDecl *MethodImpl) { 8298 // No point trying to match an unavailable/deprecated mothod. 8299 if (MethodDecl->hasAttr<UnavailableAttr>() 8300 || MethodDecl->hasAttr<DeprecatedAttr>()) 8301 return false; 8302 if (MethodDecl->getObjCDeclQualifier() != 8303 MethodImpl->getObjCDeclQualifier()) 8304 return false; 8305 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 8306 return false; 8307 8308 if (MethodDecl->param_size() != MethodImpl->param_size()) 8309 return false; 8310 8311 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 8312 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 8313 EF = MethodDecl->param_end(); 8314 IM != EM && IF != EF; ++IM, ++IF) { 8315 const ParmVarDecl *DeclVar = (*IF); 8316 const ParmVarDecl *ImplVar = (*IM); 8317 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 8318 return false; 8319 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 8320 return false; 8321 } 8322 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 8323 8324 } 8325 8326 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 8327 // doesn't include ASTContext.h 8328 template 8329 clang::LazyGenerationalUpdatePtr< 8330 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 8331 clang::LazyGenerationalUpdatePtr< 8332 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 8333 const clang::ASTContext &Ctx, Decl *Value); 8334