Sema.cpp revision 1060a03c4a8637ff3b7da7ad4c688201068cd4ac
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/SmallSet.h" 19#include "llvm/ADT/APFloat.h" 20#include "clang/AST/ASTConsumer.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/ASTDiagnostic.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/Expr.h" 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Basic/PartialDiagnostic.h" 27#include "clang/Basic/TargetInfo.h" 28using namespace clang; 29 30FunctionScopeInfo::~FunctionScopeInfo() { } 31 32void FunctionScopeInfo::Clear(unsigned NumErrors) { 33 NeedsScopeChecking = false; 34 LabelMap.clear(); 35 SwitchStack.clear(); 36 NumErrorsAtStartOfFunction = NumErrors; 37} 38 39BlockScopeInfo::~BlockScopeInfo() { } 40 41static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) { 42 if (C.getLangOptions().CPlusPlus) 43 return CXXRecordDecl::Create(C, TagDecl::TK_struct, 44 C.getTranslationUnitDecl(), 45 SourceLocation(), &C.Idents.get(Name)); 46 47 return RecordDecl::Create(C, TagDecl::TK_struct, 48 C.getTranslationUnitDecl(), 49 SourceLocation(), &C.Idents.get(Name)); 50} 51 52void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { 53 TUScope = S; 54 PushDeclContext(S, Context.getTranslationUnitDecl()); 55 56 if (PP.getTargetInfo().getPointerWidth(0) >= 64) { 57 TypeSourceInfo *TInfo; 58 59 // Install [u]int128_t for 64-bit targets. 60 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty); 61 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 62 SourceLocation(), 63 &Context.Idents.get("__int128_t"), 64 TInfo), TUScope); 65 66 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty); 67 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 68 SourceLocation(), 69 &Context.Idents.get("__uint128_t"), 70 TInfo), TUScope); 71 } 72 73 74 if (!PP.getLangOptions().ObjC1) return; 75 76 // Built-in ObjC types may already be set by PCHReader (hence isNull checks). 77 if (Context.getObjCSelType().isNull()) { 78 // Create the built-in typedef for 'SEL'. 79 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy); 80 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT); 81 TypedefDecl *SelTypedef 82 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 83 &Context.Idents.get("SEL"), SelInfo); 84 PushOnScopeChains(SelTypedef, TUScope); 85 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef)); 86 Context.ObjCSelRedefinitionType = Context.getObjCSelType(); 87 } 88 89 // Synthesize "@class Protocol; 90 if (Context.getObjCProtoType().isNull()) { 91 ObjCInterfaceDecl *ProtocolDecl = 92 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 93 &Context.Idents.get("Protocol"), 94 SourceLocation(), true); 95 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 96 PushOnScopeChains(ProtocolDecl, TUScope, false); 97 } 98 // Create the built-in typedef for 'id'. 99 if (Context.getObjCIdType().isNull()) { 100 QualType IdT = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy); 101 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(IdT); 102 TypedefDecl *IdTypedef 103 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 104 &Context.Idents.get("id"), IdInfo); 105 PushOnScopeChains(IdTypedef, TUScope); 106 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef)); 107 Context.ObjCIdRedefinitionType = Context.getObjCIdType(); 108 } 109 // Create the built-in typedef for 'Class'. 110 if (Context.getObjCClassType().isNull()) { 111 QualType ClassType 112 = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy); 113 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(ClassType); 114 TypedefDecl *ClassTypedef 115 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 116 &Context.Idents.get("Class"), ClassInfo); 117 PushOnScopeChains(ClassTypedef, TUScope); 118 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef)); 119 Context.ObjCClassRedefinitionType = Context.getObjCClassType(); 120 } 121} 122 123Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 124 bool CompleteTranslationUnit, 125 CodeCompleteConsumer *CodeCompleter) 126 : TheTargetAttributesSema(0), 127 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 128 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 129 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0), 130 PackContext(0), TopFunctionScope(0), ParsingDeclDepth(0), 131 IdResolver(pp.getLangOptions()), StdNamespace(0), StdBadAlloc(0), 132 GlobalNewDeleteDeclared(false), 133 CompleteTranslationUnit(CompleteTranslationUnit), 134 NumSFINAEErrors(0), NonInstantiationEntries(0), 135 CurrentInstantiationScope(0), TyposCorrected(0), 136 AnalysisWarnings(*this) 137{ 138 TUScope = 0; 139 if (getLangOptions().CPlusPlus) 140 FieldCollector.reset(new CXXFieldCollector()); 141 142 // Tell diagnostics how to render things from the AST library. 143 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument, 144 &Context); 145 146 ExprEvalContexts.push_back( 147 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0)); 148} 149 150Sema::~Sema() { 151 if (PackContext) FreePackedContext(); 152 delete TheTargetAttributesSema; 153 while (!FunctionScopes.empty()) 154 PopFunctionOrBlockScope(); 155} 156 157/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 158/// If there is already an implicit cast, merge into the existing one. 159/// If isLvalue, the result of the cast is an lvalue. 160void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, 161 CastExpr::CastKind Kind, 162 bool isLvalue, CXXBaseSpecifierArray BasePath) { 163 QualType ExprTy = Context.getCanonicalType(Expr->getType()); 164 QualType TypeTy = Context.getCanonicalType(Ty); 165 166 if (ExprTy == TypeTy) 167 return; 168 169 if (Expr->getType()->isPointerType() && Ty->isPointerType()) { 170 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType(); 171 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType(); 172 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { 173 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) 174 << Expr->getSourceRange(); 175 } 176 } 177 178 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { 179 if (ImpCast->getCastKind() == Kind && BasePath.empty()) { 180 ImpCast->setType(Ty); 181 ImpCast->setLvalueCast(isLvalue); 182 return; 183 } 184 } 185 186 Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, BasePath, isLvalue); 187} 188 189void Sema::DeleteExpr(ExprTy *E) { 190 if (E) static_cast<Expr*>(E)->Destroy(Context); 191} 192void Sema::DeleteStmt(StmtTy *S) { 193 if (S) static_cast<Stmt*>(S)->Destroy(Context); 194} 195 196/// ActOnEndOfTranslationUnit - This is called at the very end of the 197/// translation unit when EOF is reached and all but the top-level scope is 198/// popped. 199void Sema::ActOnEndOfTranslationUnit() { 200 while (1) { 201 // C++: Perform implicit template instantiations. 202 // 203 // FIXME: When we perform these implicit instantiations, we do not carefully 204 // keep track of the point of instantiation (C++ [temp.point]). This means 205 // that name lookup that occurs within the template instantiation will 206 // always happen at the end of the translation unit, so it will find 207 // some names that should not be found. Although this is common behavior 208 // for C++ compilers, it is technically wrong. In the future, we either need 209 // to be able to filter the results of name lookup or we need to perform 210 // template instantiations earlier. 211 PerformPendingImplicitInstantiations(); 212 213 /// If ProcessPendingClassesWithUnmarkedVirtualMembers ends up marking 214 /// any virtual member functions it might lead to more pending template 215 /// instantiations, which is why we need to loop here. 216 if (!ProcessPendingClassesWithUnmarkedVirtualMembers()) 217 break; 218 } 219 220 // Remove functions that turned out to be used. 221 UnusedStaticFuncs.erase(std::remove_if(UnusedStaticFuncs.begin(), 222 UnusedStaticFuncs.end(), 223 std::mem_fun(&FunctionDecl::isUsed)), 224 UnusedStaticFuncs.end()); 225 226 // Check for #pragma weak identifiers that were never declared 227 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 228 // order! Iterating over a densemap like this is bad. 229 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 230 I = WeakUndeclaredIdentifiers.begin(), 231 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 232 if (I->second.getUsed()) continue; 233 234 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 235 << I->first; 236 } 237 238 if (!CompleteTranslationUnit) 239 return; 240 241 // C99 6.9.2p2: 242 // A declaration of an identifier for an object that has file 243 // scope without an initializer, and without a storage-class 244 // specifier or with the storage-class specifier static, 245 // constitutes a tentative definition. If a translation unit 246 // contains one or more tentative definitions for an identifier, 247 // and the translation unit contains no external definition for 248 // that identifier, then the behavior is exactly as if the 249 // translation unit contains a file scope declaration of that 250 // identifier, with the composite type as of the end of the 251 // translation unit, with an initializer equal to 0. 252 llvm::SmallSet<VarDecl *, 32> Seen; 253 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) { 254 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition(); 255 256 // If the tentative definition was completed, getActingDefinition() returns 257 // null. If we've already seen this variable before, insert()'s second 258 // return value is false. 259 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD)) 260 continue; 261 262 if (const IncompleteArrayType *ArrayT 263 = Context.getAsIncompleteArrayType(VD->getType())) { 264 if (RequireCompleteType(VD->getLocation(), 265 ArrayT->getElementType(), 266 diag::err_tentative_def_incomplete_type_arr)) { 267 VD->setInvalidDecl(); 268 continue; 269 } 270 271 // Set the length of the array to 1 (C99 6.9.2p5). 272 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 273 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 274 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 275 One, ArrayType::Normal, 0); 276 VD->setType(T); 277 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 278 diag::err_tentative_def_incomplete_type)) 279 VD->setInvalidDecl(); 280 281 // Notify the consumer that we've completed a tentative definition. 282 if (!VD->isInvalidDecl()) 283 Consumer.CompleteTentativeDefinition(VD); 284 285 } 286 287 // Output warning for unused functions. 288 for (std::vector<FunctionDecl*>::iterator 289 F = UnusedStaticFuncs.begin(), 290 FEnd = UnusedStaticFuncs.end(); 291 F != FEnd; 292 ++F) 293 Diag((*F)->getLocation(), diag::warn_unused_function) << (*F)->getDeclName(); 294 295} 296 297 298//===----------------------------------------------------------------------===// 299// Helper functions. 300//===----------------------------------------------------------------------===// 301 302DeclContext *Sema::getFunctionLevelDeclContext() { 303 DeclContext *DC = CurContext; 304 305 while (isa<BlockDecl>(DC)) 306 DC = DC->getParent(); 307 308 return DC; 309} 310 311/// getCurFunctionDecl - If inside of a function body, this returns a pointer 312/// to the function decl for the function being parsed. If we're currently 313/// in a 'block', this returns the containing context. 314FunctionDecl *Sema::getCurFunctionDecl() { 315 DeclContext *DC = getFunctionLevelDeclContext(); 316 return dyn_cast<FunctionDecl>(DC); 317} 318 319ObjCMethodDecl *Sema::getCurMethodDecl() { 320 DeclContext *DC = getFunctionLevelDeclContext(); 321 return dyn_cast<ObjCMethodDecl>(DC); 322} 323 324NamedDecl *Sema::getCurFunctionOrMethodDecl() { 325 DeclContext *DC = getFunctionLevelDeclContext(); 326 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 327 return cast<NamedDecl>(DC); 328 return 0; 329} 330 331Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 332 if (!this->Emit()) 333 return; 334 335 // If this is not a note, and we're in a template instantiation 336 // that is different from the last template instantiation where 337 // we emitted an error, print a template instantiation 338 // backtrace. 339 if (!SemaRef.Diags.isBuiltinNote(DiagID) && 340 !SemaRef.ActiveTemplateInstantiations.empty() && 341 SemaRef.ActiveTemplateInstantiations.back() 342 != SemaRef.LastTemplateInstantiationErrorContext) { 343 SemaRef.PrintInstantiationStack(); 344 SemaRef.LastTemplateInstantiationErrorContext 345 = SemaRef.ActiveTemplateInstantiations.back(); 346 } 347} 348 349Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) { 350 if (isSFINAEContext()) { 351 switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) { 352 case Diagnostic::SFINAE_Report: 353 // Fall through; we'll report the diagnostic below. 354 break; 355 356 case Diagnostic::SFINAE_SubstitutionFailure: 357 // Count this failure so that we know that template argument deduction 358 // has failed. 359 ++NumSFINAEErrors; 360 // Fall through 361 362 case Diagnostic::SFINAE_Suppress: 363 // Suppress this diagnostic. 364 Diags.setLastDiagnosticIgnored(); 365 return SemaDiagnosticBuilder(*this); 366 } 367 } 368 369 DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID); 370 return SemaDiagnosticBuilder(DB, *this, DiagID); 371} 372 373Sema::SemaDiagnosticBuilder 374Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 375 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 376 PD.Emit(Builder); 377 378 return Builder; 379} 380 381 382/// \brief Enter a new function scope 383void Sema::PushFunctionScope() { 384 if (FunctionScopes.empty()) { 385 // Use the "top" function scope rather than having to allocate memory for 386 // a new scope. 387 TopFunctionScope.Clear(getDiagnostics().getNumErrors()); 388 FunctionScopes.push_back(&TopFunctionScope); 389 return; 390 } 391 392 FunctionScopes.push_back( 393 new FunctionScopeInfo(getDiagnostics().getNumErrors())); 394} 395 396void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 397 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(), 398 BlockScope, Block)); 399} 400 401void Sema::PopFunctionOrBlockScope() { 402 if (FunctionScopes.back() != &TopFunctionScope) 403 delete FunctionScopes.back(); 404 else 405 TopFunctionScope.Clear(getDiagnostics().getNumErrors()); 406 407 FunctionScopes.pop_back(); 408} 409 410/// \brief Determine whether any errors occurred within this function/method/ 411/// block. 412bool Sema::hasAnyErrorsInThisFunction() const { 413 unsigned NumErrors = TopFunctionScope.NumErrorsAtStartOfFunction; 414 if (!FunctionScopes.empty()) 415 NumErrors = FunctionScopes.back()->NumErrorsAtStartOfFunction; 416 return NumErrors != getDiagnostics().getNumErrors(); 417} 418 419BlockScopeInfo *Sema::getCurBlock() { 420 if (FunctionScopes.empty()) 421 return 0; 422 423 return dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 424} 425