SemaDeclCXX.cpp revision 8e9bebdea69c590dedfbf27374114cb76fe12fbd
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
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 semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/StmtVisitor.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Parse/DeclSpec.h"
21#include "llvm/Support/Compiler.h"
22#include <algorithm> // for std::equal
23
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// CheckDefaultArgumentVisitor
28//===----------------------------------------------------------------------===//
29
30namespace {
31  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
32  /// the default argument of a parameter to determine whether it
33  /// contains any ill-formed subexpressions. For example, this will
34  /// diagnose the use of local variables or parameters within the
35  /// default argument expression.
36  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
37    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
38    Expr *DefaultArg;
39    Sema *S;
40
41  public:
42    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
43      : DefaultArg(defarg), S(s) {}
44
45    bool VisitExpr(Expr *Node);
46    bool VisitDeclRefExpr(DeclRefExpr *DRE);
47  };
48
49  /// VisitExpr - Visit all of the children of this expression.
50  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
51    bool IsInvalid = false;
52    for (Stmt::child_iterator I = Node->child_begin(),
53         E = Node->child_end(); I != E; ++I)
54      IsInvalid |= Visit(*I);
55    return IsInvalid;
56  }
57
58  /// VisitDeclRefExpr - Visit a reference to a declaration, to
59  /// determine whether this declaration can be used in the default
60  /// argument expression.
61  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
62    NamedDecl *Decl = DRE->getDecl();
63    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
64      // C++ [dcl.fct.default]p9
65      //   Default arguments are evaluated each time the function is
66      //   called. The order of evaluation of function arguments is
67      //   unspecified. Consequently, parameters of a function shall not
68      //   be used in default argument expressions, even if they are not
69      //   evaluated. Parameters of a function declared before a default
70      //   argument expression are in scope and can hide namespace and
71      //   class member names.
72      return S->Diag(DRE->getSourceRange().getBegin(),
73                     diag::err_param_default_argument_references_param,
74                     Param->getName(), DefaultArg->getSourceRange());
75    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
76      // C++ [dcl.fct.default]p7
77      //   Local variables shall not be used in default argument
78      //   expressions.
79      if (VDecl->isBlockVarDecl())
80        return S->Diag(DRE->getSourceRange().getBegin(),
81                       diag::err_param_default_argument_references_local,
82                       VDecl->getName(), DefaultArg->getSourceRange());
83    }
84
85    // FIXME: when Clang has support for member functions, "this"
86    // will also need to be diagnosed.
87
88    return false;
89  }
90}
91
92/// ActOnParamDefaultArgument - Check whether the default argument
93/// provided for a function parameter is well-formed. If so, attach it
94/// to the parameter declaration.
95void
96Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
97                                ExprTy *defarg) {
98  ParmVarDecl *Param = (ParmVarDecl *)param;
99  llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
100  QualType ParamType = Param->getType();
101
102  // Default arguments are only permitted in C++
103  if (!getLangOptions().CPlusPlus) {
104    Diag(EqualLoc, diag::err_param_default_argument,
105         DefaultArg->getSourceRange());
106    return;
107  }
108
109  // C++ [dcl.fct.default]p5
110  //   A default argument expression is implicitly converted (clause
111  //   4) to the parameter type. The default argument expression has
112  //   the same semantic constraints as the initializer expression in
113  //   a declaration of a variable of the parameter type, using the
114  //   copy-initialization semantics (8.5).
115  //
116  // FIXME: CheckSingleAssignmentConstraints has the wrong semantics
117  // for C++ (since we want copy-initialization, not copy-assignment),
118  // but we don't have the right semantics implemented yet. Because of
119  // this, our error message is also very poor.
120  QualType DefaultArgType = DefaultArg->getType();
121  Expr *DefaultArgPtr = DefaultArg.get();
122  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType,
123                                                              DefaultArgPtr);
124  if (DefaultArgPtr != DefaultArg.get()) {
125    DefaultArg.take();
126    DefaultArg.reset(DefaultArgPtr);
127  }
128  if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(),
129                               ParamType, DefaultArgType, DefaultArg.get(),
130                               "in default argument")) {
131    return;
132  }
133
134  // Check that the default argument is well-formed
135  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
136  if (DefaultArgChecker.Visit(DefaultArg.get()))
137    return;
138
139  // Okay: add the default argument to the parameter
140  Param->setDefaultArg(DefaultArg.take());
141}
142
143/// CheckExtraCXXDefaultArguments - Check for any extra default
144/// arguments in the declarator, which is not a function declaration
145/// or definition and therefore is not permitted to have default
146/// arguments. This routine should be invoked for every declarator
147/// that is not a function declaration or definition.
148void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
149  // C++ [dcl.fct.default]p3
150  //   A default argument expression shall be specified only in the
151  //   parameter-declaration-clause of a function declaration or in a
152  //   template-parameter (14.1). It shall not be specified for a
153  //   parameter pack. If it is specified in a
154  //   parameter-declaration-clause, it shall not occur within a
155  //   declarator or abstract-declarator of a parameter-declaration.
156  for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
157    DeclaratorChunk &chunk = D.getTypeObject(i);
158    if (chunk.Kind == DeclaratorChunk::Function) {
159      for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
160        ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
161        if (Param->getDefaultArg()) {
162          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
163               Param->getDefaultArg()->getSourceRange());
164          Param->setDefaultArg(0);
165        }
166      }
167    }
168  }
169}
170
171// MergeCXXFunctionDecl - Merge two declarations of the same C++
172// function, once we already know that they have the same
173// type. Subroutine of MergeFunctionDecl.
174FunctionDecl *
175Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
176  // C++ [dcl.fct.default]p4:
177  //
178  //   For non-template functions, default arguments can be added in
179  //   later declarations of a function in the same
180  //   scope. Declarations in different scopes have completely
181  //   distinct sets of default arguments. That is, declarations in
182  //   inner scopes do not acquire default arguments from
183  //   declarations in outer scopes, and vice versa. In a given
184  //   function declaration, all parameters subsequent to a
185  //   parameter with a default argument shall have default
186  //   arguments supplied in this or previous declarations. A
187  //   default argument shall not be redefined by a later
188  //   declaration (not even to the same value).
189  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
190    ParmVarDecl *OldParam = Old->getParamDecl(p);
191    ParmVarDecl *NewParam = New->getParamDecl(p);
192
193    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
194      Diag(NewParam->getLocation(),
195           diag::err_param_default_argument_redefinition,
196           NewParam->getDefaultArg()->getSourceRange());
197      Diag(OldParam->getLocation(), diag::err_previous_definition);
198    } else if (OldParam->getDefaultArg()) {
199      // Merge the old default argument into the new parameter
200      NewParam->setDefaultArg(OldParam->getDefaultArg());
201    }
202  }
203
204  return New;
205}
206
207/// CheckCXXDefaultArguments - Verify that the default arguments for a
208/// function declaration are well-formed according to C++
209/// [dcl.fct.default].
210void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
211  unsigned NumParams = FD->getNumParams();
212  unsigned p;
213
214  // Find first parameter with a default argument
215  for (p = 0; p < NumParams; ++p) {
216    ParmVarDecl *Param = FD->getParamDecl(p);
217    if (Param->getDefaultArg())
218      break;
219  }
220
221  // C++ [dcl.fct.default]p4:
222  //   In a given function declaration, all parameters
223  //   subsequent to a parameter with a default argument shall
224  //   have default arguments supplied in this or previous
225  //   declarations. A default argument shall not be redefined
226  //   by a later declaration (not even to the same value).
227  unsigned LastMissingDefaultArg = 0;
228  for(; p < NumParams; ++p) {
229    ParmVarDecl *Param = FD->getParamDecl(p);
230    if (!Param->getDefaultArg()) {
231      if (Param->getIdentifier())
232        Diag(Param->getLocation(),
233             diag::err_param_default_argument_missing_name,
234             Param->getIdentifier()->getName());
235      else
236        Diag(Param->getLocation(),
237             diag::err_param_default_argument_missing);
238
239      LastMissingDefaultArg = p;
240    }
241  }
242
243  if (LastMissingDefaultArg > 0) {
244    // Some default arguments were missing. Clear out all of the
245    // default arguments up to (and including) the last missing
246    // default argument, so that we leave the function parameters
247    // in a semantically valid state.
248    for (p = 0; p <= LastMissingDefaultArg; ++p) {
249      ParmVarDecl *Param = FD->getParamDecl(p);
250      if (Param->getDefaultArg()) {
251        delete Param->getDefaultArg();
252        Param->setDefaultArg(0);
253      }
254    }
255  }
256}
257
258/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
259/// one entry in the base class list of a class specifier, for
260/// example:
261///    class foo : public bar, virtual private baz {
262/// 'public bar' and 'virtual private baz' are each base-specifiers.
263void Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
264                              bool Virtual, AccessSpecifier Access,
265                              TypeTy *basetype, SourceLocation BaseLoc) {
266  RecordDecl *Decl = (RecordDecl*)classdecl;
267  QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
268
269  // Base specifiers must be record types.
270  if (!BaseType->isRecordType()) {
271    Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
272    return;
273  }
274
275  // C++ [class.union]p1:
276  //   A union shall not be used as a base class.
277  if (BaseType->isUnionType()) {
278    Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
279    return;
280  }
281
282  // C++ [class.union]p1:
283  //   A union shall not have base classes.
284  if (Decl->isUnion()) {
285    Diag(Decl->getLocation(), diag::err_base_clause_on_union,
286         SpecifierRange);
287    Decl->setInvalidDecl();
288    return;
289  }
290
291  // C++ [class.derived]p2:
292  //   The class-name in a base-specifier shall not be an incompletely
293  //   defined class.
294  if (BaseType->isIncompleteType()) {
295    Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
296    return;
297  }
298
299  // FIXME: C++ [class.mi]p3:
300  //   A class shall not be specified as a direct base class of a
301  //   derived class more than once.
302
303  // FIXME: Attach base class to the record.
304}
305
306//===----------------------------------------------------------------------===//
307// C++ class member Handling
308//===----------------------------------------------------------------------===//
309
310/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
311/// definition, when on C++.
312void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
313  Decl *Dcl = static_cast<Decl *>(D);
314  PushDeclContext(cast<CXXRecordDecl>(Dcl));
315  FieldCollector->StartClass();
316}
317
318/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
319/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
320/// bitfield width if there is one and 'InitExpr' specifies the initializer if
321/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
322/// declarators on it.
323///
324/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
325/// an instance field is declared, a new CXXFieldDecl is created but the method
326/// does *not* return it; it returns LastInGroup instead. The other C++ members
327/// (which are all ScopedDecls) are returned after appending them to
328/// LastInGroup.
329Sema::DeclTy *
330Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
331                               ExprTy *BW, ExprTy *InitExpr,
332                               DeclTy *LastInGroup) {
333  const DeclSpec &DS = D.getDeclSpec();
334  IdentifierInfo *II = D.getIdentifier();
335  Expr *BitWidth = static_cast<Expr*>(BW);
336  Expr *Init = static_cast<Expr*>(InitExpr);
337  SourceLocation Loc = D.getIdentifierLoc();
338
339  // C++ 9.2p6: A member shall not be declared to have automatic storage
340  // duration (auto, register) or with the extern storage-class-specifier.
341  switch (DS.getStorageClassSpec()) {
342    case DeclSpec::SCS_unspecified:
343    case DeclSpec::SCS_typedef:
344    case DeclSpec::SCS_static:
345      // FALL THROUGH.
346      break;
347    default:
348      if (DS.getStorageClassSpecLoc().isValid())
349        Diag(DS.getStorageClassSpecLoc(),
350             diag::err_storageclass_invalid_for_member);
351      else
352        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
353      D.getMutableDeclSpec().ClearStorageClassSpecs();
354  }
355
356  bool isFunc = D.isFunctionDeclarator();
357  if (!isFunc &&
358      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
359      D.getNumTypeObjects() == 0) {
360    // Check also for this case:
361    //
362    // typedef int f();
363    // f a;
364    //
365    Decl *TD = static_cast<Decl *>(DS.getTypeRep());
366    isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
367  }
368
369  bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
370                      !isFunc);
371
372  Decl *Member;
373  bool InvalidDecl = false;
374
375  if (isInstField)
376    Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
377  else
378    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
379
380  if (!Member) return LastInGroup;
381
382  assert(II || isInstField && "No identifier for non-field ?");
383
384  // set/getAccess is not part of Decl's interface to avoid bloating it with C++
385  // specific methods. Use a wrapper class that can be used with all C++ class
386  // member decls.
387  CXXClassMemberWrapper(Member).setAccess(AS);
388
389  if (BitWidth) {
390    // C++ 9.6p2: Only when declaring an unnamed bit-field may the
391    // constant-expression be a value equal to zero.
392    // FIXME: Check this.
393
394    if (D.isFunctionDeclarator()) {
395      // FIXME: Emit diagnostic about only constructors taking base initializers
396      // or something similar, when constructor support is in place.
397      Diag(Loc, diag::err_not_bitfield_type,
398           II->getName(), BitWidth->getSourceRange());
399      InvalidDecl = true;
400
401    } else if (isInstField) {
402      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
403      if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
404        Diag(Loc, diag::err_not_integral_type_bitfield,
405             II->getName(), BitWidth->getSourceRange());
406        InvalidDecl = true;
407      }
408
409    } else if (isa<FunctionDecl>(Member)) {
410      // A function typedef ("typedef int f(); f a;").
411      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
412      Diag(Loc, diag::err_not_integral_type_bitfield,
413           II->getName(), BitWidth->getSourceRange());
414      InvalidDecl = true;
415
416    } else if (isa<TypedefDecl>(Member)) {
417      // "cannot declare 'A' to be a bit-field type"
418      Diag(Loc, diag::err_not_bitfield_type, II->getName(),
419           BitWidth->getSourceRange());
420      InvalidDecl = true;
421
422    } else {
423      assert(isa<CXXClassVarDecl>(Member) &&
424             "Didn't we cover all member kinds?");
425      // C++ 9.6p3: A bit-field shall not be a static member.
426      // "static member 'A' cannot be a bit-field"
427      Diag(Loc, diag::err_static_not_bitfield, II->getName(),
428           BitWidth->getSourceRange());
429      InvalidDecl = true;
430    }
431  }
432
433  if (Init) {
434    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
435    // if it declares a static member of const integral or const enumeration
436    // type.
437    if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
438      // ...static member of...
439      CVD->setInit(Init);
440      // ...const integral or const enumeration type.
441      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
442          CVD->getType()->isIntegralType()) {
443        // constant-initializer
444        if (CheckForConstantInitializer(Init, CVD->getType()))
445          InvalidDecl = true;
446
447      } else {
448        // not const integral.
449        Diag(Loc, diag::err_member_initialization,
450             II->getName(), Init->getSourceRange());
451        InvalidDecl = true;
452      }
453
454    } else {
455      // not static member.
456      Diag(Loc, diag::err_member_initialization,
457           II->getName(), Init->getSourceRange());
458      InvalidDecl = true;
459    }
460  }
461
462  if (InvalidDecl)
463    Member->setInvalidDecl();
464
465  if (isInstField) {
466    FieldCollector->Add(cast<CXXFieldDecl>(Member));
467    return LastInGroup;
468  }
469  return Member;
470}
471
472void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
473                                             DeclTy *TagDecl,
474                                             SourceLocation LBrac,
475                                             SourceLocation RBrac) {
476  ActOnFields(S, RLoc, TagDecl,
477              (DeclTy**)FieldCollector->getCurFields(),
478              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
479}
480
481void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
482  CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
483  FieldCollector->FinishClass();
484  PopDeclContext();
485
486  // Everything, including inline method definitions, have been parsed.
487  // Let the consumer know of the new TagDecl definition.
488  Consumer.HandleTagDeclDefinition(Rec);
489}
490
491//===----------------------------------------------------------------------===//
492// Namespace Handling
493//===----------------------------------------------------------------------===//
494
495/// ActOnStartNamespaceDef - This is called at the start of a namespace
496/// definition.
497Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
498                                           SourceLocation IdentLoc,
499                                           IdentifierInfo *II,
500                                           SourceLocation LBrace) {
501  NamespaceDecl *Namespc =
502      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
503  Namespc->setLBracLoc(LBrace);
504
505  Scope *DeclRegionScope = NamespcScope->getParent();
506
507  if (II) {
508    // C++ [namespace.def]p2:
509    // The identifier in an original-namespace-definition shall not have been
510    // previously defined in the declarative region in which the
511    // original-namespace-definition appears. The identifier in an
512    // original-namespace-definition is the name of the namespace. Subsequently
513    // in that declarative region, it is treated as an original-namespace-name.
514
515    Decl *PrevDecl =
516        LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
517                   /*enableLazyBuiltinCreation=*/false);
518
519    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
520      if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
521        // This is an extended namespace definition.
522        // Attach this namespace decl to the chain of extended namespace
523        // definitions.
524        NamespaceDecl *NextNS = OrigNS;
525        while (NextNS->getNextNamespace())
526          NextNS = NextNS->getNextNamespace();
527
528        NextNS->setNextNamespace(Namespc);
529        Namespc->setOriginalNamespace(OrigNS);
530
531        // We won't add this decl to the current scope. We want the namespace
532        // name to return the original namespace decl during a name lookup.
533      } else {
534        // This is an invalid name redefinition.
535        Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
536          Namespc->getName());
537        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
538        Namespc->setInvalidDecl();
539        // Continue on to push Namespc as current DeclContext and return it.
540      }
541    } else {
542      // This namespace name is declared for the first time.
543      PushOnScopeChains(Namespc, DeclRegionScope);
544    }
545  }
546  else {
547    // FIXME: Handle anonymous namespaces
548  }
549
550  // Although we could have an invalid decl (i.e. the namespace name is a
551  // redefinition), push it as current DeclContext and try to continue parsing.
552  PushDeclContext(Namespc->getOriginalNamespace());
553  return Namespc;
554}
555
556/// ActOnFinishNamespaceDef - This callback is called after a namespace is
557/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
558void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
559  Decl *Dcl = static_cast<Decl *>(D);
560  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
561  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
562  Namespc->setRBracLoc(RBrace);
563  PopDeclContext();
564}
565
566
567/// AddCXXDirectInitializerToDecl - This action is called immediately after
568/// ActOnDeclarator, when a C++ direct initializer is present.
569/// e.g: "int x(1);"
570void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
571                                         ExprTy **ExprTys, unsigned NumExprs,
572                                         SourceLocation *CommaLocs,
573                                         SourceLocation RParenLoc) {
574  assert(NumExprs != 0 && ExprTys && "missing expressions");
575  Decl *RealDecl = static_cast<Decl *>(Dcl);
576
577  // If there is no declaration, there was an error parsing it.  Just ignore
578  // the initializer.
579  if (RealDecl == 0) {
580    for (unsigned i = 0; i != NumExprs; ++i)
581      delete static_cast<Expr *>(ExprTys[i]);
582    return;
583  }
584
585  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
586  if (!VDecl) {
587    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
588    RealDecl->setInvalidDecl();
589    return;
590  }
591
592  // We will treat direct-initialization as a copy-initialization:
593  //    int x(1);  -as-> int x = 1;
594  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
595  //
596  // Clients that want to distinguish between the two forms, can check for
597  // direct initializer using VarDecl::hasCXXDirectInitializer().
598  // A major benefit is that clients that don't particularly care about which
599  // exactly form was it (like the CodeGen) can handle both cases without
600  // special case code.
601
602  // C++ 8.5p11:
603  // The form of initialization (using parentheses or '=') is generally
604  // insignificant, but does matter when the entity being initialized has a
605  // class type.
606
607  if (VDecl->getType()->isRecordType()) {
608    // FIXME: When constructors for class types are supported, determine how
609    // exactly semantic checking will be done for direct initializers.
610    unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
611                           "initialization for class types is not handled yet");
612    Diag(VDecl->getLocation(), DiagID);
613    RealDecl->setInvalidDecl();
614    return;
615  }
616
617  if (NumExprs > 1) {
618    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
619         SourceRange(VDecl->getLocation(), RParenLoc));
620    RealDecl->setInvalidDecl();
621    return;
622  }
623
624  // Let clients know that initialization was done with a direct initializer.
625  VDecl->setCXXDirectInitializer(true);
626
627  assert(NumExprs == 1 && "Expected 1 expression");
628  // Set the init expression, handles conversions.
629  AddInitializerToDecl(Dcl, ExprTys[0]);
630}
631