Debian Codegraph @

clang_delta/RemoveNestedFunction.cpp

raw symbols SCIP
1 //===----------------------------------------------------------------------===//
2 //
3 // Copyright (c) 2012, 2013, 2014, 2015, 2016, 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 "RemoveNestedFunction.h"
16
17 #include <sstream>
18
19 #include "llvm/ADT/SmallVector.h"
20 #include "clang/AST/RecursiveASTVisitor.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/Basic/SourceManager.h"
23
24 #include "TransformationManager.h"
25 #include "CommonStatementVisitor.h"
26
27 using namespace clang;
28
29 static const char *DescriptionMsg =
30 "Remove a nested function invocation from its enclosing \
31 expression. The transformation will create a temporary \
32 variable with the correct type, assgin the return value \
33 of the selected nested function to the created variable, \
34 and replace the function invocation with this temporary \
35 variable. (Note that this transformation is unsound because \
36 it changes the semantics of loop executions in some cases. \n";
37
38
39 static RegisterTransformation<RemoveNestedFunction>
40 Trans("remove-nested-function", DescriptionMsg);
41
42 class RNFCollectionVisitor : public RecursiveASTVisitor<RNFCollectionVisitor> {
43 public:
44
45 explicit RNFCollectionVisitor(RemoveNestedFunction *Instance)
46 : ConsumerInstance(Instance)
47 { }
48
49 bool VisitFunctionDecl(FunctionDecl *FD);
50
51 private:
52 RemoveNestedFunction *ConsumerInstance;
53
54 };
55
56 class RNFStatementVisitor : public CommonStatementVisitor<RNFStatementVisitor> {
57 public:
58
59 explicit RNFStatementVisitor(RemoveNestedFunction *Instance)
60 : ConsumerInstance(Instance)
61 { }
62
63 bool VisitCallExpr(CallExpr *CallE);
64
65 bool VisitStmtExpr(StmtExpr *SE);
66
67 private:
68 RemoveNestedFunction *ConsumerInstance;
69
70 };
71
72 bool RNFCollectionVisitor::VisitFunctionDecl(FunctionDecl *FD)
73 {
74 if (ConsumerInstance->isInIncludedFile(FD) ||
75 !FD->isThisDeclarationADefinition())
76 return true;
77
78 ConsumerInstance->StmtVisitor->setCurrentFunctionDecl(FD);
79 ConsumerInstance->StmtVisitor->TraverseDecl(FD);
80 ConsumerInstance->StmtVisitor->setCurrentFunctionDecl(NULL);
81 return true;
82 }
83
84 bool RNFStatementVisitor::VisitStmtExpr(StmtExpr *SE)
85 {
86 CompoundStmt *CS = SE->getSubStmt();
87 if (ConsumerInstance->CallExprQueue.empty()) {
88 TraverseStmt(CS);
89 return false;
90 }
91
92 CallExpr *CallE = ConsumerInstance->CallExprQueue.back();
93 CurrentStmt = CallE;
94
95 for (clang::CompoundStmt::body_iterator I = CS->body_begin(),
96 E = CS->body_end(); I != E; ++I) {
97 TraverseStmt(*I);
98 }
99 return false;
100 }
101
102 bool RNFStatementVisitor::VisitCallExpr(CallExpr *CallE)
103 {
104 if (const CXXOperatorCallExpr *OpE = dyn_cast<CXXOperatorCallExpr>(CallE)) {
105 if (ConsumerInstance->isInvalidOperator(OpE))
106 return true;
107 }
108
109 if (CurrentStmt &&
110 (std::find(ConsumerInstance->ValidCallExprs.begin(),
111 ConsumerInstance->ValidCallExprs.end(), CallE)
112 == ConsumerInstance->ValidCallExprs.end()) &&
113 !ConsumerInstance->CallExprQueue.empty()) {
114
115 ConsumerInstance->ValidInstanceNum++;
116 ConsumerInstance->ValidCallExprs.push_back(CallE);
117
118 if (ConsumerInstance->ValidInstanceNum ==
119 ConsumerInstance->TransformationCounter) {
120 ConsumerInstance->TheFuncDecl = CurrentFuncDecl;
121 ConsumerInstance->TheStmt = CurrentStmt;
122 ConsumerInstance->TheCallExpr = CallE;
123 ConsumerInstance->NeedParen = NeedParen;
124 }
125 }
126
127 ConsumerInstance->CallExprQueue.push_back(CallE);
128
129 for (CallExpr::arg_iterator I = CallE->arg_begin(),
130 E = CallE->arg_end(); I != E; ++I) {
131 Expr *Exp = *I;
132 TraverseStmt(Exp);
133 }
134
135 ConsumerInstance->CallExprQueue.pop_back();
136
137 return true;
138 }
139
140 void RemoveNestedFunction::Initialize(ASTContext &context)
141 {
142 Transformation::Initialize(context);
143 NestedInvocationVisitor = new RNFCollectionVisitor(this);
144 StmtVisitor = new RNFStatementVisitor(this);
145 NameQueryWrap =
146 new TransNameQueryWrap(RewriteHelper->getTmpVarNamePrefix());
147 }
148
149 bool RemoveNestedFunction::HandleTopLevelDecl(DeclGroupRef D)
150 {
151 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
152 NestedInvocationVisitor->TraverseDecl(*I);
153 }
154 return true;
155 }
156
157 void RemoveNestedFunction::HandleTranslationUnit(ASTContext &Ctx)
158 {
159 if (QueryInstanceOnly)
160 return;
161
162 if (TransformationCounter > ValidInstanceNum) {
163 TransError = TransMaxInstanceError;
164 return;
165 }
166
167 Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
168
169 TransAssert(TheFuncDecl && "NULL TheFuncDecl!");
170 TransAssert(TheStmt && "NULL TheStmt!");
171 TransAssert(TheCallExpr && "NULL TheCallExpr");
172
173 NameQueryWrap->TraverseDecl(Ctx.getTranslationUnitDecl());
174
175 addNewTmpVariable(Ctx);
176
177 if (Ctx.getDiagnostics().hasErrorOccurred() ||
178 Ctx.getDiagnostics().hasFatalErrorOccurred())
179 TransError = TransInternalError;
180 }
181
182 void RemoveNestedFunction::getVarStrForTemplateSpecialization(
183 std::string &VarStr,
184 const TemplateSpecializationType *TST)
185 {
186 unsigned NumArgs = TST->template_arguments().size();
187 if (NumArgs == 0) {
188 return;
189 }
190
191 std::string ArgStr;
192 llvm::raw_string_ostream Stream(ArgStr);
193 TST->template_arguments()[0].print(Context->getPrintingPolicy(), Stream,
194 /*IncludeType*/ true);
195
196 for (unsigned I = 1; I < NumArgs; ++I) {
197 const TemplateArgument &Arg = TST->template_arguments()[I];
198 Stream << ", ";
199 Arg.print(Context->getPrintingPolicy(), Stream, /*IncludeType*/ true);
200 }
201 size_t BeginPos = VarStr.find_first_of('<');
202 size_t EndPos = VarStr.find_last_of('>');
203 TransAssert((BeginPos != std::string::npos) && "Cannot find < !");
204 TransAssert((EndPos != std::string::npos) && "Cannot find > !");
205 TransAssert((EndPos > BeginPos) && "Invalid <> pair!");
206 VarStr.replace(BeginPos + 1, (EndPos - BeginPos - 1), Stream.str());
207 }
208
209 void RemoveNestedFunction::getNewTmpVariable(const QualType &QT,
210 std::string &VarStr)
211 {
212 QT.getAsStringInternal(VarStr, Context->getPrintingPolicy());
213 }
214
215 void RemoveNestedFunction::getNewIntTmpVariable(std::string &VarStr)
216 {
217 VarStr = "int " + VarStr;
218 }
219
220 void RemoveNestedFunction::getNewAutoTmpVariable(std::string &VarStr)
221 {
222 VarStr = "auto " + VarStr;
223 }
224
225 void RemoveNestedFunction::addNewTmpVariable(ASTContext &ASTCtx)
226 {
227 std::string VarStr;
228
229 getNewTmpVariableStr(ASTCtx, VarStr);
230 if (TransformationManager::isCXXLangOpt()) {
231 // TheStmt and TheCallExpr may share the same start location, e.g..
232 // TheCallExpr is a CXXOperatorCallExpr. In this case, we just replace
233 // TheCallExpr with tmp variable's definition and the tmp variable.
234 // Otherwise, we would end up with assertion failure, because we
235 // modify the same location twice (through addnewAssignStmtBefore
236 // and replaceExpr.
237 if (TheStmt->getBeginLoc() == TheCallExpr->getBeginLoc()) {
238 std::string ExprStr;
239 RewriteHelper->getExprString(TheCallExpr, ExprStr);
240 VarStr += " = " + ExprStr + ";\n" + TmpVarName;
241 RewriteHelper->replaceExpr(TheCallExpr, VarStr);
242 return;
243 }
244 RewriteHelper->addNewAssignStmtBefore(TheStmt, VarStr,
245 TheCallExpr, NeedParen);
246 }
247 else {
248 RewriteHelper->addLocalVarToFunc(VarStr + ";", TheFuncDecl);
249 RewriteHelper->addNewAssignStmtBefore(TheStmt, getTmpVarName(),
250 TheCallExpr, NeedParen);
251 }
252 RewriteHelper->replaceExpr(TheCallExpr, TmpVarName);
253 }
254
255 void RemoveNestedFunction::getNewTmpVariableStr(ASTContext &ASTCtx,
256 std::string &VarStr)
257 {
258 std::stringstream SS;
259 unsigned int NamePostfix = NameQueryWrap->getMaxNamePostfix();
260
261 SS << RewriteHelper->getTmpVarNamePrefix() << (NamePostfix + 1);
262 VarStr = SS.str();
263 setTmpVarName(VarStr);
264
265 QualType QT;
266 const Expr *E = TheCallExpr->getCallee();
267
268 if (const UnresolvedLookupExpr *UE = dyn_cast<UnresolvedLookupExpr>(E)) {
269 // clang doesn't always resolve CallExpr's callee. For example:
270 // template<typename T> int foo1(int p) {return p;}
271 // template<typename T> int foo2(int p) {return p;}
272 // template<typename T>
273 // void bar(void) { foo1<T>(foo2<T>(1)); }
274 // foo2<T>(1) has BuiltinType and hence
275 // TheCallExpr->getCallReturnType() will segfault.
276 // In this case, we have to lookup a corresponding function decl
277
278 DeclarationName DName = UE->getName();
279 TransAssert(((DName.getNameKind() == DeclarationName::Identifier) ||
280 (DName.getNameKind() == DeclarationName::CXXOperatorName)) &&
281 "Not an indentifier!");
282 const FunctionDecl *FD = NULL;
283 if (const NestedNameSpecifier *NNS = UE->getQualifier()) {
284 if (const DeclContext *Ctx = getDeclContextFromSpecifier(NNS)) {
285 DeclContextSet VisitedCtxs;
286 FD = lookupFunctionDecl(DName, Ctx, VisitedCtxs);
287 }
288 }
289 if (!FD) {
290 DeclContextSet VisitedCtxs;
291 FD =
292 lookupFunctionDecl(DName, TheFuncDecl->getLookupParent(), VisitedCtxs);
293 }
294 // give up and generate a tmp var of int type, e.g.:
295 // template <class T> struct S {
296 // T x;
297 // template <class A> void foo(A &a0) { x(y(a0)); }
298 // };
299 if (!FD)
300 return getNewIntTmpVariable(VarStr);
301
302 QT = FD->getReturnType();
303 //FIXME: This is actually not quite correct, we should get the instantiated
304 // type here.
305 return getNewTmpVariable(QT, VarStr);
306 }
307
308 if (const UnresolvedMemberExpr *UM = dyn_cast<UnresolvedMemberExpr>(E)) {
309 DeclarationName DName = UM->getMemberName();
310 const CXXRecordDecl *CXXRD = UM->getNamingClass();
311 DeclContextSet VisitedCtxs;
312 const FunctionDecl *FD = lookupFunctionDecl(DName, CXXRD, VisitedCtxs);
313 // FIXME: try to resolve FD here
314 if (FD)
315 QT = FD->getReturnType();
316 return getNewTmpVariable(QT, VarStr);
317 }
318
319 if (const CXXTemporaryObjectExpr *CXXTE =
320 dyn_cast<CXXTemporaryObjectExpr>(E)) {
321 const CXXConstructorDecl *CXXCtor = CXXTE->getConstructor();
322 QT = CXXCtor->getThisType();
323 return getNewTmpVariable(QT, VarStr);
324 }
325
326 if (const CXXTemporaryObjectExpr *CXXTE =
327 dyn_cast<CXXTemporaryObjectExpr>(E)) {
328 const CXXConstructorDecl *CXXCtor = CXXTE->getConstructor();
329 QT = CXXCtor->getThisType();
330 return getNewTmpVariable(QT, VarStr);
331 }
332
333 if (const CXXDependentScopeMemberExpr *ME =
334 dyn_cast<CXXDependentScopeMemberExpr>(E)) {
335
336 if (ME->isImplicitAccess())
337 return;
338 DeclarationName DName = ME->getMember();
339 TransAssert((DName.getNameKind() == DeclarationName::Identifier) &&
340 "Not an indentifier!");
341 const Expr *E = ME->getBase();
342 TransAssert(E && "NULL Base Expr!");
343 const Expr *BaseE = E->IgnoreParens();
344
345 // handle cases where base expr or member name is dependent, e.g.,
346 // template<typename T>
347 // class S {
348 // int f1(int p1) { return p1; };
349 // int f2(int p2) { return p2; };
350 // void f3(void);
351 // };
352 // template<typename T>
353 // void S<T>::f3(void)
354 // {
355 // f1(this->f2(1));
356 // }
357 // where this->f2(1) is a CXXDependentScopeMemberExpr
358 if (dyn_cast<CXXThisExpr>(BaseE)) {
359 const DeclContext *Ctx = TheFuncDecl->getLookupParent();
360 TransAssert(Ctx && "Bad DeclContext!");
361 DeclContextSet VisitedCtxs;
362 const FunctionDecl *FD = lookupFunctionDecl(DName, Ctx, VisitedCtxs);
363 TransAssert(FD && "Cannot resolve DName!");
364 QT = FD->getReturnType();
365 return getNewTmpVariable(QT, VarStr);
366 }
367
368 // handle other cases where lookupDeclContext is different from
369 // the current CXXRecord, e.g.,
370 const Type *Ty = ME->getBaseType().getTypePtr();
371 if (const DeclContext *Ctx = getBaseDeclFromType(Ty)) {
372 DeclContextSet VisitedCtxs;
373 const FunctionDecl *FD = lookupFunctionDecl(DName, Ctx, VisitedCtxs);
374 if (!FD) {
375 return getNewTmpVariable(QT, VarStr);
376 }
377 QT = FD->getReturnType();
378 const Type *RVTy = QT.getTypePtr();
379 if (RVTy->getAs<InjectedClassNameType>()) {
380 // handle cases like:
381 // template <typename> struct D {
382 // D f();
383 // };
384 // template <typename T> void foo(D<T>);
385 // template <typename T > void bar () {
386 // D<T> G;
387 // foo(G.f());
388 // }
389 // in this case, seems it's hard to retrieve the instantiated type
390 // of f's return type, because `D<T> G' is dependent. I tried
391 // findSpecialization from ClassTemplateDecl, but it didn't work.
392 // So use a really ugly way, i.e., manipulating strings...
393 const TemplateSpecializationType *TST =
394 Ty->getAs<TemplateSpecializationType>();
395 TransAssert(TST && "Invalid TemplateSpecialization Type!");
396
397 QT.getAsStringInternal(VarStr,
398 Context->getPrintingPolicy());
399 return getVarStrForTemplateSpecialization(VarStr, TST);
400 }
401 else {
402 // other cases:
403 // template <typename> struct D {
404 // int f();
405 // };
406 // void foo(int);
407 // template <typename T > void bar () {
408 // D<T> G;
409 // foo(G.f());
410 // }
411 return getNewTmpVariable(QT, VarStr);
412 }
413 }
414 else {
415 // template <typename> struct D {
416 // D f();
417 // D operator[] (int);
418 // };
419 // template <typename T> void foo(D<T>);
420 // template <typename T > void bar () {
421 // D<T> G;
422 // foo(G[0].f());
423 // }
424 // In this case, G[0] is of BuiltinType.
425 // But why does clang represent a dependent type as BuiltinType here?
426
427 TransAssert((Ty->getAs<BuiltinType>() ||
428 Ty->getAs<TemplateTypeParmType>() ||
429 Ty->getAs<TypedefType>() ||
430 Ty->getAs<DependentNameType>())
431 && "Uncaught Type");
432 // FIXME: This is incorrect!
433 // a couple of questions
434 // - how can we find a correct DeclContext where we could lookup f?
435 // - can we obtain the dependent template argument from BuiltinType?
436 // Probably we cannot do these? Comments from lib/AST/ASTContext.cpp:
437 //
438 // Placeholder type for type-dependent expressions whose type is
439 // completely unknown. No code should ever check a type against
440 // DependentTy and users should never see it; however, it is here to
441 // help diagnose failures to properly check for type-dependent
442 // expressions.
443 return getNewIntTmpVariable(VarStr);
444 }
445 }
446
447 // We can't resolve dependent scoped DeclRefExpr, and just make it
448 // type of int.
449 if (dyn_cast<DependentScopeDeclRefExpr>(E)) {
450 return getNewAutoTmpVariable(VarStr);
451 }
452
453 const Type *CalleeType = E->getType().getTypePtr();
454 // template <class T1, class T2> struct S {
455 // T1 x; T2 y;
456 // template <class A> void foo(A &a0) { x(y(a0)); }
457 // };
458 if (const TemplateTypeParmType *PT =
459 dyn_cast<TemplateTypeParmType>(CalleeType)) {
460 const TemplateTypeParmDecl *PD = PT->getDecl();
461 std::string DStr = PD->getNameAsString();
462 VarStr = DStr + " " + VarStr;
463 return;
464 }
465
466 if (const AutoType *AT =
467 dyn_cast<AutoType>(CalleeType)) {
468 VarStr = "auto " + VarStr;
469 return;
470 }
471
472 QT = TheCallExpr->getCallReturnType(ASTCtx);
473 getNewTmpVariable(
474 QT.getTypePtr()->getUnqualifiedDesugaredType()->getCanonicalTypeInternal(),
475 VarStr);
476 }
477
478 bool RemoveNestedFunction::isInvalidOperator(const CXXOperatorCallExpr *OpE)
479 {
480 OverloadedOperatorKind K = OpE->getOperator();
481 // ISSUE: overloaded Equal-family operators cause bad recursion,
482 // omit it for now.
483 switch (K) {
484 case OO_Equal:
485 case OO_EqualEqual:
486 case OO_PlusEqual:
487 case OO_MinusEqual:
488 case OO_StarEqual:
489 case OO_SlashEqual:
490 case OO_PercentEqual:
491 case OO_CaretEqual:
492 case OO_AmpEqual:
493 case OO_PipeEqual:
494 case OO_LessLessEqual:
495 case OO_GreaterGreaterEqual:
496 case OO_ExclaimEqual:
497 case OO_LessEqual:
498 case OO_LessLess:
499 case OO_GreaterEqual: // Fall-through
500 return true;
501 default:
502 return false;
503 }
504 }
505
506 RemoveNestedFunction::~RemoveNestedFunction(void)
507 {
508 delete NestedInvocationVisitor;
509 delete StmtVisitor;
510 delete NameQueryWrap;
511 }
512