Debian Codegraph @

clang_delta/EmptyStructToInt.cpp

raw symbols SCIP
1 //===----------------------------------------------------------------------===//
2 //
3 // Copyright (c) 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 The University of Utah
4 // All rights reserved.
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See the file COPYING for details.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #if HAVE_CONFIG_H
12 # include <config.h>
13 #endif
14
15 #include "EmptyStructToInt.h"
16
17 #include "clang/Basic/SourceManager.h"
18
19 #include "clang/Lex/Lexer.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/AST/RecursiveASTVisitor.h"
22 #include "clang/AST/ASTContext.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "TransformationManager.h"
25
26 using namespace clang;
27
28 static const char *DescriptionMsg =
29 "Replace an empty struct with type of int. A struct is defined to be empty if \
30 it: \
31 * does not have any field; \n\
32 * does not have any base class; \n\
33 * is not a base class of another class; \n\
34 * is not described by any template; \n\
35 * has only one unreferenced field; \n\
36 * doesn't have self pointer reference\n";
37
38 static RegisterTransformation<EmptyStructToInt>
39 Trans("empty-struct-to-int", DescriptionMsg);
40
41 class EmptyStructToIntASTVisitor : public
42 RecursiveASTVisitor<EmptyStructToIntASTVisitor> {
43
44 public:
45 explicit EmptyStructToIntASTVisitor(EmptyStructToInt *Instance)
46 : ConsumerInstance(Instance)
47 { }
48
49 bool VisitRecordDecl(RecordDecl *RD);
50
51 bool VisitCXXRecordDecl(CXXRecordDecl *CXXRD);
52
53 private:
54 EmptyStructToInt *ConsumerInstance;
55 };
56
57 class EmptyStructToIntRewriteVisitor : public
58 RecursiveASTVisitor<EmptyStructToIntRewriteVisitor> {
59
60 public:
61 explicit EmptyStructToIntRewriteVisitor(EmptyStructToInt *Instance)
62 : ConsumerInstance(Instance)
63 { }
64
65 bool VisitRecordTypeLoc(RecordTypeLoc RTLoc);
66
67 bool VisitElaboratedTypeLoc(ElaboratedTypeLoc Loc);
68
69 bool VisitRecordDecl(RecordDecl *RD);
70
71 bool VisitVarDecl(VarDecl *VD);
72
73 private:
74 EmptyStructToInt *ConsumerInstance;
75 };
76
77 bool EmptyStructToIntASTVisitor::VisitRecordDecl(RecordDecl *RD)
78 {
79 if (ConsumerInstance->isInIncludedFile(RD) ||
80 !ConsumerInstance->isValidRecordDecl(RD))
81 return true;
82
83 const RecordDecl *CanonicalRD = dyn_cast<RecordDecl>(RD->getCanonicalDecl());
84 if (ConsumerInstance->VisitedRecordDecls.count(CanonicalRD))
85 return true;
86
87 ConsumerInstance->VisitedRecordDecls.insert(CanonicalRD);
88 return true;
89 }
90
91 bool EmptyStructToIntASTVisitor::VisitCXXRecordDecl(CXXRecordDecl *CXXRD)
92 {
93 const CXXRecordDecl *CanonicalRD = CXXRD->getCanonicalDecl();
94 if (ConsumerInstance->VisitedRecordDecls.count(CanonicalRD))
95 return true;
96
97 if (!CanonicalRD->hasDefinition())
98 return true;
99
100 for (CXXRecordDecl::base_class_const_iterator I =
101 CanonicalRD->bases_begin(), E = CanonicalRD->bases_end(); I != E; ++I) {
102 const CXXBaseSpecifier *BS = I;
103 const Type *Ty = BS->getType().getTypePtr();
104 const CXXRecordDecl *Base = ConsumerInstance->getBaseDeclFromType(Ty);
105 if (Base)
106 ConsumerInstance->BaseClassDecls.insert(Base->getCanonicalDecl());
107 }
108 return true;
109 }
110
111 bool EmptyStructToIntRewriteVisitor::VisitRecordTypeLoc(RecordTypeLoc RTLoc)
112 {
113 const RecordDecl *RD = RTLoc.getDecl();
114
115 if (RD->getCanonicalDecl() == ConsumerInstance->TheRecordDecl) {
116 SourceLocation LocStart = RTLoc.getBeginLoc();
117 void *LocPtr = LocStart.getPtrEncoding();
118 if (ConsumerInstance->VisitedLocs.count(LocPtr))
119 return true;
120 ConsumerInstance->VisitedLocs.insert(LocPtr);
121
122 SourceLocation LocEnd = RTLoc.getEndLoc();
123 if (ConsumerInstance->isSourceRangeWithinRecordDecl(
124 SourceRange(LocStart, LocEnd), RD)) {
125 return true;
126 }
127 // handle a special case -
128 // struct S1 {
129 // struct { } S;
130 // };
131 const IdentifierInfo *TypeId = RTLoc.getType().getBaseTypeIdentifier();
132 if (!TypeId)
133 return true;
134 ConsumerInstance->RewriteHelper->replaceRecordType(RTLoc, "int");
135 ConsumerInstance->Rewritten = true;
136 }
137 return true;
138 }
139
140 bool EmptyStructToIntRewriteVisitor::VisitElaboratedTypeLoc(
141 ElaboratedTypeLoc Loc)
142 {
143 const ElaboratedType *ETy = dyn_cast<ElaboratedType>(Loc.getTypePtr());
144 const Type *NamedTy = ETy->getNamedType().getTypePtr();
145 const RecordType *RDTy = NamedTy->getAs<RecordType>();
146 if (!RDTy)
147 return true;
148
149 const RecordDecl *RD = RDTy->getDecl();
150 TransAssert(RD && "NULL RecordDecl!");
151 if (RD->getCanonicalDecl() != ConsumerInstance->TheRecordDecl) {
152 return true;
153 }
154
155 SourceLocation StartLoc = Loc.getBeginLoc();
156 if (StartLoc.isInvalid())
157 return true;
158 TypeLoc TyLoc = Loc.getNamedTypeLoc();
159 SourceLocation EndLoc = TyLoc.getBeginLoc();
160 if (EndLoc.isInvalid())
161 return true;
162 EndLoc = EndLoc.getLocWithOffset(-1);
163 // This ElaboratedTypeLoc has been removed along with the RD
164 if (ConsumerInstance->isSourceRangeWithinRecordDecl(
165 SourceRange(StartLoc, EndLoc), RD)) {
166 return true;
167 }
168
169 const char *StartBuf =
170 ConsumerInstance->SrcManager->getCharacterData(StartLoc);
171 const char *EndBuf = ConsumerInstance->SrcManager->getCharacterData(EndLoc);
172
173 ConsumerInstance->Rewritten = true;
174 // It's possible, e.g.,
175 // struct S1 {
176 // struct { } S;
177 // };
178 // Clang will translate struct { } S to
179 // struct {
180 // };
181 // struct <anonymous struct ...> S;
182 // the last declaration is injected by clang.
183 // We need to omit it.
184 if (StartBuf > EndBuf) {
185 SourceLocation KeywordLoc = Loc.getElaboratedKeywordLoc();
186 if (KeywordLoc.isValid()) {
187 const llvm::StringRef Keyword =
188 TypeWithKeyword::getKeywordName(ETy->getKeyword());
189 ConsumerInstance->TheRewriter.ReplaceText(KeywordLoc,
190 Keyword.size(), "int");
191 }
192 return true;
193 }
194
195 ConsumerInstance->TheRewriter.RemoveText(SourceRange(StartLoc, EndLoc));
196 return true;
197 }
198
199 bool EmptyStructToIntRewriteVisitor::VisitRecordDecl(RecordDecl *RD)
200 {
201 //if (ConsumerInstance->isSpecialRecordDecl(RD))
202 // return true;
203
204 // Skip forward declarations
205 const RecordDecl *RDDef = RD->getDefinition();
206 if (!RDDef)
207 return true;
208
209 // Skip the struct which will be deleted
210 // It is already in the list
211 if (RD->getCanonicalDecl() == ConsumerInstance->TheRecordDecl) {
212 return true;
213 }
214
215 unsigned Idx = 0;
216 for (RecordDecl::field_iterator I = RDDef->field_begin(),
217 E = RDDef->field_end(); I != E; ++I) {
218 const FieldDecl *FD = (*I);
219 const Type *FDTy = FD->getType().getTypePtr();
220 const RecordDecl *BaseRD = ConsumerInstance->getBaseRecordDef(FDTy);
221
222 // Handle all fields of struct type
223 if (BaseRD)
224 ConsumerInstance->handleOneRecordDecl(RDDef, BaseRD, FD, Idx);
225 Idx++;
226 }
227 return true;
228 }
229
230 bool EmptyStructToIntRewriteVisitor::VisitVarDecl(VarDecl *VD)
231 {
232 if (!VD->hasInit()) {
233 return true;
234 }
235
236 ConsumerInstance->handleOneVarDecl(VD);
237 return true;
238 }
239
240 void EmptyStructToInt::Initialize(ASTContext &context)
241 {
242 Transformation::Initialize(context);
243 CollectionVisitor = new EmptyStructToIntASTVisitor(this);
244 RewriteVisitor = new EmptyStructToIntRewriteVisitor(this);
245 }
246
247 void EmptyStructToInt::HandleTranslationUnit(ASTContext &Ctx)
248 {
249 CollectionVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
250 doAnalysis();
251
252 if (QueryInstanceOnly)
253 return;
254
255 if (TransformationCounter > ValidInstanceNum) {
256 TransError = TransMaxInstanceError;
257 return;
258 }
259
260 Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
261 removeRecordDecls();
262 RewriteVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
263
264 // sanity check that we actually
265 // have done some text modifications.
266 // It could be false due to invalid code being transformed.
267 if (!Rewritten) {
268 TransError = TransNoTextModificationError;
269 return;
270 }
271 if (Ctx.getDiagnostics().hasErrorOccurred() ||
272 Ctx.getDiagnostics().hasFatalErrorOccurred())
273 TransError = TransInternalError;
274 }
275
276 void EmptyStructToInt::handleOneRecordDecl(const RecordDecl *RD,
277 const RecordDecl *BaseRD,
278 const FieldDecl *FD,
279 unsigned int Idx)
280 {
281 // Skip field if it is not of the type of one of
282 // the structs that are affected by the change
283 // Works recursively through chained structs
284 if (!RecordDeclToField[BaseRD] && BaseRD != TheRecordDecl) {
285 return;
286 }
287
288 IndexVector *NewIdxVec = RecordDeclToField[RD];
289
290 if (!NewIdxVec) {
291 NewIdxVec = new IndexVector();
292 RecordDeclToField[RD] = NewIdxVec;
293 }
294
295 NewIdxVec->push_back(Idx);
296 }
297
298 void EmptyStructToInt::handleOneVarDecl(const VarDecl *VD)
299 {
300 const Type *Ty = VD->getType().getTypePtr();
301 const RecordDecl *RD = getBaseRecordDef(Ty);
302
303 // Skip all variables which are not of struct type
304 if (!RD) {
305 return;
306 }
307
308 IndexVector *IdxVec = RecordDeclToField[RD];
309
310 // Skip variables for which the struct is not changed
311 if (!IdxVec && RD != TheRecordDecl) {
312 return;
313 }
314
315 ExprVector InitExprs;
316
317 getInitExprs(Ty, VD->getInit(), IdxVec, InitExprs);
318
319 for (ExprVector::iterator I = InitExprs.begin(), E = InitExprs.end(); I != E; ++I) {
320 RewriteHelper->replaceExpr(*I, "0");
321 }
322 }
323
324 void EmptyStructToInt::doAnalysis(void)
325 {
326 for (RecordDeclSet::const_iterator I = VisitedRecordDecls.begin(),
327 E = VisitedRecordDecls.end(); I != E; ++I) {
328 const RecordDecl *RD = (*I);
329 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
330 if (BaseClassDecls.count(CXXRD->getCanonicalDecl()))
331 continue;
332 }
333 ValidInstanceNum++;
334 if (ValidInstanceNum == TransformationCounter)
335 TheRecordDecl = RD;
336 }
337 }
338
339 // ISSUE: we will have bad transformation for the case below:
340 // typedef struct S;
341 // S *s;
342 // ==>
343 // typedef
344 // int *s;
345 // This is bad because we don't catch the implicit declaration of struct S.
346 // But hopefully peephole pass will remove the keyword typedef,
347 // then we will be fine.
348 void EmptyStructToInt::removeRecordDecls(void)
349 {
350 for (RecordDecl::redecl_iterator I = TheRecordDecl->redecls_begin(),
351 E = TheRecordDecl->redecls_end(); I != E; ++I) {
352
353 const RecordDecl *RD = dyn_cast<RecordDecl>(*I);
354 SourceRange Range = RD->getSourceRange();
355 SourceLocation LocEnd = Range.getEnd();
356 SourceLocation SemiLoc =
357 Lexer::findLocationAfterToken(LocEnd,
358 tok::semi,
359 *SrcManager,
360 Context->getLangOpts(),
361 /*SkipTrailingWhitespaceAndNewLine=*/true);
362 // handle cases such as
363 // struct S {} s;
364 if (SemiLoc.isInvalid()) {
365 if (!RD->isThisDeclarationADefinition())
366 return;
367 SourceLocation RBLoc = RD->getBraceRange().getEnd();
368 if (RBLoc.isInvalid())
369 return;
370 RewriteHelper->removeTextFromLeftAt(SourceRange(RBLoc, RBLoc),
371 '{', RBLoc);
372 Rewritten = true;
373 }
374 else {
375 LocEnd = RewriteHelper->getEndLocationUntil(Range, ';');
376 TheRewriter.RemoveText(SourceRange(Range.getBegin(), LocEnd));
377 Rewritten = true;
378 }
379 }
380 }
381
382 bool EmptyStructToInt::pointToSelf(const FieldDecl *FD)
383 {
384 const Type *Ty = FD->getType().getTypePtr();
385 if (!Ty->isPointerType())
386 return false;
387 const Type *PointeeTy = getBasePointerElemType(Ty);
388 if (TransformationManager::isCXXLangOpt()) {
389 const CXXRecordDecl *Base = getBaseDeclFromType(Ty);
390 if (!Base)
391 return false;
392 const CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(FD->getParent());
393 TransAssert(Parent && "Invalid Parent!");
394 return (Parent->getCanonicalDecl() == Base->getCanonicalDecl());
395 }
396
397 const RecordType *RT = PointeeTy->getAs<RecordType>();
398 if (!RT)
399 return false;
400 const RecordDecl *RD = RT->getDecl();
401 const RecordDecl *Parent = FD->getParent();
402 return (Parent->getCanonicalDecl() == RD->getCanonicalDecl());
403 }
404
405 bool EmptyStructToInt::isValidRecordDecl(const RecordDecl *RD)
406 {
407 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
408 if (!CXXRD) {
409 const RecordDecl *Def = RD->getDefinition();
410 if (!Def) {
411 return true;
412 }
413 else if (Def->field_empty()) {
414 return true;
415 }
416 else {
417 // skip invalid decl, which causes clang assertion errors
418 if (Def->isInvalidDecl())
419 return false;
420 // handle another special case where a struct has an unreferenced
421 // field. In some cases, we cannot simply remove this field
422 // because an empty struct would make a bug disappear.
423 const ASTRecordLayout &Info = Context->getASTRecordLayout(Def);
424 unsigned Count = Info.getFieldCount();
425 if (Count != 1)
426 return false;
427 const FieldDecl *FD = *(Def->field_begin());
428 TransAssert(FD && "Invalid FieldDecl");
429 // skip case such as
430 // struct S { struct S *p; };
431 if (pointToSelf(FD))
432 return false;
433 return !FD->isReferenced();
434 }
435 }
436
437 if (dyn_cast<ClassTemplateSpecializationDecl>(CXXRD) ||
438 CXXRD->getDescribedClassTemplate() ||
439 CXXRD->getInstantiatedFromMemberClass())
440 return false;
441
442 // It's possible that the described template does not
443 // have definition, so we test hasDefinition after the
444 // above `if' guard
445 const CXXRecordDecl *CXXDef = CXXRD->getDefinition();
446 if (!CXXDef)
447 return true;
448
449 if(CXXDef->getNumBases())
450 return false;
451
452 const DeclContext *Ctx = dyn_cast<DeclContext>(CXXDef);
453 TransAssert(Ctx && "Invalid DeclContext!");
454 int count = 0;
455 for (DeclContext::decl_iterator I = Ctx->decls_begin(),
456 E = Ctx->decls_end(); I != E; ++I) {
457 if (!(*I)->isImplicit()) {
458 if ((*I)->isReferenced())
459 return false;
460 if (isa<CXXConstructorDecl>(*I) || isa<CXXDestructorDecl>(*I))
461 return false;
462 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
463 if (FD->hasBody() && !FD->isInlined())
464 return false;
465 }
466 if (const FieldDecl *FieldD = dyn_cast<FieldDecl>(*I)) {
467 if (pointToSelf(FieldD))
468 return false;
469 }
470 ++count;
471 }
472 }
473
474 if (count > 1)
475 return false;
476
477 return true;
478 }
479
480 const RecordDecl *EmptyStructToInt::getBaseRecordDef(const Type *Ty)
481 {
482 const ArrayType *ArrayTy = dyn_cast<ArrayType>(Ty);
483 if (ArrayTy) {
484 Ty = getArrayBaseElemType(ArrayTy);
485 }
486
487 if (!Ty->isStructureType())
488 return NULL;
489
490 const RecordType *RT = Ty->getAsStructureType();
491 return RT->getDecl()->getDefinition();
492 }
493
494 void EmptyStructToInt::getInitExprs(const Type *Ty,
495 const Expr *E,
496 const IndexVector *IdxVec,
497 ExprVector &InitExprs)
498 {
499 const ArrayType *ArrayTy = dyn_cast<ArrayType>(Ty);
500 if (ArrayTy) {
501 if (isa<ImplicitValueInitExpr>(E) || isa<CXXConstructExpr>(E))
502 return;
503 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
504 TransAssert(ILE && "Invalid array initializer!");
505 unsigned int NumInits = ILE->getNumInits();
506 Ty = ArrayTy->getElementType().getTypePtr();
507
508 for (unsigned I = 0; I < NumInits; ++I) {
509 const Expr *Init = ILE->getInit(I);
510 getInitExprs(Ty, Init, IdxVec, InitExprs);
511 }
512 return;
513 }
514
515 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
516 if (!ILE)
517 return;
518
519 const RecordType *RT = NULL;
520 if (Ty->isUnionType()) {
521 RT = Ty->getAsUnionType();
522 }
523 else if (Ty->isStructureType()) {
524 RT = Ty->getAsStructureType();
525 }
526 else {
527 TransAssert(0 && "Bad RecordType!");
528 }
529
530 const RecordDecl *RD = RT->getDecl();
531
532 if (RD->getCanonicalDecl() == TheRecordDecl) {
533 InitExprs.push_back(E);
534 }
535 else {
536 for (IndexVector::const_iterator FI = IdxVec->begin(), FE = IdxVec->end();
537 FI != FE; ++FI) {
538 const FieldDecl *FD = getFieldDeclByIdx(RD, (*FI));
539 TransAssert(FD && "NULL FieldDecl!");
540
541 Ty = FD->getType().getTypePtr();
542
543 const RecordDecl *BaseRD = getBaseRecordDef(Ty);
544 unsigned int InitListIdx;
545
546 if (BaseRD->isUnion()) {
547 InitListIdx = 0;
548 }
549 else {
550 InitListIdx = (*FI);
551 }
552
553 if (InitListIdx >= ILE->getNumInits()) {
554 return;
555 }
556
557 getInitExprs(Ty, ILE->getInit(InitListIdx),
558 RecordDeclToField[BaseRD], InitExprs);
559 }
560 }
561 }
562
563 const FieldDecl *EmptyStructToInt::getFieldDeclByIdx(
564 const RecordDecl *RD, unsigned int Idx)
565 {
566 unsigned I = 0;
567 for (RecordDecl::field_iterator RI = RD->field_begin(),
568 RE = RD->field_end(); RI != RE; ++RI, ++I) {
569 if (I == Idx)
570 return (*RI);
571 }
572 return NULL;
573 }
574
575 bool EmptyStructToInt::isSourceRangeWithinRecordDecl(SourceRange Range,
576 const RecordDecl *RD) {
577 const char *StartBuf = SrcManager->getCharacterData(Range.getBegin());
578 const char *EndBuf = SrcManager->getCharacterData(Range.getEnd());
579
580 SourceRange RDRange = RD->getBraceRange();
581 const char *RDStartBuf = SrcManager->getCharacterData(RDRange.getBegin());
582 const char *RDEndBuf = SrcManager->getCharacterData(RDRange.getEnd());
583
584 return RDStartBuf < StartBuf && RDEndBuf > EndBuf;
585 }
586
587 EmptyStructToInt::~EmptyStructToInt(void)
588 {
589 delete CollectionVisitor;
590 delete RewriteVisitor;
591
592 for (RecordDeclToFieldIdxVectorMap::iterator I = RecordDeclToField.begin(),
593 E = RecordDeclToField.end(); I != E; ++I) {
594 delete (*I).second;
595 }
596 }
597