SemaExprCXX.cpp revision aee3bf8be3cc87bae59b47213089aca4e9f8ee02
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/Parse/DeclSpec.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Basic/Diagnostic.h"
20using namespace clang;
21
22/// ActOnConversionFunctionExpr - Parse a C++ conversion function
23/// name (e.g., operator void const *) as an expression. This is
24/// very similar to ActOnIdentifierExpr, except that instead of
25/// providing an identifier the parser provides the type of the
26/// conversion function.
27Sema::ExprResult Sema::ActOnConversionFunctionExpr(Scope *S,
28                                                   SourceLocation OperatorLoc,
29                                                   TypeTy *Ty,
30                                                   bool HasTrailingLParen,
31                                                   const CXXScopeSpec *SS) {
32  QualType ConvType = QualType::getFromOpaquePtr(Ty);
33  QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
34  DeclarationName ConvName
35    = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
36  return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
37                                  SS);
38}
39
40/// ActOnOperatorFunctionIdExpr - Parse a C++ overloaded operator
41/// name (e.g., @c operator+ ) as an expression. This is very
42/// similar to ActOnIdentifierExpr, except that instead of providing
43/// an identifier the parser provides the kind of overloaded
44/// operator that was parsed.
45Sema::ExprResult Sema::ActOnOperatorFunctionIdExpr(Scope *S,
46                                                   SourceLocation OperatorLoc,
47                                                   OverloadedOperatorKind Op,
48                                                   bool HasTrailingLParen,
49                                                   const CXXScopeSpec *SS) {
50  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
51  return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, SS);
52}
53
54/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
55Action::ExprResult
56Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
57                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
58  const NamespaceDecl *StdNs = GetStdNamespace();
59  if (!StdNs) {
60    Diag(OpLoc, diag::err_need_header_before_typeid);
61    return ExprResult(true);
62  }
63  if (!Ident_TypeInfo) {
64    Ident_TypeInfo = &PP.getIdentifierTable().get("type_info");
65  }
66  Decl *TypeInfoDecl = LookupDecl(Ident_TypeInfo,
67                                  Decl::IDNS_Tag | Decl::IDNS_Ordinary,
68                                  0, StdNs, /*createBuiltins=*/false);
69  RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
70  if (!TypeInfoRecordDecl) {
71    Diag(OpLoc, diag::err_need_header_before_typeid);
72    return ExprResult(true);
73  }
74
75  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
76
77  return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
78                           SourceRange(OpLoc, RParenLoc));
79}
80
81/// ActOnCXXBoolLiteral - Parse {true,false} literals.
82Action::ExprResult
83Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
84  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
85         "Unknown C++ Boolean value!");
86  return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
87}
88
89/// ActOnCXXThrow - Parse throw expressions.
90Action::ExprResult
91Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
92  return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
93}
94
95Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
96  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
97  /// is a non-lvalue expression whose value is the address of the object for
98  /// which the function is called.
99
100  if (!isa<FunctionDecl>(CurContext)) {
101    Diag(ThisLoc, diag::err_invalid_this_use);
102    return ExprResult(true);
103  }
104
105  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
106    if (MD->isInstance())
107      return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
108
109  return Diag(ThisLoc, diag::err_invalid_this_use);
110}
111
112/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
113/// Can be interpreted either as function-style casting ("int(x)")
114/// or class type construction ("ClassType(x,y,z)")
115/// or creation of a value-initialized type ("int()").
116Action::ExprResult
117Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
118                                SourceLocation LParenLoc,
119                                ExprTy **ExprTys, unsigned NumExprs,
120                                SourceLocation *CommaLocs,
121                                SourceLocation RParenLoc) {
122  assert(TypeRep && "Missing type!");
123  QualType Ty = QualType::getFromOpaquePtr(TypeRep);
124  Expr **Exprs = (Expr**)ExprTys;
125  SourceLocation TyBeginLoc = TypeRange.getBegin();
126  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
127
128  if (const RecordType *RT = Ty->getAsRecordType()) {
129    // C++ 5.2.3p1:
130    // If the simple-type-specifier specifies a class type, the class type shall
131    // be complete.
132    //
133    if (!RT->getDecl()->isDefinition())
134      return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
135                  Ty.getAsString(), FullRange);
136
137    unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
138                                    "class constructors are not supported yet");
139    return Diag(TyBeginLoc, DiagID);
140  }
141
142  // C++ 5.2.3p1:
143  // If the expression list is a single expression, the type conversion
144  // expression is equivalent (in definedness, and if defined in meaning) to the
145  // corresponding cast expression.
146  //
147  if (NumExprs == 1) {
148    if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
149      return true;
150    return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
151                                     Exprs[0], RParenLoc);
152  }
153
154  // C++ 5.2.3p1:
155  // If the expression list specifies more than a single value, the type shall
156  // be a class with a suitably declared constructor.
157  //
158  if (NumExprs > 1)
159    return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg,
160                FullRange);
161
162  assert(NumExprs == 0 && "Expected 0 expressions");
163
164  // C++ 5.2.3p2:
165  // The expression T(), where T is a simple-type-specifier for a non-array
166  // complete object type or the (possibly cv-qualified) void type, creates an
167  // rvalue of the specified type, which is value-initialized.
168  //
169  if (Ty->isArrayType())
170    return Diag(TyBeginLoc, diag::err_value_init_for_array_type, FullRange);
171  if (Ty->isIncompleteType() && !Ty->isVoidType())
172    return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
173                Ty.getAsString(), FullRange);
174
175  return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
176}
177
178
179/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
180/// C++ if/switch/while/for statement.
181/// e.g: "if (int x = f()) {...}"
182Action::ExprResult
183Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
184                                       Declarator &D,
185                                       SourceLocation EqualLoc,
186                                       ExprTy *AssignExprVal) {
187  assert(AssignExprVal && "Null assignment expression");
188
189  // C++ 6.4p2:
190  // The declarator shall not specify a function or an array.
191  // The type-specifier-seq shall not contain typedef and shall not declare a
192  // new class or enumeration.
193
194  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
195         "Parser allowed 'typedef' as storage class of condition decl.");
196
197  QualType Ty = GetTypeForDeclarator(D, S);
198
199  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
200    // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
201    // would be created and CXXConditionDeclExpr wants a VarDecl.
202    return Diag(StartLoc, diag::err_invalid_use_of_function_type,
203                SourceRange(StartLoc, EqualLoc));
204  } else if (Ty->isArrayType()) { // ...or an array.
205    Diag(StartLoc, diag::err_invalid_use_of_array_type,
206         SourceRange(StartLoc, EqualLoc));
207  } else if (const RecordType *RT = Ty->getAsRecordType()) {
208    RecordDecl *RD = RT->getDecl();
209    // The type-specifier-seq shall not declare a new class...
210    if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
211      Diag(RD->getLocation(), diag::err_type_defined_in_condition);
212  } else if (const EnumType *ET = Ty->getAsEnumType()) {
213    EnumDecl *ED = ET->getDecl();
214    // ...or enumeration.
215    if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
216      Diag(ED->getLocation(), diag::err_type_defined_in_condition);
217  }
218
219  DeclTy *Dcl = ActOnDeclarator(S, D, 0);
220  if (!Dcl)
221    return true;
222  AddInitializerToDecl(Dcl, AssignExprVal);
223
224  return new CXXConditionDeclExpr(StartLoc, EqualLoc,
225                                       cast<VarDecl>(static_cast<Decl *>(Dcl)));
226}
227
228/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
229bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
230  // C++ 6.4p4:
231  // The value of a condition that is an initialized declaration in a statement
232  // other than a switch statement is the value of the declared variable
233  // implicitly converted to type bool. If that conversion is ill-formed, the
234  // program is ill-formed.
235  // The value of a condition that is an expression is the value of the
236  // expression, implicitly converted to bool.
237  //
238  QualType Ty = CondExpr->getType(); // Save the type.
239  AssignConvertType
240    ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
241  if (ConvTy == Incompatible)
242    return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition,
243                Ty.getAsString(), CondExpr->getSourceRange());
244  return false;
245}
246
247/// Helper function to determine whether this is the (deprecated) C++
248/// conversion from a string literal to a pointer to non-const char or
249/// non-const wchar_t (for narrow and wide string literals,
250/// respectively).
251bool
252Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
253  // Look inside the implicit cast, if it exists.
254  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
255    From = Cast->getSubExpr();
256
257  // A string literal (2.13.4) that is not a wide string literal can
258  // be converted to an rvalue of type "pointer to char"; a wide
259  // string literal can be converted to an rvalue of type "pointer
260  // to wchar_t" (C++ 4.2p2).
261  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
262    if (const PointerType *ToPtrType = ToType->getAsPointerType())
263      if (const BuiltinType *ToPointeeType
264          = ToPtrType->getPointeeType()->getAsBuiltinType()) {
265        // This conversion is considered only when there is an
266        // explicit appropriate pointer target type (C++ 4.2p2).
267        if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
268            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
269             (!StrLit->isWide() &&
270              (ToPointeeType->getKind() == BuiltinType::Char_U ||
271               ToPointeeType->getKind() == BuiltinType::Char_S))))
272          return true;
273      }
274
275  return false;
276}
277
278/// PerformImplicitConversion - Perform an implicit conversion of the
279/// expression From to the type ToType. Returns true if there was an
280/// error, false otherwise. The expression From is replaced with the
281/// converted expression.
282bool
283Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
284{
285  ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
286  switch (ICS.ConversionKind) {
287  case ImplicitConversionSequence::StandardConversion:
288    if (PerformImplicitConversion(From, ToType, ICS.Standard))
289      return true;
290    break;
291
292  case ImplicitConversionSequence::UserDefinedConversion:
293    // FIXME: This is, of course, wrong. We'll need to actually call
294    // the constructor or conversion operator, and then cope with the
295    // standard conversions.
296    ImpCastExprToType(From, ToType);
297    return false;
298
299  case ImplicitConversionSequence::EllipsisConversion:
300    assert(false && "Cannot perform an ellipsis conversion");
301    return false;
302
303  case ImplicitConversionSequence::BadConversion:
304    return true;
305  }
306
307  // Everything went well.
308  return false;
309}
310
311/// PerformImplicitConversion - Perform an implicit conversion of the
312/// expression From to the type ToType by following the standard
313/// conversion sequence SCS. Returns true if there was an error, false
314/// otherwise. The expression From is replaced with the converted
315/// expression.
316bool
317Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
318                                const StandardConversionSequence& SCS)
319{
320  // Overall FIXME: we are recomputing too many types here and doing
321  // far too much extra work. What this means is that we need to keep
322  // track of more information that is computed when we try the
323  // implicit conversion initially, so that we don't need to recompute
324  // anything here.
325  QualType FromType = From->getType();
326
327  if (SCS.CopyConstructor) {
328    // FIXME: Create a temporary object by calling the copy
329    // constructor.
330    ImpCastExprToType(From, ToType);
331    return false;
332  }
333
334  // Perform the first implicit conversion.
335  switch (SCS.First) {
336  case ICK_Identity:
337  case ICK_Lvalue_To_Rvalue:
338    // Nothing to do.
339    break;
340
341  case ICK_Array_To_Pointer:
342    if (FromType->isOverloadType()) {
343      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
344      if (!Fn)
345        return true;
346
347      FixOverloadedFunctionReference(From, Fn);
348      FromType = From->getType();
349    } else {
350      FromType = Context.getArrayDecayedType(FromType);
351    }
352    ImpCastExprToType(From, FromType);
353    break;
354
355  case ICK_Function_To_Pointer:
356    FromType = Context.getPointerType(FromType);
357    ImpCastExprToType(From, FromType);
358    break;
359
360  default:
361    assert(false && "Improper first standard conversion");
362    break;
363  }
364
365  // Perform the second implicit conversion
366  switch (SCS.Second) {
367  case ICK_Identity:
368    // Nothing to do.
369    break;
370
371  case ICK_Integral_Promotion:
372  case ICK_Floating_Promotion:
373  case ICK_Integral_Conversion:
374  case ICK_Floating_Conversion:
375  case ICK_Floating_Integral:
376    FromType = ToType.getUnqualifiedType();
377    ImpCastExprToType(From, FromType);
378    break;
379
380  case ICK_Pointer_Conversion:
381    if (CheckPointerConversion(From, ToType))
382      return true;
383    ImpCastExprToType(From, ToType);
384    break;
385
386  case ICK_Pointer_Member:
387    // FIXME: Implement pointer-to-member conversions.
388    assert(false && "Pointer-to-member conversions are unsupported");
389    break;
390
391  case ICK_Boolean_Conversion:
392    FromType = Context.BoolTy;
393    ImpCastExprToType(From, FromType);
394    break;
395
396  default:
397    assert(false && "Improper second standard conversion");
398    break;
399  }
400
401  switch (SCS.Third) {
402  case ICK_Identity:
403    // Nothing to do.
404    break;
405
406  case ICK_Qualification:
407    ImpCastExprToType(From, ToType);
408    break;
409
410  default:
411    assert(false && "Improper second standard conversion");
412    break;
413  }
414
415  return false;
416}
417
418