Sema.cpp revision d1b3c2dd5bc1f3103bee6137957aa7c5f8f2f0bc
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 "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/Expr.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Basic/TargetInfo.h" 22using namespace clang; 23 24/// ConvertQualTypeToStringFn - This function is used to pretty print the 25/// specified QualType as a string in diagnostics. 26static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val, 27 const char *Modifier, unsigned ModLen, 28 const char *Argument, unsigned ArgLen, 29 llvm::SmallVectorImpl<char> &Output, 30 void *Cookie) { 31 ASTContext &Context = *static_cast<ASTContext*>(Cookie); 32 33 std::string S; 34 if (Kind == Diagnostic::ak_qualtype) { 35 assert(ModLen == 0 && ArgLen == 0 && 36 "Invalid modifier for QualType argument"); 37 38 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val))); 39 40 // FIXME: Playing with std::string is really slow. 41 S = Ty.getAsString(Context.PrintingPolicy); 42 43 // If this is a sugared type (like a typedef, typeof, etc), then unwrap one 44 // level of the sugar so that the type is more obvious to the user. 45 QualType DesugaredTy = Ty->getDesugaredType(true); 46 DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() | 47 Ty.getCVRQualifiers()); 48 49 if (Ty != DesugaredTy && 50 // If the desugared type is a vector type, we don't want to expand it, 51 // it will turn into an attribute mess. People want their "vec4". 52 !isa<VectorType>(DesugaredTy) && 53 54 // Don't desugar magic Objective-C types. 55 Ty.getUnqualifiedType() != Context.getObjCIdType() && 56 Ty.getUnqualifiedType() != Context.getObjCSelType() && 57 Ty.getUnqualifiedType() != Context.getObjCProtoType() && 58 Ty.getUnqualifiedType() != Context.getObjCClassType() && 59 60 // Not va_list. 61 Ty.getUnqualifiedType() != Context.getBuiltinVaListType()) { 62 S = "'"+S+"' (aka '"; 63 S += DesugaredTy.getAsString(Context.PrintingPolicy); 64 S += "')"; 65 Output.append(S.begin(), S.end()); 66 return; 67 } 68 69 } else if (Kind == Diagnostic::ak_declarationname) { 70 71 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val); 72 S = N.getAsString(); 73 74 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0) 75 S = '+' + S; 76 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0) 77 S = '-' + S; 78 else 79 assert(ModLen == 0 && ArgLen == 0 && 80 "Invalid modifier for DeclarationName argument"); 81 } else { 82 assert(Kind == Diagnostic::ak_nameddecl); 83 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0) 84 S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString(); 85 else { 86 assert(ModLen == 0 && ArgLen == 0 && 87 "Invalid modifier for NamedDecl* argument"); 88 S = reinterpret_cast<NamedDecl*>(Val)->getNameAsString(); 89 } 90 } 91 92 Output.push_back('\''); 93 Output.append(S.begin(), S.end()); 94 Output.push_back('\''); 95} 96 97 98static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) { 99 if (C.getLangOptions().CPlusPlus) 100 return CXXRecordDecl::Create(C, TagDecl::TK_struct, 101 C.getTranslationUnitDecl(), 102 SourceLocation(), &C.Idents.get(Name)); 103 104 return RecordDecl::Create(C, TagDecl::TK_struct, 105 C.getTranslationUnitDecl(), 106 SourceLocation(), &C.Idents.get(Name)); 107} 108 109void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { 110 TUScope = S; 111 PushDeclContext(S, Context.getTranslationUnitDecl()); 112 113 if (PP.getTargetInfo().getPointerWidth(0) >= 64) { 114 // Install [u]int128_t for 64-bit targets. 115 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 116 SourceLocation(), 117 &Context.Idents.get("__int128_t"), 118 Context.Int128Ty), TUScope); 119 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 120 SourceLocation(), 121 &Context.Idents.get("__uint128_t"), 122 Context.UnsignedInt128Ty), TUScope); 123 } 124 125 126 if (!PP.getLangOptions().ObjC1) return; 127 128 // Built-in ObjC types may already be set by PCHReader (hence isNull checks). 129 if (Context.getObjCSelType().isNull()) { 130 // Synthesize "typedef struct objc_selector *SEL;" 131 RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector"); 132 PushOnScopeChains(SelTag, TUScope); 133 134 QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag)); 135 TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext, 136 SourceLocation(), 137 &Context.Idents.get("SEL"), 138 SelT); 139 PushOnScopeChains(SelTypedef, TUScope); 140 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef)); 141 } 142 143 if (Context.getObjCClassType().isNull()) { 144 RecordDecl *ClassTag = CreateStructDecl(Context, "objc_class"); 145 QualType ClassT = Context.getPointerType(Context.getTagDeclType(ClassTag)); 146 TypedefDecl *ClassTypedef = 147 TypedefDecl::Create(Context, CurContext, SourceLocation(), 148 &Context.Idents.get("Class"), ClassT); 149 PushOnScopeChains(ClassTag, TUScope); 150 PushOnScopeChains(ClassTypedef, TUScope); 151 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef)); 152 } 153 154 // Synthesize "@class Protocol; 155 if (Context.getObjCProtoType().isNull()) { 156 ObjCInterfaceDecl *ProtocolDecl = 157 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 158 &Context.Idents.get("Protocol"), 159 SourceLocation(), true); 160 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 161 PushOnScopeChains(ProtocolDecl, TUScope); 162 } 163 164 // Synthesize "typedef struct objc_object { Class isa; } *id;" 165 if (Context.getObjCIdType().isNull()) { 166 RecordDecl *ObjectTag = CreateStructDecl(Context, "objc_object"); 167 168 QualType ObjT = Context.getPointerType(Context.getTagDeclType(ObjectTag)); 169 PushOnScopeChains(ObjectTag, TUScope); 170 TypedefDecl *IdTypedef = TypedefDecl::Create(Context, CurContext, 171 SourceLocation(), 172 &Context.Idents.get("id"), 173 ObjT); 174 PushOnScopeChains(IdTypedef, TUScope); 175 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef)); 176 } 177} 178 179Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 180 bool CompleteTranslationUnit) 181 : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 182 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 183 ExternalSource(0), CurContext(0), PreDeclaratorDC(0), 184 CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()), 185 GlobalNewDeleteDeclared(false), 186 CompleteTranslationUnit(CompleteTranslationUnit), 187 NumSFINAEErrors(0), CurrentInstantiationScope(0) { 188 189 StdNamespace = 0; 190 TUScope = 0; 191 if (getLangOptions().CPlusPlus) 192 FieldCollector.reset(new CXXFieldCollector()); 193 194 // Tell diagnostics how to render things from the AST library. 195 PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context); 196} 197 198/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 199/// If there is already an implicit cast, merge into the existing one. 200/// If isLvalue, the result of the cast is an lvalue. 201void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) { 202 QualType ExprTy = Context.getCanonicalType(Expr->getType()); 203 QualType TypeTy = Context.getCanonicalType(Ty); 204 205 if (ExprTy == TypeTy) 206 return; 207 208 if (Expr->getType().getTypePtr()->isPointerType() && 209 Ty.getTypePtr()->isPointerType()) { 210 QualType ExprBaseType = 211 cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType(); 212 QualType BaseType = 213 cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType(); 214 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { 215 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) 216 << Expr->getSourceRange(); 217 } 218 } 219 220 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { 221 ImpCast->setType(Ty); 222 ImpCast->setLvalueCast(isLvalue); 223 } else 224 Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue); 225} 226 227void Sema::DeleteExpr(ExprTy *E) { 228 if (E) static_cast<Expr*>(E)->Destroy(Context); 229} 230void Sema::DeleteStmt(StmtTy *S) { 231 if (S) static_cast<Stmt*>(S)->Destroy(Context); 232} 233 234/// ActOnEndOfTranslationUnit - This is called at the very end of the 235/// translation unit when EOF is reached and all but the top-level scope is 236/// popped. 237void Sema::ActOnEndOfTranslationUnit() { 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 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator 253 D = TentativeDefinitions.begin(), 254 DEnd = TentativeDefinitions.end(); 255 D != DEnd; ++D) { 256 VarDecl *VD = D->second; 257 258 if (VD->isInvalidDecl() || !VD->isTentativeDefinition(Context)) 259 continue; 260 261 if (const IncompleteArrayType *ArrayT 262 = Context.getAsIncompleteArrayType(VD->getType())) { 263 if (RequireCompleteType(VD->getLocation(), 264 ArrayT->getElementType(), 265 diag::err_tentative_def_incomplete_type_arr)) 266 VD->setInvalidDecl(); 267 else { 268 // Set the length of the array to 1 (C99 6.9.2p5). 269 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 270 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), 271 true); 272 QualType T 273 = Context.getConstantArrayType(ArrayT->getElementType(), 274 One, ArrayType::Normal, 0); 275 VD->setType(T); 276 } 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 288 289//===----------------------------------------------------------------------===// 290// Helper functions. 291//===----------------------------------------------------------------------===// 292 293/// getCurFunctionDecl - If inside of a function body, this returns a pointer 294/// to the function decl for the function being parsed. If we're currently 295/// in a 'block', this returns the containing context. 296FunctionDecl *Sema::getCurFunctionDecl() { 297 DeclContext *DC = CurContext; 298 while (isa<BlockDecl>(DC)) 299 DC = DC->getParent(); 300 return dyn_cast<FunctionDecl>(DC); 301} 302 303ObjCMethodDecl *Sema::getCurMethodDecl() { 304 DeclContext *DC = CurContext; 305 while (isa<BlockDecl>(DC)) 306 DC = DC->getParent(); 307 return dyn_cast<ObjCMethodDecl>(DC); 308} 309 310NamedDecl *Sema::getCurFunctionOrMethodDecl() { 311 DeclContext *DC = CurContext; 312 while (isa<BlockDecl>(DC)) 313 DC = DC->getParent(); 314 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 315 return cast<NamedDecl>(DC); 316 return 0; 317} 318 319Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 320 if (!this->Emit()) 321 return; 322 323 // If this is not a note, and we're in a template instantiation 324 // that is different from the last template instantiation where 325 // we emitted an error, print a template instantiation 326 // backtrace. 327 if (!SemaRef.Diags.isBuiltinNote(DiagID) && 328 !SemaRef.ActiveTemplateInstantiations.empty() && 329 SemaRef.ActiveTemplateInstantiations.back() 330 != SemaRef.LastTemplateInstantiationErrorContext) { 331 SemaRef.PrintInstantiationStack(); 332 SemaRef.LastTemplateInstantiationErrorContext 333 = SemaRef.ActiveTemplateInstantiations.back(); 334 } 335} 336