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