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