Debian Codegraph @

clang_delta/RemoveUnusedStructField.cpp

raw symbols SCIP
1 //===----------------------------------------------------------------------===//
2 //
3 // Copyright (c) 2012, 2013, 2015, 2016, 2017, 2018 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 "RemoveUnusedStructField.h"
16
17 #include "clang/AST/RecursiveASTVisitor.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/Basic/SourceManager.h"
20
21 #include "TransformationManager.h"
22
23 using namespace clang;
24
25 static const char *DescriptionMsg =
26 "Remove unreferenced struct fields. This pass also removes the corresponding \
27 intialization expression for a variable declared as the struct under \
28 transformation. Currenttly this pass doesn't handle nested struct \
29 definition well. \n";
30
31 static RegisterTransformation<RemoveUnusedStructField>
32 Trans("remove-unused-field", DescriptionMsg);
33
34 class RemoveUnusedStructFieldVisitor : public
35 RecursiveASTVisitor<RemoveUnusedStructFieldVisitor> {
36 public:
37
38 explicit RemoveUnusedStructFieldVisitor(RemoveUnusedStructField *Instance)
39 : ConsumerInstance(Instance)
40 { }
41
42 bool VisitFieldDecl(FieldDecl *FD);
43
44 bool VisitDesignatedInitExpr(DesignatedInitExpr *DIE);
45
46 private:
47
48 RemoveUnusedStructField *ConsumerInstance;
49 };
50
51 class RemoveUnusedStructFieldRewriteVisitor : public
52 RecursiveASTVisitor<RemoveUnusedStructFieldRewriteVisitor> {
53 public:
54
55 explicit RemoveUnusedStructFieldRewriteVisitor(
56 RemoveUnusedStructField *Instance)
57 : ConsumerInstance(Instance)
58 { }
59
60 bool VisitRecordDecl(RecordDecl *RD);
61
62 bool VisitVarDecl(VarDecl *VD);
63
64 private:
65
66 RemoveUnusedStructField *ConsumerInstance;
67 };
68
69 bool RemoveUnusedStructFieldVisitor::VisitFieldDecl(FieldDecl *FD)
70 {
71 if(ConsumerInstance->isInIncludedFile(FD))
72 return true;
73
74 const RecordDecl *RD = FD->getParent();
75 if (FD->isReferenced() || !RD->isStruct() ||
76 ConsumerInstance->isSpecialRecordDecl(RD))
77 return true;
78
79 ConsumerInstance->ValidInstanceNum++;
80 if (ConsumerInstance->ValidInstanceNum ==
81 ConsumerInstance->TransformationCounter) {
82 ConsumerInstance->setBaseLine(RD, FD);
83 }
84
85 return true;
86 }
87
88 bool RemoveUnusedStructFieldVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *DIE) {
89 return true;
90 }
91
92 bool RemoveUnusedStructFieldRewriteVisitor::VisitRecordDecl(RecordDecl *RD)
93 {
94 if (ConsumerInstance->isSpecialRecordDecl(RD))
95 return true;
96
97 const RecordDecl *RDDef = RD->getDefinition();
98 if (!RDDef)
99 return true;
100 if (ConsumerInstance->RecordDeclToField[RD])
101 return true;
102
103 unsigned Idx = 0;
104 for (RecordDecl::field_iterator I = RDDef->field_begin(),
105 E = RDDef->field_end(); I != E; ++I) {
106 const FieldDecl *FD = (*I);
107 const Type *FDTy = FD->getType().getTypePtr();
108 const RecordDecl *BaseRD = ConsumerInstance->getBaseRecordDef(FDTy);
109 if (BaseRD)
110 ConsumerInstance->handleOneRecordDecl(RDDef, BaseRD, FD, Idx);
111 Idx++;
112 }
113 return true;
114 }
115
116 bool RemoveUnusedStructFieldRewriteVisitor::VisitVarDecl(VarDecl *VD)
117 {
118 if (!VD->hasInit())
119 return true;
120
121 ConsumerInstance->handleOneVarDecl(VD);
122 return true;
123 }
124
125 void RemoveUnusedStructField::Initialize(ASTContext &context)
126 {
127 Transformation::Initialize(context);
128 CollectionVisitor = new RemoveUnusedStructFieldVisitor(this);
129 RewriteVisitor = new RemoveUnusedStructFieldRewriteVisitor(this);
130 }
131
132 void RemoveUnusedStructField::HandleTranslationUnit(ASTContext &Ctx)
133 {
134 CollectionVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
135
136 if (QueryInstanceOnly)
137 return;
138
139 if (TransformationCounter > ValidInstanceNum) {
140 TransError = TransMaxInstanceError;
141 return;
142 }
143
144 Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
145
146 TransAssert(TheRecordDecl && "NULL TheRecordDecl!");
147 TransAssert(TheFieldDecl && "NULL TheFunctionDecl!");
148
149 RewriteVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
150 removeFieldDecl();
151
152 if (Ctx.getDiagnostics().hasErrorOccurred() ||
153 Ctx.getDiagnostics().hasFatalErrorOccurred())
154 TransError = TransInternalError;
155 }
156
157 void RemoveUnusedStructField::setBaseLine(const RecordDecl *RD,
158 const FieldDecl *FD)
159 {
160 TheRecordDecl = RD;
161 TheFieldDecl = FD;
162
163 IndexVector *IdxVec = new IndexVector();
164 unsigned int Idx = FD->getFieldIndex();
165 IdxVec->push_back(Idx);
166 RecordDeclToField[RD] = IdxVec;
167 FieldToIdxVector[FD] = IdxVec;
168
169 // IsLastField = (FD->getNextDeclInContext() == NULL);
170 RecordDecl::field_iterator I = RD->field_begin();
171 IsFirstField = (FD == (*I));
172 RecordDecl::field_iterator E = RD->field_end();
173
174 for (; I != E; ++I) {
175 NumFields++;
176 }
177 }
178
179 void RemoveUnusedStructField::handleOneRecordDecl(const RecordDecl *RD,
180 const RecordDecl *BaseRD,
181 const FieldDecl *FD,
182 unsigned int Idx)
183 {
184 IndexVector *BaseIdxVec = RecordDeclToField[BaseRD];
185 if (!BaseIdxVec)
186 return;
187
188 IndexVector *NewIdxVec = RecordDeclToField[RD];
189 if (!NewIdxVec) {
190 NewIdxVec = new IndexVector();
191 RecordDeclToField[RD] = NewIdxVec;
192 }
193 NewIdxVec->push_back(Idx);
194 FieldToIdxVector[FD] = BaseIdxVec;
195 }
196
197 void RemoveUnusedStructField::handleOneVarDecl(const VarDecl *VD)
198 {
199 const Type *Ty = VD->getType().getTypePtr();
200 const RecordDecl *RD = getBaseRecordDef(Ty);
201 if (!RD)
202 return;
203
204 IndexVector *IdxVec = RecordDeclToField[RD];
205 if (!IdxVec)
206 return;
207
208 const Expr *InitE = VD->getInit();
209 TransAssert(InitE && "Need initializer!");
210
211 ExprVector InitExprs;
212
213 getInitExprs(Ty, InitE, IdxVec, InitExprs);
214
215 for (ExprVector::iterator I = InitExprs.begin(),
216 E = InitExprs.end(); I != E; ++I) {
217 if (dyn_cast<ImplicitValueInitExpr>(*I))
218 continue;
219 removeOneInitExpr(*I);
220 }
221 }
222
223 const FieldDecl *RemoveUnusedStructField::getFieldDeclByIdx(
224 const RecordDecl *RD, unsigned int Idx)
225 {
226 unsigned I = 0;
227 for (RecordDecl::field_iterator RI = RD->field_begin(),
228 RE = RD->field_end(); RI != RE; ++RI, ++I) {
229 if (I == Idx)
230 return (*RI);
231 }
232 return NULL;
233 }
234
235 const Expr *RemoveUnusedStructField::getInitExprFromDesignatedInitExpr(
236 const InitListExpr *ILE, int InitListIdx,
237 const FieldDecl *FD) {
238 int NumInits = ILE->getNumInits();
239 llvm::DenseMap<int, const Expr *> LeftInits;
240 int LastFDIdx = -1;
241 for (int I = 0; I < NumInits; ++I) {
242 const Expr *Init = ILE->getInit(I);
243 if (const DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
244 if (DIE->getNumSubExprs() < 1) {
245 LeftInits[I] = Init;
246 LastFDIdx = I;
247 }
248 else {
249 const DesignatedInitExpr::Designator *DS = DIE->getDesignator(0);
250 #if LLVM_VERSION_MAJOR >= 17
251 const FieldDecl *CurrFD = DS->getFieldDecl();
252 #else
253 const FieldDecl *CurrFD = DS->getField();
254 #endif
255 if ((CurrFD && FD == CurrFD) ||
256 (CurrFD == NULL && DS->getFieldName() == FD->getIdentifier())) {
257 IsFirstField = (I == 0);
258 return Init;
259 }
260 if (CurrFD) {
261 LastFDIdx = CurrFD->getFieldIndex();
262 }
263 else {
264 LastFDIdx = I;
265 }
266 }
267 }
268 else {
269 LastFDIdx++;
270 LeftInits[LastFDIdx] = Init;
271 }
272 }
273 const Expr *Init = LeftInits[++LastFDIdx];
274 if (Init) {
275 IsFirstField = (LastFDIdx == 0);
276 return Init;
277 }
278 IsFirstField = (InitListIdx == 0);
279 return ILE->getInit(InitListIdx);
280 }
281
282 void RemoveUnusedStructField::getInitExprs(const Type *Ty,
283 const Expr *E,
284 const IndexVector *IdxVec,
285 ExprVector &InitExprs)
286 {
287 const ArrayType *ArrayTy = dyn_cast<ArrayType>(Ty);
288 if (ArrayTy) {
289 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E)) {
290 TransAssert(ILE && "Invalid array initializer!");
291 unsigned int NumInits = ILE->getNumInits();
292 Ty = ArrayTy->getElementType().getTypePtr();
293
294 for (unsigned I = 0; I < NumInits; ++I) {
295 const Expr *Init = ILE->getInit(I);
296 getInitExprs(Ty, Init, IdxVec, InitExprs);
297 }
298 }
299 return;
300 }
301
302 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
303 if (!ILE)
304 return;
305
306 // ILE can be a list of DesignatedInitExpr(s).
307 // Extract it's syntactic form in such case.
308 bool HasDesignatedInit = false;
309 if (ILE->isSemanticForm()) {
310 ILE = ILE->getSyntacticForm() == nullptr ? ILE : ILE->getSyntacticForm();
311 for (unsigned I = 0; I < ILE->getNumInits(); I++) {
312 if (isa<DesignatedInitExpr>(ILE->getInit(I))) {
313 HasDesignatedInit = true;
314 break;
315 }
316 }
317 }
318 const RecordType *RT = NULL;
319 if (Ty->isUnionType()) {
320 RT = Ty->getAsUnionType();
321 }
322 else if (Ty->isStructureType()) {
323 RT = Ty->getAsStructureType();
324 }
325 else {
326 TransAssert(0 && "Bad RecordType!");
327 }
328
329 const RecordDecl *RD = RT->getDecl();
330 unsigned int VecSz = IdxVec->size();
331 for (IndexVector::const_iterator FI = IdxVec->begin(),
332 FE = IdxVec->end(); FI != FE; ++FI)
333 {
334 const FieldDecl *FD = getFieldDeclByIdx(RD, (*FI));
335 TransAssert(FD && "NULL FieldDecl!");
336 IndexVector *FieldIdxVec = FieldToIdxVector[FD];
337 TransAssert(FieldIdxVec && "Cannot find FieldIdxVec!");
338
339 Ty = FD->getType().getTypePtr();
340 const Expr *Init;
341 unsigned int InitListIdx;
342 if (RD->isUnion())
343 InitListIdx = 0;
344 else
345 InitListIdx = (*FI);
346
347 if (InitListIdx >= ILE->getNumInits())
348 return;
349
350 Init = ILE->getInit(InitListIdx);
351
352 if (FD == TheFieldDecl) {
353 if (HasDesignatedInit) {
354 Init = getInitExprFromDesignatedInitExpr(ILE, InitListIdx, FD);
355 }
356 InitExprs.push_back(Init);
357 TransAssert((VecSz == 1) && "Bad IndexVector size!"); (void)VecSz;
358 }
359 else {
360 getInitExprs(Ty, Init, FieldIdxVec, InitExprs);
361 }
362 }
363 }
364
365 void RemoveUnusedStructField::removeOneInitExpr(const Expr *E)
366 {
367 TransAssert(NumFields && "NumFields cannot be zero!");
368
369 SourceRange ExpRange = E->getSourceRange();
370 SourceLocation StartLoc = ExpRange.getBegin();
371 SourceLocation EndLoc = ExpRange.getEnd();
372
373 if (NumFields == 1) {
374 // The last field can optionally have a trailing comma
375 // If this is the only field also the comma has to be removed
376 SourceLocation NewEndLoc =
377 RewriteHelper->getEndLocationUntil(ExpRange, '}');
378 NewEndLoc = NewEndLoc.getLocWithOffset(-1);
379
380 TheRewriter.RemoveText(SourceRange(StartLoc, NewEndLoc));
381
382 return;
383 }
384 else if (IsFirstField) {
385 EndLoc = RewriteHelper->getEndLocationUntil(ExpRange, ',');
386 TheRewriter.RemoveText(SourceRange(StartLoc, EndLoc));
387 return;
388 }
389
390 const char *Buf = SrcManager->getCharacterData(StartLoc);
391 int Offset = 0;
392 while (*Buf != ',') {
393 Buf--;
394 Offset--;
395 }
396 StartLoc = StartLoc.getLocWithOffset(Offset);
397 TheRewriter.RemoveText(SourceRange(StartLoc, EndLoc));
398 }
399
400 const RecordDecl *RemoveUnusedStructField::getBaseRecordDef(const Type *Ty)
401 {
402 const ArrayType *ArrayTy = dyn_cast<ArrayType>(Ty);
403 if (ArrayTy) {
404 Ty = getArrayBaseElemType(ArrayTy);
405 }
406
407 if (!Ty->isStructureType())
408 return NULL;
409
410 const RecordType *RT = Ty->getAsStructureType();
411 return RT->getDecl()->getDefinition();
412 }
413
414 void RemoveUnusedStructField::removeFieldDecl(void)
415 {
416 // FIXME: we don't handle nested struct definition well.
417 // For example,
418 // struct S1 {
419 // struct S2 {
420 // int f1;
421 // } f1;
422 // struct S2 f2;
423 // }
424 // will be transformed to
425 // struct S1 {
426 // struct S2 f2;
427 // }
428 // Thus we will leave an incomplete struct S2
429 RewriteHelper->removeFieldDecl(TheFieldDecl);
430 }
431
432 RemoveUnusedStructField::~RemoveUnusedStructField(void)
433 {
434 delete CollectionVisitor;
435 delete RewriteVisitor;
436
437 for (RecordDeclToFieldIdxVectorMap::iterator I = RecordDeclToField.begin(),
438 E = RecordDeclToField.end(); I != E; ++I) {
439 delete (*I).second;
440 }
441 }
442