LLVM 23.0.0git
ForceFunctionAttrs.cpp
Go to the documentation of this file.
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
10#include "llvm/IR/Function.h"
11#include "llvm/IR/Module.h"
13#include "llvm/Support/Debug.h"
17using namespace llvm;
18
19#define DEBUG_TYPE "forceattrs"
20
22 "force-attribute", cl::Hidden,
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
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
42 "forceattrs-csv-path", cl::Hidden,
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
48 switch (Kind) {
49 case Attribute::AlwaysInline:
50 return F.hasFnAttribute(Attribute::NoInline) ||
51 F.hasFnAttribute(Attribute::OptimizeNone);
52
53 case Attribute::NoInline:
54 return F.hasFnAttribute(Attribute::AlwaysInline);
55
56 case Attribute::OptimizeNone:
57 return F.hasFnAttribute(Attribute::AlwaysInline) ||
58 F.hasFnAttribute(Attribute::MinSize) ||
59 F.hasFnAttribute(Attribute::OptimizeForSize) ||
60 F.hasFnAttribute(Attribute::OptimizeForDebugging);
61
62 case Attribute::MinSize:
63 return F.hasFnAttribute(Attribute::OptimizeNone) ||
64 F.hasFnAttribute(Attribute::OptimizeForDebugging);
65
66 case Attribute::OptimizeForSize:
67 return F.hasFnAttribute(Attribute::OptimizeNone) ||
68 F.hasFnAttribute(Attribute::OptimizeForDebugging);
69
70 case Attribute::OptimizeForDebugging:
71 return F.hasFnAttribute(Attribute::OptimizeNone) ||
72 F.hasFnAttribute(Attribute::MinSize) ||
73 F.hasFnAttribute(Attribute::OptimizeForSize);
74
75 default:
76 return false;
77 }
78}
79
81 if (Kind == Attribute::OptimizeNone && !F.hasFnAttribute(Attribute::NoInline))
82 F.addFnAttr(Attribute::NoInline);
83}
84
86 if (Kind == Attribute::NoInline && F.hasFnAttribute(Attribute::OptimizeNone))
87 return true;
88 return false;
89}
90
91/// If F has any forced attributes given on the command line, add them.
92/// If F has any forced remove attributes given on the command line, remove
93/// them. When both force and force-remove are given to a function, the latter
94/// takes precedence.
95static void forceAttributes(Function &F) {
96 auto ParseFunctionAndAttr = [&](StringRef S) {
97 StringRef AttributeText;
98 if (S.contains(':')) {
99 auto KV = StringRef(S).split(':');
100 if (KV.first != F.getName())
101 return Attribute::None;
102 AttributeText = KV.second;
103 } else {
104 AttributeText = S;
105 }
106 auto Kind = Attribute::getAttrKindFromName(AttributeText);
107 if (Kind == Attribute::None || !Attribute::canUseAsFnAttr(Kind)) {
108 LLVM_DEBUG(dbgs() << "ForcedAttribute: " << AttributeText
109 << " unknown or not a function attribute!\n");
110 }
111 return Kind;
112 };
113
114 for (const auto &S : ForceAttributes) {
115 auto Kind = ParseFunctionAndAttr(S);
116 if (Kind == Attribute::None || F.hasFnAttribute(Kind) ||
117 hasConflictingFnAttr(Kind, F))
118 continue;
119 addRequiredFnAttrs(Kind, F);
120 F.addFnAttr(Kind);
121 }
122
123 for (const auto &S : ForceRemoveAttributes) {
124 auto Kind = ParseFunctionAndAttr(S);
125 if (Kind == Attribute::None || !F.hasFnAttribute(Kind) ||
127 continue;
128 F.removeFnAttr(Kind);
129 }
130}
131
132static bool hasForceAttributes() {
133 return !ForceAttributes.empty() || !ForceRemoveAttributes.empty();
134}
135
138 bool Changed = false;
139 if (!CSVFilePath.empty()) {
140 auto BufferOrError = MemoryBuffer::getFileOrSTDIN(CSVFilePath);
141 if (!BufferOrError) {
142 std::error_code EC = BufferOrError.getError();
143 M.getContext().emitError("cannot open CSV file: " + EC.message());
144 return PreservedAnalyses::all();
145 }
146
147 StringRef Buffer = BufferOrError.get()->getBuffer();
150 for (; !It.is_at_end(); ++It) {
151 auto SplitPair = It->split(',');
152 if (SplitPair.second.empty())
153 continue;
154 Function *Func = M.getFunction(SplitPair.first);
155 if (Func) {
156 if (Func->isDeclaration())
157 continue;
158 auto SecondSplitPair = SplitPair.second.split('=');
159 if (!SecondSplitPair.second.empty()) {
160 Func->addFnAttr(SecondSplitPair.first, SecondSplitPair.second);
161 Changed = true;
162 } else {
163 auto AttrKind = Attribute::getAttrKindFromName(SplitPair.second);
164 if (AttrKind != Attribute::None &&
165 Attribute::canUseAsFnAttr(AttrKind) &&
166 !hasConflictingFnAttr(AttrKind, *Func)) {
167 // TODO: There could be string attributes without a value, we should
168 // support those, too.
169 addRequiredFnAttrs(AttrKind, *Func);
170 Func->addFnAttr(AttrKind);
171 Changed = true;
172 } else
173 errs() << "Cannot add " << SplitPair.second
174 << " as an attribute name.\n";
175 }
176 } else {
177 errs() << "Function in CSV file at line " << It.line_number()
178 << " does not exist.\n";
179 // TODO: `report_fatal_error at end of pass for missing functions.
180 continue;
181 }
182 }
183 }
184 if (hasForceAttributes()) {
185 for (Function &F : M.functions())
187 Changed = true;
188 }
189 // Just conservatively invalidate analyses if we've made any changes, this
190 // isn't likely to be important.
192}
static void forceAttributes(Function &F)
If F has any forced attributes given on the command line, add them.
static bool wouldRemoveRequiredFnAttr(Attribute::AttrKind Kind, Function &F)
static bool hasConflictingFnAttr(Attribute::AttrKind Kind, Function &F)
static void addRequiredFnAttrs(Attribute::AttrKind Kind, Function &F)
static bool hasForceAttributes()
static cl::list< std::string > ForceAttributes("force-attribute", cl::Hidden, cl::desc("Add an attribute to a function. This can be a " "pair of 'function-name:attribute-name', to apply an attribute to a " "specific function. For " "example -force-attribute=foo:noinline. Specifying only an attribute " "will apply the attribute to every function in the module. This " "option can be specified multiple times."))
static cl::list< std::string > ForceRemoveAttributes("force-remove-attribute", cl::Hidden, cl::desc("Remove an attribute from a function. This can be a " "pair of 'function-name:attribute-name' to remove an attribute " "from a specific function. For " "example -force-remove-attribute=foo:noinline. Specifying only an " "attribute will remove the attribute from all functions in the " "module. This " "option can be specified multiple times."))
static cl::opt< std::string > CSVFilePath("forceattrs-csv-path", cl::Hidden, cl::desc("Path to CSV file containing lines of function names and attributes to " "add to them in the form of `f1,attr1` or `f2,attr2=str`."))
Super simple passes to force specific function attrs from the commandline into the IR for debugging p...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define LLVM_DEBUG(...)
Definition Debug.h:114
static LLVM_ABI Attribute::AttrKind getAttrKindFromName(StringRef AttrName)
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
@ None
No attributes have been set.
Definition Attributes.h:126
This interface provides simple read-only access to a block of memory, and provides simple methods for...
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
A forward iterator which reads text lines from a buffer.
int64_t line_number() const
Return the current line number. May return any number at EOF.
bool is_at_end() const
Return true if we're an "end" iterator or have reached EOF.
Changed
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)