1 //===- SymbolRewriter.cpp - Symbol Rewriter ---------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // SymbolRewriter is a LLVM pass which can rewrite symbols transparently within
11 // existing code. It is implemented as a compiler pass and is configured via a
12 // YAML configuration file.
14 // The YAML configuration file format is as follows:
16 // RewriteMapFile := RewriteDescriptors
17 // RewriteDescriptors := RewriteDescriptor | RewriteDescriptors
18 // RewriteDescriptor := RewriteDescriptorType ':' '{' RewriteDescriptorFields '}'
19 // RewriteDescriptorFields := RewriteDescriptorField | RewriteDescriptorFields
20 // RewriteDescriptorField := FieldIdentifier ':' FieldValue ','
21 // RewriteDescriptorType := Identifier
22 // FieldIdentifier := Identifier
23 // FieldValue := Identifier
24 // Identifier := [0-9a-zA-Z]+
26 // Currently, the following descriptor types are supported:
28 // - function: (function rewriting)
29 // + Source (original name of the function)
30 // + Target (explicit transformation)
31 // + Transform (pattern transformation)
32 // + Naked (boolean, whether the function is undecorated)
33 // - global variable: (external linkage global variable rewriting)
34 // + Source (original name of externally visible variable)
35 // + Target (explicit transformation)
36 // + Transform (pattern transformation)
37 // - global alias: (global alias rewriting)
38 // + Source (original name of the aliased name)
39 // + Target (explicit transformation)
40 // + Transform (pattern transformation)
42 // Note that source and exactly one of [Target, Transform] must be provided
44 // New rewrite descriptors can be created. Addding a new rewrite descriptor
47 // a) extended the rewrite descriptor kind enumeration
48 // (<anonymous>::RewriteDescriptor::RewriteDescriptorType)
49 // b) implementing the new descriptor
50 // (c.f. <anonymous>::ExplicitRewriteFunctionDescriptor)
51 // c) extending the rewrite map parser
52 // (<anonymous>::RewriteMapParser::parseEntry)
54 // Specify to rewrite the symbols using the `-rewrite-symbols` option, and
55 // specify the map file to use for the rewriting via the `-rewrite-map-file`
58 //===----------------------------------------------------------------------===//
60 #define DEBUG_TYPE "symbol-rewriter"
61 #include "llvm/CodeGen/Passes.h"
62 #include "llvm/Pass.h"
63 #include "llvm/PassManager.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/MemoryBuffer.h"
67 #include "llvm/Support/Regex.h"
68 #include "llvm/Support/SourceMgr.h"
69 #include "llvm/Support/YAMLParser.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
72 #include "llvm/Transforms/Utils/SymbolRewriter.h"
76 static cl::list<std::string> RewriteMapFiles("rewrite-map-file",
77 cl::desc("Symbol Rewrite Map"),
78 cl::value_desc("filename"));
81 namespace SymbolRewriter {
82 template <RewriteDescriptor::Type DT, typename ValueType,
83 ValueType *(llvm::Module::*Get)(StringRef) const>
84 class ExplicitRewriteDescriptor : public RewriteDescriptor {
86 const std::string Source;
87 const std::string Target;
89 ExplicitRewriteDescriptor(StringRef S, StringRef T, const bool Naked)
90 : RewriteDescriptor(DT), Source(Naked ? StringRef("\01" + S.str()) : S),
93 bool performOnModule(Module &M) override;
95 static bool classof(const RewriteDescriptor *RD) {
96 return RD->getType() == DT;
100 template <RewriteDescriptor::Type DT, typename ValueType,
101 ValueType *(llvm::Module::*Get)(StringRef) const>
102 bool ExplicitRewriteDescriptor<DT, ValueType, Get>::performOnModule(Module &M) {
103 bool Changed = false;
104 if (ValueType *S = (M.*Get)(Source)) {
105 if (Value *T = (M.*Get)(Target))
106 S->setValueName(T->getValueName());
114 template <RewriteDescriptor::Type DT, typename ValueType,
115 ValueType *(llvm::Module::*Get)(StringRef) const,
116 iterator_range<typename iplist<ValueType>::iterator>
117 (llvm::Module::*Iterator)()>
118 class PatternRewriteDescriptor : public RewriteDescriptor {
120 const std::string Pattern;
121 const std::string Transform;
123 PatternRewriteDescriptor(StringRef P, StringRef T)
124 : RewriteDescriptor(DT), Pattern(P), Transform(T) { }
126 bool performOnModule(Module &M) override;
128 static bool classof(const RewriteDescriptor *RD) {
129 return RD->getType() == DT;
133 template <RewriteDescriptor::Type DT, typename ValueType,
134 ValueType *(llvm::Module::*Get)(StringRef) const,
135 iterator_range<typename iplist<ValueType>::iterator>
136 (llvm::Module::*Iterator)()>
137 bool PatternRewriteDescriptor<DT, ValueType, Get, Iterator>::
138 performOnModule(Module &M) {
139 bool Changed = false;
140 for (auto &C : (M.*Iterator)()) {
143 std::string Name = Regex(Pattern).sub(Transform, C.getName(), &Error);
145 report_fatal_error("unable to transforn " + C.getName() + " in " +
146 M.getModuleIdentifier() + ": " + Error);
148 if (Value *V = (M.*Get)(Name))
149 C.setValueName(V->getValueName());
158 /// Represents a rewrite for an explicitly named (function) symbol. Both the
159 /// source function name and target function name of the transformation are
160 /// explicitly spelt out.
161 typedef ExplicitRewriteDescriptor<RewriteDescriptor::Type::Function,
162 llvm::Function, &llvm::Module::getFunction>
163 ExplicitRewriteFunctionDescriptor;
165 /// Represents a rewrite for an explicitly named (global variable) symbol. Both
166 /// the source variable name and target variable name are spelt out. This
167 /// applies only to module level variables.
168 typedef ExplicitRewriteDescriptor<RewriteDescriptor::Type::GlobalVariable,
169 llvm::GlobalVariable,
170 &llvm::Module::getGlobalVariable>
171 ExplicitRewriteGlobalVariableDescriptor;
173 /// Represents a rewrite for an explicitly named global alias. Both the source
174 /// and target name are explicitly spelt out.
175 typedef ExplicitRewriteDescriptor<RewriteDescriptor::Type::NamedAlias,
177 &llvm::Module::getNamedAlias>
178 ExplicitRewriteNamedAliasDescriptor;
180 /// Represents a rewrite for a regular expression based pattern for functions.
181 /// A pattern for the function name is provided and a transformation for that
182 /// pattern to determine the target function name create the rewrite rule.
183 typedef PatternRewriteDescriptor<RewriteDescriptor::Type::Function,
184 llvm::Function, &llvm::Module::getFunction,
185 &llvm::Module::functions>
186 PatternRewriteFunctionDescriptor;
188 /// Represents a rewrite for a global variable based upon a matching pattern.
189 /// Each global variable matching the provided pattern will be transformed as
190 /// described in the transformation pattern for the target. Applies only to
191 /// module level variables.
192 typedef PatternRewriteDescriptor<RewriteDescriptor::Type::GlobalVariable,
193 llvm::GlobalVariable,
194 &llvm::Module::getGlobalVariable,
195 &llvm::Module::globals>
196 PatternRewriteGlobalVariableDescriptor;
198 /// PatternRewriteNamedAliasDescriptor - represents a rewrite for global
199 /// aliases which match a given pattern. The provided transformation will be
200 /// applied to each of the matching names.
201 typedef PatternRewriteDescriptor<RewriteDescriptor::Type::NamedAlias,
203 &llvm::Module::getNamedAlias,
204 &llvm::Module::aliases>
205 PatternRewriteNamedAliasDescriptor;
207 bool RewriteMapParser::parse(const std::string &MapFile,
208 RewriteDescriptorList *DL) {
209 ErrorOr<std::unique_ptr<MemoryBuffer>> Mapping =
210 MemoryBuffer::getFile(MapFile);
213 report_fatal_error("unable to read rewrite map '" + MapFile + "': " +
214 Mapping.getError().message());
216 if (!parse(*Mapping, DL))
217 report_fatal_error("unable to parse rewrite map '" + MapFile + "'");
222 bool RewriteMapParser::parse(std::unique_ptr<MemoryBuffer> &MapFile,
223 RewriteDescriptorList *DL) {
225 yaml::Stream YS(MapFile->getBuffer(), SM);
227 for (auto &Document : YS) {
228 yaml::MappingNode *DescriptorList;
230 // ignore empty documents
231 if (isa<yaml::NullNode>(Document.getRoot()))
234 DescriptorList = dyn_cast<yaml::MappingNode>(Document.getRoot());
235 if (!DescriptorList) {
236 YS.printError(Document.getRoot(), "DescriptorList node must be a map");
240 for (auto &Descriptor : *DescriptorList)
241 if (!parseEntry(YS, Descriptor, DL))
248 bool RewriteMapParser::parseEntry(yaml::Stream &YS, yaml::KeyValueNode &Entry,
249 RewriteDescriptorList *DL) {
250 yaml::ScalarNode *Key;
251 yaml::MappingNode *Value;
252 SmallString<32> KeyStorage;
253 StringRef RewriteType;
255 Key = dyn_cast<yaml::ScalarNode>(Entry.getKey());
257 YS.printError(Entry.getKey(), "rewrite type must be a scalar");
261 Value = dyn_cast<yaml::MappingNode>(Entry.getValue());
263 YS.printError(Entry.getValue(), "rewrite descriptor must be a map");
267 RewriteType = Key->getValue(KeyStorage);
268 if (RewriteType.equals("function"))
269 return parseRewriteFunctionDescriptor(YS, Key, Value, DL);
270 else if (RewriteType.equals("global variable"))
271 return parseRewriteGlobalVariableDescriptor(YS, Key, Value, DL);
272 else if (RewriteType.equals("global alias"))
273 return parseRewriteGlobalAliasDescriptor(YS, Key, Value, DL);
275 YS.printError(Entry.getKey(), "unknown rewrite type");
279 bool RewriteMapParser::
280 parseRewriteFunctionDescriptor(yaml::Stream &YS, yaml::ScalarNode *K,
281 yaml::MappingNode *Descriptor,
282 RewriteDescriptorList *DL) {
286 std::string Transform;
288 for (auto &Field : *Descriptor) {
289 yaml::ScalarNode *Key;
290 yaml::ScalarNode *Value;
291 SmallString<32> KeyStorage;
292 SmallString<32> ValueStorage;
295 Key = dyn_cast<yaml::ScalarNode>(Field.getKey());
297 YS.printError(Field.getKey(), "descriptor key must be a scalar");
301 Value = dyn_cast<yaml::ScalarNode>(Field.getValue());
303 YS.printError(Field.getValue(), "descriptor value must be a scalar");
307 KeyValue = Key->getValue(KeyStorage);
308 if (KeyValue.equals("source")) {
311 Source = Value->getValue(ValueStorage);
312 if (!Regex(Source).isValid(Error)) {
313 YS.printError(Field.getKey(), "invalid regex: " + Error);
316 } else if (KeyValue.equals("target")) {
317 Target = Value->getValue(ValueStorage);
318 } else if (KeyValue.equals("transform")) {
319 Transform = Value->getValue(ValueStorage);
320 } else if (KeyValue.equals("naked")) {
321 std::string Undecorated;
323 Undecorated = Value->getValue(ValueStorage);
324 Naked = StringRef(Undecorated).lower() == "true" || Undecorated == "1";
326 YS.printError(Field.getKey(), "unknown key for function");
331 if (Transform.empty() == Target.empty()) {
332 YS.printError(Descriptor,
333 "exactly one of transform or target must be specified");
337 // TODO see if there is a more elegant solution to selecting the rewrite
340 DL->push_back(new ExplicitRewriteFunctionDescriptor(Source, Target, Naked));
342 DL->push_back(new PatternRewriteFunctionDescriptor(Source, Transform));
347 bool RewriteMapParser::
348 parseRewriteGlobalVariableDescriptor(yaml::Stream &YS, yaml::ScalarNode *K,
349 yaml::MappingNode *Descriptor,
350 RewriteDescriptorList *DL) {
353 std::string Transform;
355 for (auto &Field : *Descriptor) {
356 yaml::ScalarNode *Key;
357 yaml::ScalarNode *Value;
358 SmallString<32> KeyStorage;
359 SmallString<32> ValueStorage;
362 Key = dyn_cast<yaml::ScalarNode>(Field.getKey());
364 YS.printError(Field.getKey(), "descriptor Key must be a scalar");
368 Value = dyn_cast<yaml::ScalarNode>(Field.getValue());
370 YS.printError(Field.getValue(), "descriptor value must be a scalar");
374 KeyValue = Key->getValue(KeyStorage);
375 if (KeyValue.equals("source")) {
378 Source = Value->getValue(ValueStorage);
379 if (!Regex(Source).isValid(Error)) {
380 YS.printError(Field.getKey(), "invalid regex: " + Error);
383 } else if (KeyValue.equals("target")) {
384 Target = Value->getValue(ValueStorage);
385 } else if (KeyValue.equals("transform")) {
386 Transform = Value->getValue(ValueStorage);
388 YS.printError(Field.getKey(), "unknown Key for Global Variable");
393 if (Transform.empty() == Target.empty()) {
394 YS.printError(Descriptor,
395 "exactly one of transform or target must be specified");
400 DL->push_back(new ExplicitRewriteGlobalVariableDescriptor(Source, Target,
403 DL->push_back(new PatternRewriteGlobalVariableDescriptor(Source,
409 bool RewriteMapParser::
410 parseRewriteGlobalAliasDescriptor(yaml::Stream &YS, yaml::ScalarNode *K,
411 yaml::MappingNode *Descriptor,
412 RewriteDescriptorList *DL) {
415 std::string Transform;
417 for (auto &Field : *Descriptor) {
418 yaml::ScalarNode *Key;
419 yaml::ScalarNode *Value;
420 SmallString<32> KeyStorage;
421 SmallString<32> ValueStorage;
424 Key = dyn_cast<yaml::ScalarNode>(Field.getKey());
426 YS.printError(Field.getKey(), "descriptor key must be a scalar");
430 Value = dyn_cast<yaml::ScalarNode>(Field.getValue());
432 YS.printError(Field.getValue(), "descriptor value must be a scalar");
436 KeyValue = Key->getValue(KeyStorage);
437 if (KeyValue.equals("source")) {
440 Source = Value->getValue(ValueStorage);
441 if (!Regex(Source).isValid(Error)) {
442 YS.printError(Field.getKey(), "invalid regex: " + Error);
445 } else if (KeyValue.equals("target")) {
446 Target = Value->getValue(ValueStorage);
447 } else if (KeyValue.equals("transform")) {
448 Transform = Value->getValue(ValueStorage);
450 YS.printError(Field.getKey(), "unknown key for Global Alias");
455 if (Transform.empty() == Target.empty()) {
456 YS.printError(Descriptor,
457 "exactly one of transform or target must be specified");
462 DL->push_back(new ExplicitRewriteNamedAliasDescriptor(Source, Target,
465 DL->push_back(new PatternRewriteNamedAliasDescriptor(Source, Transform));
473 class RewriteSymbols : public ModulePass {
475 static char ID; // Pass identification, replacement for typeid
478 RewriteSymbols(SymbolRewriter::RewriteDescriptorList &DL);
480 bool runOnModule(Module &M) override;
483 void loadAndParseMapFiles();
485 SymbolRewriter::RewriteDescriptorList Descriptors;
488 char RewriteSymbols::ID = 0;
490 RewriteSymbols::RewriteSymbols() : ModulePass(ID) {
491 initializeRewriteSymbolsPass(*PassRegistry::getPassRegistry());
492 loadAndParseMapFiles();
495 RewriteSymbols::RewriteSymbols(SymbolRewriter::RewriteDescriptorList &DL)
497 Descriptors.splice(Descriptors.begin(), DL);
500 bool RewriteSymbols::runOnModule(Module &M) {
504 for (auto &Descriptor : Descriptors)
505 Changed |= Descriptor.performOnModule(M);
510 void RewriteSymbols::loadAndParseMapFiles() {
511 const std::vector<std::string> MapFiles(RewriteMapFiles);
512 SymbolRewriter::RewriteMapParser parser;
514 for (const auto &MapFile : MapFiles)
515 parser.parse(MapFile, &Descriptors);
519 INITIALIZE_PASS(RewriteSymbols, "rewrite-symbols", "Rewrite Symbols", false,
522 ModulePass *llvm::createRewriteSymbolsPass() { return new RewriteSymbols(); }
525 llvm::createRewriteSymbolsPass(SymbolRewriter::RewriteDescriptorList &DL) {
526 return new RewriteSymbols(DL);