This repository was archived by the owner on Nov 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathSemaExpr.cpp
9730 lines (8475 loc) · 368 KB
/
SemaExpr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for expressions.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/EvaluatedExprVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Designator.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Template.h"
using namespace clang;
using namespace sema;
/// \brief Determine whether the use of this declaration is valid, and
/// emit any corresponding diagnostics.
///
/// This routine diagnoses various problems with referencing
/// declarations that can occur when using a declaration. For example,
/// it might warn if a deprecated or unavailable declaration is being
/// used, or produce an error (and return true) if a C++0x deleted
/// function is being used.
///
/// If IgnoreDeprecated is set to true, this should not warn about deprecated
/// decls.
///
/// \returns true if there was an error (this declaration cannot be
/// referenced), false otherwise.
///
bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
bool UnknownObjCClass) {
if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
// If there were any diagnostics suppressed by template argument deduction,
// emit them now.
llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
if (Pos != SuppressedDiagnostics.end()) {
llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
Diag(Suppressed[I].first, Suppressed[I].second);
// Clear out the list of suppressed diagnostics, so that we don't emit
// them again for this specialization. However, we don't remove this
// entry from the table, because we want to avoid ever emitting these
// diagnostics again.
Suppressed.clear();
}
}
// See if this is an auto-typed variable whose initializer we are parsing.
if (ParsingInitForAutoVars.count(D)) {
Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
<< D->getDeclName();
return true;
}
// See if the decl is deprecated.
if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
// See if the decl is unavailable
if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
if (UA->getMessage().empty()) {
if (!UnknownObjCClass)
Diag(Loc, diag::err_unavailable) << D->getDeclName();
else
Diag(Loc, diag::warn_unavailable_fwdclass_message)
<< D->getDeclName();
}
else
Diag(Loc, diag::err_unavailable_message)
<< D->getDeclName() << UA->getMessage();
Diag(D->getLocation(), diag::note_unavailable_here) << 0;
}
// See if this is a deleted function.
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
if (FD->isDeleted()) {
Diag(Loc, diag::err_deleted_function_use);
Diag(D->getLocation(), diag::note_unavailable_here) << true;
return true;
}
}
// Warn if this is used but marked unused.
if (D->hasAttr<UnusedAttr>())
Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
return false;
}
/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
/// (and other functions in future), which have been declared with sentinel
/// attribute. It warns if call does not have the sentinel argument.
///
void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Expr **Args, unsigned NumArgs) {
const SentinelAttr *attr = D->getAttr<SentinelAttr>();
if (!attr)
return;
// FIXME: In C++0x, if any of the arguments are parameter pack
// expansions, we can't check for the sentinel now.
int sentinelPos = attr->getSentinel();
int nullPos = attr->getNullPos();
// FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
// base class. Then we won't be needing two versions of the same code.
unsigned int i = 0;
bool warnNotEnoughArgs = false;
int isMethod = 0;
if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
// skip over named parameters.
ObjCMethodDecl::param_iterator P, E = MD->param_end();
for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
if (nullPos)
--nullPos;
else
++i;
}
warnNotEnoughArgs = (P != E || i >= NumArgs);
isMethod = 1;
} else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
// skip over named parameters.
ObjCMethodDecl::param_iterator P, E = FD->param_end();
for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
if (nullPos)
--nullPos;
else
++i;
}
warnNotEnoughArgs = (P != E || i >= NumArgs);
} else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
// block or function pointer call.
QualType Ty = V->getType();
if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
const FunctionType *FT = Ty->isFunctionPointerType()
? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
: Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
unsigned NumArgsInProto = Proto->getNumArgs();
unsigned k;
for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
if (nullPos)
--nullPos;
else
++i;
}
warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
}
if (Ty->isBlockPointerType())
isMethod = 2;
} else
return;
} else
return;
if (warnNotEnoughArgs) {
Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
return;
}
int sentinel = i;
while (sentinelPos > 0 && i < NumArgs-1) {
--sentinelPos;
++i;
}
if (sentinelPos > 0) {
Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
return;
}
while (i < NumArgs-1) {
++i;
++sentinel;
}
Expr *sentinelExpr = Args[sentinel];
if (!sentinelExpr) return;
if (sentinelExpr->isTypeDependent()) return;
if (sentinelExpr->isValueDependent()) return;
// nullptr_t is always treated as null.
if (sentinelExpr->getType()->isNullPtrType()) return;
if (sentinelExpr->getType()->isAnyPointerType() &&
sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNull))
return;
// Unfortunately, __null has type 'int'.
if (isa<GNUNullExpr>(sentinelExpr)) return;
Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
}
SourceRange Sema::getExprRange(ExprTy *E) const {
Expr *Ex = (Expr *)E;
return Ex? Ex->getSourceRange() : SourceRange();
}
//===----------------------------------------------------------------------===//
// Standard Promotions and Conversions
//===----------------------------------------------------------------------===//
/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
void Sema::DefaultFunctionArrayConversion(Expr *&E) {
QualType Ty = E->getType();
assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
if (Ty->isFunctionType())
ImpCastExprToType(E, Context.getPointerType(Ty),
CK_FunctionToPointerDecay);
else if (Ty->isArrayType()) {
// In C90 mode, arrays only promote to pointers if the array expression is
// an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
// type 'array of type' is converted to an expression that has type 'pointer
// to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
// that has type 'array of type' ...". The relevant change is "an lvalue"
// (C90) to "an expression" (C99).
//
// C++ 4.2p1:
// An lvalue or rvalue of type "array of N T" or "array of unknown bound of
// T" can be converted to an rvalue of type "pointer to T".
//
if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
CK_ArrayToPointerDecay);
}
}
void Sema::DefaultLvalueConversion(Expr *&E) {
// C++ [conv.lval]p1:
// A glvalue of a non-function, non-array type T can be
// converted to a prvalue.
if (!E->isGLValue()) return;
QualType T = E->getType();
assert(!T.isNull() && "r-value conversion on typeless expression?");
// Create a load out of an ObjCProperty l-value, if necessary.
if (E->getObjectKind() == OK_ObjCProperty) {
ConvertPropertyForRValue(E);
if (!E->isGLValue())
return;
}
// We don't want to throw lvalue-to-rvalue casts on top of
// expressions of certain types in C++.
if (getLangOptions().CPlusPlus &&
(E->getType() == Context.OverloadTy ||
T->isDependentType() ||
T->isRecordType()))
return;
// The C standard is actually really unclear on this point, and
// DR106 tells us what the result should be but not why. It's
// generally best to say that void types just doesn't undergo
// lvalue-to-rvalue at all. Note that expressions of unqualified
// 'void' type are never l-values, but qualified void can be.
if (T->isVoidType())
return;
// C++ [conv.lval]p1:
// [...] If T is a non-class type, the type of the prvalue is the
// cv-unqualified version of T. Otherwise, the type of the
// rvalue is T.
//
// C99 6.3.2.1p2:
// If the lvalue has qualified type, the value has the unqualified
// version of the type of the lvalue; otherwise, the value has the
// type of the lvalue.
if (T.hasQualifiers())
T = T.getUnqualifiedType();
CheckArrayAccess(E);
E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
E, 0, VK_RValue);
}
void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
DefaultFunctionArrayConversion(E);
DefaultLvalueConversion(E);
}
/// UsualUnaryConversions - Performs various conversions that are common to most
/// operators (C99 6.3). The conversions of array and function types are
/// sometimes surpressed. For example, the array->pointer conversion doesn't
/// apply if the array is an argument to the sizeof or address (&) operators.
/// In these instances, this routine should *not* be called.
Expr *Sema::UsualUnaryConversions(Expr *&E) {
// First, convert to an r-value.
DefaultFunctionArrayLvalueConversion(E);
QualType Ty = E->getType();
assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
// Try to perform integral promotions if the object has a theoretically
// promotable type.
if (Ty->isIntegralOrUnscopedEnumerationType()) {
// C99 6.3.1.1p2:
//
// The following may be used in an expression wherever an int or
// unsigned int may be used:
// - an object or expression with an integer type whose integer
// conversion rank is less than or equal to the rank of int
// and unsigned int.
// - A bit-field of type _Bool, int, signed int, or unsigned int.
//
// If an int can represent all values of the original type, the
// value is converted to an int; otherwise, it is converted to an
// unsigned int. These are called the integer promotions. All
// other types are unchanged by the integer promotions.
QualType PTy = Context.isPromotableBitField(E);
if (!PTy.isNull()) {
ImpCastExprToType(E, PTy, CK_IntegralCast);
return E;
}
if (Ty->isPromotableIntegerType()) {
QualType PT = Context.getPromotedIntegerType(Ty);
ImpCastExprToType(E, PT, CK_IntegralCast);
return E;
}
}
return E;
}
/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
/// do not have a prototype. Arguments that have type float are promoted to
/// double. All other argument types are converted by UsualUnaryConversions().
void Sema::DefaultArgumentPromotion(Expr *&Expr) {
QualType Ty = Expr->getType();
assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
UsualUnaryConversions(Expr);
// If this is a 'float' (CVR qualified or typedef) promote to double.
if (Ty->isSpecificBuiltinType(BuiltinType::Float))
return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
}
/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
/// will warn if the resulting type is not a POD type, and rejects ObjC
/// interfaces passed by value. This returns true if the argument type is
/// completely illegal.
bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
FunctionDecl *FDecl) {
DefaultArgumentPromotion(Expr);
// __builtin_va_start takes the second argument as a "varargs" argument, but
// it doesn't actually do anything with it. It doesn't need to be non-pod
// etc.
if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
return false;
if (Expr->getType()->isObjCObjectType() &&
DiagRuntimeBehavior(Expr->getLocStart(), 0,
PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
<< Expr->getType() << CT))
return true;
if (!Expr->getType()->isPODType() &&
DiagRuntimeBehavior(Expr->getLocStart(), 0,
PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
<< Expr->getType() << CT))
return true;
return false;
}
/// UsualArithmeticConversions - Performs various conversions that are common to
/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
/// routine returns the first non-arithmetic type found. The client is
/// responsible for emitting appropriate error diagnostics.
/// FIXME: verify the conversion rules for "complex int" are consistent with
/// GCC.
QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
bool isCompAssign) {
if (!isCompAssign)
UsualUnaryConversions(lhsExpr);
UsualUnaryConversions(rhsExpr);
// For conversion purposes, we ignore any qualifiers.
// For example, "const float" and "float" are equivalent.
QualType lhs =
Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
QualType rhs =
Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
// If both types are identical, no conversion is needed.
if (lhs == rhs)
return lhs;
// If either side is a non-arithmetic type (e.g. a pointer), we are done.
// The caller can deal with this (e.g. pointer + int).
if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
return lhs;
// Apply unary and bitfield promotions to the LHS's type.
QualType lhs_unpromoted = lhs;
if (lhs->isPromotableIntegerType())
lhs = Context.getPromotedIntegerType(lhs);
QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
if (!LHSBitfieldPromoteTy.isNull())
lhs = LHSBitfieldPromoteTy;
if (lhs != lhs_unpromoted && !isCompAssign)
ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
// If both types are identical, no conversion is needed.
if (lhs == rhs)
return lhs;
// At this point, we have two different arithmetic types.
// Handle complex types first (C99 6.3.1.8p1).
bool LHSComplexFloat = lhs->isComplexType();
bool RHSComplexFloat = rhs->isComplexType();
if (LHSComplexFloat || RHSComplexFloat) {
// if we have an integer operand, the result is the complex type.
if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
if (rhs->isIntegerType()) {
QualType fp = cast<ComplexType>(lhs)->getElementType();
ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
} else {
assert(rhs->isComplexIntegerType());
ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
}
return lhs;
}
if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
if (!isCompAssign) {
// int -> float -> _Complex float
if (lhs->isIntegerType()) {
QualType fp = cast<ComplexType>(rhs)->getElementType();
ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
} else {
assert(lhs->isComplexIntegerType());
ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
}
}
return rhs;
}
// This handles complex/complex, complex/float, or float/complex.
// When both operands are complex, the shorter operand is converted to the
// type of the longer, and that is the type of the result. This corresponds
// to what is done when combining two real floating-point operands.
// The fun begins when size promotion occur across type domains.
// From H&S 6.3.4: When one operand is complex and the other is a real
// floating-point type, the less precise type is converted, within it's
// real or complex domain, to the precision of the other type. For example,
// when combining a "long double" with a "double _Complex", the
// "double _Complex" is promoted to "long double _Complex".
int order = Context.getFloatingTypeOrder(lhs, rhs);
// If both are complex, just cast to the more precise type.
if (LHSComplexFloat && RHSComplexFloat) {
if (order > 0) {
// _Complex float -> _Complex double
ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
return lhs;
} else if (order < 0) {
// _Complex float -> _Complex double
if (!isCompAssign)
ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
return rhs;
}
return lhs;
}
// If just the LHS is complex, the RHS needs to be converted,
// and the LHS might need to be promoted.
if (LHSComplexFloat) {
if (order > 0) { // LHS is wider
// float -> _Complex double
QualType fp = cast<ComplexType>(lhs)->getElementType();
ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
return lhs;
}
// RHS is at least as wide. Find its corresponding complex type.
QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
// double -> _Complex double
ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
// _Complex float -> _Complex double
if (!isCompAssign && order < 0)
ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
return result;
}
// Just the RHS is complex, so the LHS needs to be converted
// and the RHS might need to be promoted.
assert(RHSComplexFloat);
if (order < 0) { // RHS is wider
// float -> _Complex double
if (!isCompAssign) {
QualType fp = cast<ComplexType>(rhs)->getElementType();
ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
}
return rhs;
}
// LHS is at least as wide. Find its corresponding complex type.
QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
// double -> _Complex double
if (!isCompAssign)
ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
// _Complex float -> _Complex double
if (order > 0)
ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
return result;
}
// Now handle "real" floating types (i.e. float, double, long double).
bool LHSFloat = lhs->isRealFloatingType();
bool RHSFloat = rhs->isRealFloatingType();
if (LHSFloat || RHSFloat) {
// If we have two real floating types, convert the smaller operand
// to the bigger result.
if (LHSFloat && RHSFloat) {
int order = Context.getFloatingTypeOrder(lhs, rhs);
if (order > 0) {
ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
return lhs;
}
assert(order < 0 && "illegal float comparison");
if (!isCompAssign)
ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
return rhs;
}
// If we have an integer operand, the result is the real floating type.
if (LHSFloat) {
if (rhs->isIntegerType()) {
// Convert rhs to the lhs floating point type.
ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
return lhs;
}
// Convert both sides to the appropriate complex float.
assert(rhs->isComplexIntegerType());
QualType result = Context.getComplexType(lhs);
// _Complex int -> _Complex float
ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
// float -> _Complex float
if (!isCompAssign)
ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
return result;
}
assert(RHSFloat);
if (lhs->isIntegerType()) {
// Convert lhs to the rhs floating point type.
if (!isCompAssign)
ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
return rhs;
}
// Convert both sides to the appropriate complex float.
assert(lhs->isComplexIntegerType());
QualType result = Context.getComplexType(rhs);
// _Complex int -> _Complex float
if (!isCompAssign)
ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
// float -> _Complex float
ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
return result;
}
// Handle GCC complex int extension.
// FIXME: if the operands are (int, _Complex long), we currently
// don't promote the complex. Also, signedness?
const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
if (lhsComplexInt && rhsComplexInt) {
int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
rhsComplexInt->getElementType());
assert(order && "inequal types with equal element ordering");
if (order > 0) {
// _Complex int -> _Complex long
ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
return lhs;
}
if (!isCompAssign)
ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
return rhs;
} else if (lhsComplexInt) {
// int -> _Complex int
ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
return lhs;
} else if (rhsComplexInt) {
// int -> _Complex int
if (!isCompAssign)
ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
return rhs;
}
// Finally, we have two differing integer types.
// The rules for this case are in C99 6.3.1.8
int compare = Context.getIntegerTypeOrder(lhs, rhs);
bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
rhsSigned = rhs->hasSignedIntegerRepresentation();
if (lhsSigned == rhsSigned) {
// Same signedness; use the higher-ranked type
if (compare >= 0) {
ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
return lhs;
} else if (!isCompAssign)
ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
return rhs;
} else if (compare != (lhsSigned ? 1 : -1)) {
// The unsigned type has greater than or equal rank to the
// signed type, so use the unsigned type
if (rhsSigned) {
ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
return lhs;
} else if (!isCompAssign)
ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
return rhs;
} else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
// The two types are different widths; if we are here, that
// means the signed type is larger than the unsigned type, so
// use the signed type.
if (lhsSigned) {
ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
return lhs;
} else if (!isCompAssign)
ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
return rhs;
} else {
// The signed type is higher-ranked than the unsigned type,
// but isn't actually any bigger (like unsigned int and long
// on most 32-bit systems). Use the unsigned type corresponding
// to the signed type.
QualType result =
Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
if (!isCompAssign)
ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
return result;
}
}
//===----------------------------------------------------------------------===//
// Semantic Analysis for various Expression Types
//===----------------------------------------------------------------------===//
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
/// multiple tokens. However, the common case is that StringToks points to one
/// string.
///
ExprResult
Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
assert(NumStringToks && "Must have at least one string!");
StringLiteralParser Literal(StringToks, NumStringToks, PP);
if (Literal.hadError)
return ExprError();
llvm::SmallVector<SourceLocation, 4> StringTokLocs;
for (unsigned i = 0; i != NumStringToks; ++i)
StringTokLocs.push_back(StringToks[i].getLocation());
QualType StrTy = Context.CharTy;
if (Literal.AnyWide) StrTy = Context.getWCharType();
if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
// A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
StrTy.addConst();
// Get an array type for the string, according to C99 6.4.5. This includes
// the nul terminator character as well as the string length for pascal
// strings.
StrTy = Context.getConstantArrayType(StrTy,
llvm::APInt(32, Literal.GetNumStringChars()+1),
ArrayType::Normal, 0);
// Pass &StringTokLocs[0], StringTokLocs.size() to factory!
return Owned(StringLiteral::Create(Context, Literal.GetString(),
Literal.GetStringLength(),
Literal.AnyWide, StrTy,
&StringTokLocs[0],
StringTokLocs.size()));
}
enum CaptureResult {
/// No capture is required.
CR_NoCapture,
/// A capture is required.
CR_Capture,
/// A by-ref capture is required.
CR_CaptureByRef,
/// An error occurred when trying to capture the given variable.
CR_Error
};
/// Diagnose an uncapturable value reference.
///
/// \param var - the variable referenced
/// \param DC - the context which we couldn't capture through
static CaptureResult
diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
VarDecl *var, DeclContext *DC) {
switch (S.ExprEvalContexts.back().Context) {
case Sema::Unevaluated:
// The argument will never be evaluated, so don't complain.
return CR_NoCapture;
case Sema::PotentiallyEvaluated:
case Sema::PotentiallyEvaluatedIfUsed:
break;
case Sema::PotentiallyPotentiallyEvaluated:
// FIXME: delay these!
break;
}
// Don't diagnose about capture if we're not actually in code right
// now; in general, there are more appropriate places that will
// diagnose this.
if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
// This particular madness can happen in ill-formed default
// arguments; claim it's okay and let downstream code handle it.
if (isa<ParmVarDecl>(var) &&
S.CurContext == var->getDeclContext()->getParent())
return CR_NoCapture;
DeclarationName functionName;
if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
functionName = fn->getDeclName();
// FIXME: variable from enclosing block that we couldn't capture from!
S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
<< var->getIdentifier() << functionName;
S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
<< var->getIdentifier();
return CR_Error;
}
/// There is a well-formed capture at a particular scope level;
/// propagate it through all the nested blocks.
static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
const BlockDecl::Capture &capture) {
VarDecl *var = capture.getVariable();
// Update all the inner blocks with the capture information.
for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
i != e; ++i) {
BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
innerBlock->Captures.push_back(
BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
/*nested*/ true, capture.getCopyExpr()));
innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
}
return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
}
/// shouldCaptureValueReference - Determine if a reference to the
/// given value in the current context requires a variable capture.
///
/// This also keeps the captures set in the BlockScopeInfo records
/// up-to-date.
static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
ValueDecl *value) {
// Only variables ever require capture.
VarDecl *var = dyn_cast<VarDecl>(value);
if (!var) return CR_NoCapture;
// Fast path: variables from the current context never require capture.
DeclContext *DC = S.CurContext;
if (var->getDeclContext() == DC) return CR_NoCapture;
// Only variables with local storage require capture.
// FIXME: What about 'const' variables in C++?
if (!var->hasLocalStorage()) return CR_NoCapture;
// Otherwise, we need to capture.
unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
do {
// Only blocks (and eventually C++0x closures) can capture; other
// scopes don't work.
if (!isa<BlockDecl>(DC))
return diagnoseUncapturableValueReference(S, loc, var, DC);
BlockScopeInfo *blockScope =
cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
// Check whether we've already captured it in this block. If so,
// we're done.
if (unsigned indexPlus1 = blockScope->CaptureMap[var])
return propagateCapture(S, functionScopesIndex,
blockScope->Captures[indexPlus1 - 1]);
functionScopesIndex--;
DC = cast<BlockDecl>(DC)->getDeclContext();
} while (var->getDeclContext() != DC);
// Okay, we descended all the way to the block that defines the variable.
// Actually try to capture it.
QualType type = var->getType();
// Prohibit variably-modified types.
if (type->isVariablyModifiedType()) {
S.Diag(loc, diag::err_ref_vm_type);
S.Diag(var->getLocation(), diag::note_declared_at);
return CR_Error;
}
// Prohibit arrays, even in __block variables, but not references to
// them.
if (type->isArrayType()) {
S.Diag(loc, diag::err_ref_array_type);
S.Diag(var->getLocation(), diag::note_declared_at);
return CR_Error;
}
S.MarkDeclarationReferenced(loc, var);
// The BlocksAttr indicates the variable is bound by-reference.
bool byRef = var->hasAttr<BlocksAttr>();
// Build a copy expression.
Expr *copyExpr = 0;
if (!byRef && S.getLangOptions().CPlusPlus &&
!type->isDependentType() && type->isStructureOrClassType()) {
// According to the blocks spec, the capture of a variable from
// the stack requires a const copy constructor. This is not true
// of the copy/move done to move a __block variable to the heap.
type.addConst();
Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
ExprResult result =
S.PerformCopyInitialization(
InitializedEntity::InitializeBlock(var->getLocation(),
type, false),
loc, S.Owned(declRef));
// Build a full-expression copy expression if initialization
// succeeded and used a non-trivial constructor. Recover from
// errors by pretending that the copy isn't necessary.
if (!result.isInvalid() &&
!cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
result = S.MaybeCreateExprWithCleanups(result);
copyExpr = result.take();
}
}
// We're currently at the declarer; go back to the closure.
functionScopesIndex++;
BlockScopeInfo *blockScope =
cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
// Build a valid capture in this scope.
blockScope->Captures.push_back(
BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
// Propagate that to inner captures if necessary.
return propagateCapture(S, functionScopesIndex,
blockScope->Captures.back());
}
static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
const DeclarationNameInfo &NameInfo,
bool byRef) {
assert(isa<VarDecl>(vd) && "capturing non-variable");
VarDecl *var = cast<VarDecl>(vd);
assert(var->hasLocalStorage() && "capturing non-local");
assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
QualType exprType = var->getType().getNonReferenceType();
BlockDeclRefExpr *BDRE;
if (!byRef) {
// The variable will be bound by copy; make it const within the
// closure, but record that this was done in the expression.
bool constAdded = !exprType.isConstQualified();
exprType.addConst();
BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
NameInfo.getLoc(), false,
constAdded);
} else {
BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
NameInfo.getLoc(), true);
}
return S.Owned(BDRE);
}
ExprResult
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS) {
DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
}
/// BuildDeclRefExpr - Build an expression that references a
/// declaration that does not require a closure capture.
ExprResult
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS) {
MarkDeclarationReferenced(NameInfo.getLoc(), D);
Expr *E = DeclRefExpr::Create(Context,
SS? SS->getWithLocInContext(Context)
: NestedNameSpecifierLoc(),
D, NameInfo, Ty, VK);
// Just in case we're building an illegal pointer-to-member.
if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
E->setObjectKind(OK_BitField);
return Owned(E);
}
static ExprResult
BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
const CXXScopeSpec &SS, FieldDecl *Field,
DeclAccessPair FoundDecl,
const DeclarationNameInfo &MemberNameInfo);
ExprResult
Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
SourceLocation loc,
IndirectFieldDecl *indirectField,
Expr *baseObjectExpr,
SourceLocation opLoc) {
// First, build the expression that refers to the base object.