]> granicus.if.org Git - clang/blob - Sema/Sema.h
add parsing, ast building and pretty printing support for C++ throw expressions.
[clang] / Sema / Sema.h
1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
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 defines the Sema class, which performs semantic analysis and
11 // builds ASTs.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_AST_SEMA_H
16 #define LLVM_CLANG_AST_SEMA_H
17
18 #include "clang/Parse/Action.h"
19 #include "clang/Parse/DeclSpec.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include <vector>
24 #include <string>
25
26 namespace llvm {
27   class APSInt;
28 }
29
30 namespace clang {
31   class ASTContext;
32   class ASTConsumer;
33   class Preprocessor;
34   class Decl;
35   class ScopedDecl;
36   class Expr;
37   class InitListExpr;
38   class CallExpr;
39   class VarDecl;
40   class ParmVarDecl;
41   class TypedefDecl;
42   class FunctionDecl;
43   class QualType;
44   struct LangOptions;
45   class Token;
46   class IntegerLiteral;
47   class StringLiteral;
48   class ArrayType;
49   class LabelStmt;
50   class SwitchStmt;
51   class OCUVectorType;
52   class TypedefDecl;
53   class ObjCInterfaceDecl;
54   class ObjCProtocolDecl;
55   class ObjCImplementationDecl;
56   class ObjCCategoryImplDecl;
57   class ObjCCategoryDecl;
58   class ObjCIvarDecl;
59   class ObjCMethodDecl;
60
61 /// Sema - This implements semantic analysis and AST building for C.
62 class Sema : public Action {
63   Preprocessor &PP;
64   ASTContext &Context;
65   ASTConsumer &Consumer;
66   
67   /// CurFunctionDecl - If inside of a function body, this contains a pointer to
68   /// the function decl for the function being parsed.
69   FunctionDecl *CurFunctionDecl;
70
71   /// CurMethodDecl - If inside of a method body, this contains a pointer to
72   /// the method decl for the method being parsed.
73   ObjCMethodDecl *CurMethodDecl;
74   
75   /// LabelMap - This is a mapping from label identifiers to the LabelStmt for
76   /// it (which acts like the label decl in some ways).  Forward referenced
77   /// labels have a LabelStmt created for them with a null location & SubStmt.
78   llvm::DenseMap<IdentifierInfo*, LabelStmt*> LabelMap;
79   
80   llvm::SmallVector<SwitchStmt*, 8> SwitchStack;
81   
82   /// OCUVectorDecls - This is a list all the OCU vector types. This allows
83   /// us to associate a raw vector type with one of the OCU type names.
84   /// This is only necessary for issuing pretty diagnostics.
85   llvm::SmallVector<TypedefDecl*, 24> OCUVectorDecls;
86
87   /// ObjCImplementations - Keep track of all of the classes with
88   /// @implementation's, so that we can emit errors on duplicates.
89   llvm::DenseMap<IdentifierInfo*, ObjCImplementationDecl*> ObjCImplementations;
90   
91   /// ObjCProtocols - Keep track of all protocol declarations declared
92   /// with @protocol keyword, so that we can emit errors on duplicates and
93   /// find the declarations when needed.
94   llvm::DenseMap<IdentifierInfo*, ObjCProtocolDecl*> ObjCProtocols;
95   
96   // Enum values used by KnownFunctionIDs (see below).
97   enum {
98     id_printf,
99     id_fprintf,
100     id_sprintf,
101     id_snprintf,
102     id_asprintf,
103     id_vsnprintf,
104     id_vasprintf,
105     id_vfprintf,
106     id_vsprintf,
107     id_vprintf,
108     id_num_known_functions
109   };
110   
111   /// KnownFunctionIDs - This is a list of IdentifierInfo objects to a set
112   /// of known functions used by the semantic analysis to do various
113   /// kinds of checking (e.g. checking format string errors in printf calls).
114   /// This list is populated upon the creation of a Sema object.    
115   IdentifierInfo* KnownFunctionIDs[ id_num_known_functions ];
116   
117   /// Translation Unit Scope - useful to Objective-C actions that need
118   /// to lookup file scope declarations in the "ordinary" C decl namespace.
119   /// For example, user-defined classes, built-in "id" type, etc.
120   Scope *TUScope;
121   
122   /// ObjCMethodList - a linked list of methods with different signatures.
123   struct ObjCMethodList {
124     ObjCMethodDecl *Method;
125     ObjCMethodList *Next;
126     
127     ObjCMethodList() {
128       Method = 0; 
129       Next = 0;
130     }
131     ObjCMethodList(ObjCMethodDecl *M, ObjCMethodList *C) {
132       Method = M;
133       Next = C;
134     }
135   };
136   /// Instance/Factory Method Pools - allows efficient lookup when typechecking
137   /// messages to "id". We need to maintain a list, since selectors can have
138   /// differing signatures across classes. In Cocoa, this happens to be 
139   /// extremely uncommon (only 1% of selectors are "overloaded").
140   llvm::DenseMap<Selector, ObjCMethodList> InstanceMethodPool;
141   llvm::DenseMap<Selector, ObjCMethodList> FactoryMethodPool;
142 public:
143   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer);
144   
145   const LangOptions &getLangOptions() const;
146   
147   /// The primitive diagnostic helpers - always returns true, which simplifies 
148   /// error handling (i.e. less code).
149   bool Diag(SourceLocation Loc, unsigned DiagID);
150   bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg);
151   bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg1,
152             const std::string &Msg2);
153
154   /// More expressive diagnostic helpers for expressions (say that 6 times:-)
155   bool Diag(SourceLocation Loc, unsigned DiagID, SourceRange R1);
156   bool Diag(SourceLocation Loc, unsigned DiagID, 
157             SourceRange R1, SourceRange R2);
158   bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg,
159             SourceRange R1);
160   bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg,
161             SourceRange R1, SourceRange R2);
162   bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg1, 
163             const std::string &Msg2, SourceRange R1);
164   bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg1, 
165             const std::string &Msg2, const std::string &Msg3, SourceRange R1);
166   bool Diag(SourceLocation Loc, unsigned DiagID, 
167             const std::string &Msg1, const std::string &Msg2, 
168             SourceRange R1, SourceRange R2);
169   
170   virtual void DeleteExpr(ExprTy *E);
171   virtual void DeleteStmt(StmtTy *S);
172
173   //===--------------------------------------------------------------------===//
174   // Type Analysis / Processing: SemaType.cpp.
175   //
176   QualType ConvertDeclSpecToType(DeclSpec &DS);
177   AttributeList *ProcessTypeAttributes(QualType &Result, AttributeList *AL);
178   QualType GetTypeForDeclarator(Declarator &D, Scope *S);
179
180   
181   QualType ObjCGetTypeForMethodDefinition(DeclTy *D);
182
183   
184   virtual TypeResult ActOnTypeName(Scope *S, Declarator &D);
185   
186   virtual TypeResult ActOnParamDeclaratorType(Scope *S, Declarator &D);
187 private:
188   //===--------------------------------------------------------------------===//
189   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
190   //
191   virtual DeclTy *isTypeName(const IdentifierInfo &II, Scope *S) const;
192   virtual DeclTy *ActOnDeclarator(Scope *S, Declarator &D, DeclTy *LastInGroup);
193   void AddInitializerToDecl(DeclTy *dcl, ExprTy *init);
194   virtual DeclTy *FinalizeDeclaratorGroup(Scope *S, DeclTy *Group);
195
196   virtual DeclTy *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
197   virtual void ObjCActOnStartOfMethodDef(Scope *S, DeclTy *D);
198   
199   virtual DeclTy *ActOnFinishFunctionBody(DeclTy *Decl, StmtTy *Body);
200   virtual DeclTy *ActOnLinkageSpec(SourceLocation Loc, SourceLocation LBrace,
201                                    SourceLocation RBrace, const char *Lang,
202                                    unsigned StrSize, DeclTy *D);
203   virtual DeclTy *ActOnFileScopeAsmDecl(SourceLocation Loc, ExprTy *expr);
204
205   /// Scope actions.
206   virtual void ActOnPopScope(SourceLocation Loc, Scope *S);
207   virtual void ActOnTranslationUnitScope(SourceLocation Loc, Scope *S);
208
209   /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
210   /// no declarator (e.g. "struct foo;") is parsed.
211   virtual DeclTy *ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS);  
212   
213   virtual DeclTy *ActOnTag(Scope *S, unsigned TagType, TagKind TK,
214                            SourceLocation KWLoc, IdentifierInfo *Name,
215                            SourceLocation NameLoc, AttributeList *Attr);
216   virtual DeclTy *ActOnField(Scope *S, DeclTy *TagDecl,SourceLocation DeclStart,
217                              Declarator &D, ExprTy *BitfieldWidth);
218                                       
219   // This is used for both record definitions and ObjC interface declarations.
220   virtual void ActOnFields(Scope* S,
221                            SourceLocation RecLoc, DeclTy *TagDecl,
222                            DeclTy **Fields, unsigned NumFields,
223                            SourceLocation LBrac, SourceLocation RBrac,
224                            tok::ObjCKeywordKind *visibility = 0);
225   virtual DeclTy *ActOnEnumConstant(Scope *S, DeclTy *EnumDecl,
226                                     DeclTy *LastEnumConstant,
227                                     SourceLocation IdLoc, IdentifierInfo *Id,
228                                     SourceLocation EqualLoc, ExprTy *Val);
229   virtual void ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDecl,
230                              DeclTy **Elements, unsigned NumElements);
231 private:
232   /// Subroutines of ActOnDeclarator().
233   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
234                                 ScopedDecl *LastDecl);
235   TypedefDecl *MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *Old);
236   FunctionDecl *MergeFunctionDecl(FunctionDecl *New, ScopedDecl *Old);
237   VarDecl *MergeVarDecl(VarDecl *New, ScopedDecl *Old);
238
239   /// More parsing and symbol table subroutines...
240   ParmVarDecl *ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, 
241                                     Scope *FnBodyScope);  
242   ScopedDecl *LookupScopedDecl(IdentifierInfo *II, unsigned NSI, 
243                                SourceLocation IdLoc, Scope *S);
244   ScopedDecl *LookupInterfaceDecl(IdentifierInfo *II);
245   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *Id);
246   ScopedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S);
247   ScopedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
248                                  Scope *S);
249   // Decl attributes - this routine is the top level dispatcher. 
250   void HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
251                             AttributeList *declarator_postfix);
252   void HandleDeclAttribute(Decl *New, AttributeList *rawAttr);
253
254   /// HandleAddressSpaceTypeAttribute - this attribute is only applicable to 
255   /// objects without automatic storage duration. 
256   /// The raw attribute contains 1 argument, the id of the address space 
257   /// for the type.
258   QualType HandleAddressSpaceTypeAttribute(QualType curType, 
259                                            AttributeList *rawAttr);                                
260
261   // HandleVectorTypeAttribute - this attribute is only applicable to 
262   // integral and float scalars, although arrays, pointers, and function
263   // return values are allowed in conjunction with this construct. Aggregates
264   // with this attribute are invalid, even if they are of the same size as a
265   // corresponding scalar.
266   // The raw attribute should contain precisely 1 argument, the vector size 
267   // for the variable, measured in bytes. If curType and rawAttr are well
268   // formed, this routine will return a new vector type.
269   QualType HandleVectorTypeAttribute(QualType curType, AttributeList *rawAttr);
270   void HandleOCUVectorTypeAttribute(TypedefDecl *d, AttributeList *rawAttr);
271   
272   void HandleAlignedAttribute(Decl *d, AttributeList *rawAttr);
273   void HandlePackedAttribute(Decl *d, AttributeList *rawAttr);
274   void HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr);
275   
276   void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
277                            bool &IncompleteImpl);
278                            
279   /// CheckProtocolMethodDefs - This routine checks unimpletented methods
280   /// Declared in protocol, and those referenced by it.
281   void CheckProtocolMethodDefs(SourceLocation ImpLoc,
282                                ObjCProtocolDecl *PDecl,
283                                bool& IncompleteImpl,
284                                const llvm::DenseSet<Selector> &InsMap,
285                                const llvm::DenseSet<Selector> &ClsMap);
286   
287   /// CheckImplementationIvars - This routine checks if the instance variables
288   /// listed in the implelementation match those listed in the interface. 
289   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
290                                 ObjCIvarDecl **Fields, unsigned nIvars,
291                                 SourceLocation Loc);
292   
293   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
294   /// remains unimplemented in the @implementation class.
295   void ImplMethodsVsClassMethods(ObjCImplementationDecl* IMPDecl, 
296                                  ObjCInterfaceDecl* IDecl);
297   
298   /// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
299   /// category interface is implemented in the category @implementation.
300   void ImplCategoryMethodsVsIntfMethods(ObjCCategoryImplDecl *CatImplDecl,
301                                         ObjCCategoryDecl *CatClassDecl);
302   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
303   /// true, or false, accordingly.
304   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 
305                                   const ObjCMethodDecl *PrevMethod); 
306
307   /// isBuiltinObjCType - Returns true of the type is "id", "SEL", "Class"
308   /// or "Protocol".
309   bool isBuiltinObjCType(TypedefDecl *TD);
310   
311   /// isObjCObjectPointerType - Returns true if type is an objective-c pointer
312   /// to an object type; such as "id", "Class", Intf*, id<P>, etc.
313   bool isObjCObjectPointerType(QualType type) const;
314
315   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
316   /// unit are added to a global pool. This allows us to efficiently associate
317   /// a selector with a method declaraation for purposes of typechecking
318   /// messages sent to "id" (where the class of the object is unknown).
319   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method);
320   
321   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
322   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method);
323   //===--------------------------------------------------------------------===//
324   // Statement Parsing Callbacks: SemaStmt.cpp.
325 public:
326   virtual StmtResult ActOnExprStmt(ExprTy *Expr);
327   
328   virtual StmtResult ActOnNullStmt(SourceLocation SemiLoc);
329   virtual StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
330                                        StmtTy **Elts, unsigned NumElts,
331                                        bool isStmtExpr);
332   virtual StmtResult ActOnDeclStmt(DeclTy *Decl);
333   virtual StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprTy *LHSVal,
334                                    SourceLocation DotDotDotLoc, ExprTy *RHSVal,
335                                    SourceLocation ColonLoc, StmtTy *SubStmt);
336   virtual StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
337                                       SourceLocation ColonLoc, StmtTy *SubStmt,
338                                       Scope *CurScope);
339   virtual StmtResult ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
340                                     SourceLocation ColonLoc, StmtTy *SubStmt);
341   virtual StmtResult ActOnIfStmt(SourceLocation IfLoc, ExprTy *CondVal,
342                                  StmtTy *ThenVal, SourceLocation ElseLoc,
343                                  StmtTy *ElseVal);
344   virtual StmtResult ActOnStartOfSwitchStmt(ExprTy *Cond);
345   virtual StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
346                                            StmtTy *Switch, ExprTy *Body);
347   virtual StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ExprTy *Cond,
348                                     StmtTy *Body);
349   virtual StmtResult ActOnDoStmt(SourceLocation DoLoc, StmtTy *Body,
350                                  SourceLocation WhileLoc, ExprTy *Cond);
351   
352   virtual StmtResult ActOnForStmt(SourceLocation ForLoc, 
353                                   SourceLocation LParenLoc, 
354                                   StmtTy *First, ExprTy *Second, ExprTy *Third,
355                                   SourceLocation RParenLoc, StmtTy *Body);
356   virtual StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 
357                                   SourceLocation LParenLoc, 
358                                   StmtTy *First, ExprTy *Second,
359                                   SourceLocation RParenLoc, StmtTy *Body);
360   
361   virtual StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
362                                    SourceLocation LabelLoc,
363                                    IdentifierInfo *LabelII);
364   virtual StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
365                                            SourceLocation StarLoc,
366                                            ExprTy *DestExp);
367   virtual StmtResult ActOnContinueStmt(SourceLocation ContinueLoc,
368                                        Scope *CurScope);
369   virtual StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope);
370   
371   virtual StmtResult ActOnReturnStmt(SourceLocation ReturnLoc,
372                                      ExprTy *RetValExp);
373   
374   virtual StmtResult ActOnAsmStmt(SourceLocation AsmLoc,
375                                   bool IsSimple,
376                                   bool IsVolatile,
377                                   unsigned NumOutputs,
378                                   unsigned NumInputs,
379                                   std::string *Names,
380                                   ExprTy **Constraints,
381                                   ExprTy **Exprs,
382                                   ExprTy *AsmString,
383                                   unsigned NumClobbers,
384                                   ExprTy **Clobbers,
385                                   SourceLocation RParenLoc);
386   
387   virtual StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, 
388                                           SourceLocation RParen, StmtTy *Parm, 
389                                           StmtTy *Body, StmtTy *CatchList);
390   
391   virtual StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, 
392                                             StmtTy *Body);
393   
394   virtual StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, 
395                                         StmtTy *Try, 
396                                         StmtTy *Catch, StmtTy *Finally);
397   
398   virtual StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, 
399                                           StmtTy *Throw);
400   virtual StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 
401                                                  ExprTy *SynchExpr, 
402                                                  StmtTy *SynchBody);
403   
404   //===--------------------------------------------------------------------===//
405   // Expression Parsing Callbacks: SemaExpr.cpp.
406
407   // Primary Expressions.
408   virtual ExprResult ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
409                                          IdentifierInfo &II,
410                                          bool HasTrailingLParen);
411   virtual ExprResult ActOnPreDefinedExpr(SourceLocation Loc,
412                                             tok::TokenKind Kind);
413   virtual ExprResult ActOnNumericConstant(const Token &);
414   virtual ExprResult ActOnCharacterConstant(const Token &);
415   virtual ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R,
416                                     ExprTy *Val);
417
418   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
419   /// fragments (e.g. "foo" "bar" L"baz").
420   virtual ExprResult ActOnStringLiteral(const Token *Toks, unsigned NumToks);
421     
422   // Binary/Unary Operators.  'Tok' is the token for the operator.
423   virtual ExprResult ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
424                                   ExprTy *Input);
425   virtual ExprResult 
426     ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof, 
427                                SourceLocation LParenLoc, TypeTy *Ty,
428                                SourceLocation RParenLoc);
429   
430   virtual ExprResult ActOnPostfixUnaryOp(SourceLocation OpLoc, 
431                                          tok::TokenKind Kind, ExprTy *Input);
432   
433   virtual ExprResult ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
434                                              ExprTy *Idx, SourceLocation RLoc);
435   virtual ExprResult ActOnMemberReferenceExpr(ExprTy *Base,SourceLocation OpLoc,
436                                               tok::TokenKind OpKind,
437                                               SourceLocation MemberLoc,
438                                               IdentifierInfo &Member);
439   
440   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
441   /// This provides the location of the left/right parens and a list of comma
442   /// locations.
443   virtual ExprResult ActOnCallExpr(ExprTy *Fn, SourceLocation LParenLoc,
444                                    ExprTy **Args, unsigned NumArgs,
445                                    SourceLocation *CommaLocs,
446                                    SourceLocation RParenLoc);
447   
448   virtual ExprResult ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
449                                    SourceLocation RParenLoc, ExprTy *Op);
450                                    
451   virtual ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
452                                           SourceLocation RParenLoc, ExprTy *Op);
453   
454   virtual ExprResult ActOnInitList(SourceLocation LParenLoc, 
455                                    ExprTy **InitList, unsigned NumInit,
456                                    SourceLocation RParenLoc);
457                                    
458   virtual ExprResult ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
459                                 ExprTy *LHS,ExprTy *RHS);
460   
461   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
462   /// in the case of a the GNU conditional expr extension.
463   virtual ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 
464                                         SourceLocation ColonLoc,
465                                         ExprTy *Cond, ExprTy *LHS, ExprTy *RHS);
466
467   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
468   virtual ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
469                                     IdentifierInfo *LabelII);
470   
471   virtual ExprResult ActOnStmtExpr(SourceLocation LPLoc, StmtTy *SubStmt,
472                                    SourceLocation RPLoc); // "({..})"
473
474   /// __builtin_offsetof(type, a.b[123][456].c)
475   virtual ExprResult ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
476                                           SourceLocation TypeLoc, TypeTy *Arg1,
477                                           OffsetOfComponent *CompPtr,
478                                           unsigned NumComponents,
479                                           SourceLocation RParenLoc);
480     
481   // __builtin_types_compatible_p(type1, type2)
482   virtual ExprResult ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 
483                                               TypeTy *arg1, TypeTy *arg2,
484                                               SourceLocation RPLoc);
485                                               
486   // __builtin_choose_expr(constExpr, expr1, expr2)
487   virtual ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 
488                                      ExprTy *cond, ExprTy *expr1, ExprTy *expr2,
489                                      SourceLocation RPLoc);
490   
491   // __builtin_overload(...)
492   virtual ExprResult ActOnOverloadExpr(ExprTy **Args, unsigned NumArgs,
493                                        SourceLocation *CommaLocs,
494                                        SourceLocation BuiltinLoc, 
495                                        SourceLocation RParenLoc);
496   
497   // __builtin_va_arg(expr, type)
498   virtual ExprResult ActOnVAArg(SourceLocation BuiltinLoc,
499                                 ExprTy *expr, TypeTy *type,
500                                 SourceLocation RPLoc);
501   
502   /// ActOnCXXCasts - Parse {dynamic,static,reinterpret,const}_cast's.
503   virtual ExprResult ActOnCXXCasts(SourceLocation OpLoc, tok::TokenKind Kind,
504                                    SourceLocation LAngleBracketLoc, TypeTy *Ty,
505                                    SourceLocation RAngleBracketLoc,
506                                    SourceLocation LParenLoc, ExprTy *E,
507                                    SourceLocation RParenLoc);
508
509   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
510   virtual ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc,
511                                          tok::TokenKind Kind);
512   
513   //// ActOnCXXThrow -  Parse throw expressions.
514   virtual ExprResult ActOnCXXThrow(SourceLocation OpLoc,
515                                    ExprTy *expr);
516
517   // ParseObjCStringLiteral - Parse Objective-C string literals.
518   virtual ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 
519                                             ExprTy **Strings,
520                                             unsigned NumStrings);
521   virtual ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
522                                                SourceLocation EncodeLoc,
523                                                SourceLocation LParenLoc,
524                                                TypeTy *Ty,
525                                                SourceLocation RParenLoc);
526   
527   // ParseObjCSelectorExpression - Build selector expression for @selector
528   virtual ExprResult ParseObjCSelectorExpression(Selector Sel,
529                                                  SourceLocation AtLoc,
530                                                  SourceLocation SelLoc,
531                                                  SourceLocation LParenLoc,
532                                                  SourceLocation RParenLoc);
533   
534   // ParseObjCProtocolExpression - Build protocol expression for @protocol
535   virtual ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
536                                                  SourceLocation AtLoc,
537                                                  SourceLocation ProtoLoc,
538                                                  SourceLocation LParenLoc,
539                                                  SourceLocation RParenLoc);
540   
541   // Objective-C declarations.
542   virtual DeclTy *ActOnStartClassInterface(
543                     SourceLocation AtInterafceLoc,
544                     IdentifierInfo *ClassName, SourceLocation ClassLoc,
545                     IdentifierInfo *SuperName, SourceLocation SuperLoc,
546                     IdentifierInfo **ProtocolNames, unsigned NumProtocols,
547                     SourceLocation EndProtoLoc, AttributeList *AttrList);
548   
549   virtual DeclTy *ActOnCompatiblityAlias(
550                     SourceLocation AtCompatibilityAliasLoc,
551                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
552                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
553                     
554   virtual DeclTy *ActOnStartProtocolInterface(
555                     SourceLocation AtProtoInterfaceLoc,
556                     IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
557                     IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs,
558                     SourceLocation EndProtoLoc);
559   
560   virtual DeclTy *ActOnStartCategoryInterface(
561                     SourceLocation AtInterfaceLoc,
562                     IdentifierInfo *ClassName, SourceLocation ClassLoc,
563                     IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
564                     IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs,
565                     SourceLocation EndProtoLoc);
566   
567   virtual DeclTy *ActOnStartClassImplementation(
568                     SourceLocation AtClassImplLoc,
569                     IdentifierInfo *ClassName, SourceLocation ClassLoc,
570                     IdentifierInfo *SuperClassname, 
571                     SourceLocation SuperClassLoc);
572   
573   virtual DeclTy *ActOnStartCategoryImplementation(
574                                                   SourceLocation AtCatImplLoc,
575                                                   IdentifierInfo *ClassName, 
576                                                   SourceLocation ClassLoc,
577                                                   IdentifierInfo *CatName,
578                                                   SourceLocation CatLoc);
579   
580   virtual DeclTy *ActOnForwardClassDeclaration(SourceLocation Loc,
581                                                IdentifierInfo **IdentList,
582                                                unsigned NumElts);
583   
584   virtual DeclTy *ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
585                                                   IdentifierInfo **IdentList,
586                                                   unsigned NumElts);
587   
588   virtual void FindProtocolDeclaration(SourceLocation TypeLoc,
589                                        IdentifierInfo **ProtocolId,
590                                        unsigned NumProtocols,
591                                        llvm::SmallVector<DeclTy *, 8> & 
592                                        Protocols);
593
594   virtual void ActOnAtEnd(SourceLocation AtEndLoc, DeclTy *classDecl,
595                       DeclTy **allMethods = 0, unsigned allNum = 0,
596                       DeclTy **allProperties = 0, unsigned pNum = 0);
597   
598   virtual DeclTy *ActOnAddObjCProperties(SourceLocation AtLoc, 
599                                          DeclTy **allProperties,
600                                          unsigned NumProperties,
601                                          ObjCDeclSpec &DS);
602   
603   virtual DeclTy *ActOnMethodDeclaration(
604     SourceLocation BeginLoc, // location of the + or -.
605     SourceLocation EndLoc,   // location of the ; or {.
606     tok::TokenKind MethodType, 
607     DeclTy *ClassDecl, ObjCDeclSpec &ReturnQT, TypeTy *ReturnType, 
608     Selector Sel,
609     // optional arguments. The number of types/arguments is obtained
610     // from the Sel.getNumArgs().
611     ObjCDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
612     AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
613     bool isVariadic = false);
614
615   // ActOnClassMessage - used for both unary and keyword messages.
616   // ArgExprs is optional - if it is present, the number of expressions
617   // is obtained from NumArgs.
618   virtual ExprResult ActOnClassMessage(
619     Scope *S,
620     IdentifierInfo *receivingClassName, Selector Sel,
621     SourceLocation lbrac, SourceLocation rbrac, 
622     ExprTy **ArgExprs, unsigned NumArgs);
623
624   // ActOnInstanceMessage - used for both unary and keyword messages.
625   // ArgExprs is optional - if it is present, the number of expressions
626   // is obtained from NumArgs.
627   virtual ExprResult ActOnInstanceMessage(
628     ExprTy *receiver, Selector Sel,
629     SourceLocation lbrac, SourceLocation rbrac, 
630     ExprTy **ArgExprs, unsigned NumArgs);
631 private:
632   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
633   /// cast.  If there is already an implicit cast, merge into the existing one.
634   void ImpCastExprToType(Expr *&Expr, QualType Type);
635
636   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
637   // functions and arrays to their respective pointers (C99 6.3.2.1).
638   Expr *UsualUnaryConversions(Expr *&expr); 
639   
640   // DefaultFunctionArrayConversion - converts functions and arrays
641   // to their respective pointers (C99 6.3.2.1). 
642   void DefaultFunctionArrayConversion(Expr *&expr);
643   
644   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
645   // do not have a prototype. Integer promotions are performed on each 
646   // argument, and arguments that have type float are promoted to double.
647   void DefaultArgumentPromotion(Expr *&Expr);
648   
649   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
650   // operands and then handles various conversions that are common to binary
651   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
652   // routine returns the first non-arithmetic type found. The client is 
653   // responsible for emitting appropriate error diagnostics.
654   QualType UsualArithmeticConversions(Expr *&lExpr, Expr *&rExpr,
655                                       bool isCompAssign = false);
656   
657   /// AssignConvertType - All of the 'assignment' semantic checks return this
658   /// enum to indicate whether the assignment was allowed.  These checks are
659   /// done for simple assignments, as well as initialization, return from
660   /// function, argument passing, etc.  The query is phrased in terms of a
661   /// source and destination type.
662   enum AssignConvertType {
663     /// Compatible - the types are compatible according to the standard.
664     Compatible,
665     
666     /// PointerToInt - The assignment converts a pointer to an int, which we
667     /// accept as an extension.
668     PointerToInt,
669     
670     /// IntToPointer - The assignment converts an int to a pointer, which we
671     /// accept as an extension.
672     IntToPointer,
673     
674     /// FunctionVoidPointer - The assignment is between a function pointer and
675     /// void*, which the standard doesn't allow, but we accept as an extension.
676     FunctionVoidPointer,
677
678     /// IncompatiblePointer - The assignment is between two pointers types that
679     /// are not compatible, but we accept them as an extension.
680     IncompatiblePointer,
681     
682     /// CompatiblePointerDiscardsQualifiers - The assignment discards
683     /// c/v/r qualifiers, which we accept as an extension.
684     CompatiblePointerDiscardsQualifiers,
685     
686     /// Incompatible - We reject this conversion outright, it is invalid to
687     /// represent it in the AST.
688     Incompatible
689   };
690   
691   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
692   /// assignment conversion type specified by ConvTy.  This returns true if the
693   /// conversion was invalid or false if the conversion was accepted.
694   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
695                                 SourceLocation Loc,
696                                 QualType DstType, QualType SrcType,
697                                 Expr *SrcExpr, const char *Flavor);
698   
699   /// CheckAssignmentConstraints - Perform type checking for assignment, 
700   /// argument passing, variable initialization, and function return values. 
701   /// This routine is only used by the following two methods. C99 6.5.16.
702   AssignConvertType CheckAssignmentConstraints(QualType lhs, QualType rhs);
703   
704   // CheckSingleAssignmentConstraints - Currently used by ActOnCallExpr,
705   // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 
706   // this routine performs the default function/array converions.
707   AssignConvertType CheckSingleAssignmentConstraints(QualType lhs, 
708                                                      Expr *&rExpr);
709   // CheckCompoundAssignmentConstraints - Type check without performing any 
710   // conversions. For compound assignments, the "Check...Operands" methods 
711   // perform the necessary conversions. 
712   AssignConvertType CheckCompoundAssignmentConstraints(QualType lhs, 
713                                                        QualType rhs);
714   
715   // Helper function for CheckAssignmentConstraints (C99 6.5.16.1p1)
716   AssignConvertType CheckPointerTypesForAssignment(QualType lhsType, 
717                                                    QualType rhsType);
718   
719   /// the following "Check" methods will return a valid/converted QualType
720   /// or a null QualType (indicating an error diagnostic was issued).
721     
722   /// type checking binary operators (subroutines of ActOnBinOp).
723   inline QualType InvalidOperands(SourceLocation l, Expr *&lex, Expr *&rex);
724   inline QualType CheckVectorOperands(SourceLocation l, Expr *&lex, Expr *&rex);
725   inline QualType CheckMultiplyDivideOperands( // C99 6.5.5
726     Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false); 
727   inline QualType CheckRemainderOperands( // C99 6.5.5
728     Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false); 
729   inline QualType CheckAdditionOperands( // C99 6.5.6
730     Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false);
731   inline QualType CheckSubtractionOperands( // C99 6.5.6
732     Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false);
733   inline QualType CheckShiftOperands( // C99 6.5.7
734     Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false);
735   inline QualType CheckCompareOperands( // C99 6.5.8/9
736     Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isRelational);
737   inline QualType CheckBitwiseOperands( // C99 6.5.[10...12]
738     Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false); 
739   inline QualType CheckLogicalOperands( // C99 6.5.[13,14]
740     Expr *&lex, Expr *&rex, SourceLocation OpLoc);
741   // CheckAssignmentOperands is used for both simple and compound assignment.
742   // For simple assignment, pass both expressions and a null converted type.
743   // For compound assignment, pass both expressions and the converted type.
744   inline QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
745     Expr *lex, Expr *&rex, SourceLocation OpLoc, QualType convertedType);
746   inline QualType CheckCommaOperands( // C99 6.5.17
747     Expr *&lex, Expr *&rex, SourceLocation OpLoc);
748   inline QualType CheckConditionalOperands( // C99 6.5.15
749     Expr *&cond, Expr *&lhs, Expr *&rhs, SourceLocation questionLoc);
750   
751   /// type checking unary operators (subroutines of ActOnUnaryOp).
752   /// C99 6.5.3.1, 6.5.3.2, 6.5.3.4
753   QualType CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc);   
754   QualType CheckAddressOfOperand(Expr *op, SourceLocation OpLoc);
755   QualType CheckIndirectionOperand(Expr *op, SourceLocation OpLoc);
756   QualType CheckSizeOfAlignOfOperand(QualType type, SourceLocation loc, 
757                                      bool isSizeof);
758   QualType CheckRealImagOperand(Expr *&Op, SourceLocation OpLoc);
759   
760   /// type checking primary expressions.
761   QualType CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
762                                    IdentifierInfo &Comp, SourceLocation CmpLoc);
763   
764   /// type checking declaration initializers (C99 6.7.8)
765   bool CheckInitializerTypes(Expr *&simpleInit_or_initList, QualType &declType);
766   bool CheckSingleInitializer(Expr *&simpleInit, QualType declType);
767   bool CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
768                      QualType ElementType);
769   bool CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
770                                  bool topLevel, unsigned& startIndex);
771   bool CheckForConstantInitializer(Expr *e, QualType t);
772   
773   StringLiteral *IsStringLiteralInit(Expr *Init, QualType DeclType);
774   bool CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT);
775   
776   // CheckVectorCast - check type constraints for vectors. 
777   // Since vectors are an extension, there are no C standard reference for this.
778   // We allow casting between vectors and integer datatypes of the same size.
779   // returns true if the cast is invalid
780   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty);
781   
782   // returns true if there were any incompatible arguments.                           
783   bool CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
784                                  ObjCMethodDecl *Method);
785                     
786   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
787   /// the specified width and sign.  If an overflow occurs, detect it and emit
788   /// the specified diagnostic.
789   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 
790                                           unsigned NewWidth, bool NewSign,
791                                           SourceLocation Loc, unsigned DiagID);
792   
793   void InitBuiltinVaListType();
794   
795   //===--------------------------------------------------------------------===//
796   // Extra semantic analysis beyond the C type system
797 private:
798   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
799   bool CheckBuiltinCFStringArgument(Expr* Arg);
800   bool SemaBuiltinVAStart(CallExpr *TheCall);
801   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
802   void CheckPrintfArguments(CallExpr *TheCall,
803                             bool HasVAListArg, unsigned format_idx);
804   void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
805                             SourceLocation ReturnLoc);
806   void CheckFloatComparison(SourceLocation loc, Expr* lex, Expr* rex);
807 };
808
809
810 }  // end namespace clang
811
812 #endif