forked from checkedc/checkedc-clang
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathConstraintVariables.cpp
More file actions
2328 lines (2098 loc) · 84.4 KB
/
Copy pathConstraintVariables.cpp
File metadata and controls
2328 lines (2098 loc) · 84.4 KB
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
//=--ConstraintVariables.cpp--------------------------------------*- C++-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Implementation of ConstraintVariables methods.
//
//===----------------------------------------------------------------------===//
#include "clang/3C/ConstraintVariables.h"
#include "clang/3C/3CGlobalOptions.h"
#include "clang/3C/ProgramInfo.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/CommandLine.h"
#include <sstream>
using namespace clang;
// Macro for boolean implication.
#define IMPLIES(a, b) ((a) ? (b) : true)
static llvm::cl::OptionCategory OptimizationCategory("Optimization category");
static llvm::cl::opt<bool>
DisableRDs("disable-rds",
llvm::cl::desc("Disable reverse edges for Checked Constraints."),
llvm::cl::init(false), llvm::cl::cat(OptimizationCategory));
static llvm::cl::opt<bool> DisableFunctionEdges(
"disable-fnedgs",
llvm::cl::desc("Disable reverse edges for external functions."),
llvm::cl::init(false), llvm::cl::cat(OptimizationCategory));
std::string ConstraintVariable::getRewritableOriginalTy() const {
std::string OrigTyString = getOriginalTy();
std::string SpaceStr = " ";
std::string AsterixStr = "*";
// If the type does not end with " " or *
// we need to add space.
if (!std::equal(SpaceStr.rbegin(), SpaceStr.rend(), OrigTyString.rbegin()) &&
!std::equal(AsterixStr.rbegin(), AsterixStr.rend(),
OrigTyString.rbegin())) {
OrigTyString += " ";
}
return OrigTyString;
}
PointerVariableConstraint *PointerVariableConstraint::getWildPVConstraint(
Constraints &CS, const std::string &Rsn, PersistentSourceLoc *PSL) {
auto *WildPVC = new PointerVariableConstraint("wildvar");
VarAtom *VA = CS.createFreshGEQ("wildvar", VarAtom::V_Other, CS.getWild(),
Rsn, PSL);
WildPVC->Vars.push_back(VA);
WildPVC->SrcVars.push_back(CS.getWild());
// Mark this constraint variable as generic. This is done because we do not
// know the type of the constraint, and therefore we also don't know the
// number of atoms it needs to have. Fortunately, it's already WILD, so any
// constraint made with it will force the other constraint to WILD, safely
// handling assignment between incompatible pointer depths.
WildPVC->InferredGenericIndex = 0;
return WildPVC;
}
PointerVariableConstraint *
PointerVariableConstraint::getNonPtrPVConstraint(Constraints &CS) {
static PointerVariableConstraint *GlobalNonPtrPV = nullptr;
if (GlobalNonPtrPV == nullptr)
GlobalNonPtrPV = new PointerVariableConstraint("basevar");
return GlobalNonPtrPV;
}
PointerVariableConstraint *
PointerVariableConstraint::getNamedNonPtrPVConstraint(StringRef Name,
Constraints &CS) {
return new PointerVariableConstraint(std::string(Name));
}
PointerVariableConstraint *
PointerVariableConstraint::derefPVConstraint(PointerVariableConstraint *PVC) {
// Make a copy of the PVConstraint using the same VarAtoms
auto *Copy = new PointerVariableConstraint(PVC);
// Get rid of the outer atom to dereference the pointer.
assert(!Copy->Vars.empty() && !Copy->SrcVars.empty());
Copy->Vars.erase(Copy->Vars.begin());
Copy->SrcVars.erase(Copy->SrcVars.begin());
// This can't have bounds because bounds only apply to the top pointer level.
Copy->BKey = 0;
Copy->ValidBoundsKey = false;
return Copy;
}
PointerVariableConstraint *PointerVariableConstraint::addAtomPVConstraint(
PointerVariableConstraint *PVC, ConstAtom *PtrTyp, Constraints &CS) {
auto *Copy = new PointerVariableConstraint(PVC);
std::vector<Atom *> &Vars = Copy->Vars;
std::vector<ConstAtom *> &SrcVars = Copy->SrcVars;
VarAtom *NewA = CS.getFreshVar("&" + Copy->Name, VarAtom::V_Other);
CS.addConstraint(CS.createGeq(NewA, PtrTyp, false));
// Add a constraint between the new atom and any existing atom for this
// pointer. This is the same constraint that is added between atoms of a
// pointer in the PointerVariableConstraint constructor. It forces all inner
// atoms to be wild if an outer atom in wild.
if (!Vars.empty())
if (auto *VA = dyn_cast<VarAtom>(*Vars.begin()))
CS.addConstraint(new Geq(VA, NewA));
Vars.insert(Vars.begin(), NewA);
SrcVars.insert(SrcVars.begin(), PtrTyp);
return Copy;
}
PointerVariableConstraint::PointerVariableConstraint(
PointerVariableConstraint *Ot)
: ConstraintVariable(ConstraintVariable::PointerVariable, Ot->OriginalType,
Ot->Name), BaseType(Ot->BaseType), Vars(Ot->Vars),
SrcVars(Ot->SrcVars), FV(Ot->FV), QualMap(Ot->QualMap),
ArrSizes(Ot->ArrSizes), ArrSizeStrs(Ot->ArrSizeStrs),
SrcHasItype(Ot->SrcHasItype), ItypeStr(Ot->ItypeStr),
PartOfFuncPrototype(Ot->PartOfFuncPrototype), Parent(Ot),
BoundsAnnotationStr(Ot->BoundsAnnotationStr),
SourceGenericIndex(Ot->SourceGenericIndex),
InferredGenericIndex(Ot->InferredGenericIndex),
IsZeroWidthArray(Ot->IsZeroWidthArray),
IsTypedef(Ot->IsTypedef), TypedefString(Ot->TypedefString),
TypedefLevelInfo(Ot->TypedefLevelInfo), IsVoidPtr(Ot->IsVoidPtr) {
// These are fields of the super class Constraint Variable
this->HasEqArgumentConstraints = Ot->HasEqArgumentConstraints;
this->ValidBoundsKey = Ot->ValidBoundsKey;
this->BKey = Ot->BKey;
}
PointerVariableConstraint::PointerVariableConstraint(DeclaratorDecl *D,
ProgramInfo &I,
const ASTContext &C)
: PointerVariableConstraint(D->getType(), D, std::string(D->getName()), I,
C, nullptr, -1, false, false,
D->getTypeSourceInfo()) {}
PointerVariableConstraint::PointerVariableConstraint(TypedefDecl *D,
ProgramInfo &I,
const ASTContext &C)
: PointerVariableConstraint(D->getUnderlyingType(), nullptr,
D->getNameAsString(), I, C, nullptr, -1, false,
false, D->getTypeSourceInfo()) {}
PointerVariableConstraint::PointerVariableConstraint(Expr *E, ProgramInfo &I,
const ASTContext &C)
: PointerVariableConstraint(E->getType(), nullptr, E->getStmtClassName(), I,
C, nullptr) {}
// Simple recursive visitor for determining if a type contains a typedef
// entrypoint is find().
class TypedefLevelFinder : public RecursiveASTVisitor<TypedefLevelFinder> {
public:
static struct InternalTypedefInfo find(const QualType &QT) {
TypedefLevelFinder TLF;
QualType ToSearch;
// If the type is currently a typedef, desugar that.
// This is so we can see if the type _contains_ a typedef.
if (const auto *TDT = dyn_cast<TypedefType>(QT))
ToSearch = TDT->desugar();
else
ToSearch = QT;
TLF.TraverseType(ToSearch);
// If we found a typedef then we need to have filled out the name field.
assert(IMPLIES(TLF.HasTypedef, TLF.TDname != ""));
struct InternalTypedefInfo Info = {TLF.HasTypedef, TLF.TypedefLevel,
TLF.TDname};
return Info;
}
bool VisitTypedefType(TypedefType *TT) {
HasTypedef = true;
auto *TDT = TT->getDecl();
TDname = TDT->getNameAsString();
return false;
}
bool VisitPointerType(PointerType *PT) {
TypedefLevel++;
return true;
}
bool VisitArrayType(ArrayType *AT) {
TypedefLevel++;
return true;
}
private:
int TypedefLevel = 0;
std::string TDname = "";
bool HasTypedef = false;
};
PointerVariableConstraint::PointerVariableConstraint(
const QualType &QT, DeclaratorDecl *D, std::string N, ProgramInfo &I,
const ASTContext &C, std::string *InFunc, int ForceGenericIndex,
bool PotentialGeneric,
bool VarAtomForChecked, TypeSourceInfo *TSInfo, const QualType &ITypeT)
: ConstraintVariable(ConstraintVariable::PointerVariable, qtyToStr(QT), N),
FV(nullptr), SrcHasItype(false), PartOfFuncPrototype(InFunc != nullptr),
Parent(nullptr) {
QualType QTy = QT;
const Type *Ty = QTy.getTypePtr();
auto &CS = I.getConstraints();
// If the type is a decayed type, then maybe this is the result of
// decaying an array to a pointer. If the original type is some
// kind of array type, we want to use that instead.
if (const DecayedType *DC = dyn_cast<DecayedType>(Ty)) {
QualType QTytmp = DC->getOriginalType();
if (QTytmp->isArrayType() || QTytmp->isIncompleteArrayType()) {
QTy = QTytmp;
Ty = QTy.getTypePtr();
}
}
bool IsTypedef = false;
if (Ty->getAs<TypedefType>())
IsTypedef = true;
bool IsDeclTy = false;
auto &ABInfo = I.getABoundsInfo();
if (D != nullptr) {
if (ABInfo.tryGetVariable(D, BKey)) {
ValidBoundsKey = true;
}
if (D->hasBoundsAnnotations()) {
BoundsAnnotations BA = D->getBoundsAnnotations();
BoundsExpr *BExpr = BA.getBoundsExpr();
if (BExpr != nullptr) {
SourceRange R = BExpr->getSourceRange();
if (R.isValid()) {
BoundsAnnotationStr = getSourceText(R, C);
}
if (D->hasBoundsAnnotations() && ABInfo.isValidBoundVariable(D)) {
assert(ABInfo.tryGetVariable(D, BKey) &&
"Is expected to have valid Bounds key");
ABounds *NewB = ABounds::getBoundsInfo(&ABInfo, BExpr, C);
ABInfo.insertDeclaredBounds(D, NewB);
}
}
}
IsDeclTy = D->getType() == QT; // If false, then QT may be D's return type
if (InteropTypeExpr *ITE = D->getInteropTypeExpr()) {
// External variables can also have itype.
// Check if the provided declaration is an external
// variable.
// For functions, check to see that if we are analyzing
// function return types.
bool AnalyzeITypeExpr = IsDeclTy;
if (!AnalyzeITypeExpr) {
const Type *OrigType = Ty;
if (isa<FunctionDecl>(D)) {
FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
OrigType = FD->getType().getTypePtr();
}
if (OrigType->isFunctionProtoType()) {
const FunctionProtoType *FPT = OrigType->getAs<FunctionProtoType>();
AnalyzeITypeExpr = (FPT->getReturnType() == QT);
}
}
if (AnalyzeITypeExpr) {
QualType InteropType = ITE->getTypeAsWritten();
QTy = InteropType;
Ty = QTy.getTypePtr();
SrcHasItype = true;
SourceRange R = ITE->getSourceRange();
if (R.isValid()) {
ItypeStr = getSourceText(R, C);
assert(ItypeStr.size() > 0);
}
}
}
}
if (!SrcHasItype && !ITypeT.isNull()) {
QTy = ITypeT;
Ty = QTy.getTypePtr();
SrcHasItype = true;
}
// At this point `QTy`/`Ty` hold the computed type (and `QT` still holds the
// input type). It will be consumed to create atoms, so any code that needs
// to be coordinated with the atoms should access it here first.
TypedefLevelInfo = TypedefLevelFinder::find(QTy);
if (ForceGenericIndex >= 0) {
SourceGenericIndex = ForceGenericIndex;
} else {
SourceGenericIndex = -1;
// This makes a lot of assumptions about how the AST will look, and limits
// it to one level.
// TODO: Enhance TypedefLevelFinder to get this info.
if (Ty->isPointerType()) {
auto *PtrTy = Ty->getPointeeType().getTypePtr();
if (auto *TypdefTy = dyn_cast_or_null<TypedefType>(PtrTy)) {
const auto *Tv = dyn_cast<TypeVariableType>(TypdefTy->desugar());
if (Tv)
SourceGenericIndex = Tv->GetIndex();
}
}
}
InferredGenericIndex = SourceGenericIndex;
bool VarCreated = false;
bool IsArr = false;
bool IsIncompleteArr = false;
bool IsTopMost = true;
uint32_t TypeIdx = 0;
std::string Npre = InFunc ? ((*InFunc) + ":") : "";
VarAtom::VarKind VK =
InFunc ? (N == RETVAR ? VarAtom::V_Return : VarAtom::V_Param)
: VarAtom::V_Other;
// Even though references don't exist in C, `va_list` is a typedef of
// `__builtin_va_list &` on windows. In order to generate correct constraints
// for var arg functions on windows, we need to strip the reference type.
if (Ty->isLValueReferenceType()) {
QTy = Ty->getPointeeType();
Ty = QTy.getTypePtr();
}
IsZeroWidthArray = false;
TypeLoc TLoc = TypeLoc();
if (D && D->getTypeSourceInfo())
TLoc = D->getTypeSourceInfo()->getTypeLoc();
while (Ty->isPointerType() || Ty->isArrayType()) {
// Is this a VarArg type?
std::string TyName = tyToStr(Ty);
if (isVarArgType(TyName)) {
// Variable number of arguments. Make it WILD.
std::string Rsn = "Variable number of arguments.";
VarAtom *WildVA = CS.createFreshGEQ(Npre + N, VK, CS.getWild(), Rsn);
Vars.push_back(WildVA);
SrcVars.push_back(CS.getWild());
VarCreated = true;
break;
}
if (Ty->isCheckedPointerType() || Ty->isCheckedArrayType()) {
ConstAtom *CAtom = nullptr;
if (Ty->isCheckedPointerNtArrayType() || Ty->isNtCheckedArrayType()) {
// This is an NT array type.
CAtom = CS.getNTArr();
} else if (Ty->isCheckedPointerArrayType() || Ty->isCheckedArrayType()) {
// This is an array type.
CAtom = CS.getArr();
// In CheckedC, a pointer can be freely converted to a size 0 array
// pointer, but our constraint system does not allow this. To enable
// converting calls to functions with types similar to free, size 0
// array pointers are made PTR instead of ARR.
if (D && D->hasBoundsExpr())
if (BoundsExpr *BE = D->getBoundsExpr())
if (isZeroBoundsExpr(BE, C)) {
IsZeroWidthArray = true;
CAtom = CS.getPtr();
}
} else if (Ty->isCheckedPointerPtrType()) {
// This is a regular checked pointer.
CAtom = CS.getPtr();
}
VarCreated = true;
assert(CAtom != nullptr && "Unable to find the type "
"of the checked pointer.");
Atom *NewAtom;
if (VarAtomForChecked)
NewAtom = CS.getFreshVar(Npre + N, VK);
else
NewAtom = CAtom;
Vars.push_back(NewAtom);
SrcVars.push_back(CAtom);
}
if (Ty->isArrayType() || Ty->isIncompleteArrayType()) {
IsArr = true;
IsIncompleteArr = Ty->isIncompleteArrayType();
// Boil off the typedefs in the array case.
// TODO this will need to change to properly account for typedefs
bool Boiling = true;
while (Boiling) {
if (const TypedefType *TydTy = dyn_cast<TypedefType>(Ty)) {
QTy = TydTy->desugar();
Ty = QTy.getTypePtr();
if (!TLoc.isNull()) {
auto TDefTLoc = TLoc.getAs<TypedefTypeLoc>();
if (!TDefTLoc.isNull())
TLoc = TDefTLoc.getNextTypeLoc();
}
} else if (const ParenType *ParenTy = dyn_cast<ParenType>(Ty)) {
QTy = ParenTy->desugar();
Ty = QTy.getTypePtr();
if (!TLoc.isNull()) {
auto ParenTLoc = TLoc.getAs<ParenTypeLoc>();
if (!ParenTLoc.isNull())
TLoc = ParenTLoc.getInnerLoc();
}
} else {
Boiling = false;
}
}
// See if there is a constant size to this array type at this position.
if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
ArrSizes[TypeIdx] = std::pair<OriginalArrType, uint64_t>(
O_SizedArray, CAT->getSize().getZExtValue());
if (!TLoc.isNull()) {
auto ArrTLoc = TLoc.getAs<ArrayTypeLoc>();
if (!ArrTLoc.isNull()) {
std::string SizeStr = getSourceText(ArrTLoc.getBracketsRange(), C);
if (!SizeStr.empty())
ArrSizeStrs[TypeIdx] = SizeStr;
}
}
// If this is the top-most pointer variable?
if (hasBoundsKey() && IsTopMost) {
BoundsKey CBKey = ABInfo.getConstKey(CAT->getSize().getZExtValue());
ABounds *NB = new CountBound(CBKey);
ABInfo.insertDeclaredBounds(D, NB);
}
} else {
ArrSizes[TypeIdx] =
std::pair<OriginalArrType, uint64_t>(O_UnSizedArray, 0);
}
// Iterate.
if (const ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
QTy = ArrTy->getElementType();
Ty = QTy.getTypePtr();
} else {
llvm_unreachable("unknown array type");
}
} else {
// Save here if QTy is qualified or not into a map that
// indexes K to the qualification of QTy, if any.
insertQualType(TypeIdx, QTy);
ArrSizes[TypeIdx] = std::pair<OriginalArrType, uint64_t>(O_Pointer, 0);
// Iterate.
QTy = QTy.getSingleStepDesugaredType(C);
QTy = QTy.getTypePtr()->getPointeeType();
Ty = QTy.getTypePtr();
}
// This type is not a constant atom. We need to create a VarAtom for this.
if (!VarCreated) {
VarAtom *VA = CS.getFreshVar(Npre + N, VK);
Vars.push_back(VA);
SrcVars.push_back(CS.getWild());
// Incomplete arrays are lower bounded to ARR because the transformation
// int[] -> _Ptr<int> is permitted while int[1] -> _Ptr<int> is not.
if (IsIncompleteArr)
CS.addConstraint(CS.createGeq(VA, CS.getArr(), false));
else if (IsArr)
CS.addConstraint(CS.createGeq(CS.getArr(), VA, false));
}
// Prepare for next level of pointer
VarCreated = false;
IsArr = false;
TypeIdx++;
Npre = Npre + "*";
VK = VarAtom::
V_Other; // only the outermost pointer considered a param/return
IsTopMost = false;
if (!TLoc.isNull())
TLoc = TLoc.getNextTypeLoc();
}
insertQualType(TypeIdx, QTy);
// If, after boiling off the pointer-ness from this type, we hit a
// function, then create a base-level FVConstraint that we carry
// around too.
if (Ty->isFunctionType())
// C function-pointer type declarator syntax embeds the variable
// name within the function-like syntax. For example:
// void (*fname)(int, int) = ...;
// If a typedef'ed type name is used, the name can be omitted
// because it is not embedded like that. Instead, it has the form
// tn fname = ...,
// where tn is the typedef'ed type name.
// There is possibly something more elegant to do in the code here.
FV = new FVConstraint(Ty, IsDeclTy ? D : nullptr, IsTypedef ? "" : N, I, C,
TSInfo);
// Get a string representing the type without pointer and array indirection.
BaseType = extractBaseType(D, TSInfo, QT, Ty, C);
// check if the type is some depth of pointers to void
// TODO: is this what the field should mean? do we want to include other
// indirection options like arrays?
// https://github.com/correctcomputation/checkedc-clang/issues/648
IsVoidPtr = QT->isPointerType() && isTypeHasVoid(QT);
// varargs are always wild, as are void pointers that are not generic
bool IsWild = isVarArgType(BaseType) ||
(!(PotentialGeneric || isGeneric()) && IsVoidPtr);
if (IsWild) {
std::string Rsn =
IsVoidPtr ? VOID_TYPE_REASON : "Default Var arg list type";
// TODO: Github issue #61: improve handling of types for variable arguments.
for (const auto &V : Vars)
if (VarAtom *VA = dyn_cast<VarAtom>(V))
CS.addConstraint(CS.createGeq(VA, CS.getWild(), Rsn));
}
// Add qualifiers.
std::ostringstream QualStr;
getQualString(TypeIdx, QualStr);
BaseType = QualStr.str() + BaseType;
// If an outer pointer is wild, then the inner pointer must also be wild.
if (Vars.size() > 1) {
for (unsigned VarIdx = 0; VarIdx < Vars.size() - 1; VarIdx++) {
VarAtom *VI = dyn_cast<VarAtom>(Vars[VarIdx]);
VarAtom *VJ = dyn_cast<VarAtom>(Vars[VarIdx + 1]);
if (VI && VJ)
CS.addConstraint(new Geq(VJ, VI));
}
}
}
std::string PointerVariableConstraint::tryExtractBaseType(DeclaratorDecl *D,
TypeSourceInfo *TSI,
QualType QT,
const Type *Ty,
const ASTContext &C) {
// Implicit parameters declarations from typedef function declarations will
// still have valid and non-empty source ranges, but implicit declarations
// aren't written in the source, so extracting the base type from this range
// gives incorrect type strings. For example, the base type for the implicit
// parameter for `foo_decl` in `typedef void foo(int*); foo foo_decl;` would
// be extracted as "foo_decl", when it should be "int".
if (!D || D->isImplicit())
return "";
if (!TSI)
TSI = D->getTypeSourceInfo();
if (!QT->isOrContainsCheckedType() && !Ty->getAs<TypedefType>() && TSI) {
// Try to extract the type from original source to preserve defines
TypeLoc TL = TSI->getTypeLoc();
bool FoundBaseTypeInSrc = false;
if (isa<FunctionDecl>(D)) {
FoundBaseTypeInSrc = D->getAsFunction()->getReturnType() == QT;
TL = getBaseTypeLoc(TL).getAs<FunctionTypeLoc>();
// FunctionDecl that doesn't have function type? weird
if (TL.isNull())
return "";
TL = TL.getAs<clang::FunctionTypeLoc>().getReturnLoc();
} else {
FoundBaseTypeInSrc = D->getType() == QT;
}
if (!TL.isNull()) {
TypeLoc BaseLoc = getBaseTypeLoc(TL);
// Only proceed if the base type location is not null, amd it is not a
// typedef type location.
if (!BaseLoc.isNull() && BaseLoc.getAs<TypedefTypeLoc>().isNull()) {
SourceRange SR = BaseLoc.getSourceRange();
if (FoundBaseTypeInSrc && SR.isValid())
return getSourceText(SR, C);
}
}
}
return "";
}
std::string PointerVariableConstraint::extractBaseType(DeclaratorDecl *D,
TypeSourceInfo *TSI,
QualType QT,
const Type *Ty,
const ASTContext &C) {
std::string BaseTypeStr = tryExtractBaseType(D, TSI, QT, Ty, C);
// Fall back to rebuilding the base type based on type passed to constructor
if (BaseTypeStr.empty())
BaseTypeStr = tyToStr(Ty);
return BaseTypeStr;
}
void PointerVariableConstraint::print(raw_ostream &O) const {
O << "{ ";
for (const auto &I : Vars) {
I->print(O);
O << " ";
}
O << " }";
if (FV) {
O << "(";
FV->print(O);
O << ")";
}
}
void PointerVariableConstraint::dumpJson(llvm::raw_ostream &O) const {
O << "{\"PointerVar\":{";
O << "\"Vars\":[";
bool AddComma = false;
for (const auto &I : Vars) {
if (AddComma) {
O << ",";
}
I->dumpJson(O);
AddComma = true;
}
O << "], \"name\":\"" << getName() << "\"";
if (FV) {
O << ", \"FunctionVariable\":";
FV->dumpJson(O);
}
O << "}}";
}
void PointerVariableConstraint::getQualString(uint32_t TypeIdx,
std::ostringstream &Ss) const {
auto QIter = QualMap.find(TypeIdx);
if (QIter != QualMap.end()) {
for (Qualification Q : QIter->second) {
switch (Q) {
case ConstQualification:
Ss << "const ";
break;
case VolatileQualification:
Ss << "volatile ";
break;
case RestrictQualification:
Ss << "restrict ";
break;
}
}
}
}
void PointerVariableConstraint::insertQualType(uint32_t TypeIdx,
QualType &QTy) {
if (QTy.isConstQualified())
QualMap[TypeIdx].insert(ConstQualification);
if (QTy.isVolatileQualified())
QualMap[TypeIdx].insert(VolatileQualification);
if (QTy.isRestrictQualified())
QualMap[TypeIdx].insert(RestrictQualification);
}
// Take an array or nt_array variable, determines if it is a constant array,
// and if so emits the appropriate syntax for a stack-based array.
bool PointerVariableConstraint::emitArraySize(
std::stack<std::string> &ConstSizeArrs, uint32_t TypeIdx,
Atom::AtomKind Kind) const {
auto I = ArrSizes.find(TypeIdx);
assert(I != ArrSizes.end());
OriginalArrType Oat = I->second.first;
uint64_t Oas = I->second.second;
if (Oat == O_SizedArray) {
std::ostringstream SizeStr;
if (Kind != Atom::A_Wild)
SizeStr << (Kind == Atom::A_NTArr ? " _Nt_checked" : " _Checked");
if (ArrSizeStrs.find(TypeIdx) != ArrSizeStrs.end()) {
std::string SrcSizeStr = ArrSizeStrs.find(TypeIdx)->second;
assert(!SrcSizeStr.empty());
// In some weird edge cases the size of the array is defined by a macro
// where the macro also includes the brackets. We need to add a space
// between the _Checked annotation and this macro to ensure they aren't
// concatenated into a single token.
if (SrcSizeStr[0] != '[')
SizeStr << " ";
SizeStr << SrcSizeStr;
} else
SizeStr << "[" << Oas << "]";
ConstSizeArrs.push(SizeStr.str());
return true;
}
return false;
}
/* addArrayAnnotiations
* This function takes all the stacked annotations for constant arrays
* and pops them onto the EndStrs, this ensures the right order of annotations
* */
void PointerVariableConstraint::addArrayAnnotations(
std::stack<std::string> &ConstArrs,
std::deque<std::string> &EndStrs) const {
while (!ConstArrs.empty()) {
auto NextStr = ConstArrs.top();
ConstArrs.pop();
EndStrs.push_front(NextStr);
}
assert(ConstArrs.empty());
}
bool PointerVariableConstraint::isTypedef(void) const { return IsTypedef; }
void PointerVariableConstraint::setTypedef(ConstraintVariable *TDVar,
std::string S) {
IsTypedef = true;
TypedefVar = TDVar;
TypedefString = S;
}
const ConstraintVariable *PointerVariableConstraint::getTypedefVar() const {
assert(isTypedef());
return TypedefVar;
}
// Mesh resolved constraints with the PointerVariableConstraints set of
// variables and potentially nested function pointer declaration. Produces a
// string that can be replaced in the source code.
std::string PointerVariableConstraint::gatherQualStrings(void) const {
std::ostringstream S;
getQualString(0, S);
return S.str();
}
std::string
PointerVariableConstraint::mkString(Constraints &CS,
const MkStringOpts &Opts) const {
UNPACK_OPTS(EmitName, ForItype, EmitPointee, UnmaskTypedef, UseName,
ForItypeBase);
// The name field encodes if this variable is the return type for a function.
// TODO: store this information in a separate field.
bool IsReturn = getName() == RETVAR;
if (UseName.empty())
UseName = getName();
if (IsTypedef && !UnmaskTypedef) {
std::string QualTypedef = gatherQualStrings() + TypedefString;
if (!ForItype)
QualTypedef += " ";
if (EmitName && !IsReturn)
QualTypedef += UseName;
return QualTypedef;
}
std::ostringstream Ss;
// Annotations that will need to be placed on the identifier of an unchecked
// function pointer.
std::ostringstream FptrInner;
// This deque will store all the type strings that need to pushed
// to the end of the type string. This is typically things like
// closing delimiters.
std::deque<std::string> EndStrs;
// This will store stacked array decls to ensure correct order
// We encounter constant arrays variables in the reverse order they
// need to appear in, so the LIFO structure reverses these annotations
std::stack<std::string> ConstArrs;
// Have we emitted the string for the base type
bool EmittedBase = false;
// Have we emitted the name of the variable yet?
bool EmittedName = false;
// Was the last variable an Array?
bool PrevArr = false;
// Is the entire type so far an array?
bool AllArrays = true;
if (!EmitName || IsReturn)
EmittedName = true;
uint32_t TypeIdx = 0;
// If we've set a GenericIndex for void, it means we're converting it into
// a generic function so give it the default generic type name.
// Add more type names below if we expect to use a lot.
std::string BaseTypeName = BaseType;
if (InferredGenericIndex > -1 && isVoidPtr() &&
isSolutionChecked(CS.getVariables())) {
assert(InferredGenericIndex < 3
&& "Trying to use an unexpected type variable name");
BaseTypeName = std::begin({"T","U","V"})[InferredGenericIndex];
}
auto It = Vars.begin();
auto I = 0;
// Skip over first pointer level if only emitting pointee string.
// This is needed when inserting type arguments.
if (EmitPointee)
++It;
// Iterate through the vars(), but if we have an internal typedef, then stop
// once you reach the typedef's level.
for (; It != Vars.end() && IMPLIES(TypedefLevelInfo.HasTypedef,
I < TypedefLevelInfo.TypedefLevel);
++It, I++) {
const auto &V = *It;
ConstAtom *C = nullptr;
if (ForItypeBase) {
C = CS.getWild();
} else if (ConstAtom *CA = dyn_cast<ConstAtom>(V)) {
C = CA;
} else {
VarAtom *VA = dyn_cast<VarAtom>(V);
assert(VA != nullptr && "Constraint variable can "
"be either constant or VarAtom.");
C = CS.getVariables().at(VA).first;
}
assert(C != nullptr);
Atom::AtomKind K = C->getKind();
// If this is not an itype or generic
// make this wild as it can hold any pointer type.
if (!ForItype && InferredGenericIndex == -1 && isVoidPtr())
K = Atom::A_Wild;
if (PrevArr && ArrSizes.at(TypeIdx).first != O_SizedArray && !EmittedName) {
EmittedName = true;
addArrayAnnotations(ConstArrs, EndStrs);
EndStrs.push_front(" " + UseName);
}
PrevArr = ArrSizes.at(TypeIdx).first == O_SizedArray;
switch (K) {
case Atom::A_Ptr:
getQualString(TypeIdx, Ss);
// We need to check and see if this level of variable
// is constrained by a bounds safe interface. If it is,
// then we shouldn't re-write it.
AllArrays = false;
EmittedBase = false;
Ss << "_Ptr<";
EndStrs.push_front(">");
break;
case Atom::A_Arr:
// If this is an array.
getQualString(TypeIdx, Ss);
// If it's an Arr, then the character we substitute should
// be [] instead of *, IF, the original type was an array.
// And, if the original type was a sized array of size K.
// we should substitute [K].
if (emitArraySize(ConstArrs, TypeIdx, K))
break;
AllArrays = false;
// We need to check and see if this level of variable
// is constrained by a bounds safe interface. If it is,
// then we shouldn't re-write it.
EmittedBase = false;
Ss << "_Array_ptr<";
EndStrs.push_front(">");
break;
case Atom::A_NTArr:
if (emitArraySize(ConstArrs, TypeIdx, K))
break;
AllArrays = false;
// This additional check is to prevent fall-through from the array.
if (K == Atom::A_NTArr) {
// If this is an NTArray.
getQualString(TypeIdx, Ss);
// We need to check and see if this level of variable
// is constrained by a bounds safe interface. If it is,
// then we shouldn't re-write it.
EmittedBase = false;
Ss << "_Nt_array_ptr<";
EndStrs.push_front(">");
break;
}
LLVM_FALLTHROUGH;
// If there is no array in the original program, then we fall through to
// the case where we write a pointer value.
case Atom::A_Wild:
if (emitArraySize(ConstArrs, TypeIdx, K))
break;
AllArrays = false;
if (FV != nullptr) {
FptrInner << "*";
getQualString(TypeIdx, FptrInner);
} else {
if (!EmittedBase) {
assert(!BaseTypeName.empty());
EmittedBase = true;
Ss << BaseTypeName << " ";
}
Ss << "*";
getQualString(TypeIdx, Ss);
}
break;
case Atom::A_Const:
case Atom::A_Var:
llvm_unreachable("impossible");
break;
}
TypeIdx++;
}
// If the previous variable was an array or
// if we are leaving an array run, we need to emit the
// annotation for a stack-array
if (PrevArr && !ConstArrs.empty())
addArrayAnnotations(ConstArrs, EndStrs);
// If the whole type is an array so far, and we haven't emitted
// a name yet, then emit the name so that it appears before
// the the stack array type.
if (PrevArr && !EmittedName && AllArrays) {
EmittedName = true;
EndStrs.push_front(" " + UseName);
}
if (!EmittedBase) {
// If we have a FV pointer, then our "base" type is a function pointer type.
if (FV) {
if (Ss.str().empty()) {
if (!EmittedName) {
FptrInner << UseName;
EmittedName = true;
}
for (std::string Str : EndStrs)
FptrInner << Str;
EndStrs.clear();
}
bool EmitFVName = !FptrInner.str().empty();
if (EmitFVName)
Ss << FV->mkString(CS, MKSTRING_OPTS(UseName = FptrInner.str(),
ForItypeBase = ForItypeBase));
else
Ss << FV->mkString(
CS, MKSTRING_OPTS(EmitName = false, ForItypeBase = ForItypeBase));
} else if (TypedefLevelInfo.HasTypedef) {
std::ostringstream Buf;
getQualString(TypedefLevelInfo.TypedefLevel, Buf);
auto Name = TypedefLevelInfo.TypedefName;
Ss << Buf.str() << Name;
} else {
Ss << BaseTypeName;
}
}
// Add closing elements to type
for (std::string Str : EndStrs) {
Ss << Str;
}
// No space after itype.
if (!EmittedName && !UseName.empty())
Ss << " " << UseName;
// Final array dropping.
if (!ConstArrs.empty()) {
std::deque<std::string> ArrStrs;
addArrayAnnotations(ConstArrs, ArrStrs);
for (std::string Str : ArrStrs)
Ss << Str;
}
if (IsReturn && !ForItype)
Ss << " ";
return Ss.str();
}
bool PVConstraint::addArgumentConstraint(ConstraintVariable *DstCons,
ProgramInfo &Info) {
if (this->Parent == nullptr) {
bool RetVal = false;
if (isPartOfFunctionPrototype()) {
RetVal = ArgumentConstraints.insert(DstCons).second;
if (RetVal && this->HasEqArgumentConstraints) {
constrainConsVarGeq(DstCons, this, Info.getConstraints(), nullptr,
Same_to_Same, true, &Info);
}
}
return RetVal;
}
return this->Parent->addArgumentConstraint(DstCons, Info);
}
const CVarSet &PVConstraint::getArgumentConstraints() const {
return ArgumentConstraints;
}
FunctionVariableConstraint::FunctionVariableConstraint(FVConstraint *Ot)
: ConstraintVariable(ConstraintVariable::FunctionVariable, Ot->OriginalType,
Ot->getName()), ReturnVar(Ot->ReturnVar),
ParamVars(Ot->ParamVars), FileName(Ot->FileName), Hasproto(Ot->Hasproto),
Hasbody(Ot->Hasbody), IsStatic(Ot->IsStatic), Parent(Ot),