1 //===--- AMDGPUPropagateAttributes.cpp --------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 /// \brief This pass propagates attributes from kernels to the non-entry
11 /// functions. Most of the library functions were not compiled for specific ABI,
12 /// yet will be correctly compiled if proper attributes are propagated from the
15 /// The pass analyzes call graph and propagates ABI target features through the
18 /// It can run in two modes: as a function or module pass. A function pass
19 /// simply propagates attributes. A module pass clones functions if there are
20 /// callers with different ABI. If a function is cloned all call sites will
21 /// be updated to use a correct clone.
23 /// A function pass is limited in functionality but can run early in the
24 /// pipeline. A module pass is more powerful but has to run late, so misses
25 /// library folding opportunities.
27 //===----------------------------------------------------------------------===//
30 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
31 #include "Utils/AMDGPUBaseInfo.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "llvm/CodeGen/TargetSubtargetInfo.h"
35 #include "llvm/IR/InstrTypes.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
39 #define DEBUG_TYPE "amdgpu-propagate-attributes"
44 extern const SubtargetFeatureKV AMDGPUFeatureKV[AMDGPU::NumSubtargetFeatures-1];
49 // Target features to propagate.
50 static constexpr const FeatureBitset TargetFeatures = {
51 AMDGPU::FeatureWavefrontSize16,
52 AMDGPU::FeatureWavefrontSize32,
53 AMDGPU::FeatureWavefrontSize64
56 // Attributes to propagate.
57 // TODO: Support conservative min/max merging instead of cloning.
58 static constexpr const char *AttributeNames[] = {"amdgpu-waves-per-eu"};
60 static constexpr unsigned NumAttr = std::size(AttributeNames);
62 class AMDGPUPropagateAttributes {
66 explicit FnProperties(const FeatureBitset &&FB) : Features(FB) {}
69 explicit FnProperties(const TargetMachine &TM, const Function &F) {
70 Features = TM.getSubtargetImpl(F)->getFeatureBits();
72 for (unsigned I = 0; I < NumAttr; ++I)
73 if (F.hasFnAttribute(AttributeNames[I]))
74 Attributes[I] = F.getFnAttribute(AttributeNames[I]);
77 bool operator == (const FnProperties &Other) const {
78 if ((Features & TargetFeatures) != (Other.Features & TargetFeatures))
80 for (unsigned I = 0; I < NumAttr; ++I)
81 if (Attributes[I] != Other.Attributes[I])
86 FnProperties adjustToCaller(const FnProperties &CallerProps) const {
87 FnProperties New((Features & ~TargetFeatures) | CallerProps.Features);
88 for (unsigned I = 0; I < NumAttr; ++I)
89 New.Attributes[I] = CallerProps.Attributes[I];
93 FeatureBitset Features;
94 std::optional<Attribute> Attributes[NumAttr];
99 Clone(const FnProperties &Props, Function *OrigF, Function *NewF) :
100 Properties(Props), OrigF(OrigF), NewF(NewF) {}
102 FnProperties Properties;
107 const TargetMachine *TM;
109 // Clone functions as needed or just set attributes.
112 // Option propagation roots.
113 SmallSet<Function *, 32> Roots;
115 // Clones of functions with their attributes.
116 SmallVector<Clone, 32> Clones;
118 // Find a clone with required features.
119 Function *findFunction(const FnProperties &PropsNeeded,
122 // Clone function \p F and set \p NewProps on the clone.
123 // Cole takes the name of original function.
124 Function *cloneWithProperties(Function &F, const FnProperties &NewProps);
126 // Set new function's features in place.
127 void setFeatures(Function &F, const FeatureBitset &NewFeatures);
129 // Set new function's attributes in place.
130 void setAttributes(Function &F,
131 const ArrayRef<std::optional<Attribute>> NewAttrs);
133 std::string getFeatureString(const FeatureBitset &Features) const;
135 // Propagate attributes from Roots.
139 AMDGPUPropagateAttributes(const TargetMachine *TM, bool AllowClone) :
140 TM(TM), AllowClone(AllowClone) {}
142 // Use F as a root and propagate its attributes.
143 bool process(Function &F);
145 // Propagate attributes starting from kernel functions.
146 bool process(Module &M);
149 // Allows to propagate attributes early, but no cloning is allowed as it must
150 // be a function pass to run before any optimizations.
151 // TODO: We shall only need a one instance of module pass, but that needs to be
152 // in the linker pipeline which is currently not possible.
153 class AMDGPUPropagateAttributesEarly : public FunctionPass {
154 const TargetMachine *TM;
157 static char ID; // Pass identification
159 AMDGPUPropagateAttributesEarly(const TargetMachine *TM = nullptr) :
160 FunctionPass(ID), TM(TM) {
161 initializeAMDGPUPropagateAttributesEarlyPass(
162 *PassRegistry::getPassRegistry());
165 bool runOnFunction(Function &F) override;
168 // Allows to propagate attributes with cloning but does that late in the
170 class AMDGPUPropagateAttributesLate : public ModulePass {
171 const TargetMachine *TM;
174 static char ID; // Pass identification
176 AMDGPUPropagateAttributesLate(const TargetMachine *TM = nullptr) :
177 ModulePass(ID), TM(TM) {
178 initializeAMDGPUPropagateAttributesLatePass(
179 *PassRegistry::getPassRegistry());
182 bool runOnModule(Module &M) override;
185 } // end anonymous namespace.
187 char AMDGPUPropagateAttributesEarly::ID = 0;
188 char AMDGPUPropagateAttributesLate::ID = 0;
190 INITIALIZE_PASS(AMDGPUPropagateAttributesEarly,
191 "amdgpu-propagate-attributes-early",
192 "Early propagate attributes from kernels to functions",
194 INITIALIZE_PASS(AMDGPUPropagateAttributesLate,
195 "amdgpu-propagate-attributes-late",
196 "Late propagate attributes from kernels to functions",
200 AMDGPUPropagateAttributes::findFunction(const FnProperties &PropsNeeded,
202 // TODO: search for clone's clones.
203 for (Clone &C : Clones)
204 if (C.OrigF == OrigF && PropsNeeded == C.Properties)
210 bool AMDGPUPropagateAttributes::process(Module &M) {
211 for (auto &F : M.functions())
212 if (AMDGPU::isKernel(F.getCallingConv()))
215 return Roots.empty() ? false : process();
218 bool AMDGPUPropagateAttributes::process(Function &F) {
223 bool AMDGPUPropagateAttributes::process() {
224 bool Changed = false;
225 SmallSet<Function *, 32> NewRoots;
226 SmallSet<Function *, 32> Replaced;
228 assert(!Roots.empty());
229 Module &M = *(*Roots.begin())->getParent();
232 Roots.insert(NewRoots.begin(), NewRoots.end());
235 for (auto &F : M.functions()) {
236 if (F.isDeclaration())
239 const FnProperties CalleeProps(*TM, F);
240 SmallVector<std::pair<CallBase *, Function *>, 32> ToReplace;
241 SmallSet<CallBase *, 32> Visited;
243 for (User *U : F.users()) {
244 Instruction *I = dyn_cast<Instruction>(U);
247 CallBase *CI = dyn_cast<CallBase>(I);
248 // Only propagate attributes if F is the called function. Specifically,
249 // do not propagate attributes if F is passed as an argument.
250 // FIXME: handle bitcasted callee, e.g.
251 // %retval = call i8* bitcast (i32* ()* @f to i8* ()*)()
252 if (!CI || CI->getCalledOperand() != &F)
254 Function *Caller = CI->getCaller();
255 if (!Caller || !Visited.insert(CI).second)
257 if (!Roots.count(Caller) && !NewRoots.count(Caller))
260 const FnProperties CallerProps(*TM, *Caller);
262 if (CalleeProps == CallerProps) {
263 if (!Roots.count(&F))
268 Function *NewF = findFunction(CallerProps, &F);
270 const FnProperties NewProps = CalleeProps.adjustToCaller(CallerProps);
272 // This may set different features on different iterations if
273 // there is a contradiction in callers' attributes. In this case
274 // we rely on a second pass running on Module, which is allowed
276 setFeatures(F, NewProps.Features);
277 setAttributes(F, NewProps.Attributes);
283 NewF = cloneWithProperties(F, NewProps);
284 Clones.push_back(Clone(CallerProps, &F, NewF));
285 NewRoots.insert(NewF);
288 ToReplace.push_back(std::pair(CI, NewF));
294 while (!ToReplace.empty()) {
295 auto R = ToReplace.pop_back_val();
296 R.first->setCalledFunction(R.second);
299 } while (!NewRoots.empty());
301 for (Function *F : Replaced) {
303 F->eraseFromParent();
313 AMDGPUPropagateAttributes::cloneWithProperties(Function &F,
314 const FnProperties &NewProps) {
315 LLVM_DEBUG(dbgs() << "Cloning " << F.getName() << '\n');
317 ValueToValueMapTy dummy;
318 Function *NewF = CloneFunction(&F, dummy);
319 setFeatures(*NewF, NewProps.Features);
320 setAttributes(*NewF, NewProps.Attributes);
321 NewF->setVisibility(GlobalValue::DefaultVisibility);
322 NewF->setLinkage(GlobalValue::InternalLinkage);
324 // Swap names. If that is the only clone it will retain the name of now
325 // dead value. Preserve original name for externally visible functions.
326 if (F.hasName() && F.hasLocalLinkage()) {
327 std::string NewName = std::string(NewF->getName());
335 void AMDGPUPropagateAttributes::setFeatures(Function &F,
336 const FeatureBitset &NewFeatures) {
337 std::string NewFeatureStr = getFeatureString(NewFeatures);
339 LLVM_DEBUG(dbgs() << "Set features "
340 << getFeatureString(NewFeatures & TargetFeatures)
341 << " on " << F.getName() << '\n');
343 F.removeFnAttr("target-features");
344 F.addFnAttr("target-features", NewFeatureStr);
347 void AMDGPUPropagateAttributes::setAttributes(
348 Function &F, const ArrayRef<std::optional<Attribute>> NewAttrs) {
349 LLVM_DEBUG(dbgs() << "Set attributes on " << F.getName() << ":\n");
350 for (unsigned I = 0; I < NumAttr; ++I) {
351 F.removeFnAttr(AttributeNames[I]);
353 LLVM_DEBUG(dbgs() << '\t' << NewAttrs[I]->getAsString() << '\n');
354 F.addFnAttr(*NewAttrs[I]);
360 AMDGPUPropagateAttributes::getFeatureString(const FeatureBitset &Features) const
363 for (const SubtargetFeatureKV &KV : AMDGPUFeatureKV) {
364 if (Features[KV.Value])
365 Ret += (StringRef("+") + KV.Key + ",").str();
366 else if (TargetFeatures[KV.Value])
367 Ret += (StringRef("-") + KV.Key + ",").str();
369 Ret.pop_back(); // Remove last comma.
373 bool AMDGPUPropagateAttributesEarly::runOnFunction(Function &F) {
375 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
379 TM = &TPC->getTM<TargetMachine>();
382 if (!AMDGPU::isKernel(F.getCallingConv()))
385 return AMDGPUPropagateAttributes(TM, false).process(F);
388 bool AMDGPUPropagateAttributesLate::runOnModule(Module &M) {
390 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
394 TM = &TPC->getTM<TargetMachine>();
397 return AMDGPUPropagateAttributes(TM, true).process(M);
401 *llvm::createAMDGPUPropagateAttributesEarlyPass(const TargetMachine *TM) {
402 return new AMDGPUPropagateAttributesEarly(TM);
406 *llvm::createAMDGPUPropagateAttributesLatePass(const TargetMachine *TM) {
407 return new AMDGPUPropagateAttributesLate(TM);
411 AMDGPUPropagateAttributesEarlyPass::run(Function &F,
412 FunctionAnalysisManager &AM) {
413 if (!AMDGPU::isEntryFunctionCC(F.getCallingConv()))
414 return PreservedAnalyses::all();
416 return AMDGPUPropagateAttributes(&TM, false).process(F)
417 ? PreservedAnalyses::none()
418 : PreservedAnalyses::all();
422 AMDGPUPropagateAttributesLatePass::run(Module &M, ModuleAnalysisManager &AM) {
423 return AMDGPUPropagateAttributes(&TM, true).process(M)
424 ? PreservedAnalyses::none()
425 : PreservedAnalyses::all();