Sema.cpp revision 82d0a418c8699fc6f4a9417457ffe93d43bba1c1
1//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===// 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 actions class which performs semantic analysis and 11// builds an AST out of a parse stream. 12// 13//===----------------------------------------------------------------------===// 14 15#include "Sema.h" 16#include "TargetAttributesSema.h" 17#include "llvm/ADT/DenseMap.h" 18#include "llvm/ADT/APFloat.h" 19#include "clang/AST/ASTConsumer.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/DeclObjC.h" 22#include "clang/AST/Expr.h" 23#include "clang/Lex/Preprocessor.h" 24#include "clang/Basic/PartialDiagnostic.h" 25#include "clang/Basic/TargetInfo.h" 26using namespace clang; 27 28/// Determines whether we should have an a.k.a. clause when 29/// pretty-printing a type. There are three main criteria: 30/// 31/// 1) Some types provide very minimal sugar that doesn't impede the 32/// user's understanding --- for example, elaborated type 33/// specifiers. If this is all the sugar we see, we don't want an 34/// a.k.a. clause. 35/// 2) Some types are technically sugared but are much more familiar 36/// when seen in their sugared form --- for example, va_list, 37/// vector types, and the magic Objective C types. We don't 38/// want to desugar these, even if we do produce an a.k.a. clause. 39/// 3) Some types may have already been desugared previously in this diagnostic. 40/// if this is the case, doing another "aka" would just be clutter. 41/// 42static bool ShouldAKA(ASTContext &Context, QualType QT, 43 const Diagnostic::ArgumentValue *PrevArgs, 44 unsigned NumPrevArgs, 45 QualType &DesugaredQT) { 46 QualType InputTy = QT; 47 48 bool AKA = false; 49 QualifierCollector Qc; 50 51 while (true) { 52 const Type *Ty = Qc.strip(QT); 53 54 // Don't aka just because we saw an elaborated type... 55 if (isa<ElaboratedType>(Ty)) { 56 QT = cast<ElaboratedType>(Ty)->desugar(); 57 continue; 58 } 59 60 // ...or a qualified name type... 61 if (isa<QualifiedNameType>(Ty)) { 62 QT = cast<QualifiedNameType>(Ty)->desugar(); 63 continue; 64 } 65 66 // ...or a substituted template type parameter. 67 if (isa<SubstTemplateTypeParmType>(Ty)) { 68 QT = cast<SubstTemplateTypeParmType>(Ty)->desugar(); 69 continue; 70 } 71 72 // Don't desugar template specializations. 73 if (isa<TemplateSpecializationType>(Ty)) 74 break; 75 76 // Don't desugar magic Objective-C types. 77 if (QualType(Ty,0) == Context.getObjCIdType() || 78 QualType(Ty,0) == Context.getObjCClassType() || 79 QualType(Ty,0) == Context.getObjCSelType() || 80 QualType(Ty,0) == Context.getObjCProtoType()) 81 break; 82 83 // Don't desugar va_list. 84 if (QualType(Ty,0) == Context.getBuiltinVaListType()) 85 break; 86 87 // Otherwise, do a single-step desugar. 88 QualType Underlying; 89 bool IsSugar = false; 90 switch (Ty->getTypeClass()) { 91#define ABSTRACT_TYPE(Class, Base) 92#define TYPE(Class, Base) \ 93 case Type::Class: { \ 94 const Class##Type *CTy = cast<Class##Type>(Ty); \ 95 if (CTy->isSugared()) { \ 96 IsSugar = true; \ 97 Underlying = CTy->desugar(); \ 98 } \ 99 break; \ 100 } 101#include "clang/AST/TypeNodes.def" 102 } 103 104 // If it wasn't sugared, we're done. 105 if (!IsSugar) 106 break; 107 108 // If the desugared type is a vector type, we don't want to expand 109 // it, it will turn into an attribute mess. People want their "vec4". 110 if (isa<VectorType>(Underlying)) 111 break; 112 113 // Otherwise, we're tearing through something opaque; note that 114 // we'll eventually need an a.k.a. clause and keep going. 115 AKA = true; 116 QT = Underlying; 117 continue; 118 } 119 120 // If we never tore through opaque sugar, don't print aka. 121 if (!AKA) return false; 122 123 // If we did, check to see if we already desugared this type in this 124 // diagnostic. If so, don't do it again. 125 for (unsigned i = 0; i != NumPrevArgs; ++i) { 126 // TODO: Handle ak_declcontext case. 127 if (PrevArgs[i].first == Diagnostic::ak_qualtype) { 128 void *Ptr = (void*)PrevArgs[i].second; 129 QualType PrevTy(QualType::getFromOpaquePtr(Ptr)); 130 if (PrevTy == InputTy) 131 return false; 132 } 133 } 134 135 DesugaredQT = Qc.apply(QT); 136 return true; 137} 138 139/// \brief Convert the given type to a string suitable for printing as part of 140/// a diagnostic. 141/// 142/// \param Context the context in which the type was allocated 143/// \param Ty the type to print 144static std::string 145ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty, 146 const Diagnostic::ArgumentValue *PrevArgs, 147 unsigned NumPrevArgs) { 148 // FIXME: Playing with std::string is really slow. 149 std::string S = Ty.getAsString(Context.PrintingPolicy); 150 151 // Consider producing an a.k.a. clause if removing all the direct 152 // sugar gives us something "significantly different". 153 154 QualType DesugaredTy; 155 if (ShouldAKA(Context, Ty, PrevArgs, NumPrevArgs, DesugaredTy)) { 156 S = "'"+S+"' (aka '"; 157 S += DesugaredTy.getAsString(Context.PrintingPolicy); 158 S += "')"; 159 return S; 160 } 161 162 S = "'" + S + "'"; 163 return S; 164} 165 166/// ConvertQualTypeToStringFn - This function is used to pretty print the 167/// specified QualType as a string in diagnostics. 168static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val, 169 const char *Modifier, unsigned ModLen, 170 const char *Argument, unsigned ArgLen, 171 const Diagnostic::ArgumentValue *PrevArgs, 172 unsigned NumPrevArgs, 173 llvm::SmallVectorImpl<char> &Output, 174 void *Cookie) { 175 ASTContext &Context = *static_cast<ASTContext*>(Cookie); 176 177 std::string S; 178 bool NeedQuotes = true; 179 180 switch (Kind) { 181 default: assert(0 && "unknown ArgumentKind"); 182 case Diagnostic::ak_qualtype: { 183 assert(ModLen == 0 && ArgLen == 0 && 184 "Invalid modifier for QualType argument"); 185 186 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val))); 187 S = ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, NumPrevArgs); 188 NeedQuotes = false; 189 break; 190 } 191 case Diagnostic::ak_declarationname: { 192 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val); 193 S = N.getAsString(); 194 195 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0) 196 S = '+' + S; 197 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0) 198 S = '-' + S; 199 else 200 assert(ModLen == 0 && ArgLen == 0 && 201 "Invalid modifier for DeclarationName argument"); 202 break; 203 } 204 case Diagnostic::ak_nameddecl: { 205 bool Qualified; 206 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0) 207 Qualified = true; 208 else { 209 assert(ModLen == 0 && ArgLen == 0 && 210 "Invalid modifier for NamedDecl* argument"); 211 Qualified = false; 212 } 213 reinterpret_cast<NamedDecl*>(Val)-> 214 getNameForDiagnostic(S, Context.PrintingPolicy, Qualified); 215 break; 216 } 217 case Diagnostic::ak_nestednamespec: { 218 llvm::raw_string_ostream OS(S); 219 reinterpret_cast<NestedNameSpecifier*>(Val)->print(OS, 220 Context.PrintingPolicy); 221 NeedQuotes = false; 222 break; 223 } 224 case Diagnostic::ak_declcontext: { 225 DeclContext *DC = reinterpret_cast<DeclContext *> (Val); 226 assert(DC && "Should never have a null declaration context"); 227 228 if (DC->isTranslationUnit()) { 229 // FIXME: Get these strings from some localized place 230 if (Context.getLangOptions().CPlusPlus) 231 S = "the global namespace"; 232 else 233 S = "the global scope"; 234 } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) { 235 S = ConvertTypeToDiagnosticString(Context, Context.getTypeDeclType(Type), 236 PrevArgs, NumPrevArgs); 237 } else { 238 // FIXME: Get these strings from some localized place 239 NamedDecl *ND = cast<NamedDecl>(DC); 240 if (isa<NamespaceDecl>(ND)) 241 S += "namespace "; 242 else if (isa<ObjCMethodDecl>(ND)) 243 S += "method "; 244 else if (isa<FunctionDecl>(ND)) 245 S += "function "; 246 247 S += "'"; 248 ND->getNameForDiagnostic(S, Context.PrintingPolicy, true); 249 S += "'"; 250 } 251 NeedQuotes = false; 252 break; 253 } 254 } 255 256 if (NeedQuotes) 257 Output.push_back('\''); 258 259 Output.append(S.begin(), S.end()); 260 261 if (NeedQuotes) 262 Output.push_back('\''); 263} 264 265 266static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) { 267 if (C.getLangOptions().CPlusPlus) 268 return CXXRecordDecl::Create(C, TagDecl::TK_struct, 269 C.getTranslationUnitDecl(), 270 SourceLocation(), &C.Idents.get(Name)); 271 272 return RecordDecl::Create(C, TagDecl::TK_struct, 273 C.getTranslationUnitDecl(), 274 SourceLocation(), &C.Idents.get(Name)); 275} 276 277void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { 278 TUScope = S; 279 PushDeclContext(S, Context.getTranslationUnitDecl()); 280 281 if (PP.getTargetInfo().getPointerWidth(0) >= 64) { 282 TypeSourceInfo *TInfo; 283 284 // Install [u]int128_t for 64-bit targets. 285 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty); 286 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 287 SourceLocation(), 288 &Context.Idents.get("__int128_t"), 289 TInfo), TUScope); 290 291 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty); 292 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 293 SourceLocation(), 294 &Context.Idents.get("__uint128_t"), 295 TInfo), TUScope); 296 } 297 298 299 if (!PP.getLangOptions().ObjC1) return; 300 301 // Built-in ObjC types may already be set by PCHReader (hence isNull checks). 302 if (Context.getObjCSelType().isNull()) { 303 // Create the built-in typedef for 'SEL'. 304 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy); 305 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT); 306 TypedefDecl *SelTypedef 307 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 308 &Context.Idents.get("SEL"), SelInfo); 309 PushOnScopeChains(SelTypedef, TUScope); 310 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef)); 311 Context.ObjCSelRedefinitionType = Context.getObjCSelType(); 312 } 313 314 // Synthesize "@class Protocol; 315 if (Context.getObjCProtoType().isNull()) { 316 ObjCInterfaceDecl *ProtocolDecl = 317 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 318 &Context.Idents.get("Protocol"), 319 SourceLocation(), true); 320 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 321 PushOnScopeChains(ProtocolDecl, TUScope, false); 322 } 323 // Create the built-in typedef for 'id'. 324 if (Context.getObjCIdType().isNull()) { 325 QualType IdT = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy); 326 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(IdT); 327 TypedefDecl *IdTypedef 328 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 329 &Context.Idents.get("id"), IdInfo); 330 PushOnScopeChains(IdTypedef, TUScope); 331 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef)); 332 Context.ObjCIdRedefinitionType = Context.getObjCIdType(); 333 } 334 // Create the built-in typedef for 'Class'. 335 if (Context.getObjCClassType().isNull()) { 336 QualType ClassType 337 = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy); 338 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(ClassType); 339 TypedefDecl *ClassTypedef 340 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 341 &Context.Idents.get("Class"), ClassInfo); 342 PushOnScopeChains(ClassTypedef, TUScope); 343 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef)); 344 Context.ObjCClassRedefinitionType = Context.getObjCClassType(); 345 } 346} 347 348Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 349 bool CompleteTranslationUnit, 350 CodeCompleteConsumer *CodeCompleter) 351 : TheTargetAttributesSema(0), 352 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 353 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 354 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0), 355 CurBlock(0), PackContext(0), ParsingDeclDepth(0), 356 IdResolver(pp.getLangOptions()), StdNamespace(0), StdBadAlloc(0), 357 GlobalNewDeleteDeclared(false), 358 CompleteTranslationUnit(CompleteTranslationUnit), 359 NumSFINAEErrors(0), NonInstantiationEntries(0), 360 CurrentInstantiationScope(0) 361{ 362 TUScope = 0; 363 if (getLangOptions().CPlusPlus) 364 FieldCollector.reset(new CXXFieldCollector()); 365 366 // Tell diagnostics how to render things from the AST library. 367 PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context); 368 369 ExprEvalContexts.push_back( 370 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0)); 371} 372 373Sema::~Sema() { 374 if (PackContext) FreePackedContext(); 375 delete TheTargetAttributesSema; 376} 377 378/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 379/// If there is already an implicit cast, merge into the existing one. 380/// If isLvalue, the result of the cast is an lvalue. 381void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, 382 CastExpr::CastKind Kind, bool isLvalue) { 383 QualType ExprTy = Context.getCanonicalType(Expr->getType()); 384 QualType TypeTy = Context.getCanonicalType(Ty); 385 386 if (ExprTy == TypeTy) 387 return; 388 389 if (Expr->getType()->isPointerType() && Ty->isPointerType()) { 390 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType(); 391 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType(); 392 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { 393 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) 394 << Expr->getSourceRange(); 395 } 396 } 397 398 CheckImplicitConversion(Expr, Ty); 399 400 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { 401 if (ImpCast->getCastKind() == Kind) { 402 ImpCast->setType(Ty); 403 ImpCast->setLvalueCast(isLvalue); 404 return; 405 } 406 } 407 408 Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, isLvalue); 409} 410 411void Sema::DeleteExpr(ExprTy *E) { 412 if (E) static_cast<Expr*>(E)->Destroy(Context); 413} 414void Sema::DeleteStmt(StmtTy *S) { 415 if (S) static_cast<Stmt*>(S)->Destroy(Context); 416} 417 418/// ActOnEndOfTranslationUnit - This is called at the very end of the 419/// translation unit when EOF is reached and all but the top-level scope is 420/// popped. 421void Sema::ActOnEndOfTranslationUnit() { 422 423 while (1) { 424 // C++: Perform implicit template instantiations. 425 // 426 // FIXME: When we perform these implicit instantiations, we do not carefully 427 // keep track of the point of instantiation (C++ [temp.point]). This means 428 // that name lookup that occurs within the template instantiation will 429 // always happen at the end of the translation unit, so it will find 430 // some names that should not be found. Although this is common behavior 431 // for C++ compilers, it is technically wrong. In the future, we either need 432 // to be able to filter the results of name lookup or we need to perform 433 // template instantiations earlier. 434 PerformPendingImplicitInstantiations(); 435 436 /// If ProcessPendingClassesWithUnmarkedVirtualMembers ends up marking 437 /// any virtual member functions it might lead to more pending template 438 /// instantiations, which is why we need to loop here. 439 if (!ProcessPendingClassesWithUnmarkedVirtualMembers()) 440 break; 441 } 442 443 // Check for #pragma weak identifiers that were never declared 444 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 445 // order! Iterating over a densemap like this is bad. 446 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 447 I = WeakUndeclaredIdentifiers.begin(), 448 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 449 if (I->second.getUsed()) continue; 450 451 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 452 << I->first; 453 } 454 455 if (!CompleteTranslationUnit) 456 return; 457 458 // C99 6.9.2p2: 459 // A declaration of an identifier for an object that has file 460 // scope without an initializer, and without a storage-class 461 // specifier or with the storage-class specifier static, 462 // constitutes a tentative definition. If a translation unit 463 // contains one or more tentative definitions for an identifier, 464 // and the translation unit contains no external definition for 465 // that identifier, then the behavior is exactly as if the 466 // translation unit contains a file scope declaration of that 467 // identifier, with the composite type as of the end of the 468 // translation unit, with an initializer equal to 0. 469 for (unsigned i = 0, e = TentativeDefinitionList.size(); i != e; ++i) { 470 VarDecl *VD = TentativeDefinitions.lookup(TentativeDefinitionList[i]); 471 472 // If the tentative definition was completed, it will be in the list, but 473 // not the map. 474 if (VD == 0 || VD->isInvalidDecl() || !VD->isTentativeDefinition(Context)) 475 continue; 476 477 if (const IncompleteArrayType *ArrayT 478 = Context.getAsIncompleteArrayType(VD->getType())) { 479 if (RequireCompleteType(VD->getLocation(), 480 ArrayT->getElementType(), 481 diag::err_tentative_def_incomplete_type_arr)) { 482 VD->setInvalidDecl(); 483 continue; 484 } 485 486 // Set the length of the array to 1 (C99 6.9.2p5). 487 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 488 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 489 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 490 One, ArrayType::Normal, 0); 491 VD->setType(T); 492 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 493 diag::err_tentative_def_incomplete_type)) 494 VD->setInvalidDecl(); 495 496 // Notify the consumer that we've completed a tentative definition. 497 if (!VD->isInvalidDecl()) 498 Consumer.CompleteTentativeDefinition(VD); 499 500 } 501} 502 503 504//===----------------------------------------------------------------------===// 505// Helper functions. 506//===----------------------------------------------------------------------===// 507 508DeclContext *Sema::getFunctionLevelDeclContext() { 509 DeclContext *DC = CurContext; 510 511 while (isa<BlockDecl>(DC)) 512 DC = DC->getParent(); 513 514 return DC; 515} 516 517/// getCurFunctionDecl - If inside of a function body, this returns a pointer 518/// to the function decl for the function being parsed. If we're currently 519/// in a 'block', this returns the containing context. 520FunctionDecl *Sema::getCurFunctionDecl() { 521 DeclContext *DC = getFunctionLevelDeclContext(); 522 return dyn_cast<FunctionDecl>(DC); 523} 524 525ObjCMethodDecl *Sema::getCurMethodDecl() { 526 DeclContext *DC = getFunctionLevelDeclContext(); 527 return dyn_cast<ObjCMethodDecl>(DC); 528} 529 530NamedDecl *Sema::getCurFunctionOrMethodDecl() { 531 DeclContext *DC = getFunctionLevelDeclContext(); 532 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 533 return cast<NamedDecl>(DC); 534 return 0; 535} 536 537Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 538 if (!this->Emit()) 539 return; 540 541 // If this is not a note, and we're in a template instantiation 542 // that is different from the last template instantiation where 543 // we emitted an error, print a template instantiation 544 // backtrace. 545 if (!SemaRef.Diags.isBuiltinNote(DiagID) && 546 !SemaRef.ActiveTemplateInstantiations.empty() && 547 SemaRef.ActiveTemplateInstantiations.back() 548 != SemaRef.LastTemplateInstantiationErrorContext) { 549 SemaRef.PrintInstantiationStack(); 550 SemaRef.LastTemplateInstantiationErrorContext 551 = SemaRef.ActiveTemplateInstantiations.back(); 552 } 553} 554 555Sema::SemaDiagnosticBuilder 556Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 557 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 558 PD.Emit(Builder); 559 560 return Builder; 561} 562 563void Sema::ActOnComment(SourceRange Comment) { 564 Context.Comments.push_back(Comment); 565} 566 567