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