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