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"
18#include "clang/Basic/CodeGenOptions.h"
19#include "clang/CodeGen/CGFunctionInfo.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(O&: 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(O&: OS);
65 break;
66 case TargetSpecific:
67 OS << "TargetSpecific Type=";
68 if (llvm::Type *Ty = getCoerceToType())
69 Ty->print(O&: OS);
70 else
71 OS << "null";
72 break;
73 }
74 OS << ")\n";
75}
76
77TargetCodeGenInfo::TargetCodeGenInfo(std::unique_ptr<ABIInfo> Info)
78 : Info(std::move(Info)) {}
79
80TargetCodeGenInfo::~TargetCodeGenInfo() = default;
81
82// If someone can figure out a general rule for this, that would be great.
83// It's probably just doomed to be platform-dependent, though.
84unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
85 if (getABIInfo().getCodeGenOpts().hasSEHExceptions())
86 return getABIInfo().getDataLayout().getPointerSizeInBits() > 32 ? 64 : 48;
87 // Verified for:
88 // x86-64 FreeBSD, Linux, Darwin
89 // x86-32 FreeBSD, Linux, Darwin
90 // PowerPC Linux
91 // ARM Darwin (*not* EABI)
92 // AArch64 Linux
93 return 32;
94}
95
96bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
97 const FunctionNoProtoType *fnType) const {
98 // The following conventions are known to require this to be false:
99 // x86_stdcall
100 // MIPS
101 // For everything else, we just prefer false unless we opt out.
102 return false;
103}
104
105void
106TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
107 llvm::SmallString<24> &Opt) const {
108 // This assumes the user is passing a library name like "rt" instead of a
109 // filename like "librt.a/so", and that they don't care whether it's static or
110 // dynamic.
111 Opt = "-l";
112 Opt += Lib;
113}
114
115unsigned TargetCodeGenInfo::getDeviceKernelCallingConv() const {
116 if (getABIInfo().getContext().getLangOpts().OpenCL) {
117 // Device kernels are called via an explicit runtime API with arguments,
118 // such as set with clSetKernelArg() for OpenCL, not as normal
119 // sub-functions. Return SPIR_KERNEL by default as the kernel calling
120 // convention to ensure the fingerprint is fixed such way that each kernel
121 // argument gets one matching argument in the produced kernel function
122 // argument list to enable feasible implementation of clSetKernelArg() with
123 // aggregates etc. In case we would use the default C calling conv here,
124 // clSetKernelArg() might break depending on the target-specific
125 // conventions; different targets might split structs passed as values
126 // to multiple function arguments etc.
127 return llvm::CallingConv::SPIR_KERNEL;
128 }
129 llvm_unreachable("Unknown kernel calling convention");
130}
131
132void TargetCodeGenInfo::setOCLKernelStubCallingConvention(
133 const FunctionType *&FT) const {
134 FT = getABIInfo().getContext().adjustFunctionType(
135 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
136}
137
138llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
139 llvm::PointerType *T, QualType QT) const {
140 return llvm::ConstantPointerNull::get(T);
141}
142
143LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
144 const VarDecl *D) const {
145 assert(!CGM.getLangOpts().OpenCL &&
146 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
147 "Address space agnostic languages only");
148 return D ? D->getType().getAddressSpace() : LangAS::Default;
149}
150
151StringRef
152TargetCodeGenInfo::getLLVMSyncScopeStr(const LangOptions &LangOpts,
153 SyncScope Scope,
154 llvm::AtomicOrdering Ordering) const {
155 return ""; /* default sync scope */
156}
157
158llvm::SyncScope::ID
159TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
160 SyncScope Scope,
161 llvm::AtomicOrdering Ordering,
162 llvm::LLVMContext &Ctx) const {
163 return Ctx.getOrInsertSyncScopeID(
164 SSN: getLLVMSyncScopeStr(LangOpts, Scope, Ordering));
165}
166
167void TargetCodeGenInfo::addStackProbeTargetAttributes(
168 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
169 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(Val: GV)) {
170 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
171 Fn->addFnAttr(Kind: "stack-probe-size",
172 Val: llvm::utostr(X: CGM.getCodeGenOpts().StackProbeSize));
173 if (CGM.getCodeGenOpts().NoStackArgProbe)
174 Fn->addFnAttr(Kind: "no-stack-arg-probe");
175 }
176}
177
178/// Create an OpenCL kernel for an enqueued block.
179///
180/// The kernel has the same function type as the block invoke function. Its
181/// name is the name of the block invoke function postfixed with "_kernel".
182/// It simply calls the block invoke function then returns.
183llvm::Value *TargetCodeGenInfo::createEnqueuedBlockKernel(
184 CodeGenFunction &CGF, llvm::Function *Invoke, llvm::Type *BlockTy) const {
185 auto *InvokeFT = Invoke->getFunctionType();
186 auto &C = CGF.getLLVMContext();
187 std::string Name = Invoke->getName().str() + "_kernel";
188 auto *FT = llvm::FunctionType::get(Result: llvm::Type::getVoidTy(C),
189 Params: InvokeFT->params(), isVarArg: false);
190 auto *F = llvm::Function::Create(Ty: FT, Linkage: llvm::GlobalValue::ExternalLinkage, N: Name,
191 M: &CGF.CGM.getModule());
192 llvm::CallingConv::ID KernelCC =
193 CGF.getTypes().ClangCallConvToLLVMCallConv(CC: CallingConv::CC_DeviceKernel);
194 F->setCallingConv(KernelCC);
195
196 llvm::AttrBuilder KernelAttrs(C);
197
198 // FIXME: This is missing setTargetAttributes
199 CGF.CGM.addDefaultFunctionDefinitionAttributes(attrs&: KernelAttrs);
200 F->addFnAttrs(Attrs: KernelAttrs);
201
202 auto IP = CGF.Builder.saveIP();
203 auto *BB = llvm::BasicBlock::Create(Context&: C, Name: "entry", Parent: F);
204 auto &Builder = CGF.Builder;
205 Builder.SetInsertPoint(BB);
206 llvm::SmallVector<llvm::Value *, 2> Args(llvm::make_pointer_range(Range: F->args()));
207 llvm::CallInst *Call = Builder.CreateCall(Callee: Invoke, Args);
208 Call->setCallingConv(Invoke->getCallingConv());
209
210 Builder.CreateRetVoid();
211 Builder.restoreIP(IP);
212 return F;
213}
214
215void TargetCodeGenInfo::setBranchProtectionFnAttributes(
216 const TargetInfo::BranchProtectionInfo &BPI, llvm::Function &F) {
217 // Called on already created and initialized function where attributes already
218 // set from command line attributes but some might need to be removed as the
219 // actual BPI is different.
220 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
221 F.addFnAttr(Kind: "sign-return-address", Val: BPI.getSignReturnAddrStr());
222 F.addFnAttr(Kind: "sign-return-address-key", Val: BPI.getSignKeyStr());
223 } else {
224 if (F.hasFnAttribute(Kind: "sign-return-address"))
225 F.removeFnAttr(Kind: "sign-return-address");
226 if (F.hasFnAttribute(Kind: "sign-return-address-key"))
227 F.removeFnAttr(Kind: "sign-return-address-key");
228 }
229
230 auto AddRemoveAttributeAsSet = [&](bool Set, const StringRef &ModAttr) {
231 if (Set)
232 F.addFnAttr(Kind: ModAttr);
233 else if (F.hasFnAttribute(Kind: ModAttr))
234 F.removeFnAttr(Kind: ModAttr);
235 };
236
237 AddRemoveAttributeAsSet(BPI.BranchTargetEnforcement,
238 "branch-target-enforcement");
239 AddRemoveAttributeAsSet(BPI.BranchProtectionPAuthLR,
240 "branch-protection-pauth-lr");
241 AddRemoveAttributeAsSet(BPI.GuardedControlStack, "guarded-control-stack");
242}
243
244void TargetCodeGenInfo::initBranchProtectionFnAttributes(
245 const TargetInfo::BranchProtectionInfo &BPI, llvm::AttrBuilder &FuncAttrs) {
246 // Only used for initializing attributes in the AttrBuilder, which will not
247 // contain any of these attributes so no need to remove anything.
248 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
249 FuncAttrs.addAttribute(A: "sign-return-address", V: BPI.getSignReturnAddrStr());
250 FuncAttrs.addAttribute(A: "sign-return-address-key", V: BPI.getSignKeyStr());
251 }
252 if (BPI.BranchTargetEnforcement)
253 FuncAttrs.addAttribute(A: "branch-target-enforcement");
254 if (BPI.BranchProtectionPAuthLR)
255 FuncAttrs.addAttribute(A: "branch-protection-pauth-lr");
256 if (BPI.GuardedControlStack)
257 FuncAttrs.addAttribute(A: "guarded-control-stack");
258}
259
260void TargetCodeGenInfo::setPointerAuthFnAttributes(
261 const PointerAuthOptions &Opts, llvm::Function &F) {
262 auto UpdateAttr = [&F](bool AttrShouldExist, StringRef AttrName) {
263 if (AttrShouldExist && !F.hasFnAttribute(Kind: AttrName))
264 F.addFnAttr(Kind: AttrName);
265 if (!AttrShouldExist && F.hasFnAttribute(Kind: AttrName))
266 F.removeFnAttr(Kind: AttrName);
267 };
268 UpdateAttr(Opts.ReturnAddresses, "ptrauth-returns");
269 UpdateAttr((bool)Opts.FunctionPointers, "ptrauth-calls");
270 UpdateAttr(Opts.AuthTraps, "ptrauth-auth-traps");
271 UpdateAttr(Opts.IndirectGotos, "ptrauth-indirect-gotos");
272 UpdateAttr(Opts.AArch64JumpTableHardening, "aarch64-jump-table-hardening");
273}
274
275void TargetCodeGenInfo::initPointerAuthFnAttributes(
276 const PointerAuthOptions &Opts, llvm::AttrBuilder &FuncAttrs) {
277 if (Opts.ReturnAddresses)
278 FuncAttrs.addAttribute(A: "ptrauth-returns");
279 if (Opts.FunctionPointers)
280 FuncAttrs.addAttribute(A: "ptrauth-calls");
281 if (Opts.AuthTraps)
282 FuncAttrs.addAttribute(A: "ptrauth-auth-traps");
283 if (Opts.IndirectGotos)
284 FuncAttrs.addAttribute(A: "ptrauth-indirect-gotos");
285 if (Opts.AArch64JumpTableHardening)
286 FuncAttrs.addAttribute(A: "aarch64-jump-table-hardening");
287}
288
289namespace {
290class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
291public:
292 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
293 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(args&: CGT)) {}
294};
295} // namespace
296
297std::unique_ptr<TargetCodeGenInfo>
298CodeGen::createDefaultTargetCodeGenInfo(CodeGenModule &CGM) {
299 return std::make_unique<DefaultTargetCodeGenInfo>(args&: CGM.getTypes());
300}
301