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