clang 20.0.0git
TargetInfo.cpp
Go to the documentation of this file.
1//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
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// These classes wrap the information about a call or function
10// definition used to handle ABI compliancy.
11//
12//===----------------------------------------------------------------------===//
13
14#include "TargetInfo.h"
15#include "ABIInfo.h"
16#include "ABIInfoImpl.h"
17#include "CodeGenFunction.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/Type.h"
24#include "llvm/Support/raw_ostream.h"
25
26using namespace clang;
27using namespace CodeGen;
28
29LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
30 raw_ostream &OS = llvm::errs();
31 OS << "(ABIArgInfo Kind=";
32 switch (TheKind) {
33 case Direct:
34 OS << "Direct Type=";
35 if (llvm::Type *Ty = getCoerceToType())
36 Ty->print(OS);
37 else
38 OS << "null";
39 break;
40 case Extend:
41 OS << "Extend";
42 break;
43 case Ignore:
44 OS << "Ignore";
45 break;
46 case InAlloca:
47 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
48 break;
49 case Indirect:
50 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
51 << " ByVal=" << getIndirectByVal()
52 << " Realign=" << getIndirectRealign();
53 break;
54 case IndirectAliased:
55 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
56 << " AadrSpace=" << getIndirectAddrSpace()
57 << " Realign=" << getIndirectRealign();
58 break;
59 case Expand:
60 OS << "Expand";
61 break;
62 case CoerceAndExpand:
63 OS << "CoerceAndExpand Type=";
64 getCoerceAndExpandType()->print(OS);
65 break;
66 }
67 OS << ")\n";
68}
69
70TargetCodeGenInfo::TargetCodeGenInfo(std::unique_ptr<ABIInfo> Info)
71 : Info(std::move(Info)) {}
72
74
75// If someone can figure out a general rule for this, that would be great.
76// It's probably just doomed to be platform-dependent, though.
78 // Verified for:
79 // x86-64 FreeBSD, Linux, Darwin
80 // x86-32 FreeBSD, Linux, Darwin
81 // PowerPC Linux
82 // ARM Darwin (*not* EABI)
83 // AArch64 Linux
84 return 32;
85}
86
88 const FunctionNoProtoType *fnType) const {
89 // The following conventions are known to require this to be false:
90 // x86_stdcall
91 // MIPS
92 // For everything else, we just prefer false unless we opt out.
93 return false;
94}
95
96void
98 llvm::SmallString<24> &Opt) const {
99 // This assumes the user is passing a library name like "rt" instead of a
100 // filename like "librt.a/so", and that they don't care whether it's static or
101 // dynamic.
102 Opt = "-l";
103 Opt += Lib;
104}
105
107 // OpenCL kernels are called via an explicit runtime API with arguments
108 // set with clSetKernelArg(), not as normal sub-functions.
109 // Return SPIR_KERNEL by default as the kernel calling convention to
110 // ensure the fingerprint is fixed such way that each OpenCL argument
111 // gets one matching argument in the produced kernel function argument
112 // list to enable feasible implementation of clSetKernelArg() with
113 // aggregates etc. In case we would use the default C calling conv here,
114 // clSetKernelArg() might break depending on the target-specific
115 // conventions; different targets might split structs passed as values
116 // to multiple function arguments etc.
117 return llvm::CallingConv::SPIR_KERNEL;
118}
119
121 llvm::PointerType *T, QualType QT) const {
122 return llvm::ConstantPointerNull::get(T);
123}
124
126 const VarDecl *D) const {
127 assert(!CGM.getLangOpts().OpenCL &&
128 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
129 "Address space agnostic languages only");
130 return D ? D->getType().getAddressSpace() : LangAS::Default;
131}
132
134 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
135 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
136 // Since target may map different address spaces in AST to the same address
137 // space, an address space conversion may end up as a bitcast.
138 if (auto *C = dyn_cast<llvm::Constant>(Src))
139 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
140 // Try to preserve the source's name to make IR more readable.
141 return CGF.Builder.CreateAddrSpaceCast(
142 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
143}
144
145llvm::Constant *
147 LangAS SrcAddr, LangAS DestAddr,
148 llvm::Type *DestTy) const {
149 // Since target may map different address spaces in AST to the same address
150 // space, an address space conversion may end up as a bitcast.
151 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
152}
153
154llvm::SyncScope::ID
157 llvm::AtomicOrdering Ordering,
158 llvm::LLVMContext &Ctx) const {
159 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
160}
161
163 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
164 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
165 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
166 Fn->addFnAttr("stack-probe-size",
167 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
168 if (CGM.getCodeGenOpts().NoStackArgProbe)
169 Fn->addFnAttr("no-stack-arg-probe");
170 }
171}
172
173/// Create an OpenCL kernel for an enqueued block.
174///
175/// The kernel has the same function type as the block invoke function. Its
176/// name is the name of the block invoke function postfixed with "_kernel".
177/// It simply calls the block invoke function then returns.
179 CodeGenFunction &CGF, llvm::Function *Invoke, llvm::Type *BlockTy) const {
180 auto *InvokeFT = Invoke->getFunctionType();
181 auto &C = CGF.getLLVMContext();
182 std::string Name = Invoke->getName().str() + "_kernel";
183 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C),
184 InvokeFT->params(), false);
185 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
186 &CGF.CGM.getModule());
187 llvm::CallingConv::ID KernelCC =
189 F->setCallingConv(KernelCC);
190
191 llvm::AttrBuilder KernelAttrs(C);
192
193 // FIXME: This is missing setTargetAttributes
195 F->addFnAttrs(KernelAttrs);
196
197 auto IP = CGF.Builder.saveIP();
198 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
199 auto &Builder = CGF.Builder;
200 Builder.SetInsertPoint(BB);
201 llvm::SmallVector<llvm::Value *, 2> Args(llvm::make_pointer_range(F->args()));
202 llvm::CallInst *Call = Builder.CreateCall(Invoke, Args);
203 Call->setCallingConv(Invoke->getCallingConv());
204
205 Builder.CreateRetVoid();
206 Builder.restoreIP(IP);
207 return F;
208}
209
211 const TargetInfo::BranchProtectionInfo &BPI, llvm::Function &F) {
212 llvm::AttrBuilder FuncAttrs(F.getContext());
213 setBranchProtectionFnAttributes(BPI, FuncAttrs);
214 F.addFnAttrs(FuncAttrs);
215}
216
218 const TargetInfo::BranchProtectionInfo &BPI, llvm::AttrBuilder &FuncAttrs) {
220 FuncAttrs.addAttribute("sign-return-address", BPI.getSignReturnAddrStr());
221 FuncAttrs.addAttribute("sign-return-address-key", BPI.getSignKeyStr());
222 }
224 FuncAttrs.addAttribute("branch-target-enforcement");
226 FuncAttrs.addAttribute("branch-protection-pauth-lr");
227 if (BPI.GuardedControlStack)
228 FuncAttrs.addAttribute("guarded-control-stack");
229}
230
231namespace {
232class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
233public:
234 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
235 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
236};
237} // namespace
238
239std::unique_ptr<TargetCodeGenInfo>
241 return std::make_unique<DefaultTargetCodeGenInfo>(CGM.getTypes());
242}
const Decl * D
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
unsigned getInAllocaFieldIndex() const
llvm::StructType * getCoerceAndExpandType() const
unsigned getIndirectAddrSpace() const
@ Extend
Extend - Valid only for integer argument types.
@ Ignore
Ignore - Ignore the argument (treat as void).
@ IndirectAliased
IndirectAliased - Similar to Indirect, but the pointer may be to an object that is otherwise referenc...
@ Expand
Expand - Only valid for aggregate argument types.
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
@ CoerceAndExpand
CoerceAndExpand - Only valid for aggregate argument types.
@ Direct
Direct - Pass the argument directly using the normal converted LLVM type, or by coercing to another s...
llvm::Type * getCoerceToType() const
CharUnits getIndirectAlign() const
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition: CGBuilder.h:188
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:274
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
CodeGenTypes & getTypes() const
llvm::LLVMContext & getLLVMContext()
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
const LangOptions & getLangOpts() const
const CodeGenOptions & getCodeGenOpts() const
void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs)
Like the overload taking a Function &, but intended specifically for frontends that want to build on ...
Definition: CGCall.cpp:2161
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
Definition: CodeGenTypes.h:54
unsigned ClangCallConvToLLVMCallConv(CallingConv CC)
Convert clang calling convention to LLVM callilng convention.
Definition: CGCall.cpp:50
DefaultABIInfo - The default implementation for ABI specific details.
Definition: ABIInfoImpl.h:21
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
Definition: TargetInfo.h:47
virtual unsigned getSizeOfUnwindException() const
Determines the size of struct _Unwind_Exception on this platform, in 8-bit units.
Definition: TargetInfo.cpp:77
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
Definition: TargetInfo.cpp:97
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
virtual llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, SyncScope Scope, llvm::AtomicOrdering Ordering, llvm::LLVMContext &Ctx) const
Get the syncscope used in LLVM IR.
Definition: TargetInfo.cpp:155
static void setBranchProtectionFnAttributes(const TargetInfo::BranchProtectionInfo &BPI, llvm::Function &F)
Definition: TargetInfo.cpp:210
virtual unsigned getOpenCLKernelCallingConv() const
Get LLVM calling convention for OpenCL kernel.
Definition: TargetInfo.cpp:106
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA.
Definition: TargetInfo.cpp:125
void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const
Definition: TargetInfo.cpp:162
virtual llvm::Constant * getNullPointer(const CodeGen::CodeGenModule &CGM, llvm::PointerType *T, QualType QT) const
Get target specific null pointer.
Definition: TargetInfo.cpp:120
TargetCodeGenInfo(std::unique_ptr< ABIInfo > Info)
Definition: TargetInfo.cpp:70
virtual llvm::Value * createEnqueuedBlockKernel(CodeGenFunction &CGF, llvm::Function *BlockInvokeFunc, llvm::Type *BlockTy) const
Create an OpenCL kernel for an enqueued block.
Definition: TargetInfo.cpp:178
virtual bool isNoProtoCallVariadic(const CodeGen::CallArgList &args, const FunctionNoProtoType *fnType) const
Determine whether a call to an unprototyped functions under the given calling convention should use t...
Definition: TargetInfo.cpp:87
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4638
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
A (possibly-)qualified type.
Definition: Type.h:941
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
LangOptions::SignReturnAddressScopeKind SignReturnAddr
Definition: TargetInfo.h:1405
const char * getSignReturnAddrStr() const
Definition: TargetInfo.h:1411
Represents a variable declaration or definition.
Definition: Decl.h:879
std::unique_ptr< TargetCodeGenInfo > createDefaultTargetCodeGenInfo(CodeGenModule &CGM)
Definition: TargetInfo.cpp:240
The JSON file list parser is used to communicate input to InstallAPI.
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
const FunctionProtoType * T
SyncScope
Defines synch scope values used internally by clang.
Definition: SyncScope.h:42
@ CC_OpenCLKernel
Definition: Specifiers.h:289