forked from vgvassilev/creduce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleInliner.cpp
546 lines (447 loc) · 14.6 KB
/
SimpleInliner.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
//===----------------------------------------------------------------------===//
//
// Copyright (c) 2012, 2013, 2014 The University of Utah
// All rights reserved.
//
// This file is distributed under the University of Illinois Open Source
// License. See the file COPYING for details.
//
//===----------------------------------------------------------------------===//
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include "SimpleInliner.h"
#include <sstream>
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/SourceManager.h"
#include "TransformationManager.h"
#include "CommonStatementVisitor.h"
using namespace clang;
using namespace llvm;
static const char *DescriptionMsg =
"A really simple inliner. \
This transformation does a simple source-to-source \
inlining. To avoid the abuse of inlining, I put \
some constraints on the size of a function which \
can be inlined - if a function has less than 10 statements, \
then it's legitimate. \n\
\n\
Steps of inlining: \n\
* create a tmp var for function return value; \n\
* create a new block which is a copy of the inlined function; \n\
* at the top of this newly block, inlined function's parameters \
will be declared as local vars with callexpr's arguments as their \
initialization values (if any) \n\
* inside this newly block, replace all return statements as \
assignment statements, where the LHS is the created tmp var \
(Note that if the inlined function returns void, then \
this step is skipped) \n\
* replace the callexpr with tmp var above \n\
\n\
Each transformation iteration only transforms one callexpr, \
also it will keep the inlined function body unchanged. \
If the inlined body has no reference anymore, c_delta \
will remove it entirely. \n";
static RegisterTransformation<SimpleInliner>
Trans("simple-inliner", DescriptionMsg);
class SimpleInlinerCollectionVisitor : public
RecursiveASTVisitor<SimpleInlinerCollectionVisitor> {
public:
explicit SimpleInlinerCollectionVisitor(SimpleInliner *Instance)
: ConsumerInstance(Instance),
NumStmts(0)
{ }
bool VisitStmt(Stmt *S);
bool VisitCallExpr(CallExpr *CE);
bool TraverseConstructorInitializer(CXXCtorInitializer *Init);
unsigned int getNumStmts(void) {
return NumStmts;
}
void setNumStmts(unsigned int Num) {
NumStmts = Num;
}
private:
SimpleInliner *ConsumerInstance;
unsigned int NumStmts;
};
class SimpleInlinerFunctionVisitor : public
RecursiveASTVisitor<SimpleInlinerFunctionVisitor> {
public:
explicit SimpleInlinerFunctionVisitor(SimpleInliner *Instance)
: ConsumerInstance(Instance)
{ }
bool VisitReturnStmt(ReturnStmt *RS);
bool VisitDeclRefExpr(DeclRefExpr *DRE);
private:
SimpleInliner *ConsumerInstance;
};
class SimpleInlinerFunctionStmtVisitor : public
RecursiveASTVisitor<SimpleInlinerFunctionStmtVisitor> {
public:
explicit SimpleInlinerFunctionStmtVisitor(SimpleInliner *Instance)
: ConsumerInstance(Instance)
{ }
bool VisitFunctionDecl(FunctionDecl *FD);
private:
SimpleInliner *ConsumerInstance;
};
class SimpleInlinerStmtVisitor : public
CommonStatementVisitor<SimpleInlinerStmtVisitor> {
public:
explicit SimpleInlinerStmtVisitor(SimpleInliner *Instance)
: ConsumerInstance(Instance)
{ }
bool VisitCallExpr(CallExpr *CallE);
private:
SimpleInliner *ConsumerInstance;
};
bool SimpleInlinerCollectionVisitor::VisitStmt(Stmt *S)
{
Stmt::StmtClass SC = S->getStmtClass();
switch (SC) {
case Stmt::BreakStmtClass:
case Stmt::CompoundStmtClass:
case Stmt::ContinueStmtClass:
case Stmt::DeclStmtClass:
case Stmt::DoStmtClass:
case Stmt::ForStmtClass:
case Stmt::GotoStmtClass:
case Stmt::IndirectGotoStmtClass:
case Stmt::IfStmtClass:
case Stmt::ReturnStmtClass:
case Stmt::CaseStmtClass:
case Stmt::SwitchStmtClass:
case Stmt::WhileStmtClass:
case Stmt::BinaryOperatorClass:
NumStmts++;
break;
default:
break;
}
return true;
}
bool SimpleInlinerCollectionVisitor::VisitCallExpr(CallExpr *CE)
{
FunctionDecl *FD = CE->getDirectCallee();
if (!FD)
return true;
ConsumerInstance->AllCallExprs.push_back(CE);
ConsumerInstance->CalleeToCallerMap[CE] = ConsumerInstance->CurrentFD;
FunctionDecl *CanonicalFD = FD->getCanonicalDecl();
unsigned int NumCalls = ConsumerInstance->FunctionDeclNumCalls[CanonicalFD];
NumCalls++;
ConsumerInstance->FunctionDeclNumCalls[CanonicalFD] = NumCalls;
NumStmts++;
return true;
}
// Overload the default traverse function, because we cannot inline
// Ctor's initializer
bool SimpleInlinerCollectionVisitor::TraverseConstructorInitializer(
CXXCtorInitializer *Init)
{
return true;
}
bool SimpleInlinerFunctionVisitor::VisitReturnStmt(ReturnStmt *RS)
{
ConsumerInstance->ReturnStmts.push_back(RS);
return true;
}
bool SimpleInlinerFunctionVisitor::VisitDeclRefExpr(DeclRefExpr *DRE)
{
const ValueDecl *OrigDecl = DRE->getDecl();
const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(OrigDecl);
if (PD)
ConsumerInstance->ParmRefs.push_back(DRE);
return true;
}
bool SimpleInlinerFunctionStmtVisitor::VisitFunctionDecl(FunctionDecl *FD)
{
if (!FD->isThisDeclarationADefinition())
return true;
ConsumerInstance->CurrentFD = FD;
ConsumerInstance->CollectionVisitor->setNumStmts(0);
ConsumerInstance->CollectionVisitor->TraverseDecl(FD);
if (!FD->isVariadic()) {
ConsumerInstance->FunctionDeclNumStmts[FD->getCanonicalDecl()] =
ConsumerInstance->CollectionVisitor->getNumStmts();
}
return true;
}
bool SimpleInlinerStmtVisitor::VisitCallExpr(CallExpr *CallE)
{
if (ConsumerInstance->TheCallExpr == CallE) {
ConsumerInstance->TheStmt = CurrentStmt;
ConsumerInstance->NeedParen = NeedParen;
// Stop recursion
return false;
}
return true;
}
void SimpleInliner::Initialize(ASTContext &context)
{
Transformation::Initialize(context);
NameQueryWrap =
new TransNameQueryWrap(RewriteHelper->getTmpVarNamePrefix());
CollectionVisitor = new SimpleInlinerCollectionVisitor(this);
FunctionVisitor = new SimpleInlinerFunctionVisitor(this);
FunctionStmtVisitor = new SimpleInlinerFunctionStmtVisitor(this);
StmtVisitor = new SimpleInlinerStmtVisitor(this);
}
bool SimpleInliner::HandleTopLevelDecl(DeclGroupRef D)
{
for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
FunctionStmtVisitor->TraverseDecl(*I);
}
return true;
}
void SimpleInliner::HandleTranslationUnit(ASTContext &Ctx)
{
doAnalysis();
if (QueryInstanceOnly)
return;
if (TransformationCounter > ValidInstanceNum) {
TransError = TransMaxInstanceError;
return;
}
TransAssert(CurrentFD && "NULL CurrentFD!");
TransAssert(TheCallExpr && "NULL TheCallExpr!");
Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
NameQueryWrap->TraverseDecl(Ctx.getTranslationUnitDecl());
NamePostfix = NameQueryWrap->getMaxNamePostfix() + 1;
FunctionVisitor->TraverseDecl(CurrentFD);
StmtVisitor->TraverseDecl(TheCaller);
TransAssert(TheStmt && "NULL TheStmt!");
replaceCallExpr();
if (Ctx.getDiagnostics().hasErrorOccurred() ||
Ctx.getDiagnostics().hasFatalErrorOccurred())
TransError = TransInternalError;
}
bool SimpleInliner::isValidArgExpr(const Expr *E)
{
TransAssert(E && "NULL Expr!");
switch(E->getStmtClass()) {
case Expr::FloatingLiteralClass:
case Expr::StringLiteralClass:
case Expr::IntegerLiteralClass:
case Expr::GNUNullExprClass:
case Expr::CharacterLiteralClass: // Fall-through
return true;
case Expr::ParenExprClass:
return isValidArgExpr(cast<ParenExpr>(E)->getSubExpr());
case Expr::ImplicitCastExprClass:
case Expr::CStyleCastExprClass: // Fall-through
return isValidArgExpr(cast<CastExpr>(E)->getSubExpr());
case Expr::MemberExprClass:
return true;
case Expr::ArraySubscriptExprClass: {
const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
return isValidArgExpr(AE->getIdx());
}
case Expr::DeclRefExprClass:
return true;
default:
return false;
}
TransAssert(0 && "Unreachable code!");
return false;
}
bool SimpleInliner::hasValidArgExprs(const CallExpr *CE)
{
for(CallExpr::const_arg_iterator I = CE->arg_begin(), E = CE->arg_end();
I != E; ++I) {
if (!isValidArgExpr(*I))
return false;
}
return true;
}
void SimpleInliner::getValidFunctionDecls(void)
{
for (FunctionDeclToNumStmtsMap::iterator I = FunctionDeclNumStmts.begin(),
E = FunctionDeclNumStmts.end(); I != E; ++I) {
FunctionDecl *FD = (*I).first;
unsigned int NumStmts = (*I).second;
unsigned int NumCalls = FunctionDeclNumCalls[FD];
if (((NumCalls == 1) && (NumStmts <= SingleMaxNumStmts)) ||
((NumCalls > 1) && (NumStmts <= MaxNumStmts))) {
ValidFunctionDecls.insert(FD);
}
}
}
void SimpleInliner::doAnalysis(void)
{
getValidFunctionDecls();
for (SmallVector<CallExpr *, 10>::iterator CI = AllCallExprs.begin(),
CE = AllCallExprs.end(); CI != CE; ++CI) {
FunctionDecl *CalleeDecl = (*CI)->getDirectCallee();
TransAssert(CalleeDecl && "Bad CalleeDecl!");
FunctionDecl *CanonicalDecl = CalleeDecl->getCanonicalDecl();
if (!ValidFunctionDecls.count(CanonicalDecl))
continue;
if (!hasValidArgExprs(*CI))
continue;
ValidInstanceNum++;
if (TransformationCounter == ValidInstanceNum) {
// It's possible the direct callee is not a definition
if (!CalleeDecl->isThisDeclarationADefinition()) {
CalleeDecl = CalleeDecl->getCanonicalDecl();
for(FunctionDecl::redecl_iterator RI = CalleeDecl->redecls_begin(),
RE = CalleeDecl->redecls_end(); RI != RE; ++RI) {
if ((*RI)->isThisDeclarationADefinition()) {
CalleeDecl = (*RI);
break;
}
}
}
TransAssert(CalleeDecl->isThisDeclarationADefinition() &&
"Bad CalleeDecl!");
CurrentFD = CalleeDecl;
TheCaller = CalleeToCallerMap[(*CI)];
TransAssert(TheCaller && "NULL TheCaller!");
TheCallExpr = (*CI);
}
}
}
std::string SimpleInliner::getNewTmpName(void)
{
std::stringstream SS;
SS << RewriteHelper->getTmpVarNamePrefix() << NamePostfix;
NamePostfix++;
return SS.str();
}
void SimpleInliner::createReturnVar(void)
{
const Type *FDType = CurrentFD->getResultType().getTypePtr();
const Type *CallExprType = TheCallExpr->getCallReturnType().getTypePtr();
// We don't need tmp var
if (FDType->isVoidType() && CallExprType->isVoidType()) {
return;
}
TmpVarName = getNewTmpName();
std::string VarStr = TmpVarName;
CurrentFD->getResultType().getAsStringInternal(VarStr,
Context->getPrintingPolicy());
VarStr += ";";
RewriteHelper->addLocalVarToFunc(VarStr, TheCaller);
}
void SimpleInliner::generateParamStrings(void)
{
unsigned int ArgNum = TheCallExpr->getNumArgs();
FunctionDecl *FD = TheCallExpr->getDirectCallee();
unsigned int Idx;
for(Idx = 0; Idx < FD->getNumParams(); ++Idx) {
const ParmVarDecl *PD = FD->getParamDecl(Idx);
std::string ParmStr = PD->getNameAsString();
PD->getType().getAsStringInternal(ParmStr,
Context->getPrintingPolicy());
if (Idx < ArgNum) {
const Expr *Arg = TheCallExpr->getArg(Idx);
ParmStr += " = ";
std::string ArgStr("");
RewriteHelper->getExprString(Arg, ArgStr);
ParmStr += ArgStr;
}
ParmStr += ";\n";
ParmStrings.push_back(ParmStr);
}
}
void SimpleInliner::insertReturnStmt
(std::vector< std::pair<ReturnStmt *, int> > &SortedReturnStmts,
ReturnStmt *RS, int Off)
{
std::pair<ReturnStmt *, int> ReturnStmtOffPair(RS, Off);
if (SortedReturnStmts.empty()) {
SortedReturnStmts.push_back(ReturnStmtOffPair);
return;
}
std::vector< std::pair<ReturnStmt *, int> >::iterator I, E;
for(I = SortedReturnStmts.begin(), E = SortedReturnStmts.end(); I != E; ++I) {
int TmpOff = (*I).second;
if (Off < TmpOff)
break;
}
if (I == E)
SortedReturnStmts.push_back(ReturnStmtOffPair);
else
SortedReturnStmts.insert(I, ReturnStmtOffPair);
}
void SimpleInliner::sortReturnStmtsByOffs(const char *StartBuf,
std::vector< std::pair<ReturnStmt *, int> > &SortedReturnStmts)
{
for (ReturnStmtsVector::iterator I = ReturnStmts.begin(),
E = ReturnStmts.end(); I != E; ++I) {
ReturnStmt *RS = (*I);
SourceLocation RSLocStart = RS->getLocStart();
const char *RSStartBuf = SrcManager->getCharacterData(RSLocStart);
int Off = RSStartBuf - StartBuf;
TransAssert((Off >= 0) && "Bad Offset!");
insertReturnStmt(SortedReturnStmts, RS, Off);
}
}
void SimpleInliner::copyFunctionBody(void)
{
Stmt *Body = CurrentFD->getBody();
TransAssert(Body && "NULL Body!");
std::string FuncBodyStr("");
RewriteHelper->getStmtString(Body, FuncBodyStr);
TransAssert(FuncBodyStr[0] == '{');
SourceLocation StartLoc = Body->getLocStart();
const char *StartBuf = SrcManager->getCharacterData(StartLoc);
std::vector< std::pair<ReturnStmt *, int> > SortedReturnStmts;
sortReturnStmtsByOffs(StartBuf, SortedReturnStmts);
// Now we start rewriting
int Delta = 1; // skip the first { symbol
for(SmallVector<std::string, 10>::iterator I = ParmStrings.begin(),
E = ParmStrings.end(); I != E; ++I) {
std::string PStr = (*I);
FuncBodyStr.insert(Delta, PStr);
Delta += PStr.size();
}
// restore the effect of {
Delta--;
int ReturnSZ = 6;
std::string TmpVarStr = TmpVarName + " = ";
int TmpVarNameSize = static_cast<int>(TmpVarStr.size());
for(std::vector< std::pair<ReturnStmt *, int> >::iterator
I = SortedReturnStmts.begin(), E = SortedReturnStmts.end();
I != E; ++I) {
ReturnStmt *RS = (*I).first;
int Off = (*I).second + Delta;
Expr *Exp = RS->getRetValue();
if (Exp) {
const Type *T = Exp->getType().getTypePtr();
if (!T->isVoidType()) {
FuncBodyStr.replace(Off, ReturnSZ, TmpVarStr);
Delta += (TmpVarNameSize - ReturnSZ);
continue;
}
}
FuncBodyStr.replace(Off, ReturnSZ, "");
Delta -= ReturnSZ;
}
RewriteHelper->addStringBeforeStmt(TheStmt, FuncBodyStr, NeedParen);
}
void SimpleInliner::removeFunctionBody(void)
{
SourceRange FDRange = CurrentFD->getSourceRange();
TheRewriter.RemoveText(FDRange);
}
void SimpleInliner::replaceCallExpr(void)
{
// Create a new tmp var for return value
createReturnVar();
generateParamStrings();
copyFunctionBody();
RewriteHelper->replaceExprNotInclude(TheCallExpr, TmpVarName);
FunctionDecl *CanonicalFD = CurrentFD->getCanonicalDecl();
if (FunctionDeclNumCalls[CanonicalFD] == 1)
removeFunctionBody();
}
SimpleInliner::~SimpleInliner(void)
{
delete NameQueryWrap;
delete CollectionVisitor;
delete FunctionVisitor;
delete FunctionStmtVisitor;
delete StmtVisitor;
}