| 1 | //===----------------------------------------------------------------------===// |
| 2 | // |
| 3 | // Copyright (c) 2012, 2013, 2014, 2015, 2016, 2017, 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 "ReplaceFunctionDefWithDecl.h" |
| 16 | |
| 17 | #include <cctype> |
| 18 | #include "clang/AST/RecursiveASTVisitor.h" |
| 19 | #include "clang/AST/ASTContext.h" |
| 20 | #include "clang/Basic/SourceManager.h" |
| 21 | |
| 22 | #include "TransformationManager.h" |
| 23 | |
| 24 | using namespace clang; |
| 25 | |
| 26 | static const char *DescriptionMsg = |
| 27 | "This pass replaces a function's definition with its declaration.\n"; |
| 28 | |
| 29 | static RegisterTransformation<ReplaceFunctionDefWithDecl> |
| 30 | Trans("replace-function-def-with-decl", DescriptionMsg); |
| 31 | |
| 32 | class ReplaceFunctionDefWithDeclCollectionVisitor : public |
| 33 | RecursiveASTVisitor<ReplaceFunctionDefWithDeclCollectionVisitor> { |
| 34 | public: |
| 35 | |
| 36 | explicit ReplaceFunctionDefWithDeclCollectionVisitor( |
| 37 | ReplaceFunctionDefWithDecl *Instance) |
| 38 | : ConsumerInstance(Instance) |
| 39 | { } |
| 40 | |
| 41 | bool VisitFunctionDecl(FunctionDecl *FD); |
| 42 | |
| 43 | private: |
| 44 | |
| 45 | ReplaceFunctionDefWithDecl *ConsumerInstance; |
| 46 | }; |
| 47 | |
| 48 | bool ReplaceFunctionDefWithDeclCollectionVisitor::VisitFunctionDecl( |
| 49 | FunctionDecl *FD) |
| 50 | { |
| 51 | if (ConsumerInstance->isInIncludedFile(FD)) |
| 52 | return true; |
| 53 | |
| 54 | if (FD->isThisDeclarationADefinition() && |
| 55 | FD->hasBody() && |
| 56 | !FD->isDeleted() && |
| 57 | !FD->isDefaulted()) { |
| 58 | ConsumerInstance->addOneFunctionDef(FD); |
| 59 | } |
| 60 | return true; |
| 61 | } |
| 62 | |
| 63 | void ReplaceFunctionDefWithDecl::Initialize(ASTContext &context) |
| 64 | { |
| 65 | Transformation::Initialize(context); |
| 66 | CollectionVisitor = new ReplaceFunctionDefWithDeclCollectionVisitor(this); |
| 67 | } |
| 68 | |
| 69 | void ReplaceFunctionDefWithDecl::HandleTranslationUnit(ASTContext &Ctx) |
| 70 | { |
| 71 | CollectionVisitor->TraverseDecl(Ctx.getTranslationUnitDecl()); |
| 72 | |
| 73 | if (QueryInstanceOnly) |
| 74 | return; |
| 75 | |
| 76 | if (TransformationCounter > ValidInstanceNum) { |
| 77 | TransError = TransMaxInstanceError; |
| 78 | return; |
| 79 | } |
| 80 | if (ToCounter > ValidInstanceNum) { |
| 81 | TransError = TransToCounterTooBigError; |
| 82 | return; |
| 83 | } |
| 84 | |
| 85 | Ctx.getDiagnostics().setSuppressAllDiagnostics(false); |
| 86 | |
| 87 | doRewriting(); |
| 88 | |
| 89 | if (Ctx.getDiagnostics().hasErrorOccurred() || |
| 90 | Ctx.getDiagnostics().hasFatalErrorOccurred()) |
| 91 | TransError = TransInternalError; |
| 92 | } |
| 93 | |
| 94 | unsigned ReplaceFunctionDefWithDecl::getNumWrittenInitializers( |
| 95 | const CXXConstructorDecl *Ctor) |
| 96 | { |
| 97 | unsigned Num = 0; |
| 98 | for (CXXConstructorDecl::init_const_iterator I = Ctor->init_begin(), |
| 99 | E = Ctor->init_end(); I != E; ++I) { |
| 100 | const CXXCtorInitializer *Init = (*I); |
| 101 | if (Init->isWritten()) |
| 102 | Num++; |
| 103 | } |
| 104 | return Num; |
| 105 | } |
| 106 | |
| 107 | void ReplaceFunctionDefWithDecl::removeCtorInitializers( |
| 108 | const CXXConstructorDecl *Ctor) |
| 109 | { |
| 110 | if (!getNumWrittenInitializers(Ctor)) |
| 111 | return; |
| 112 | CXXConstructorDecl::init_const_iterator I = Ctor->init_begin(); |
| 113 | while (!(*I)->isWritten()) |
| 114 | ++I; |
| 115 | const CXXCtorInitializer *FirstInit = (*I); |
| 116 | SourceRange Range = FirstInit->getSourceRange(); |
| 117 | SourceLocation LocStart = Range.getBegin(); |
| 118 | // RewriteHelper->removeTextFromLeftAt(Range, ':', |
| 119 | // LocStart.getLocWithOffset(-1)); |
| 120 | // make sure we handle cases like: |
| 121 | // namespace NS { struct A {}; } |
| 122 | // struct B : NS::A { B() : NS::A() {} }; |
| 123 | SourceLocation Loc = RewriteHelper->getLocationFromLeftUntil(LocStart, ':'); |
| 124 | Loc = RewriteHelper->getLocationFromLeftUntil(Loc, ')'); |
| 125 | TheRewriter.RemoveText(SourceRange(Loc.getLocWithOffset(1), |
| 126 | LocStart.getLocWithOffset(-1))); |
| 127 | CXXConstructorDecl::init_const_iterator E = Ctor->init_end(); |
| 128 | --E; |
| 129 | while (!(*E)->isWritten()) |
| 130 | --E; |
| 131 | const CXXCtorInitializer *LastInit = (*E); |
| 132 | TransAssert(LastInit->isWritten() && "Init is not written!"); |
| 133 | SourceLocation LocEnd = LastInit->getSourceRange().getEnd(); |
| 134 | TheRewriter.RemoveText(SourceRange(LocStart, LocEnd)); |
| 135 | } |
| 136 | |
| 137 | bool ReplaceFunctionDefWithDecl::hasValidOuterLocStart( |
| 138 | const FunctionTemplateDecl *FTD, const FunctionDecl *FD) |
| 139 | { |
| 140 | SourceLocation FTDLocStart = FTD->getSourceRange().getBegin(); |
| 141 | SourceLocation FDLocStart = FD->getSourceRange().getBegin(); |
| 142 | const char *FTDStartPos = SrcManager->getCharacterData(FTDLocStart); |
| 143 | const char *FDStartPos = SrcManager->getCharacterData(FDLocStart); |
| 144 | return (FDStartPos < FTDStartPos); |
| 145 | } |
| 146 | |
| 147 | bool ReplaceFunctionDefWithDecl::removeOneInlineKeyword( |
| 148 | const std::string &LeadingInlineStr, |
| 149 | const std::string &InlineStr, |
| 150 | const std::string &Str, |
| 151 | const SourceLocation &StartLoc) |
| 152 | { |
| 153 | if (!Str.compare(0, LeadingInlineStr.length(), LeadingInlineStr)) { |
| 154 | TheRewriter.RemoveText(SourceRange( |
| 155 | StartLoc, |
| 156 | StartLoc.getLocWithOffset(LeadingInlineStr.length() - 1))); |
| 157 | return true; |
| 158 | } |
| 159 | |
| 160 | size_t Off = Str.find(InlineStr); |
| 161 | if (Off == std::string::npos) |
| 162 | return false; |
| 163 | |
| 164 | TheRewriter.RemoveText(SourceRange( |
| 165 | StartLoc.getLocWithOffset(Off), |
| 166 | StartLoc.getLocWithOffset(Off + InlineStr.length() - 1))); |
| 167 | return true; |
| 168 | } |
| 169 | |
| 170 | bool ReplaceFunctionDefWithDecl::removeInlineKeyword( |
| 171 | const std::string &InlineStr, |
| 172 | const std::string &Str, |
| 173 | const SourceLocation &StartLoc) |
| 174 | { |
| 175 | char Spaces[] = {' ', '\t', '\r', '\n'}; |
| 176 | unsigned Len = sizeof(Spaces) / sizeof(char); |
| 177 | for (unsigned I = 0; I < Len; ++I) { |
| 178 | std::string LeadingInlineStr = InlineStr + Spaces[I]; |
| 179 | for (unsigned J = 0; J < Len; ++J) { |
| 180 | for (unsigned K = 0; K < Len; ++K) { |
| 181 | std::string InlineStrVariant = Spaces[J] + InlineStr + Spaces[K]; |
| 182 | if (removeOneInlineKeyword(LeadingInlineStr, InlineStrVariant, |
| 183 | Str, StartLoc)) |
| 184 | return true; |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | return false; |
| 189 | } |
| 190 | |
| 191 | void ReplaceFunctionDefWithDecl::removeStringBeforeTypeIdentifier( |
| 192 | const SourceLocation &StartLoc, const SourceLocation &EndLoc) |
| 193 | { |
| 194 | const char *StartPos = SrcManager->getCharacterData(StartLoc); |
| 195 | const char *EndPos = SrcManager->getCharacterData(EndLoc); |
| 196 | // skip the first char of function's name |
| 197 | EndPos--; |
| 198 | while (isspace(*EndPos) && (EndPos != StartPos)) { |
| 199 | EndPos--; |
| 200 | } |
| 201 | assert((EndPos > StartPos) && "Invalid EndPos!"); |
| 202 | while (!isspace(*EndPos) && (EndPos != StartPos)) { |
| 203 | EndPos--; |
| 204 | } |
| 205 | EndPos++; |
| 206 | assert((EndPos != StartPos) && "Bad Type Location?"); |
| 207 | TheRewriter.RemoveText(StartLoc, EndPos - StartPos); |
| 208 | } |
| 209 | |
| 210 | void ReplaceFunctionDefWithDecl::removeInlineKeywordFromOneFunctionDecl( |
| 211 | const FunctionDecl *FD) |
| 212 | { |
| 213 | if (!FD->isInlineSpecified()) |
| 214 | return; |
| 215 | SourceLocation StartLoc = FD->getSourceRange().getBegin(); |
| 216 | SourceLocation EndLoc = FD->getLocation(); |
| 217 | std::string Str; |
| 218 | RewriteHelper->getStringBetweenLocs(Str, StartLoc, EndLoc); |
| 219 | if (removeInlineKeyword("inline", Str, StartLoc)) |
| 220 | return; |
| 221 | if (removeInlineKeyword("_inline", Str, StartLoc)) |
| 222 | return; |
| 223 | if (removeInlineKeyword("__inline", Str, StartLoc)) |
| 224 | return; |
| 225 | if (removeInlineKeyword("__forceinline", Str, StartLoc)) |
| 226 | return; |
| 227 | if (removeInlineKeyword("__inline__", Str, StartLoc)) |
| 228 | return; |
| 229 | // OK, just remove whatever appears before the type identifier... |
| 230 | // It's mainly for dealing with non-preprocessed code |
| 231 | removeStringBeforeTypeIdentifier(StartLoc, EndLoc); |
| 232 | } |
| 233 | |
| 234 | void ReplaceFunctionDefWithDecl::removeInlineKeywordFromFunctionDecls( |
| 235 | const FunctionDecl *FD) |
| 236 | { |
| 237 | if (!FD->isInlineSpecified()) |
| 238 | return; |
| 239 | |
| 240 | const FunctionDecl *FirstFD = FD->getCanonicalDecl(); |
| 241 | for (FunctionDecl::redecl_iterator I = FirstFD->redecls_begin(), |
| 242 | E = FirstFD->redecls_end(); I != E; ++I) { |
| 243 | removeInlineKeywordFromOneFunctionDecl(*I); |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | void ReplaceFunctionDefWithDecl::rewriteOneFunctionDef( |
| 248 | const FunctionDecl *FD) |
| 249 | { |
| 250 | const CXXMethodDecl *CXXMD = dyn_cast<CXXMethodDecl>(FD); |
| 251 | if (!CXXMD) { |
| 252 | RewriteHelper->replaceFunctionDefWithStr(FD, ";"); |
| 253 | // compiler warns about used-but-not-defined inlined specified function, |
| 254 | // so get rid of the inline keyword from FD's decls |
| 255 | removeInlineKeywordFromFunctionDecls(FD); |
| 256 | return; |
| 257 | } |
| 258 | |
| 259 | if (CXXMD->isOutOfLine()) { |
| 260 | // Not sure why, but FD->getOuterLocStart() doesn't work well for |
| 261 | // function template decl, e.g. for the code below: |
| 262 | // struct A { template<typename T> A(); }; |
| 263 | // template <typename T> A::A() {} |
| 264 | // FD->getOuterLocStart() returns the same LocStart as |
| 265 | // FD->getSourceRange().getBegin(), so we have to check if FD has |
| 266 | // described function template |
| 267 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { |
| 268 | // here is another ugly part, without this check, we couldn't remove |
| 269 | // "template <typename T> in the following code: |
| 270 | // template <typename T> struct S {template <typename T1> void foo();}; |
| 271 | // template<typename T> template<typename T1> void S<T>::foo() { } |
| 272 | if (!hasValidOuterLocStart(FTD, FD)) { |
| 273 | TheRewriter.RemoveText(FTD->getSourceRange()); |
| 274 | return; |
| 275 | } |
| 276 | } |
| 277 | SourceRange R = FD->getSourceRange(); |
| 278 | SourceLocation LocStart = R.getBegin(); |
| 279 | SourceLocation LocEnd = R.getEnd(); |
| 280 | if (LocStart.isMacroID()) { |
| 281 | LocStart = SrcManager->getFileLoc(LocStart); |
| 282 | } |
| 283 | TheRewriter.RemoveText(SourceRange(LocStart, LocEnd)); |
| 284 | return; |
| 285 | } |
| 286 | |
| 287 | if (const CXXConstructorDecl *Ctor = |
| 288 | dyn_cast<const CXXConstructorDecl>(FD)) { |
| 289 | removeCtorInitializers(Ctor); |
| 290 | } |
| 291 | RewriteHelper->replaceFunctionDefWithStr(FD, ";"); |
| 292 | removeInlineKeywordFromFunctionDecls(FD); |
| 293 | } |
| 294 | |
| 295 | void ReplaceFunctionDefWithDecl::doRewriting() |
| 296 | { |
| 297 | if (ToCounter <= 0) { |
| 298 | TransAssert(TheFunctionDef && "NULL TheFunctionDef!"); |
| 299 | rewriteOneFunctionDef(TheFunctionDef); |
| 300 | return; |
| 301 | } |
| 302 | |
| 303 | TransAssert((TransformationCounter <= |
| 304 | static_cast<int>(AllValidFunctionDefs.size())) && |
| 305 | "TransformationCounter is larger than the number of defs!"); |
| 306 | TransAssert((ToCounter <= static_cast<int>(AllValidFunctionDefs.size())) && |
| 307 | "ToCounter is larger than the number of defs!"); |
| 308 | // To cope with local struct definition defined inside a function |
| 309 | // to be replaced, e.g.: |
| 310 | // void foo(void) { { struct A { A() {} }; } } |
| 311 | // If we replace foo() {...} first, we will mess up when we try to |
| 312 | // replace A() {} because its text has gone already |
| 313 | for (int I = ToCounter; I >= TransformationCounter; --I) { |
| 314 | TransAssert((I >= 1) && "Invalid Index!"); |
| 315 | const FunctionDecl *FD = AllValidFunctionDefs[I-1]; |
| 316 | TransAssert(FD && "NULL FunctionDecl!"); |
| 317 | rewriteOneFunctionDef(FD); |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | void ReplaceFunctionDefWithDecl::addOneFunctionDef(const FunctionDecl *FD) |
| 322 | { |
| 323 | ValidInstanceNum++; |
| 324 | if (ToCounter > 0) { |
| 325 | AllValidFunctionDefs.push_back(FD); |
| 326 | return; |
| 327 | } |
| 328 | if (ValidInstanceNum == TransformationCounter) |
| 329 | TheFunctionDef = FD; |
| 330 | } |
| 331 | |
| 332 | ReplaceFunctionDefWithDecl::~ReplaceFunctionDefWithDecl() |
| 333 | { |
| 334 | delete CollectionVisitor; |
| 335 | } |
| 336 |