1//===- ForceFunctionAttrs.cpp - Force function attrs for debugging --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
10#include "llvm/IR/Function.h"
11#include "llvm/IR/Module.h"
12#include "llvm/Support/CommandLine.h"
13#include "llvm/Support/Debug.h"
14#include "llvm/Support/LineIterator.h"
15#include "llvm/Support/MemoryBuffer.h"
16#include "llvm/Support/raw_ostream.h"
17using namespace llvm;
18
19#define DEBUG_TYPE "forceattrs"
20
21static cl::list<std::string> ForceAttributes(
22 "force-attribute", cl::Hidden,
23 cl::desc(
24 "Add an attribute to a function. This can be a "
25 "pair of 'function-name:attribute-name', to apply an attribute to a "
26 "specific function. For "
27 "example -force-attribute=foo:noinline. Specifying only an attribute "
28 "will apply the attribute to every function in the module. This "
29 "option can be specified multiple times."));
30
31static cl::list<std::string> ForceRemoveAttributes(
32 "force-remove-attribute", cl::Hidden,
33 cl::desc("Remove an attribute from a function. This can be a "
34 "pair of 'function-name:attribute-name' to remove an attribute "
35 "from a specific function. For "
36 "example -force-remove-attribute=foo:noinline. Specifying only an "
37 "attribute will remove the attribute from all functions in the "
38 "module. This "
39 "option can be specified multiple times."));
40
41static cl::opt<std::string> CSVFilePath(
42 "forceattrs-csv-path", cl::Hidden,
43 cl::desc(
44 "Path to CSV file containing lines of function names and attributes to "
45 "add to them in the form of `f1,attr1` or `f2,attr2=str`."));
46
47static bool hasConflictingFnAttr(Attribute::AttrKind Kind, Function &F) {
48 if (Kind == Attribute::AlwaysInline)
49 return F.hasFnAttribute(Kind: Attribute::NoInline);
50 if (Kind == Attribute::NoInline)
51 return F.hasFnAttribute(Kind: Attribute::AlwaysInline);
52 return false;
53}
54
55/// If F has any forced attributes given on the command line, add them.
56/// If F has any forced remove attributes given on the command line, remove
57/// them. When both force and force-remove are given to a function, the latter
58/// takes precedence.
59static void forceAttributes(Function &F) {
60 auto ParseFunctionAndAttr = [&](StringRef S) {
61 StringRef AttributeText;
62 if (S.contains(C: ':')) {
63 auto KV = StringRef(S).split(Separator: ':');
64 if (KV.first != F.getName())
65 return Attribute::None;
66 AttributeText = KV.second;
67 } else {
68 AttributeText = S;
69 }
70 auto Kind = Attribute::getAttrKindFromName(AttrName: AttributeText);
71 if (Kind == Attribute::None || !Attribute::canUseAsFnAttr(Kind)) {
72 LLVM_DEBUG(dbgs() << "ForcedAttribute: " << AttributeText
73 << " unknown or not a function attribute!\n");
74 }
75 return Kind;
76 };
77
78 for (const auto &S : ForceAttributes) {
79 auto Kind = ParseFunctionAndAttr(S);
80 if (Kind == Attribute::None || F.hasFnAttribute(Kind) ||
81 hasConflictingFnAttr(Kind, F))
82 continue;
83 F.addFnAttr(Kind);
84 }
85
86 for (const auto &S : ForceRemoveAttributes) {
87 auto Kind = ParseFunctionAndAttr(S);
88 if (Kind == Attribute::None || !F.hasFnAttribute(Kind))
89 continue;
90 F.removeFnAttr(Kind);
91 }
92}
93
94static bool hasForceAttributes() {
95 return !ForceAttributes.empty() || !ForceRemoveAttributes.empty();
96}
97
98PreservedAnalyses ForceFunctionAttrsPass::run(Module &M,
99 ModuleAnalysisManager &) {
100 bool Changed = false;
101 if (!CSVFilePath.empty()) {
102 auto BufferOrError = MemoryBuffer::getFileOrSTDIN(Filename: CSVFilePath);
103 if (!BufferOrError) {
104 std::error_code EC = BufferOrError.getError();
105 M.getContext().emitError(ErrorStr: "cannot open CSV file: " + EC.message());
106 return PreservedAnalyses::all();
107 }
108
109 StringRef Buffer = BufferOrError.get()->getBuffer();
110 auto MemoryBuffer = MemoryBuffer::getMemBuffer(InputData: Buffer);
111 line_iterator It(*MemoryBuffer);
112 for (; !It.is_at_end(); ++It) {
113 auto SplitPair = It->split(Separator: ',');
114 if (SplitPair.second.empty())
115 continue;
116 Function *Func = M.getFunction(Name: SplitPair.first);
117 if (Func) {
118 if (Func->isDeclaration())
119 continue;
120 auto SecondSplitPair = SplitPair.second.split(Separator: '=');
121 if (!SecondSplitPair.second.empty()) {
122 Func->addFnAttr(Kind: SecondSplitPair.first, Val: SecondSplitPair.second);
123 Changed = true;
124 } else {
125 auto AttrKind = Attribute::getAttrKindFromName(AttrName: SplitPair.second);
126 if (AttrKind != Attribute::None &&
127 Attribute::canUseAsFnAttr(Kind: AttrKind) &&
128 !hasConflictingFnAttr(Kind: AttrKind, F&: *Func)) {
129 // TODO: There could be string attributes without a value, we should
130 // support those, too.
131 Func->addFnAttr(Kind: AttrKind);
132 Changed = true;
133 } else
134 errs() << "Cannot add " << SplitPair.second
135 << " as an attribute name.\n";
136 }
137 } else {
138 errs() << "Function in CSV file at line " << It.line_number()
139 << " does not exist.\n";
140 // TODO: `report_fatal_error at end of pass for missing functions.
141 continue;
142 }
143 }
144 }
145 if (hasForceAttributes()) {
146 for (Function &F : M.functions())
147 forceAttributes(F);
148 Changed = true;
149 }
150 // Just conservatively invalidate analyses if we've made any changes, this
151 // isn't likely to be important.
152 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
153}
154