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