Sema.cpp revision 1eb4433ac451dc16f4133a88af2d002ac26c58ef
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 "llvm/ADT/DenseMap.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/Expr.h" 21#include "clang/Lex/Preprocessor.h" 22#include "clang/Basic/PartialDiagnostic.h" 23#include "clang/Basic/TargetInfo.h" 24using namespace clang; 25 26/// ConvertQualTypeToStringFn - This function is used to pretty print the 27/// specified QualType as a string in diagnostics. 28static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val, 29 const char *Modifier, unsigned ModLen, 30 const char *Argument, unsigned ArgLen, 31 llvm::SmallVectorImpl<char> &Output, 32 void *Cookie) { 33 ASTContext &Context = *static_cast<ASTContext*>(Cookie); 34 35 std::string S; 36 if (Kind == Diagnostic::ak_qualtype) { 37 assert(ModLen == 0 && ArgLen == 0 && 38 "Invalid modifier for QualType argument"); 39 40 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val))); 41 42 // FIXME: Playing with std::string is really slow. 43 S = Ty.getAsString(Context.PrintingPolicy); 44 45 // If this is a sugared type (like a typedef, typeof, etc), then unwrap one 46 // level of the sugar so that the type is more obvious to the user. 47 QualType DesugaredTy = Ty->getDesugaredType(true); 48 DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() | 49 Ty.getCVRQualifiers()); 50 51 if (Ty != DesugaredTy && 52 // If the desugared type is a vector type, we don't want to expand it, 53 // it will turn into an attribute mess. People want their "vec4". 54 !isa<VectorType>(DesugaredTy) && 55 56 // Don't aka just because we saw an elaborated type. 57 (!isa<ElaboratedType>(Ty) || 58 cast<ElaboratedType>(Ty)->getUnderlyingType() != DesugaredTy) && 59 60 // Don't desugar magic Objective-C types. 61 Ty.getUnqualifiedType() != Context.getObjCIdType() && 62 Ty.getUnqualifiedType() != Context.getObjCClassType() && 63 Ty.getUnqualifiedType() != Context.getObjCSelType() && 64 Ty.getUnqualifiedType() != Context.getObjCProtoType() && 65 66 // Not va_list. 67 Ty.getUnqualifiedType() != Context.getBuiltinVaListType()) { 68 S = "'"+S+"' (aka '"; 69 S += DesugaredTy.getAsString(Context.PrintingPolicy); 70 S += "')"; 71 Output.append(S.begin(), S.end()); 72 return; 73 } 74 75 } else if (Kind == Diagnostic::ak_declarationname) { 76 77 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val); 78 S = N.getAsString(); 79 80 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0) 81 S = '+' + S; 82 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0) 83 S = '-' + S; 84 else 85 assert(ModLen == 0 && ArgLen == 0 && 86 "Invalid modifier for DeclarationName argument"); 87 } else if (Kind == Diagnostic::ak_nameddecl) { 88 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0) 89 S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString(); 90 else { 91 assert(ModLen == 0 && ArgLen == 0 && 92 "Invalid modifier for NamedDecl* argument"); 93 S = reinterpret_cast<NamedDecl*>(Val)->getNameAsString(); 94 } 95 } else { 96 llvm::raw_string_ostream OS(S); 97 assert(Kind == Diagnostic::ak_nestednamespec); 98 reinterpret_cast<NestedNameSpecifier*> (Val)->print(OS, 99 Context.PrintingPolicy); 100 } 101 102 Output.push_back('\''); 103 Output.append(S.begin(), S.end()); 104 Output.push_back('\''); 105} 106 107 108static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) { 109 if (C.getLangOptions().CPlusPlus) 110 return CXXRecordDecl::Create(C, TagDecl::TK_struct, 111 C.getTranslationUnitDecl(), 112 SourceLocation(), &C.Idents.get(Name)); 113 114 return RecordDecl::Create(C, TagDecl::TK_struct, 115 C.getTranslationUnitDecl(), 116 SourceLocation(), &C.Idents.get(Name)); 117} 118 119void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { 120 TUScope = S; 121 PushDeclContext(S, Context.getTranslationUnitDecl()); 122 123 if (PP.getTargetInfo().getPointerWidth(0) >= 64) { 124 // Install [u]int128_t for 64-bit targets. 125 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 126 SourceLocation(), 127 &Context.Idents.get("__int128_t"), 128 Context.Int128Ty), TUScope); 129 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 130 SourceLocation(), 131 &Context.Idents.get("__uint128_t"), 132 Context.UnsignedInt128Ty), TUScope); 133 } 134 135 136 if (!PP.getLangOptions().ObjC1) return; 137 138 // Built-in ObjC types may already be set by PCHReader (hence isNull checks). 139 if (Context.getObjCSelType().isNull()) { 140 // Synthesize "typedef struct objc_selector *SEL;" 141 RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector"); 142 PushOnScopeChains(SelTag, TUScope); 143 144 QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag)); 145 TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext, 146 SourceLocation(), 147 &Context.Idents.get("SEL"), 148 SelT); 149 PushOnScopeChains(SelTypedef, TUScope); 150 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef)); 151 } 152 153 // Synthesize "@class Protocol; 154 if (Context.getObjCProtoType().isNull()) { 155 ObjCInterfaceDecl *ProtocolDecl = 156 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 157 &Context.Idents.get("Protocol"), 158 SourceLocation(), true); 159 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 160 PushOnScopeChains(ProtocolDecl, TUScope); 161 } 162 // Create the built-in typedef for 'id'. 163 if (Context.getObjCIdType().isNull()) { 164 TypedefDecl *IdTypedef = 165 TypedefDecl::Create( 166 Context, CurContext, SourceLocation(), &Context.Idents.get("id"), 167 Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy) 168 ); 169 PushOnScopeChains(IdTypedef, TUScope); 170 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef)); 171 Context.ObjCIdRedefinitionType = Context.getObjCIdType(); 172 } 173 // Create the built-in typedef for 'Class'. 174 if (Context.getObjCClassType().isNull()) { 175 TypedefDecl *ClassTypedef = 176 TypedefDecl::Create( 177 Context, CurContext, SourceLocation(), &Context.Idents.get("Class"), 178 Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy) 179 ); 180 PushOnScopeChains(ClassTypedef, TUScope); 181 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef)); 182 Context.ObjCClassRedefinitionType = Context.getObjCClassType(); 183 } 184} 185 186Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 187 bool CompleteTranslationUnit) 188 : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 189 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 190 ExternalSource(0), CurContext(0), PreDeclaratorDC(0), 191 CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()), 192 GlobalNewDeleteDeclared(false), ExprEvalContext(PotentiallyEvaluated), 193 CompleteTranslationUnit(CompleteTranslationUnit), 194 NumSFINAEErrors(0), CurrentInstantiationScope(0) { 195 196 StdNamespace = 0; 197 TUScope = 0; 198 if (getLangOptions().CPlusPlus) 199 FieldCollector.reset(new CXXFieldCollector()); 200 201 // Tell diagnostics how to render things from the AST library. 202 PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context); 203} 204 205/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 206/// If there is already an implicit cast, merge into the existing one. 207/// If isLvalue, the result of the cast is an lvalue. 208void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, 209 const CastExpr::CastInfo &Info, bool isLvalue) { 210 QualType ExprTy = Context.getCanonicalType(Expr->getType()); 211 QualType TypeTy = Context.getCanonicalType(Ty); 212 213 if (ExprTy == TypeTy) 214 return; 215 216 if (Expr->getType().getTypePtr()->isPointerType() && 217 Ty.getTypePtr()->isPointerType()) { 218 QualType ExprBaseType = 219 cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType(); 220 QualType BaseType = 221 cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType(); 222 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { 223 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) 224 << Expr->getSourceRange(); 225 } 226 } 227 228 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { 229 ImpCast->setType(Ty); 230 ImpCast->setLvalueCast(isLvalue); 231 } else 232 Expr = new (Context) ImplicitCastExpr(Ty, Info, Expr, 233 isLvalue); 234} 235 236void Sema::DeleteExpr(ExprTy *E) { 237 if (E) static_cast<Expr*>(E)->Destroy(Context); 238} 239void Sema::DeleteStmt(StmtTy *S) { 240 if (S) static_cast<Stmt*>(S)->Destroy(Context); 241} 242 243/// ActOnEndOfTranslationUnit - This is called at the very end of the 244/// translation unit when EOF is reached and all but the top-level scope is 245/// popped. 246void Sema::ActOnEndOfTranslationUnit() { 247 // C++: Perform implicit template instantiations. 248 // 249 // FIXME: When we perform these implicit instantiations, we do not carefully 250 // keep track of the point of instantiation (C++ [temp.point]). This means 251 // that name lookup that occurs within the template instantiation will 252 // always happen at the end of the translation unit, so it will find 253 // some names that should not be found. Although this is common behavior 254 // for C++ compilers, it is technically wrong. In the future, we either need 255 // to be able to filter the results of name lookup or we need to perform 256 // template instantiations earlier. 257 PerformPendingImplicitInstantiations(); 258 259 // Check for #pragma weak identifiers that were never declared 260 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 261 // order! Iterating over a densemap like this is bad. 262 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 263 I = WeakUndeclaredIdentifiers.begin(), 264 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 265 if (I->second.getUsed()) continue; 266 267 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 268 << I->first; 269 } 270 271 if (!CompleteTranslationUnit) 272 return; 273 274 // C99 6.9.2p2: 275 // A declaration of an identifier for an object that has file 276 // scope without an initializer, and without a storage-class 277 // specifier or with the storage-class specifier static, 278 // constitutes a tentative definition. If a translation unit 279 // contains one or more tentative definitions for an identifier, 280 // and the translation unit contains no external definition for 281 // that identifier, then the behavior is exactly as if the 282 // translation unit contains a file scope declaration of that 283 // identifier, with the composite type as of the end of the 284 // translation unit, with an initializer equal to 0. 285 for (unsigned i = 0, e = TentativeDefinitionList.size(); i != e; ++i) { 286 VarDecl *VD = TentativeDefinitions.lookup(TentativeDefinitionList[i]); 287 288 // If the tentative definition was completed, it will be in the list, but 289 // not the map. 290 if (VD == 0 || VD->isInvalidDecl() || !VD->isTentativeDefinition(Context)) 291 continue; 292 293 if (const IncompleteArrayType *ArrayT 294 = Context.getAsIncompleteArrayType(VD->getType())) { 295 if (RequireCompleteType(VD->getLocation(), 296 ArrayT->getElementType(), 297 diag::err_tentative_def_incomplete_type_arr)) { 298 VD->setInvalidDecl(); 299 continue; 300 } 301 302 // Set the length of the array to 1 (C99 6.9.2p5). 303 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 304 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 305 QualType T 306 = Context.getConstantArrayWithoutExprType(ArrayT->getElementType(), 307 One, ArrayType::Normal, 0); 308 VD->setType(T); 309 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 310 diag::err_tentative_def_incomplete_type)) 311 VD->setInvalidDecl(); 312 313 // Notify the consumer that we've completed a tentative definition. 314 if (!VD->isInvalidDecl()) 315 Consumer.CompleteTentativeDefinition(VD); 316 317 } 318} 319 320 321//===----------------------------------------------------------------------===// 322// Helper functions. 323//===----------------------------------------------------------------------===// 324 325DeclContext *Sema::getFunctionLevelDeclContext() { 326 DeclContext *DC = PreDeclaratorDC ? PreDeclaratorDC : CurContext; 327 328 while (isa<BlockDecl>(DC)) 329 DC = DC->getParent(); 330 331 return DC; 332} 333 334/// getCurFunctionDecl - If inside of a function body, this returns a pointer 335/// to the function decl for the function being parsed. If we're currently 336/// in a 'block', this returns the containing context. 337FunctionDecl *Sema::getCurFunctionDecl() { 338 DeclContext *DC = getFunctionLevelDeclContext(); 339 return dyn_cast<FunctionDecl>(DC); 340} 341 342ObjCMethodDecl *Sema::getCurMethodDecl() { 343 DeclContext *DC = getFunctionLevelDeclContext(); 344 return dyn_cast<ObjCMethodDecl>(DC); 345} 346 347NamedDecl *Sema::getCurFunctionOrMethodDecl() { 348 DeclContext *DC = getFunctionLevelDeclContext(); 349 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 350 return cast<NamedDecl>(DC); 351 return 0; 352} 353 354void Sema::DiagnoseMissingMember(SourceLocation MemberLoc, 355 DeclarationName Member, 356 NestedNameSpecifier *NNS, SourceRange Range) { 357 switch (NNS->getKind()) { 358 default: assert(0 && "Unexpected nested name specifier kind!"); 359 case NestedNameSpecifier::TypeSpec: { 360 const Type *Ty = Context.getCanonicalType(NNS->getAsType()); 361 RecordDecl *RD = cast<RecordType>(Ty)->getDecl(); 362 Diag(MemberLoc, diag::err_typecheck_record_no_member) 363 << Member << RD->getTagKind() << RD << Range; 364 break; 365 } 366 case NestedNameSpecifier::Namespace: { 367 Diag(MemberLoc, diag::err_typecheck_namespace_no_member) 368 << Member << NNS->getAsNamespace() << Range; 369 break; 370 } 371 case NestedNameSpecifier::Global: { 372 Diag(MemberLoc, diag::err_typecheck_global_namespace_no_member) 373 << Member << Range; 374 break; 375 } 376 } 377} 378 379Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 380 if (!this->Emit()) 381 return; 382 383 // If this is not a note, and we're in a template instantiation 384 // that is different from the last template instantiation where 385 // we emitted an error, print a template instantiation 386 // backtrace. 387 if (!SemaRef.Diags.isBuiltinNote(DiagID) && 388 !SemaRef.ActiveTemplateInstantiations.empty() && 389 SemaRef.ActiveTemplateInstantiations.back() 390 != SemaRef.LastTemplateInstantiationErrorContext) { 391 SemaRef.PrintInstantiationStack(); 392 SemaRef.LastTemplateInstantiationErrorContext 393 = SemaRef.ActiveTemplateInstantiations.back(); 394 } 395} 396 397Sema::SemaDiagnosticBuilder 398Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 399 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 400 PD.Emit(Builder); 401 402 return Builder; 403} 404 405void Sema::ActOnComment(SourceRange Comment) { 406 Context.Comments.push_back(Comment); 407} 408 409