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