LLVM  10.0.0
InjectTLIMappings.cpp
Go to the documentation of this file.
1 //===- InjectTLIMAppings.cpp - TLI to VFABI attribute injection ----------===//
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 // Populates the VFABI attribute with the scalar-to-vector mappings
10 // from the TargetLibraryInfo.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/Statistic.h"
17 #include "llvm/IR/InstIterator.h"
18 #include "llvm/Transforms/Utils.h"
20 
21 using namespace llvm;
22 
23 #define DEBUG_TYPE "inject-tli-mappings"
24 
25 STATISTIC(NumCallInjected,
26  "Number of calls in which the mappings have been injected.");
27 
28 STATISTIC(NumVFDeclAdded,
29  "Number of function declarations that have been added.");
30 STATISTIC(NumCompUsedAdded,
31  "Number of `@llvm.compiler.used` operands that have been added.");
32 
33 /// Helper function to map the TLI name to a strings that holds
34 /// scalar-to-vector mapping.
35 ///
36 /// _ZGV<isa><mask><vlen><vparams>_<scalarname>(<vectorname>)
37 ///
38 /// where:
39 ///
40 /// <isa> = "_LLVM_"
41 /// <mask> = "N". Note: TLI does not support masked interfaces.
42 /// <vlen> = Number of concurrent lanes, stored in the `VectorizationFactor`
43 /// field of the `VecDesc` struct.
44 /// <vparams> = "v", as many as are the number of parameters of CI.
45 /// <scalarname> = the name of the scalar function called by CI.
46 /// <vectorname> = the name of the vector function mapped by the TLI.
47 static std::string mangleTLIName(StringRef VectorName, const CallInst &CI,
48  unsigned VF) {
49  SmallString<256> Buffer;
50  llvm::raw_svector_ostream Out(Buffer);
51  Out << "_ZGV" << VFABI::_LLVM_ << "N" << VF;
52  for (unsigned I = 0; I < CI.getNumArgOperands(); ++I)
53  Out << "v";
54  Out << "_" << CI.getCalledFunction()->getName() << "(" << VectorName << ")";
55  return Out.str();
56 }
57 
58 /// A helper function for converting Scalar types to vector types.
59 /// If the incoming type is void, we return void. If the VF is 1, we return
60 /// the scalar type.
61 static Type *ToVectorTy(Type *Scalar, unsigned VF, bool isScalable = false) {
62  if (Scalar->isVoidTy() || VF == 1)
63  return Scalar;
64  return VectorType::get(Scalar, {VF, isScalable});
65 }
66 
67 /// A helper function that adds the vector function declaration that
68 /// vectorizes the CallInst CI with a vectorization factor of VF
69 /// lanes. The TLI assumes that all parameters and the return type of
70 /// CI (other than void) need to be widened to a VectorType of VF
71 /// lanes.
72 static void addVariantDeclaration(CallInst &CI, const unsigned VF,
73  const StringRef VFName) {
74  Module *M = CI.getModule();
75 
76  // Add function declaration.
77  Type *RetTy = ToVectorTy(CI.getType(), VF);
79  for (Value *ArgOperand : CI.arg_operands())
80  Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
81  assert(!CI.getFunctionType()->isVarArg() &&
82  "VarArg functions are not supported.");
83  FunctionType *FTy = FunctionType::get(RetTy, Tys, /*isVarArg=*/false);
84  Function *VectorF =
87  ++NumVFDeclAdded;
88  LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Added to the module: `" << VFName
89  << "` of type " << *(VectorF->getType()) << "\n");
90 
91  // Make function declaration (without a body) "sticky" in the IR by
92  // listing it in the @llvm.compiler.used intrinsic.
93  assert(!VectorF->size() && "VFABI attribute requires `@llvm.compiler.used` "
94  "only on declarations.");
95  appendToCompilerUsed(*M, {VectorF});
96  LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Adding `" << VFName
97  << "` to `@llvm.compiler.used`.\n");
98  ++NumCompUsedAdded;
99 }
100 
101 static void addMappingsFromTLI(const TargetLibraryInfo &TLI, CallInst &CI) {
102  // This is needed to make sure we don't query the TLI for calls to
103  // bitcast of function pointers, like `%call = call i32 (i32*, ...)
104  // bitcast (i32 (...)* @goo to i32 (i32*, ...)*)(i32* nonnull %i)`,
105  // as such calls make the `isFunctionVectorizable` raise an
106  // exception.
107  if (CI.isNoBuiltin() || !CI.getCalledFunction())
108  return;
109 
110  const std::string ScalarName = CI.getCalledFunction()->getName();
111  // Nothing to be done if the TLI thinks the function is not
112  // vectorizable.
113  if (!TLI.isFunctionVectorizable(ScalarName))
114  return;
116  VFABI::getVectorVariantNames(CI, Mappings);
117  Module *M = CI.getModule();
118  const SetVector<StringRef> OriginalSetOfMappings(Mappings.begin(),
119  Mappings.end());
120  // All VFs in the TLI are powers of 2.
121  for (unsigned VF = 2, WidestVF = TLI.getWidestVF(ScalarName); VF <= WidestVF;
122  VF *= 2) {
123  const std::string TLIName = TLI.getVectorizedFunction(ScalarName, VF);
124  if (!TLIName.empty()) {
125  std::string MangledName = mangleTLIName(TLIName, CI, VF);
126  if (!OriginalSetOfMappings.count(MangledName)) {
127  Mappings.push_back(MangledName);
128  ++NumCallInjected;
129  }
130  Function *VariantF = M->getFunction(TLIName);
131  if (!VariantF)
132  addVariantDeclaration(CI, VF, TLIName);
133  }
134  }
135 
136  VFABI::setVectorVariantNames(&CI, Mappings);
137 }
138 
139 static bool runImpl(const TargetLibraryInfo &TLI, Function &F) {
140  for (auto &I : instructions(F))
141  if (auto CI = dyn_cast<CallInst>(&I))
142  addMappingsFromTLI(TLI, *CI);
143  // Even if the pass adds IR attributes, the analyses are preserved.
144  return false;
145 }
146 
147 ////////////////////////////////////////////////////////////////////////////////
148 // New pass manager implementation.
149 ////////////////////////////////////////////////////////////////////////////////
153  runImpl(TLI, F);
154  // Even if the pass adds IR attributes, the analyses are preserved.
155  return PreservedAnalyses::all();
156 }
157 
158 ////////////////////////////////////////////////////////////////////////////////
159 // Legacy PM Implementation.
160 ////////////////////////////////////////////////////////////////////////////////
162  const TargetLibraryInfo &TLI =
163  getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
164  return runImpl(TLI, F);
165 }
166 
168  AU.setPreservesCFG();
171 }
172 
173 ////////////////////////////////////////////////////////////////////////////////
174 // Legacy Pass manager initialization
175 ////////////////////////////////////////////////////////////////////////////////
177 
179  "Inject TLI Mappings", false, false)
182  false, false)
183 
185  return new InjectTLIMappingsLegacy();
186 }
size_t size() const
Definition: Function.h:696
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.compiler.used list.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void getVectorVariantNames(const CallInst &CI, SmallVectorImpl< std::string > &VariantMappings)
Populates a set of strings representing the Vector Function ABI variants associated to the CallInst C...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:777
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
void push_back(const T &Elt)
Definition: SmallVector.h:211
This class represents a function call, abstracting a target machine&#39;s calling convention.
Inject TLI Mappings
static Type * ToVectorTy(Type *Scalar, unsigned VF, bool isScalable=false)
A helper function for converting Scalar types to vector types.
Externally visible function.
Definition: GlobalValue.h:48
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:543
STATISTIC(NumFunctions, "Total number of functions")
F(f)
static constexpr char const * _LLVM_
LLVM Internal VFABI ISA token for vector functions.
Definition: VectorUtils.h:133
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
#define DEBUG_TYPE
Class to represent function types.
Definition: DerivedTypes.h:108
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
bool isVarArg() const
Definition: DerivedTypes.h:128
iterator_range< User::op_iterator > arg_operands()
Definition: InstrTypes.h:1238
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:135
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Definition: InstrTypes.h:1647
static void addMappingsFromTLI(const TargetLibraryInfo &TLI, CallInst &CI)
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:515
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1149
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:282
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:301
FunctionPass * createInjectTLIMappingsLegacyPass()
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
bool isFunctionVectorizable(StringRef F, unsigned VF) const
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Provides information about what library functions are available for the current target.
static std::string mangleTLIName(StringRef VectorName, const CallInst &CI, unsigned VF)
Helper function to map the TLI name to a strings that holds scalar-to-vector mapping.
INITIALIZE_PASS_BEGIN(InjectTLIMappingsLegacy, DEBUG_TYPE, "Inject TLI Mappings", false, false) INITIALIZE_PASS_END(InjectTLIMappingsLegacy
StringRef str()
Return a StringRef for the vector contents.
Definition: raw_ostream.h:568
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
StringRef getVectorizedFunction(StringRef F, unsigned VF) const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:174
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
unsigned getNumArgOperands() const
Definition: InstrTypes.h:1244
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:614
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
Definition: InstrTypes.h:1305
#define I(x, y, z)
Definition: MD5.cpp:58
static void addVariantDeclaration(CallInst &CI, const unsigned VF, const StringRef VFName)
A helper function that adds the vector function declaration that vectorizes the CallInst CI with a ve...
Analysis pass providing the TargetLibraryInfo.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:74
A vector that has set insertion semantics.
Definition: SetVector.h:40
static bool runImpl(const TargetLibraryInfo &TLI, Function &F)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
inst_range instructions(Function *F)
Definition: InstIterator.h:133
A container for analyses that lazily runs them and caches their results.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
unsigned getWidestVF(StringRef ScalarF) const
Returns the largest vectorization factor used in the list of vector functions.
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:277
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void setVectorVariantNames(CallInst *CI, const SmallVector< std::string, 8 > &VariantMappings)
Overwrite the Vector Function ABI variants attribute with the names provide in VariantMappings.