]> granicus.if.org Git - clang/blob - Sema/SemaDecl.cpp
9a19928ce7d171ee9e9522ce1e1b0b19930837b2
[clang] / Sema / SemaDecl.cpp
1 //===--- SemaDecl.cpp - Semantic Analysis for 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 declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Sema.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Builtins.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/Type.h"
22 #include "clang/Parse/DeclSpec.h"
23 #include "clang/Parse/Scope.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Basic/SourceManager.h"
27 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Lex/HeaderSearch.h" 
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/DenseSet.h"
33 using namespace clang;
34
35 Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
36   Decl *IIDecl = II.getFETokenInfo<Decl>();
37   // Find first occurance of none-tagged declaration
38   while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
39     IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
40   if (!IIDecl)
41     return 0;
42   if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
43     return IIDecl;
44   if (ObjCCompatibleAliasDecl *ADecl = 
45       dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
46     return ADecl->getClassInterface(); 
47   return 0;
48 }
49
50 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
51   if (S->decl_empty()) return;
52   assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
53          
54   for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
55        I != E; ++I) {
56     Decl *TmpD = static_cast<Decl*>(*I);
57     assert(TmpD && "This decl didn't get pushed??");
58     ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
59     assert(D && "This decl isn't a ScopedDecl?");
60     
61     IdentifierInfo *II = D->getIdentifier();
62     if (!II) continue;
63     
64     // Unlink this decl from the identifier.  Because the scope contains decls
65     // in an unordered collection, and because we have multiple identifier
66     // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
67     if (II->getFETokenInfo<Decl>() == D) {
68       // Normal case, no multiple decls in different namespaces.
69       II->setFETokenInfo(D->getNext());
70     } else {
71       // Scan ahead.  There are only three namespaces in C, so this loop can
72       // never execute more than 3 times.
73       ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
74       while (SomeDecl->getNext() != D) {
75         SomeDecl = SomeDecl->getNext();
76         assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
77       }
78       SomeDecl->setNext(D->getNext());
79     }
80     
81     // This will have to be revisited for C++: there we want to nest stuff in
82     // namespace decls etc.  Even for C, we might want a top-level translation
83     // unit decl or something.
84     if (!CurFunctionDecl)
85       continue;
86
87     // Chain this decl to the containing function, it now owns the memory for
88     // the decl.
89     D->setNext(CurFunctionDecl->getDeclChain());
90     CurFunctionDecl->setDeclChain(D);
91   }
92 }
93
94 /// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
95 /// Return the first declaration found (which may or may not be a class
96 /// declaration. Caller is responsible for handling the none-class case.
97 /// Bypassing the alias of a class by returning the aliased class.
98 ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
99   ScopedDecl *IDecl;
100   // Scan up the scope chain looking for a decl that matches this identifier
101   // that is in the appropriate namespace.
102   for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl; 
103        IDecl = IDecl->getNext())
104     if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
105       break;
106   
107   if (ObjCCompatibleAliasDecl *ADecl =
108       dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
109     return ADecl->getClassInterface();
110   return IDecl;
111 }
112
113 /// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
114 /// return 0 if one not found.
115 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
116   ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
117   return cast_or_null<ObjCInterfaceDecl>(IdDecl);
118 }
119
120 /// LookupScopedDecl - Look up the inner-most declaration in the specified
121 /// namespace.
122 ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
123                                    SourceLocation IdLoc, Scope *S) {
124   if (II == 0) return 0;
125   Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
126   
127   // Scan up the scope chain looking for a decl that matches this identifier
128   // that is in the appropriate namespace.  This search should not take long, as
129   // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
130   for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
131     if (D->getIdentifierNamespace() == NS)
132       return D;
133   
134   // If we didn't find a use of this identifier, and if the identifier
135   // corresponds to a compiler builtin, create the decl object for the builtin
136   // now, injecting it into translation unit scope, and return it.
137   if (NS == Decl::IDNS_Ordinary) {
138     // If this is a builtin on some other target, or if this builtin varies
139     // across targets (e.g. in type), emit a diagnostic and mark the translation
140     // unit non-portable for using it.
141     if (II->isNonPortableBuiltin()) {
142       // Only emit this diagnostic once for this builtin.
143       II->setNonPortableBuiltin(false);
144       Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
145                                             diag::port_target_builtin_use);
146     }
147     // If this is a builtin on this (or all) targets, create the decl.
148     if (unsigned BuiltinID = II->getBuiltinID())
149       return LazilyCreateBuiltin(II, BuiltinID, S);
150   }
151   return 0;
152 }
153
154 void Sema::InitBuiltinVaListType()
155 {
156   if (!Context.getBuiltinVaListType().isNull())
157     return;
158   
159   IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
160   ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary, 
161                                           SourceLocation(), TUScope);
162   TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
163   Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
164 }
165
166 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
167 /// lazily create a decl for it.
168 ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
169                                       Scope *S) {
170   Builtin::ID BID = (Builtin::ID)bid;
171
172   if (BID == Builtin::BI__builtin_va_start ||
173        BID == Builtin::BI__builtin_va_copy ||
174        BID == Builtin::BI__builtin_va_end)
175     InitBuiltinVaListType();
176     
177   QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);  
178   FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
179                                        FunctionDecl::Extern, false, 0);
180   
181   // Find translation-unit scope to insert this function into.
182   if (Scope *FnS = S->getFnParent())
183     S = FnS->getParent();   // Skip all scopes in a function at once.
184   while (S->getParent())
185     S = S->getParent();
186   S->AddDecl(New);
187   
188   // Add this decl to the end of the identifier info.
189   if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
190     // Scan until we find the last (outermost) decl in the id chain. 
191     while (LastDecl->getNext())
192       LastDecl = LastDecl->getNext();
193     // Insert before (outside) it.
194     LastDecl->setNext(New);
195   } else {
196     II->setFETokenInfo(New);
197   }    
198   return New;
199 }
200
201 /// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
202 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
203 /// situation, merging decls or emitting diagnostics as appropriate.
204 ///
205 TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
206   // Verify the old decl was also a typedef.
207   TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
208   if (!Old) {
209     Diag(New->getLocation(), diag::err_redefinition_different_kind,
210          New->getName());
211     Diag(OldD->getLocation(), diag::err_previous_definition);
212     return New;
213   }
214   
215   // Allow multiple definitions for ObjC built-in typedefs.
216   // FIXME: Verify the underlying types are equivalent!
217   if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
218     return Old;
219   
220   // Redeclaration of a type is a constraint violation (6.7.2.3p1).
221   // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
222   // *either* declaration is in a system header. The code below implements
223   // this adhoc compatibility rule. FIXME: The following code will not
224   // work properly when compiling ".i" files (containing preprocessed output).
225   SourceManager &SrcMgr = Context.getSourceManager();
226   const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
227   const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
228   HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
229   DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
230   DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
231   
232   if ((OldDirType == DirectoryLookup::ExternCSystemHeaderDir || 
233        NewDirType == DirectoryLookup::ExternCSystemHeaderDir) ||
234       getLangOptions().Microsoft)
235     return New;
236     
237   // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
238   // TODO: This is totally simplistic.  It should handle merging functions
239   // together etc, merging extern int X; int X; ...
240   Diag(New->getLocation(), diag::err_redefinition, New->getName());
241   Diag(Old->getLocation(), diag::err_previous_definition);
242   return New;
243 }
244
245 /// MergeFunctionDecl - We just parsed a function 'New' which has the same name
246 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
247 /// situation, merging decls or emitting diagnostics as appropriate.
248 ///
249 FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
250   // Verify the old decl was also a function.
251   FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
252   if (!Old) {
253     Diag(New->getLocation(), diag::err_redefinition_different_kind,
254          New->getName());
255     Diag(OldD->getLocation(), diag::err_previous_definition);
256     return New;
257   }
258   
259   QualType OldQType = Old->getCanonicalType();
260   QualType NewQType = New->getCanonicalType();
261   
262   // Function types need to be compatible, not identical. This handles
263   // duplicate function decls like "void f(int); void f(enum X);" properly.
264   if (Context.functionTypesAreCompatible(OldQType, NewQType))
265     return New;
266
267   // A function that has already been declared has been redeclared or defined
268   // with a different type- show appropriate diagnostic
269   diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
270                                          diag::err_previous_declaration; 
271
272   // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
273   // TODO: This is totally simplistic.  It should handle merging functions
274   // together etc, merging extern int X; int X; ...
275   Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
276   Diag(Old->getLocation(), PrevDiag);
277   return New;
278 }
279
280 /// equivalentArrayTypes - Used to determine whether two array types are 
281 /// equivalent.
282 /// We need to check this explicitly as an incomplete array definition is
283 /// considered a VariableArrayType, so will not match a complete array 
284 /// definition that would be otherwise equivalent.
285 static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
286   const ArrayType *NewAT = NewQType->getAsArrayType();
287   const ArrayType *OldAT = OldQType->getAsArrayType();
288
289   if (!NewAT || !OldAT)
290     return false;
291   
292   // If either (or both) array types in incomplete we need to strip off the
293   // outer VariableArrayType.  Once the outer VAT is removed the remaining
294   // types must be identical if the array types are to be considered 
295   // equivalent.
296   // eg. int[][1] and int[1][1] become
297   //     VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
298   // removing the outermost VAT gives
299   //     CAT(1, int) and CAT(1, int)
300   // which are equal, therefore the array types are equivalent.
301   if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
302     if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
303       return false;
304     NewQType = NewAT->getElementType().getCanonicalType();
305     OldQType = OldAT->getElementType().getCanonicalType();
306   }
307   
308   return NewQType == OldQType;
309 }
310
311 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
312 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
313 /// situation, merging decls or emitting diagnostics as appropriate.
314 ///
315 /// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
316 /// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
317 /// 
318 VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
319   // Verify the old decl was also a variable.
320   VarDecl *Old = dyn_cast<VarDecl>(OldD);
321   if (!Old) {
322     Diag(New->getLocation(), diag::err_redefinition_different_kind,
323          New->getName());
324     Diag(OldD->getLocation(), diag::err_previous_definition);
325     return New;
326   }
327   // Verify the types match.
328   if (Old->getCanonicalType() != New->getCanonicalType() && 
329       !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
330     Diag(New->getLocation(), diag::err_redefinition, New->getName());
331     Diag(Old->getLocation(), diag::err_previous_definition);
332     return New;
333   }
334   // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
335   if (New->getStorageClass() == VarDecl::Static &&
336       (Old->getStorageClass() == VarDecl::None ||
337        Old->getStorageClass() == VarDecl::Extern)) {
338     Diag(New->getLocation(), diag::err_static_non_static, New->getName());
339     Diag(Old->getLocation(), diag::err_previous_definition);
340     return New;
341   }
342   // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
343   if (New->getStorageClass() != VarDecl::Static &&
344       Old->getStorageClass() == VarDecl::Static) {
345     Diag(New->getLocation(), diag::err_non_static_static, New->getName());
346     Diag(Old->getLocation(), diag::err_previous_definition);
347     return New;
348   }
349   // We've verified the types match, now handle "tentative" definitions.
350   FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
351   FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
352   
353   if (OldFSDecl && NewFSDecl) {
354     // Handle C "tentative" external object definitions (C99 6.9.2).
355     bool OldIsTentative = false;
356     bool NewIsTentative = false;
357     
358     if (!OldFSDecl->getInit() &&
359         (OldFSDecl->getStorageClass() == VarDecl::None ||
360          OldFSDecl->getStorageClass() == VarDecl::Static))
361       OldIsTentative = true;
362       
363     // FIXME: this check doesn't work (since the initializer hasn't been
364     // attached yet). This check should be moved to FinalizeDeclaratorGroup.
365     // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've 
366     // thrown out the old decl.
367     if (!NewFSDecl->getInit() &&
368         (NewFSDecl->getStorageClass() == VarDecl::None ||
369          NewFSDecl->getStorageClass() == VarDecl::Static))
370       ; // change to NewIsTentative = true; once the code is moved.
371     
372     if (NewIsTentative || OldIsTentative)
373       return New;
374   }
375   if (Old->getStorageClass() != VarDecl::Extern &&
376       New->getStorageClass() != VarDecl::Extern) {
377     Diag(New->getLocation(), diag::err_redefinition, New->getName());
378     Diag(Old->getLocation(), diag::err_previous_definition);
379   }
380   return New;
381 }
382
383 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
384 /// no declarator (e.g. "struct foo;") is parsed.
385 Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
386   // TODO: emit error on 'int;' or 'const enum foo;'.
387   // TODO: emit error on 'typedef int;'
388   // if (!DS.isMissingDeclaratorOk()) Diag(...);
389   
390   return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
391 }
392
393 bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {  
394   // Get the type before calling CheckSingleAssignmentConstraints(), since
395   // it can promote the expression.
396   QualType InitType = Init->getType(); 
397   
398   AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
399   return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
400                                   InitType, Init, "initializing");
401 }
402
403 bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
404                          QualType ElementType) {
405   Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
406   if (CheckSingleInitializer(expr, ElementType))
407     return true; // types weren't compatible.
408   
409   if (savExpr != expr) // The type was promoted, update initializer list.
410     IList->setInit(slot, expr);
411   return false;
412 }
413
414 bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
415   if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
416     // C99 6.7.8p14. We have an array of character type with unknown size 
417     // being initialized to a string literal.
418     llvm::APSInt ConstVal(32);
419     ConstVal = strLiteral->getByteLength() + 1;
420     // Return a new array type (C99 6.7.8p22).
421     DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal, 
422                                          ArrayType::Normal, 0);
423   } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
424     // C99 6.7.8p14. We have an array of character type with known size.
425     if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
426       Diag(strLiteral->getSourceRange().getBegin(),
427            diag::warn_initializer_string_for_char_array_too_long,
428            strLiteral->getSourceRange());
429   } else {
430     assert(0 && "HandleStringLiteralInit(): Invalid array type");
431   }
432   // Set type from "char *" to "constant array of char".
433   strLiteral->setType(DeclT);
434   // For now, we always return false (meaning success).
435   return false;
436 }
437
438 StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
439   const ArrayType *AT = DeclType->getAsArrayType();
440   if (AT && AT->getElementType()->isCharType()) {
441     return dyn_cast<StringLiteral>(Init);
442   }
443   return 0;
444 }
445
446 // CheckInitializerListTypes - Checks the types of elements of an initializer
447 // list. This function is recursive: it calls itself to initialize subelements
448 // of aggregate types.  Note that the topLevel parameter essentially refers to
449 // whether this expression "owns" the initializer list passed in, or if this
450 // initialization is taking elements out of a parent initializer.  Each
451 // call to this function adds zero or more to startIndex, reports any errors,
452 // and returns true if it found any inconsistent types.
453 bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
454                                      bool topLevel, unsigned& startIndex) {
455   bool hadError = false;
456
457   if (DeclType->isScalarType()) {
458     // The simplest case: initializing a single scalar
459     if (topLevel) {
460       Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init, 
461            IList->getSourceRange());
462     }
463     if (startIndex < IList->getNumInits()) {
464       Expr* expr = IList->getInit(startIndex);
465       if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
466         // FIXME: Should an error be reported here instead?
467         unsigned newIndex = 0;
468         CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
469       } else {
470         hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
471       }
472       ++startIndex;
473     }
474     // FIXME: Should an error be reported for empty initializer list + scalar?
475   } else if (DeclType->isVectorType()) {
476     if (startIndex < IList->getNumInits()) {
477       const VectorType *VT = DeclType->getAsVectorType();
478       int maxElements = VT->getNumElements();
479       QualType elementType = VT->getElementType();
480       
481       for (int i = 0; i < maxElements; ++i) {
482         // Don't attempt to go past the end of the init list
483         if (startIndex >= IList->getNumInits())
484           break;
485         Expr* expr = IList->getInit(startIndex);
486         if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
487           unsigned newIndex = 0;
488           hadError |= CheckInitializerListTypes(SubInitList, elementType, 
489                                                 true, newIndex);
490           ++startIndex;
491         } else {
492           hadError |= CheckInitializerListTypes(IList, elementType, 
493                                                 false, startIndex);
494         }
495       }
496     }
497   } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
498     if (DeclType->isStructureType() || DeclType->isUnionType()) {
499       if (startIndex < IList->getNumInits() && !topLevel &&
500           Context.typesAreCompatible(IList->getInit(startIndex)->getType(), 
501                                      DeclType)) {
502         // We found a compatible struct; per the standard, this initializes the
503         // struct.  (The C standard technically says that this only applies for
504         // initializers for declarations with automatic scope; however, this
505         // construct is unambiguous anyway because a struct cannot contain
506         // a type compatible with itself. We'll output an error when we check
507         // if the initializer is constant.)
508         // FIXME: Is a call to CheckSingleInitializer required here?
509         ++startIndex;
510       } else {
511         RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
512         
513         // If the record is invalid, some of it's members are invalid. To avoid
514         // confusion, we forgo checking the intializer for the entire record.
515         if (structDecl->isInvalidDecl())
516           return true;
517           
518         // If structDecl is a forward declaration, this loop won't do anything;
519         // That's okay, because an error should get printed out elsewhere. It
520         // might be worthwhile to skip over the rest of the initializer, though.
521         int numMembers = structDecl->getNumMembers() -
522                          structDecl->hasFlexibleArrayMember();
523         for (int i = 0; i < numMembers; i++) {
524           // Don't attempt to go past the end of the init list
525           if (startIndex >= IList->getNumInits())
526             break;
527           FieldDecl * curField = structDecl->getMember(i);
528           if (!curField->getIdentifier()) {
529             // Don't initialize unnamed fields, e.g. "int : 20;"
530             continue;
531           }
532           QualType fieldType = curField->getType();
533           Expr* expr = IList->getInit(startIndex);
534           if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
535             unsigned newStart = 0;
536             hadError |= CheckInitializerListTypes(SubInitList, fieldType, 
537                                                   true, newStart);
538             ++startIndex;
539           } else {
540             hadError |= CheckInitializerListTypes(IList, fieldType, 
541                                                   false, startIndex);
542           }
543           if (DeclType->isUnionType())
544             break;
545         }
546         // FIXME: Implement flexible array initialization GCC extension (it's a 
547         // really messy extension to implement, unfortunately...the necessary
548         // information isn't actually even here!)
549       }
550     } else if (DeclType->isArrayType()) {
551       // Check for the special-case of initializing an array with a string.
552       if (startIndex < IList->getNumInits()) {
553         if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex), 
554                                                      DeclType)) {
555           CheckStringLiteralInit(lit, DeclType);
556           ++startIndex;
557           if (topLevel && startIndex < IList->getNumInits()) {
558             // We have leftover initializers; warn
559             Diag(IList->getInit(startIndex)->getLocStart(), 
560                  diag::err_excess_initializers_in_char_array_initializer, 
561                  IList->getInit(startIndex)->getSourceRange());
562           }
563           return false;
564         }
565       }
566       int maxElements;
567       if (DeclType->isIncompleteArrayType()) {
568         // FIXME: use a proper constant
569         maxElements = 0x7FFFFFFF;
570       } else if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
571         // Check for VLAs; in standard C it would be possible to check this
572         // earlier, but I don't know where clang accepts VLAs (gcc accepts
573         // them in all sorts of strange places).
574         Diag(VAT->getSizeExpr()->getLocStart(),
575              diag::err_variable_object_no_init,
576              VAT->getSizeExpr()->getSourceRange());
577         hadError = true;
578         maxElements = 0x7FFFFFFF;
579       } else {
580         const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
581         maxElements = static_cast<int>(CAT->getSize().getZExtValue());
582       }
583       QualType elementType = DeclType->getAsArrayType()->getElementType();
584       int numElements = 0;
585       for (int i = 0; i < maxElements; ++i, ++numElements) {
586         // Don't attempt to go past the end of the init list
587         if (startIndex >= IList->getNumInits())
588           break;
589         Expr* expr = IList->getInit(startIndex);
590         if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
591           unsigned newIndex = 0;
592           hadError |= CheckInitializerListTypes(SubInitList, elementType, 
593                                                 true, newIndex);
594           ++startIndex;
595         } else {
596           hadError |= CheckInitializerListTypes(IList, elementType, 
597                                                 false, startIndex);
598         }
599       }
600       if (DeclType->isIncompleteArrayType()) {
601         // If this is an incomplete array type, the actual type needs to
602         // be calculated here
603         if (numElements == 0) {
604           // Sizing an array implicitly to zero is not allowed
605           // (It could in theory be allowed, but it doesn't really matter.)
606           Diag(IList->getLocStart(),
607                diag::err_at_least_one_initializer_needed_to_size_array);
608           hadError = true;
609         } else {
610           llvm::APSInt ConstVal(32);
611           ConstVal = numElements;
612           DeclType = Context.getConstantArrayType(elementType, ConstVal, 
613                                                   ArrayType::Normal, 0);
614         }
615       }
616     } else {
617       assert(0 && "Aggregate that isn't a function or array?!");
618     }
619   } else {
620     // In C, all types are either scalars or aggregates, but
621     // additional handling is needed here for C++ (and possibly others?). 
622     assert(0 && "Unsupported initializer type");
623   }
624
625   // If this init list is a base list, we set the type; an initializer doesn't
626   // fundamentally have a type, but this makes the ASTs a bit easier to read
627   if (topLevel)
628     IList->setType(DeclType);
629
630   if (topLevel && startIndex < IList->getNumInits()) {
631     // We have leftover initializers; warn
632     Diag(IList->getInit(startIndex)->getLocStart(), 
633          diag::warn_excess_initializers, 
634          IList->getInit(startIndex)->getSourceRange());
635   }
636   return hadError;
637 }
638
639 bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {  
640   // C99 6.7.8p3: The type of the entity to be initialized shall be an array
641   // of unknown size ("[]") or an object type that is not a variable array type.
642   if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
643     return Diag(VAT->getSizeExpr()->getLocStart(), 
644                 diag::err_variable_object_no_init, 
645                 VAT->getSizeExpr()->getSourceRange());
646   
647   InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
648   if (!InitList) {
649     // FIXME: Handle wide strings
650     if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
651       return CheckStringLiteralInit(strLiteral, DeclType);
652
653     if (DeclType->isArrayType())
654       return Diag(Init->getLocStart(),
655                   diag::err_array_init_list_required, 
656                   Init->getSourceRange());
657
658     return CheckSingleInitializer(Init, DeclType);
659   }
660   unsigned newIndex = 0;
661   return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
662 }
663
664 Sema::DeclTy *
665 Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
666   ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
667   IdentifierInfo *II = D.getIdentifier();
668   
669   // All of these full declarators require an identifier.  If it doesn't have
670   // one, the ParsedFreeStandingDeclSpec action should be used.
671   if (II == 0) {
672     Diag(D.getDeclSpec().getSourceRange().getBegin(),
673          diag::err_declarator_need_ident,
674          D.getDeclSpec().getSourceRange(), D.getSourceRange());
675     return 0;
676   }
677   
678   // The scope passed in may not be a decl scope.  Zip up the scope tree until
679   // we find one that is.
680   while ((S->getFlags() & Scope::DeclScope) == 0)
681     S = S->getParent();
682   
683   // See if this is a redefinition of a variable in the same scope.
684   ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
685                                           D.getIdentifierLoc(), S);
686   ScopedDecl *New;
687   bool InvalidDecl = false;
688   
689   QualType R = GetTypeForDeclarator(D, S);
690   assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
691
692   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
693     TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
694     if (!NewTD) return 0;
695
696     // Handle attributes prior to checking for duplicates in MergeVarDecl
697     HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
698                          D.getAttributes());
699     // Merge the decl with the existing one if appropriate. If the decl is
700     // in an outer scope, it isn't the same thing.
701     if (PrevDecl && S->isDeclScope(PrevDecl)) {
702       NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
703       if (NewTD == 0) return 0;
704     }
705     New = NewTD;
706     if (S->getParent() == 0) {
707       // C99 6.7.7p2: If a typedef name specifies a variably modified type
708       // then it shall have block scope.
709       if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
710         // FIXME: Diagnostic needs to be fixed.
711         Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
712         InvalidDecl = true;
713       }
714     }
715   } else if (R.getTypePtr()->isFunctionType()) {
716     FunctionDecl::StorageClass SC = FunctionDecl::None;
717     switch (D.getDeclSpec().getStorageClassSpec()) {
718       default: assert(0 && "Unknown storage class!");
719       case DeclSpec::SCS_auto:        
720       case DeclSpec::SCS_register:
721         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
722              R.getAsString());
723         InvalidDecl = true;
724         break;
725       case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
726       case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
727       case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
728       case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
729     }
730
731     FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
732                                            D.getDeclSpec().isInlineSpecified(),
733                                            LastDeclarator);
734     // FIXME: Handle attributes.
735     D.getDeclSpec().clearAttributes();
736     
737     // Merge the decl with the existing one if appropriate. Since C functions
738     // are in a flat namespace, make sure we consider decls in outer scopes.
739     if (PrevDecl) {
740       NewFD = MergeFunctionDecl(NewFD, PrevDecl);
741       if (NewFD == 0) return 0;
742     }
743     New = NewFD;
744   } else {
745     if (R.getTypePtr()->isObjCInterfaceType()) {
746       Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
747            D.getIdentifier()->getName());
748       InvalidDecl = true;
749     }
750
751     VarDecl *NewVD;
752     VarDecl::StorageClass SC;
753     switch (D.getDeclSpec().getStorageClassSpec()) {
754       default: assert(0 && "Unknown storage class!");
755       case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
756       case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
757       case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
758       case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
759       case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
760       case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
761     }    
762     if (S->getParent() == 0) {
763       // C99 6.9p2: The storage-class specifiers auto and register shall not
764       // appear in the declaration specifiers in an external declaration.
765       if (SC == VarDecl::Auto || SC == VarDecl::Register) {
766         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
767              R.getAsString());
768         InvalidDecl = true;
769       }
770       NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
771     } else {
772       NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
773     }
774     // Handle attributes prior to checking for duplicates in MergeVarDecl
775     HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
776                          D.getAttributes());
777      
778     // Merge the decl with the existing one if appropriate. If the decl is
779     // in an outer scope, it isn't the same thing.
780     if (PrevDecl && S->isDeclScope(PrevDecl)) {
781       NewVD = MergeVarDecl(NewVD, PrevDecl);
782       if (NewVD == 0) return 0;
783     }
784     New = NewVD;
785   }
786   
787   // If this has an identifier, add it to the scope stack.
788   if (II) {
789     New->setNext(II->getFETokenInfo<ScopedDecl>());
790     II->setFETokenInfo(New);
791     S->AddDecl(New);
792   }
793   // If any semantic error occurred, mark the decl as invalid.
794   if (D.getInvalidType() || InvalidDecl)
795     New->setInvalidDecl();
796   
797   return New;
798 }
799
800 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
801   SourceLocation loc;
802   // FIXME: Remove the isReference check and handle assignment to a reference.
803   if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) { 
804     assert(loc.isValid() && "isConstantExpr didn't return a loc!");
805     Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
806     return true;
807   }
808   return false;
809 }
810
811 void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
812   Decl *RealDecl = static_cast<Decl *>(dcl);
813   Expr *Init = static_cast<Expr *>(init);
814   assert(Init && "missing initializer");
815   
816   // If there is no declaration, there was an error parsing it.  Just ignore
817   // the initializer.
818   if (RealDecl == 0) {
819     delete Init;
820     return;
821   }
822   
823   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
824   if (!VDecl) {
825     Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(), 
826          diag::err_illegal_initializer);
827     RealDecl->setInvalidDecl();
828     return;
829   }  
830   // Get the decls type and save a reference for later, since
831   // CheckInitializerTypes may change it.
832   QualType DclT = VDecl->getType(), SavT = DclT;
833   if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
834     VarDecl::StorageClass SC = BVD->getStorageClass();
835     if (SC == VarDecl::Extern) { // C99 6.7.8p5
836       Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
837       BVD->setInvalidDecl();
838     } else if (!BVD->isInvalidDecl()) {
839       if (CheckInitializerTypes(Init, DclT))
840         BVD->setInvalidDecl();
841       if (SC == VarDecl::Static) // C99 6.7.8p4.
842         CheckForConstantInitializer(Init, DclT);
843     }
844   } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
845     if (FVD->getStorageClass() == VarDecl::Extern)
846       Diag(VDecl->getLocation(), diag::warn_extern_init);
847     if (!FVD->isInvalidDecl())
848       if (CheckInitializerTypes(Init, DclT))
849         FVD->setInvalidDecl();
850     
851     // C99 6.7.8p4. All file scoped initializers need to be constant.
852     CheckForConstantInitializer(Init, DclT);
853   }
854   // If the type changed, it means we had an incomplete type that was
855   // completed by the initializer. For example: 
856   //   int ary[] = { 1, 3, 5 };
857   // "ary" transitions from a VariableArrayType to a ConstantArrayType.
858   if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
859     VDecl->setType(DclT);
860     Init->setType(DclT);
861   }
862     
863   // Attach the initializer to the decl.
864   VDecl->setInit(Init);
865   return;
866 }
867
868 /// The declarators are chained together backwards, reverse the list.
869 Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
870   // Often we have single declarators, handle them quickly.
871   Decl *GroupDecl = static_cast<Decl*>(group);
872   if (GroupDecl == 0)
873     return 0;
874   
875   ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
876   ScopedDecl *NewGroup = 0;
877   if (Group->getNextDeclarator() == 0) 
878     NewGroup = Group;
879   else { // reverse the list.
880     while (Group) {
881       ScopedDecl *Next = Group->getNextDeclarator();
882       Group->setNextDeclarator(NewGroup);
883       NewGroup = Group;
884       Group = Next;
885     }
886   }
887   // Perform semantic analysis that depends on having fully processed both
888   // the declarator and initializer.
889   for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
890     VarDecl *IDecl = dyn_cast<VarDecl>(ID);
891     if (!IDecl)
892       continue;
893     FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
894     BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
895     QualType T = IDecl->getType();
896     
897     // C99 6.7.5.2p2: If an identifier is declared to be an object with 
898     // static storage duration, it shall not have a variable length array.
899     if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
900       if (T->getAsVariableArrayType()) {
901         Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
902         IDecl->setInvalidDecl();
903       }
904     }
905     // Block scope. C99 6.7p7: If an identifier for an object is declared with
906     // no linkage (C99 6.2.2p6), the type for the object shall be complete...
907     if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
908       if (T->isIncompleteType()) {
909         Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
910              T.getAsString());
911         IDecl->setInvalidDecl();
912       }
913     }
914     // File scope. C99 6.9.2p2: A declaration of an identifier for and 
915     // object that has file scope without an initializer, and without a
916     // storage-class specifier or with the storage-class specifier "static",
917     // constitutes a tentative definition. Note: A tentative definition with
918     // external linkage is valid (C99 6.2.2p5).
919     if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static || 
920                                    FVD->getStorageClass() == VarDecl::None)) {
921       if (T->isIncompleteArrayType()) {
922         // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
923         // array to be completed. Don't issue a diagnostic.
924       } else if (T->isIncompleteType()) {
925         // C99 6.9.2p3: If the declaration of an identifier for an object is
926         // a tentative definition and has internal linkage (C99 6.2.2p3), the  
927         // declared type shall not be an incomplete type.
928         Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
929              T.getAsString());
930         IDecl->setInvalidDecl();
931       }
932     }
933   }
934   return NewGroup;
935 }
936
937 // Called from Sema::ParseStartOfFunctionDef().
938 ParmVarDecl *
939 Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
940                            Scope *FnScope) {
941   IdentifierInfo *II = PI.Ident;
942   // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
943   // Can this happen for params?  We already checked that they don't conflict
944   // among each other.  Here they can only shadow globals, which is ok.
945   if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
946                                         PI.IdentLoc, FnScope)) {
947     
948   }
949   
950   // FIXME: Handle storage class (auto, register). No declarator?
951   // TODO: Chain to previous parameter with the prevdeclarator chain?
952
953   // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
954   // Doing the promotion here has a win and a loss. The win is the type for
955   // both Decl's and DeclRefExpr's will match (a convenient invariant for the
956   // code generator). The loss is the orginal type isn't preserved. For example:
957   //
958   // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
959   //    int blockvardecl[5];
960   //    sizeof(parmvardecl);  // size == 4
961   //    sizeof(blockvardecl); // size == 20
962   // }
963   //
964   // For expressions, all implicit conversions are captured using the
965   // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
966   //
967   // FIXME: If a source translation tool needs to see the original type, then
968   // we need to consider storing both types (in ParmVarDecl)...
969   // 
970   QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
971   if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
972     // int x[restrict 4] ->  int *restrict
973     parmDeclType = Context.getPointerType(AT->getElementType());
974     parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
975   } else if (parmDeclType->isFunctionType())
976     parmDeclType = Context.getPointerType(parmDeclType);
977   
978   ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType, 
979                                      VarDecl::None, 0);
980   
981   if (PI.InvalidType)
982     New->setInvalidDecl();
983     
984   // If this has an identifier, add it to the scope stack.
985   if (II) {
986     New->setNext(II->getFETokenInfo<ScopedDecl>());
987     II->setFETokenInfo(New);
988     FnScope->AddDecl(New);
989   }
990
991   HandleDeclAttributes(New, PI.AttrList, 0);
992   return New;
993 }
994
995 Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
996   assert(CurFunctionDecl == 0 && "Function parsing confused");
997   assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
998          "Not a function declarator!");
999   DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1000   
1001   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1002   // for a K&R function.
1003   if (!FTI.hasPrototype) {
1004     for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1005       if (FTI.ArgInfo[i].TypeInfo == 0) {
1006         Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1007              FTI.ArgInfo[i].Ident->getName());
1008         // Implicitly declare the argument as type 'int' for lack of a better
1009         // type.
1010         FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1011       }
1012     }
1013
1014     // Since this is a function definition, act as though we have information
1015     // about the arguments.
1016     if (FTI.NumArgs)
1017       FTI.hasPrototype = true;
1018   } else {
1019     // FIXME: Diagnose arguments without names in C.
1020     
1021   }
1022   
1023   Scope *GlobalScope = FnBodyScope->getParent();
1024
1025   // See if this is a redefinition.
1026   ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1027                                          D.getIdentifierLoc(), GlobalScope);
1028   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1029     if (FD->getBody()) {
1030       Diag(D.getIdentifierLoc(), diag::err_redefinition, 
1031            D.getIdentifier()->getName());
1032       Diag(FD->getLocation(), diag::err_previous_definition);
1033     }
1034   }
1035   Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
1036   FunctionDecl *FD = cast<FunctionDecl>(decl);
1037   CurFunctionDecl = FD;
1038   
1039   // Create Decl objects for each parameter, adding them to the FunctionDecl.
1040   llvm::SmallVector<ParmVarDecl*, 16> Params;
1041   
1042   // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1043   // no arguments, not a function that takes a single void argument.
1044   if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1045       !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
1046       QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
1047     // empty arg list, don't push any params.
1048   } else {
1049     for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1050       Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
1051                                             FnBodyScope));
1052     }
1053   }
1054   
1055   FD->setParams(&Params[0], Params.size());
1056   
1057   return FD;
1058 }
1059
1060 Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1061   Decl *dcl = static_cast<Decl *>(D);
1062   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1063     FD->setBody((Stmt*)Body);
1064     assert(FD == CurFunctionDecl && "Function parsing confused");
1065     CurFunctionDecl = 0;
1066   } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
1067     MD->setBody((Stmt*)Body);
1068     CurMethodDecl = 0;
1069   }  
1070   // Verify and clean out per-function state.
1071   
1072   // Check goto/label use.
1073   for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1074        I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1075     // Verify that we have no forward references left.  If so, there was a goto
1076     // or address of a label taken, but no definition of it.  Label fwd
1077     // definitions are indicated with a null substmt.
1078     if (I->second->getSubStmt() == 0) {
1079       LabelStmt *L = I->second;
1080       // Emit error.
1081       Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1082       
1083       // At this point, we have gotos that use the bogus label.  Stitch it into
1084       // the function body so that they aren't leaked and that the AST is well
1085       // formed.
1086       if (Body) {
1087         L->setSubStmt(new NullStmt(L->getIdentLoc()));
1088         cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1089       } else {
1090         // The whole function wasn't parsed correctly, just delete this.
1091         delete L;
1092       }
1093     }
1094   }
1095   LabelMap.clear();
1096   
1097   return D;
1098 }
1099
1100 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1101 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
1102 ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 
1103                                            IdentifierInfo &II, Scope *S) {
1104   if (getLangOptions().C99)  // Extension in C99.
1105     Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1106   else  // Legal in C90, but warn about it.
1107     Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1108   
1109   // FIXME: handle stuff like:
1110   // void foo() { extern float X(); }
1111   // void bar() { X(); }  <-- implicit decl for X in another scope.
1112
1113   // Set a Declarator for the implicit definition: int foo();
1114   const char *Dummy;
1115   DeclSpec DS;
1116   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1117   Error = Error; // Silence warning.
1118   assert(!Error && "Error setting up implicit decl!");
1119   Declarator D(DS, Declarator::BlockContext);
1120   D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1121   D.SetIdentifier(&II, Loc);
1122   
1123   // Find translation-unit scope to insert this function into.
1124   if (Scope *FnS = S->getFnParent())
1125     S = FnS->getParent();   // Skip all scopes in a function at once.
1126   while (S->getParent())
1127     S = S->getParent();
1128   
1129   return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1130 }
1131
1132
1133 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1134                                     ScopedDecl *LastDeclarator) {
1135   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
1136   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1137   
1138   // Scope manipulation handled by caller.
1139   TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(), 
1140                                        T, LastDeclarator);
1141   if (D.getInvalidType())
1142     NewTD->setInvalidDecl();
1143   return NewTD;
1144 }
1145
1146 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
1147 /// former case, Name will be non-null.  In the later case, Name will be null.
1148 /// TagType indicates what kind of tag this is. TK indicates whether this is a
1149 /// reference/declaration/definition of a tag.
1150 Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
1151                              SourceLocation KWLoc, IdentifierInfo *Name,
1152                              SourceLocation NameLoc, AttributeList *Attr) {
1153   // If this is a use of an existing tag, it must have a name.
1154   assert((Name != 0 || TK == TK_Definition) &&
1155          "Nameless record must be a definition!");
1156   
1157   Decl::Kind Kind;
1158   switch (TagType) {
1159   default: assert(0 && "Unknown tag type!");
1160   case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1161   case DeclSpec::TST_union:  Kind = Decl::Union; break;
1162 //case DeclSpec::TST_class:  Kind = Decl::Class; break;
1163   case DeclSpec::TST_enum:   Kind = Decl::Enum; break;
1164   }
1165   
1166   // If this is a named struct, check to see if there was a previous forward
1167   // declaration or definition.
1168   if (TagDecl *PrevDecl = 
1169           dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1170                                                      NameLoc, S))) {
1171     
1172     // If this is a use of a previous tag, or if the tag is already declared in
1173     // the same scope (so that the definition/declaration completes or
1174     // rementions the tag), reuse the decl.
1175     if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1176       // Make sure that this wasn't declared as an enum and now used as a struct
1177       // or something similar.
1178       if (PrevDecl->getKind() != Kind) {
1179         Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1180         Diag(PrevDecl->getLocation(), diag::err_previous_use);
1181       }
1182       
1183       // If this is a use or a forward declaration, we're good.
1184       if (TK != TK_Definition)
1185         return PrevDecl;
1186
1187       // Diagnose attempts to redefine a tag.
1188       if (PrevDecl->isDefinition()) {
1189         Diag(NameLoc, diag::err_redefinition, Name->getName());
1190         Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1191         // If this is a redefinition, recover by making this struct be
1192         // anonymous, which will make any later references get the previous
1193         // definition.
1194         Name = 0;
1195       } else {
1196         // Okay, this is definition of a previously declared or referenced tag.
1197         // Move the location of the decl to be the definition site.
1198         PrevDecl->setLocation(NameLoc);
1199         return PrevDecl;
1200       }
1201     }
1202     // If we get here, this is a definition of a new struct type in a nested
1203     // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1204     // type.
1205   }
1206   
1207   // If there is an identifier, use the location of the identifier as the
1208   // location of the decl, otherwise use the location of the struct/union
1209   // keyword.
1210   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1211   
1212   // Otherwise, if this is the first time we've seen this tag, create the decl.
1213   TagDecl *New;
1214   switch (Kind) {
1215   default: assert(0 && "Unknown tag kind!");
1216   case Decl::Enum:
1217     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1218     // enum X { A, B, C } D;    D should chain to X.
1219     New = new EnumDecl(Loc, Name, 0);
1220     // If this is an undefined enum, warn.
1221     if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1222     break;
1223   case Decl::Union:
1224   case Decl::Struct:
1225   case Decl::Class:
1226     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1227     // struct X { int A; } D;    D should chain to X.
1228     New = new RecordDecl(Kind, Loc, Name, 0);
1229     break;
1230   }    
1231   
1232   // If this has an identifier, add it to the scope stack.
1233   if (Name) {
1234     // The scope passed in may not be a decl scope.  Zip up the scope tree until
1235     // we find one that is.
1236     while ((S->getFlags() & Scope::DeclScope) == 0)
1237       S = S->getParent();
1238     
1239     // Add it to the decl chain.
1240     New->setNext(Name->getFETokenInfo<ScopedDecl>());
1241     Name->setFETokenInfo(New);
1242     S->AddDecl(New);
1243   }
1244   
1245   HandleDeclAttributes(New, Attr, 0);
1246   return New;
1247 }
1248
1249 /// ActOnField - Each field of a struct/union/class is passed into this in order
1250 /// to create a FieldDecl object for it.
1251 Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
1252                                SourceLocation DeclStart, 
1253                                Declarator &D, ExprTy *BitfieldWidth) {
1254   IdentifierInfo *II = D.getIdentifier();
1255   Expr *BitWidth = (Expr*)BitfieldWidth;
1256   SourceLocation Loc = DeclStart;
1257   if (II) Loc = D.getIdentifierLoc();
1258   
1259   // FIXME: Unnamed fields can be handled in various different ways, for
1260   // example, unnamed unions inject all members into the struct namespace!
1261   
1262   
1263   if (BitWidth) {
1264     // TODO: Validate.
1265     //printf("WARNING: BITFIELDS IGNORED!\n");
1266     
1267     // 6.7.2.1p3
1268     // 6.7.2.1p4
1269     
1270   } else {
1271     // Not a bitfield.
1272
1273     // validate II.
1274     
1275   }
1276   
1277   QualType T = GetTypeForDeclarator(D, S);
1278   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1279   bool InvalidDecl = false;
1280
1281   // C99 6.7.2.1p8: A member of a structure or union may have any type other
1282   // than a variably modified type.
1283   if (T->isVariablyModifiedType()) {
1284     // FIXME: This diagnostic needs work
1285     Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1286     InvalidDecl = true;
1287   }
1288   // FIXME: Chain fielddecls together.
1289   FieldDecl *NewFD;
1290   
1291   if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
1292     NewFD = new FieldDecl(Loc, II, T, BitWidth);
1293   else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1294            isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1295            isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
1296            // FIXME: ivars are currently used to model properties, and
1297            // properties can appear within a protocol.
1298            // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1299            isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1300     NewFD = new ObjCIvarDecl(Loc, II, T);
1301   else
1302     assert(0 && "Sema::ActOnField(): Unknown TagDecl");
1303     
1304   HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1305                        D.getAttributes());
1306
1307   if (D.getInvalidType() || InvalidDecl)
1308     NewFD->setInvalidDecl();
1309   return NewFD;
1310 }
1311
1312 /// TranslateIvarVisibility - Translate visibility from a token ID to an 
1313 ///  AST enum value.
1314 static ObjCIvarDecl::AccessControl
1315 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
1316   switch (ivarVisibility) {
1317     case tok::objc_private: return ObjCIvarDecl::Private;
1318     case tok::objc_public: return ObjCIvarDecl::Public;
1319     case tok::objc_protected: return ObjCIvarDecl::Protected;
1320     case tok::objc_package: return ObjCIvarDecl::Package;
1321     default: assert(false && "Unknown visitibility kind");
1322   }
1323 }
1324
1325 void Sema::ActOnFields(Scope* S,
1326                        SourceLocation RecLoc, DeclTy *RecDecl,
1327                        DeclTy **Fields, unsigned NumFields,
1328                        SourceLocation LBrac, SourceLocation RBrac,
1329                        tok::ObjCKeywordKind *visibility) {
1330   Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1331   assert(EnclosingDecl && "missing record or interface decl");
1332   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1333   
1334   if (Record && Record->isDefinition()) {
1335     // Diagnose code like:
1336     //     struct S { struct S {} X; };
1337     // We discover this when we complete the outer S.  Reject and ignore the
1338     // outer S.
1339     Diag(Record->getLocation(), diag::err_nested_redefinition,
1340          Record->getKindName());
1341     Diag(RecLoc, diag::err_previous_definition);
1342     Record->setInvalidDecl();
1343     return;
1344   }
1345   // Verify that all the fields are okay.
1346   unsigned NumNamedMembers = 0;
1347   llvm::SmallVector<FieldDecl*, 32> RecFields;
1348   llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1349   
1350   for (unsigned i = 0; i != NumFields; ++i) {
1351     
1352     FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1353     assert(FD && "missing field decl");
1354     
1355     // Remember all fields.
1356     RecFields.push_back(FD);
1357     
1358     // Get the type for the field.
1359     Type *FDTy = FD->getType().getTypePtr();
1360     
1361     // If we have visibility info, make sure the AST is set accordingly.
1362     if (visibility)
1363       cast<ObjCIvarDecl>(FD)->setAccessControl(
1364                                 TranslateIvarVisibility(visibility[i]));
1365       
1366     // C99 6.7.2.1p2 - A field may not be a function type.
1367     if (FDTy->isFunctionType()) {
1368       Diag(FD->getLocation(), diag::err_field_declared_as_function, 
1369            FD->getName());
1370       FD->setInvalidDecl();
1371       EnclosingDecl->setInvalidDecl();
1372       continue;
1373     }
1374     // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1375     if (FDTy->isIncompleteType()) {
1376       if (!Record) {  // Incomplete ivar type is always an error.
1377         Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1378         FD->setInvalidDecl();
1379         EnclosingDecl->setInvalidDecl();
1380         continue;
1381       }
1382       if (i != NumFields-1 ||                   // ... that the last member ...
1383           Record->getKind() != Decl::Struct ||  // ... of a structure ...
1384           !FDTy->isArrayType()) {         //... may have incomplete array type.
1385         Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1386         FD->setInvalidDecl();
1387         EnclosingDecl->setInvalidDecl();
1388         continue;
1389       }
1390       if (NumNamedMembers < 1) {  //... must have more than named member ...
1391         Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1392              FD->getName());
1393         FD->setInvalidDecl();
1394         EnclosingDecl->setInvalidDecl();
1395         continue;
1396       }
1397       // Okay, we have a legal flexible array member at the end of the struct.
1398       if (Record)
1399         Record->setHasFlexibleArrayMember(true);
1400     }
1401     /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1402     /// field of another structure or the element of an array.
1403     if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
1404       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1405         // If this is a member of a union, then entire union becomes "flexible".
1406         if (Record && Record->getKind() == Decl::Union) {
1407           Record->setHasFlexibleArrayMember(true);
1408         } else {
1409           // If this is a struct/class and this is not the last element, reject
1410           // it.  Note that GCC supports variable sized arrays in the middle of
1411           // structures.
1412           if (i != NumFields-1) {
1413             Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1414                  FD->getName());
1415             FD->setInvalidDecl();
1416             EnclosingDecl->setInvalidDecl();
1417             continue;
1418           }
1419           // We support flexible arrays at the end of structs in other structs
1420           // as an extension.
1421           Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1422                FD->getName());
1423           if (Record)
1424             Record->setHasFlexibleArrayMember(true);
1425         }
1426       }
1427     }
1428     /// A field cannot be an Objective-c object
1429     if (FDTy->isObjCInterfaceType()) {
1430       Diag(FD->getLocation(), diag::err_statically_allocated_object,
1431            FD->getName());
1432       FD->setInvalidDecl();
1433       EnclosingDecl->setInvalidDecl();
1434       continue;
1435     }
1436     // Keep track of the number of named members.
1437     if (IdentifierInfo *II = FD->getIdentifier()) {
1438       // Detect duplicate member names.
1439       if (!FieldIDs.insert(II)) {
1440         Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1441         // Find the previous decl.
1442         SourceLocation PrevLoc;
1443         for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1444           assert(i != e && "Didn't find previous def!");
1445           if (RecFields[i]->getIdentifier() == II) {
1446             PrevLoc = RecFields[i]->getLocation();
1447             break;
1448           }
1449         }
1450         Diag(PrevLoc, diag::err_previous_definition);
1451         FD->setInvalidDecl();
1452         EnclosingDecl->setInvalidDecl();
1453         continue;
1454       }
1455       ++NumNamedMembers;
1456     }
1457   }
1458  
1459   // Okay, we successfully defined 'Record'.
1460   if (Record) {
1461     Record->defineBody(&RecFields[0], RecFields.size());
1462     Consumer.HandleTagDeclDefinition(Record);
1463   } else {
1464     ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1465     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1466       ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1467     else if (ObjCImplementationDecl *IMPDecl = 
1468                dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
1469       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1470       IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
1471       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
1472     }
1473   }
1474 }
1475
1476 Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
1477                                       DeclTy *lastEnumConst,
1478                                       SourceLocation IdLoc, IdentifierInfo *Id,
1479                                       SourceLocation EqualLoc, ExprTy *val) {
1480   theEnumDecl = theEnumDecl;  // silence unused warning.
1481   EnumConstantDecl *LastEnumConst =
1482     cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1483   Expr *Val = static_cast<Expr*>(val);
1484
1485   // The scope passed in may not be a decl scope.  Zip up the scope tree until
1486   // we find one that is.
1487   while ((S->getFlags() & Scope::DeclScope) == 0)
1488     S = S->getParent();
1489   
1490   // Verify that there isn't already something declared with this name in this
1491   // scope.
1492   if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, 
1493                                               IdLoc, S)) {
1494     if (S->isDeclScope(PrevDecl)) {
1495       if (isa<EnumConstantDecl>(PrevDecl))
1496         Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1497       else
1498         Diag(IdLoc, diag::err_redefinition, Id->getName());
1499       Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1500       // FIXME: Don't leak memory: delete Val;
1501       return 0;
1502     }
1503   }
1504
1505   llvm::APSInt EnumVal(32);
1506   QualType EltTy;
1507   if (Val) {
1508     // Make sure to promote the operand type to int.
1509     UsualUnaryConversions(Val);
1510     
1511     // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1512     SourceLocation ExpLoc;
1513     if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1514       Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr, 
1515            Id->getName());
1516       // FIXME: Don't leak memory: delete Val;
1517       Val = 0;  // Just forget about it.
1518     } else {
1519       EltTy = Val->getType();
1520     }
1521   }
1522   
1523   if (!Val) {
1524     if (LastEnumConst) {
1525       // Assign the last value + 1.
1526       EnumVal = LastEnumConst->getInitVal();
1527       ++EnumVal;
1528
1529       // Check for overflow on increment.
1530       if (EnumVal < LastEnumConst->getInitVal())
1531         Diag(IdLoc, diag::warn_enum_value_overflow);
1532       
1533       EltTy = LastEnumConst->getType();
1534     } else {
1535       // First value, set to zero.
1536       EltTy = Context.IntTy;
1537       EnumVal.zextOrTrunc(
1538         static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
1539     }
1540   }
1541   
1542   EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1543                                                LastEnumConst);
1544   
1545   // Register this decl in the current scope stack.
1546   New->setNext(Id->getFETokenInfo<ScopedDecl>());
1547   Id->setFETokenInfo(New);
1548   S->AddDecl(New);
1549   return New;
1550 }
1551
1552 void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1553                          DeclTy **Elements, unsigned NumElements) {
1554   EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1555   assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1556   
1557   // TODO: If the result value doesn't fit in an int, it must be a long or long
1558   // long value.  ISO C does not support this, but GCC does as an extension,
1559   // emit a warning.
1560   unsigned IntWidth =
1561     Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
1562   
1563   
1564   // Verify that all the values are okay, compute the size of the values, and
1565   // reverse the list.
1566   unsigned NumNegativeBits = 0;
1567   unsigned NumPositiveBits = 0;
1568   
1569   // Keep track of whether all elements have type int.
1570   bool AllElementsInt = true;
1571   
1572   EnumConstantDecl *EltList = 0;
1573   for (unsigned i = 0; i != NumElements; ++i) {
1574     EnumConstantDecl *ECD =
1575       cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1576     if (!ECD) continue;  // Already issued a diagnostic.
1577     
1578     // If the enum value doesn't fit in an int, emit an extension warning.
1579     assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1580            "Should have promoted value to int");
1581     const llvm::APSInt &InitVal = ECD->getInitVal();
1582     if (InitVal.getBitWidth() > IntWidth) {
1583       llvm::APSInt V(InitVal);
1584       V.trunc(IntWidth);
1585       V.extend(InitVal.getBitWidth());
1586       if (V != InitVal)
1587         Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1588              InitVal.toString());
1589     }
1590     
1591     // Keep track of the size of positive and negative values.
1592     if (InitVal.isUnsigned() || !InitVal.isNegative())
1593       NumPositiveBits = std::max(NumPositiveBits,
1594                                  (unsigned)InitVal.getActiveBits());
1595     else
1596       NumNegativeBits = std::max(NumNegativeBits,
1597                                  (unsigned)InitVal.getMinSignedBits());
1598
1599     // Keep track of whether every enum element has type int (very commmon).
1600     if (AllElementsInt)
1601       AllElementsInt = ECD->getType() == Context.IntTy; 
1602     
1603     ECD->setNextDeclarator(EltList);
1604     EltList = ECD;
1605   }
1606   
1607   // Figure out the type that should be used for this enum.
1608   // FIXME: Support attribute(packed) on enums and -fshort-enums.
1609   QualType BestType;
1610   unsigned BestWidth;
1611   
1612   if (NumNegativeBits) {
1613     // If there is a negative value, figure out the smallest integer type (of 
1614     // int/long/longlong) that fits.
1615     if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
1616       BestType = Context.IntTy;
1617       BestWidth = IntWidth;
1618     } else {
1619       BestWidth = 
1620         Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1621       
1622       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
1623         BestType = Context.LongTy;
1624       else {
1625         BestWidth = Context.Target.getLongLongWidth(
1626                        Context.getFullLoc(Enum->getLocation()));
1627         
1628         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
1629           Diag(Enum->getLocation(), diag::warn_enum_too_large);
1630         BestType = Context.LongLongTy;
1631       }
1632     }
1633   } else {
1634     // If there is no negative value, figure out which of uint, ulong, ulonglong
1635     // fits.
1636     if (NumPositiveBits <= IntWidth) {
1637       BestType = Context.UnsignedIntTy;
1638       BestWidth = IntWidth;
1639     } else if (NumPositiveBits <=
1640                (BestWidth = Context.Target.getLongWidth(
1641                               Context.getFullLoc(Enum->getLocation()))))
1642
1643       BestType = Context.UnsignedLongTy;
1644     else {
1645       BestWidth =
1646        Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1647       
1648       assert(NumPositiveBits <= BestWidth &&
1649              "How could an initializer get larger than ULL?");
1650       BestType = Context.UnsignedLongLongTy;
1651     }
1652   }
1653   
1654   // Loop over all of the enumerator constants, changing their types to match
1655   // the type of the enum if needed.
1656   for (unsigned i = 0; i != NumElements; ++i) {
1657     EnumConstantDecl *ECD =
1658       cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1659     if (!ECD) continue;  // Already issued a diagnostic.
1660
1661     // Standard C says the enumerators have int type, but we allow, as an
1662     // extension, the enumerators to be larger than int size.  If each
1663     // enumerator value fits in an int, type it as an int, otherwise type it the
1664     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
1665     // that X has type 'int', not 'unsigned'.
1666     if (ECD->getType() == Context.IntTy)
1667       continue;  // Already int type.
1668
1669     // Determine whether the value fits into an int.
1670     llvm::APSInt InitVal = ECD->getInitVal();
1671     bool FitsInInt;
1672     if (InitVal.isUnsigned() || !InitVal.isNegative())
1673       FitsInInt = InitVal.getActiveBits() < IntWidth;
1674     else
1675       FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1676
1677     // If it fits into an integer type, force it.  Otherwise force it to match
1678     // the enum decl type.
1679     QualType NewTy;
1680     unsigned NewWidth;
1681     bool NewSign;
1682     if (FitsInInt) {
1683       NewTy = Context.IntTy;
1684       NewWidth = IntWidth;
1685       NewSign = true;
1686     } else if (ECD->getType() == BestType) {
1687       // Already the right type!
1688       continue;
1689     } else {
1690       NewTy = BestType;
1691       NewWidth = BestWidth;
1692       NewSign = BestType->isSignedIntegerType();
1693     }
1694
1695     // Adjust the APSInt value.
1696     InitVal.extOrTrunc(NewWidth);
1697     InitVal.setIsSigned(NewSign);
1698     ECD->setInitVal(InitVal);
1699     
1700     // Adjust the Expr initializer and type.
1701     ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1702     ECD->setType(NewTy);
1703   }
1704   
1705   Enum->defineElements(EltList, BestType);
1706   Consumer.HandleTagDeclDefinition(Enum);
1707 }
1708
1709 Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1710                                           ExprTy *expr) {
1711   StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1712   
1713   return new FileScopeAsmDecl(Loc, AsmString);
1714 }
1715
1716 Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1717                                      SourceLocation LBrace,
1718                                      SourceLocation RBrace,
1719                                      const char *Lang,
1720                                      unsigned StrSize,
1721                                      DeclTy *D) {
1722   LinkageSpecDecl::LanguageIDs Language;
1723   Decl *dcl = static_cast<Decl *>(D);
1724   if (strncmp(Lang, "\"C\"", StrSize) == 0)
1725     Language = LinkageSpecDecl::lang_c;
1726   else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1727     Language = LinkageSpecDecl::lang_cxx;
1728   else {
1729     Diag(Loc, diag::err_bad_language);
1730     return 0;
1731   }
1732
1733   // FIXME: Add all the various semantics of linkage specifications
1734   return new LinkageSpecDecl(Loc, Language, dcl);
1735 }
1736
1737 void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1738   const char *attrName = rawAttr->getAttributeName()->getName();
1739   unsigned attrLen = rawAttr->getAttributeName()->getLength();
1740   
1741   // Normalize the attribute name, __foo__ becomes foo.
1742   if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1743       attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1744     attrName += 2;
1745     attrLen -= 4;
1746   }
1747   
1748   if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
1749     if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1750       QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1751       if (!newType.isNull()) // install the new vector type into the decl
1752         vDecl->setType(newType);
1753     } 
1754     if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1755       QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(), 
1756                                                    rawAttr);
1757       if (!newType.isNull()) // install the new vector type into the decl
1758         tDecl->setUnderlyingType(newType);
1759     }
1760   } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
1761     if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1762       HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1763     else
1764       Diag(rawAttr->getAttributeLoc(), 
1765            diag::err_typecheck_ocu_vector_not_typedef);
1766   } else if (attrLen == 13 && !memcmp(attrName, "address_space", 13)) {
1767     if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1768       QualType newType = HandleAddressSpaceTypeAttribute(
1769                                                   tDecl->getUnderlyingType(), 
1770                                                   rawAttr);
1771       if (!newType.isNull()) // install the new addr spaced type into the decl
1772         tDecl->setUnderlyingType(newType);
1773     } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1774       QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(), 
1775                                                          rawAttr);
1776       if (!newType.isNull()) // install the new addr spaced  type into the decl
1777         vDecl->setType(newType);
1778     }
1779   } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7))
1780     HandleAlignedAttribute(New, rawAttr);
1781   else if (attrLen == 6 && !memcmp(attrName, "packed", 6))
1782     HandlePackedAttribute(New, rawAttr);
1783
1784   // FIXME: add other attributes...
1785 }
1786
1787 void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1788                                 AttributeList *declarator_postfix) {
1789   while (declspec_prefix) {
1790     HandleDeclAttribute(New, declspec_prefix);
1791     declspec_prefix = declspec_prefix->getNext();
1792   }
1793   while (declarator_postfix) {
1794     HandleDeclAttribute(New, declarator_postfix);
1795     declarator_postfix = declarator_postfix->getNext();
1796   }
1797 }
1798
1799 QualType Sema::HandleAddressSpaceTypeAttribute(QualType curType, 
1800                                                AttributeList *rawAttr) {
1801   // check the attribute arugments.
1802   if (rawAttr->getNumArgs() != 1) {
1803     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1804          std::string("1"));
1805     return QualType();
1806   }
1807   Expr *addrSpaceExpr = static_cast<Expr *>(rawAttr->getArg(0));
1808   llvm::APSInt addrSpace(32);
1809   if (!addrSpaceExpr->isIntegerConstantExpr(addrSpace, Context)) {
1810     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_address_space_not_int,
1811          addrSpaceExpr->getSourceRange());
1812     return QualType();
1813   }
1814   unsigned addressSpace = static_cast<unsigned>(addrSpace.getZExtValue()); 
1815   
1816   // Zero is the default memory space, so no qualification is needed
1817   if (addressSpace == 0)
1818     return curType;
1819   
1820   // TODO: Should we convert contained types of address space 
1821   // qualified types here or or where they directly participate in conversions
1822   // (i.e. elsewhere)
1823   
1824   return Context.getASQualType(curType, addressSpace);
1825 }
1826
1827 void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl, 
1828                                         AttributeList *rawAttr) {
1829   QualType curType = tDecl->getUnderlyingType();
1830   // check the attribute arguments.
1831   if (rawAttr->getNumArgs() != 1) {
1832     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1833          std::string("1"));
1834     return;
1835   }
1836   Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1837   llvm::APSInt vecSize(32);
1838   if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1839     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_argument_not_int,
1840          "ocu_vector_type", sizeExpr->getSourceRange());
1841     return;
1842   }
1843   // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1844   // in conjunction with complex types (pointers, arrays, functions, etc.).
1845   Type *canonType = curType.getCanonicalType().getTypePtr();
1846   if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1847     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1848          curType.getCanonicalType().getAsString());
1849     return;
1850   }
1851   // unlike gcc's vector_size attribute, the size is specified as the 
1852   // number of elements, not the number of bytes.
1853   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 
1854   
1855   if (vectorSize == 0) {
1856     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1857          sizeExpr->getSourceRange());
1858     return;
1859   }
1860   // Instantiate/Install the vector type, the number of elements is > 0.
1861   tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1862   // Remember this typedef decl, we will need it later for diagnostics.
1863   OCUVectorDecls.push_back(tDecl);
1864 }
1865
1866 QualType Sema::HandleVectorTypeAttribute(QualType curType, 
1867                                          AttributeList *rawAttr) {
1868   // check the attribute arugments.
1869   if (rawAttr->getNumArgs() != 1) {
1870     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1871          std::string("1"));
1872     return QualType();
1873   }
1874   Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1875   llvm::APSInt vecSize(32);
1876   if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1877     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_argument_not_int,
1878          "vector_size", sizeExpr->getSourceRange());
1879     return QualType();
1880   }
1881   // navigate to the base type - we need to provide for vector pointers, 
1882   // vector arrays, and functions returning vectors.
1883   Type *canonType = curType.getCanonicalType().getTypePtr();
1884   
1885   if (canonType->isPointerType() || canonType->isArrayType() ||
1886       canonType->isFunctionType()) {
1887     assert(0 && "HandleVector(): Complex type construction unimplemented");
1888     /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1889         do {
1890           if (PointerType *PT = dyn_cast<PointerType>(canonType))
1891             canonType = PT->getPointeeType().getTypePtr();
1892           else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1893             canonType = AT->getElementType().getTypePtr();
1894           else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1895             canonType = FT->getResultType().getTypePtr();
1896         } while (canonType->isPointerType() || canonType->isArrayType() ||
1897                  canonType->isFunctionType());
1898     */
1899   }
1900   // the base type must be integer or float.
1901   if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1902     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1903          curType.getCanonicalType().getAsString());
1904     return QualType();
1905   }
1906   unsigned typeSize = static_cast<unsigned>(
1907     Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
1908   // vecSize is specified in bytes - convert to bits.
1909   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 
1910   
1911   // the vector size needs to be an integral multiple of the type size.
1912   if (vectorSize % typeSize) {
1913     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1914          sizeExpr->getSourceRange());
1915     return QualType();
1916   }
1917   if (vectorSize == 0) {
1918     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1919          sizeExpr->getSourceRange());
1920     return QualType();
1921   }
1922   // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1923   // the number of elements to be a power of two (unlike GCC).
1924   // Instantiate the vector type, the number of elements is > 0.
1925   return Context.getVectorType(curType, vectorSize/typeSize);
1926 }
1927
1928 void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr)
1929 {
1930   // check the attribute arguments.
1931   if (rawAttr->getNumArgs() > 0) {
1932     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1933          std::string("0"));
1934     return;
1935   }
1936   
1937   if (TagDecl *TD = dyn_cast<TagDecl>(d))
1938     TD->addAttr(new PackedAttr);
1939   else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
1940     // If the alignment is less than or equal to 8 bits, the packed attribute
1941     // has no effect.
1942     if (Context.getTypeAlign(FD->getType(), SourceLocation()) <= 8)
1943       Diag(rawAttr->getAttributeLoc(), 
1944            diag::warn_attribute_ignored_for_field_of_type,
1945            rawAttr->getAttributeName()->getName(),
1946            FD->getType().getAsString());
1947     else
1948       FD->addAttr(new PackedAttr);
1949   } else
1950     Diag(rawAttr->getAttributeLoc(), diag::warn_attribute_ignored,
1951          rawAttr->getAttributeName()->getName());
1952 }
1953   
1954 void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1955 {
1956   // check the attribute arguments.
1957   if (rawAttr->getNumArgs() > 1) {
1958     Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1959          std::string("1"));
1960     return;
1961   }
1962
1963   unsigned Align = 0;
1964   
1965   if (rawAttr->getNumArgs() == 0) {
1966     // FIXME: This should be the target specific maximum alignment.
1967     // (For now we just use 128 bits which is the maximum on X86.
1968     Align = 128;
1969     return;
1970   } else {
1971     Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1972     llvm::APSInt alignment(32);
1973     if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1974       Diag(rawAttr->getAttributeLoc(), diag::err_attribute_argument_not_int,
1975            "aligned", alignmentExpr->getSourceRange());
1976       return;
1977     }
1978     
1979     Align = alignment.getZExtValue() * 8;
1980   }
1981
1982   d->addAttr(new AlignedAttr(Align));
1983 }