clang 20.0.0git
AMDGPU.cpp
Go to the documentation of this file.
1//===- AMDGPU.cpp ---------------------------------------------------------===//
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#include "ABIInfoImpl.h"
10#include "TargetInfo.h"
12#include "llvm/Support/AMDGPUAddrSpace.h"
13
14using namespace clang;
15using namespace clang::CodeGen;
16
17//===----------------------------------------------------------------------===//
18// AMDGPU ABI Implementation
19//===----------------------------------------------------------------------===//
20
21namespace {
22
23class AMDGPUABIInfo final : public DefaultABIInfo {
24private:
25 static const unsigned MaxNumRegsForArgsRet = 16;
26
27 unsigned numRegsForType(QualType Ty) const;
28
29 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
31 uint64_t Members) const override;
32
33 // Coerce HIP scalar pointer arguments from generic pointers to global ones.
34 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
35 unsigned ToAS) const {
36 // Single value types.
37 auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
38 if (PtrTy && PtrTy->getAddressSpace() == FromAS)
39 return llvm::PointerType::get(Ty->getContext(), ToAS);
40 return Ty;
41 }
42
43public:
44 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
45 DefaultABIInfo(CGT) {}
46
48 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
50 unsigned &NumRegsLeft) const;
51
52 void computeInfo(CGFunctionInfo &FI) const override;
53 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
54 AggValueSlot Slot) const override;
55};
56
57bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
58 return true;
59}
60
61bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
62 const Type *Base, uint64_t Members) const {
63 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
64
65 // Homogeneous Aggregates may occupy at most 16 registers.
66 return Members * NumRegs <= MaxNumRegsForArgsRet;
67}
68
69/// Estimate number of registers the type will use when passed in registers.
70unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
71 unsigned NumRegs = 0;
72
73 if (const VectorType *VT = Ty->getAs<VectorType>()) {
74 // Compute from the number of elements. The reported size is based on the
75 // in-memory size, which includes the padding 4th element for 3-vectors.
76 QualType EltTy = VT->getElementType();
77 unsigned EltSize = getContext().getTypeSize(EltTy);
78
79 // 16-bit element vectors should be passed as packed.
80 if (EltSize == 16)
81 return (VT->getNumElements() + 1) / 2;
82
83 unsigned EltNumRegs = (EltSize + 31) / 32;
84 return EltNumRegs * VT->getNumElements();
85 }
86
87 if (const RecordType *RT = Ty->getAs<RecordType>()) {
88 const RecordDecl *RD = RT->getDecl();
89 assert(!RD->hasFlexibleArrayMember());
90
91 for (const FieldDecl *Field : RD->fields()) {
92 QualType FieldTy = Field->getType();
93 NumRegs += numRegsForType(FieldTy);
94 }
95
96 return NumRegs;
97 }
98
99 return (getContext().getTypeSize(Ty) + 31) / 32;
100}
101
102void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
103 llvm::CallingConv::ID CC = FI.getCallingConvention();
104
105 if (!getCXXABI().classifyReturnType(FI))
107
108 unsigned ArgumentIndex = 0;
109 const unsigned numFixedArguments = FI.getNumRequiredArgs();
110
111 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
112 for (auto &Arg : FI.arguments()) {
113 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
114 Arg.info = classifyKernelArgumentType(Arg.type);
115 } else {
116 bool FixedArgument = ArgumentIndex++ < numFixedArguments;
117 Arg.info = classifyArgumentType(Arg.type, !FixedArgument, NumRegsLeft);
118 }
119 }
120}
121
122RValue AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
123 QualType Ty, AggValueSlot Slot) const {
124 const bool IsIndirect = false;
125 const bool AllowHigherAlign = false;
126 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
127 getContext().getTypeInfoInChars(Ty),
128 CharUnits::fromQuantity(4), AllowHigherAlign, Slot);
129}
130
131ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
132 if (isAggregateTypeForABI(RetTy)) {
133 // Records with non-trivial destructors/copy-constructors should not be
134 // returned by value.
135 if (!getRecordArgABI(RetTy, getCXXABI())) {
136 // Ignore empty structs/unions.
137 if (isEmptyRecord(getContext(), RetTy, true))
138 return ABIArgInfo::getIgnore();
139
140 // Lower single-element structs to just return a regular value.
141 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
142 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
143
144 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
145 const RecordDecl *RD = RT->getDecl();
146 if (RD->hasFlexibleArrayMember())
148 }
149
150 // Pack aggregates <= 4 bytes into single VGPR or pair.
151 uint64_t Size = getContext().getTypeSize(RetTy);
152 if (Size <= 16)
153 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
154
155 if (Size <= 32)
156 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
157
158 if (Size <= 64) {
159 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
160 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
161 }
162
163 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
164 return ABIArgInfo::getDirect();
165 }
166 }
167
168 // Otherwise just do the default thing.
170}
171
172/// For kernels all parameters are really passed in a special buffer. It doesn't
173/// make sense to pass anything byval, so everything must be direct.
174ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
176
177 // TODO: Can we omit empty structs?
178
179 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
180 Ty = QualType(SeltTy, 0);
181
182 llvm::Type *OrigLTy = CGT.ConvertType(Ty);
183 llvm::Type *LTy = OrigLTy;
184 if (getContext().getLangOpts().HIP) {
185 LTy = coerceKernelArgumentType(
186 OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
187 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
188 }
189
190 // FIXME: Should also use this for OpenCL, but it requires addressing the
191 // problem of kernels being called.
192 //
193 // FIXME: This doesn't apply the optimization of coercing pointers in structs
194 // to global address space when using byref. This would require implementing a
195 // new kind of coercion of the in-memory type when for indirect arguments.
196 if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
199 getContext().getTypeAlignInChars(Ty),
200 getContext().getTargetAddressSpace(LangAS::opencl_constant),
201 false /*Realign*/, nullptr /*Padding*/);
202 }
203
204 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
205 // individual elements, which confuses the Clover OpenCL backend; therefore we
206 // have to set it to false here. Other args of getDirect() are just defaults.
207 return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
208}
209
210ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, bool Variadic,
211 unsigned &NumRegsLeft) const {
212 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
213
215
216 if (Variadic) {
217 return ABIArgInfo::getDirect(/*T=*/nullptr,
218 /*Offset=*/0,
219 /*Padding=*/nullptr,
220 /*CanBeFlattened=*/false,
221 /*Align=*/0);
222 }
223
224 if (isAggregateTypeForABI(Ty)) {
225 // Records with non-trivial destructors/copy-constructors should not be
226 // passed by value.
227 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
228 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
229
230 // Ignore empty structs/unions.
231 if (isEmptyRecord(getContext(), Ty, true))
232 return ABIArgInfo::getIgnore();
233
234 // Lower single-element structs to just pass a regular value. TODO: We
235 // could do reasonable-size multiple-element structs too, using getExpand(),
236 // though watch out for things like bitfields.
237 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
238 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
239
240 if (const RecordType *RT = Ty->getAs<RecordType>()) {
241 const RecordDecl *RD = RT->getDecl();
242 if (RD->hasFlexibleArrayMember())
244 }
245
246 // Pack aggregates <= 8 bytes into single VGPR or pair.
247 uint64_t Size = getContext().getTypeSize(Ty);
248 if (Size <= 64) {
249 unsigned NumRegs = (Size + 31) / 32;
250 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
251
252 if (Size <= 16)
253 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
254
255 if (Size <= 32)
256 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
257
258 // XXX: Should this be i64 instead, and should the limit increase?
259 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
260 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
261 }
262
263 if (NumRegsLeft > 0) {
264 unsigned NumRegs = numRegsForType(Ty);
265 if (NumRegsLeft >= NumRegs) {
266 NumRegsLeft -= NumRegs;
267 return ABIArgInfo::getDirect();
268 }
269 }
270
271 // Use pass-by-reference in stead of pass-by-value for struct arguments in
272 // function ABI.
274 getContext().getTypeAlignInChars(Ty),
275 getContext().getTargetAddressSpace(LangAS::opencl_private));
276 }
277
278 // Otherwise just do the default thing.
280 if (!ArgInfo.isIndirect()) {
281 unsigned NumRegs = numRegsForType(Ty);
282 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
283 }
284
285 return ArgInfo;
286}
287
288class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
289public:
290 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
291 : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
292
293 void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
294 CodeGenModule &CGM) const;
295
296 void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const override;
297
298 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
299 CodeGen::CodeGenModule &M) const override;
300 unsigned getOpenCLKernelCallingConv() const override;
301
302 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
303 llvm::PointerType *T, QualType QT) const override;
304
305 LangAS getASTAllocaAddressSpace() const override {
307 getABIInfo().getDataLayout().getAllocaAddrSpace());
308 }
310 const VarDecl *D) const override;
311 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
313 llvm::AtomicOrdering Ordering,
314 llvm::LLVMContext &Ctx) const override;
316 llvm::Instruction &AtomicInst,
317 const AtomicExpr *Expr = nullptr) const override;
319 llvm::Function *BlockInvokeFunc,
320 llvm::Type *BlockTy) const override;
321 bool shouldEmitStaticExternCAliases() const override;
322 bool shouldEmitDWARFBitFieldSeparators() const override;
323 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
324};
325}
326
328 llvm::GlobalValue *GV) {
329 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
330 return false;
331
332 return !D->hasAttr<OMPDeclareTargetDeclAttr>() &&
333 (D->hasAttr<OpenCLKernelAttr>() ||
334 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
335 (isa<VarDecl>(D) &&
336 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
337 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
338 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())));
339}
340
341void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
342 const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
343 const auto *ReqdWGS =
344 M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
345 const bool IsOpenCLKernel =
346 M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
347 const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
348
349 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
350 if (ReqdWGS || FlatWGS) {
351 M.handleAMDGPUFlatWorkGroupSizeAttr(F, FlatWGS, ReqdWGS);
352 } else if (IsOpenCLKernel || IsHIPKernel) {
353 // By default, restrict the maximum size to a value specified by
354 // --gpu-max-threads-per-block=n or its default value for HIP.
355 const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
356 const unsigned DefaultMaxWorkGroupSize =
357 IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
358 : M.getLangOpts().GPUMaxThreadsPerBlock;
359 std::string AttrVal =
360 std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
361 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
362 }
363
364 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>())
366
367 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
368 unsigned NumSGPR = Attr->getNumSGPR();
369
370 if (NumSGPR != 0)
371 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
372 }
373
374 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
375 uint32_t NumVGPR = Attr->getNumVGPR();
376
377 if (NumVGPR != 0)
378 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
379 }
380
381 if (const auto *Attr = FD->getAttr<AMDGPUMaxNumWorkGroupsAttr>()) {
382 uint32_t X = Attr->getMaxNumWorkGroupsX()
383 ->EvaluateKnownConstInt(M.getContext())
384 .getExtValue();
385 // Y and Z dimensions default to 1 if not specified
386 uint32_t Y = Attr->getMaxNumWorkGroupsY()
387 ? Attr->getMaxNumWorkGroupsY()
388 ->EvaluateKnownConstInt(M.getContext())
389 .getExtValue()
390 : 1;
391 uint32_t Z = Attr->getMaxNumWorkGroupsZ()
392 ? Attr->getMaxNumWorkGroupsZ()
393 ->EvaluateKnownConstInt(M.getContext())
394 .getExtValue()
395 : 1;
396
397 llvm::SmallString<32> AttrVal;
398 llvm::raw_svector_ostream OS(AttrVal);
399 OS << X << ',' << Y << ',' << Z;
400
401 F->addFnAttr("amdgpu-max-num-workgroups", AttrVal.str());
402 }
403}
404
405/// Emits control constants used to change per-architecture behaviour in the
406/// AMDGPU ROCm device libraries.
407void AMDGPUTargetCodeGenInfo::emitTargetGlobals(
408 CodeGen::CodeGenModule &CGM) const {
409 StringRef Name = "__oclc_ABI_version";
410 llvm::GlobalVariable *OriginalGV = CGM.getModule().getNamedGlobal(Name);
411 if (OriginalGV && !llvm::GlobalVariable::isExternalLinkage(OriginalGV->getLinkage()))
412 return;
413
415 llvm::CodeObjectVersionKind::COV_None)
416 return;
417
418 auto *Type = llvm::IntegerType::getIntNTy(CGM.getModule().getContext(), 32);
419 llvm::Constant *COV = llvm::ConstantInt::get(
421
422 // It needs to be constant weak_odr without externally_initialized so that
423 // the load instuction can be eliminated by the IPSCCP.
424 auto *GV = new llvm::GlobalVariable(
425 CGM.getModule(), Type, true, llvm::GlobalValue::WeakODRLinkage, COV, Name,
426 nullptr, llvm::GlobalValue::ThreadLocalMode::NotThreadLocal,
427 CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant));
428 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Local);
429 GV->setVisibility(llvm::GlobalValue::VisibilityTypes::HiddenVisibility);
430
431 // Replace any external references to this variable with the new global.
432 if (OriginalGV) {
433 OriginalGV->replaceAllUsesWith(GV);
434 GV->takeName(OriginalGV);
435 OriginalGV->eraseFromParent();
436 }
437}
438
439void AMDGPUTargetCodeGenInfo::setTargetAttributes(
440 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
442 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
443 GV->setDSOLocal(true);
444 }
445
446 if (GV->isDeclaration())
447 return;
448
449 llvm::Function *F = dyn_cast<llvm::Function>(GV);
450 if (!F)
451 return;
452
453 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
454 if (FD)
455 setFunctionDeclAttributes(FD, F, M);
456
457 if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
458 F->addFnAttr("amdgpu-ieee", "false");
459}
460
461unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
462 return llvm::CallingConv::AMDGPU_KERNEL;
463}
464
465// Currently LLVM assumes null pointers always have value 0,
466// which results in incorrectly transformed IR. Therefore, instead of
467// emitting null pointers in private and local address spaces, a null
468// pointer in generic address space is emitted which is casted to a
469// pointer in local or private address space.
470llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
471 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
472 QualType QT) const {
473 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
474 return llvm::ConstantPointerNull::get(PT);
475
476 auto &Ctx = CGM.getContext();
477 auto NPT = llvm::PointerType::get(
478 PT->getContext(), Ctx.getTargetAddressSpace(LangAS::opencl_generic));
479 return llvm::ConstantExpr::getAddrSpaceCast(
480 llvm::ConstantPointerNull::get(NPT), PT);
481}
482
483LangAS
484AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
485 const VarDecl *D) const {
486 assert(!CGM.getLangOpts().OpenCL &&
487 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
488 "Address space agnostic languages only");
489 LangAS DefaultGlobalAS = getLangASFromTargetAS(
490 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
491 if (!D)
492 return DefaultGlobalAS;
493
494 LangAS AddrSpace = D->getType().getAddressSpace();
495 if (AddrSpace != LangAS::Default)
496 return AddrSpace;
497
498 // Only promote to address space 4 if VarDecl has constant initialization.
499 if (D->getType().isConstantStorage(CGM.getContext(), false, false) &&
500 D->hasConstantInitialization()) {
501 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
502 return *ConstAS;
503 }
504 return DefaultGlobalAS;
505}
506
507llvm::SyncScope::ID
508AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
510 llvm::AtomicOrdering Ordering,
511 llvm::LLVMContext &Ctx) const {
512 std::string Name;
513 switch (Scope) {
514 case SyncScope::HIPSingleThread:
515 case SyncScope::SingleScope:
516 Name = "singlethread";
517 break;
518 case SyncScope::HIPWavefront:
519 case SyncScope::OpenCLSubGroup:
520 case SyncScope::WavefrontScope:
521 Name = "wavefront";
522 break;
523 case SyncScope::HIPWorkgroup:
524 case SyncScope::OpenCLWorkGroup:
525 case SyncScope::WorkgroupScope:
526 Name = "workgroup";
527 break;
528 case SyncScope::HIPAgent:
529 case SyncScope::OpenCLDevice:
530 case SyncScope::DeviceScope:
531 Name = "agent";
532 break;
533 case SyncScope::SystemScope:
534 case SyncScope::HIPSystem:
535 case SyncScope::OpenCLAllSVMDevices:
536 Name = "";
537 break;
538 }
539
540 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
541 if (!Name.empty())
542 Name = Twine(Twine(Name) + Twine("-")).str();
543
544 Name = Twine(Twine(Name) + Twine("one-as")).str();
545 }
546
547 return Ctx.getOrInsertSyncScopeID(Name);
548}
549
550void AMDGPUTargetCodeGenInfo::setTargetAtomicMetadata(
551 CodeGenFunction &CGF, llvm::Instruction &AtomicInst,
552 const AtomicExpr *AE) const {
553 auto *RMW = dyn_cast<llvm::AtomicRMWInst>(&AtomicInst);
554 auto *CmpX = dyn_cast<llvm::AtomicCmpXchgInst>(&AtomicInst);
555
556 // OpenCL and old style HIP atomics consider atomics targeting thread private
557 // memory to be undefined.
558 //
559 // TODO: This is probably undefined for atomic load/store, but there's not
560 // much direct codegen benefit to knowing this.
561 if (((RMW && RMW->getPointerAddressSpace() == llvm::AMDGPUAS::FLAT_ADDRESS) ||
562 (CmpX &&
563 CmpX->getPointerAddressSpace() == llvm::AMDGPUAS::FLAT_ADDRESS)) &&
565 llvm::MDBuilder MDHelper(CGF.getLLVMContext());
566 llvm::MDNode *ASRange = MDHelper.createRange(
567 llvm::APInt(32, llvm::AMDGPUAS::PRIVATE_ADDRESS),
568 llvm::APInt(32, llvm::AMDGPUAS::PRIVATE_ADDRESS + 1));
569 AtomicInst.setMetadata(llvm::LLVMContext::MD_noalias_addrspace, ASRange);
570 }
571
572 if (!RMW || !CGF.getTarget().allowAMDGPUUnsafeFPAtomics())
573 return;
574
575 // TODO: Introduce new, more controlled options that also work for integers,
576 // and deprecate allowAMDGPUUnsafeFPAtomics.
577 llvm::AtomicRMWInst::BinOp RMWOp = RMW->getOperation();
578 if (llvm::AtomicRMWInst::isFPOperation(RMWOp)) {
579 llvm::MDNode *Empty = llvm::MDNode::get(CGF.getLLVMContext(), {});
580 RMW->setMetadata("amdgpu.no.fine.grained.memory", Empty);
581
582 if (RMWOp == llvm::AtomicRMWInst::FAdd && RMW->getType()->isFloatTy())
583 RMW->setMetadata("amdgpu.ignore.denormal.mode", Empty);
584 }
585}
586
587bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
588 return false;
589}
590
591bool AMDGPUTargetCodeGenInfo::shouldEmitDWARFBitFieldSeparators() const {
592 return true;
593}
594
595void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
596 const FunctionType *&FT) const {
597 FT = getABIInfo().getContext().adjustFunctionType(
599}
600
601/// Create an OpenCL kernel for an enqueued block.
602///
603/// The type of the first argument (the block literal) is the struct type
604/// of the block literal instead of a pointer type. The first argument
605/// (block literal) is passed directly by value to the kernel. The kernel
606/// allocates the same type of struct on stack and stores the block literal
607/// to it and passes its pointer to the block invoke function. The kernel
608/// has "enqueued-block" function attribute and kernel argument metadata.
609llvm::Value *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
610 CodeGenFunction &CGF, llvm::Function *Invoke, llvm::Type *BlockTy) const {
611 auto &Builder = CGF.Builder;
612 auto &C = CGF.getLLVMContext();
613
614 auto *InvokeFT = Invoke->getFunctionType();
622
623 ArgTys.push_back(BlockTy);
624 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
625 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
626 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
627 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
628 AccessQuals.push_back(llvm::MDString::get(C, "none"));
629 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
630 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
631 ArgTys.push_back(InvokeFT->getParamType(I));
632 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
633 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
634 AccessQuals.push_back(llvm::MDString::get(C, "none"));
635 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
636 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
637 ArgNames.push_back(
638 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
639 }
640 std::string Name = Invoke->getName().str() + "_kernel";
641 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
642 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
643 &CGF.CGM.getModule());
644 F->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
645
646 llvm::AttrBuilder KernelAttrs(C);
647 // FIXME: The invoke isn't applying the right attributes either
648 // FIXME: This is missing setTargetAttributes
650 KernelAttrs.addAttribute("enqueued-block");
651 F->addFnAttrs(KernelAttrs);
652
653 auto IP = CGF.Builder.saveIP();
654 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
655 Builder.SetInsertPoint(BB);
656 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
657 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
658 BlockPtr->setAlignment(BlockAlign);
659 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
660 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
662 Args.push_back(Cast);
663 for (llvm::Argument &A : llvm::drop_begin(F->args()))
664 Args.push_back(&A);
665 llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
666 call->setCallingConv(Invoke->getCallingConv());
667 Builder.CreateRetVoid();
668 Builder.restoreIP(IP);
669
670 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
671 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
672 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
673 F->setMetadata("kernel_arg_base_type",
674 llvm::MDNode::get(C, ArgBaseTypeNames));
675 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
676 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
677 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
678
679 return F;
680}
681
683 llvm::Function *F, const AMDGPUFlatWorkGroupSizeAttr *FlatWGS,
684 const ReqdWorkGroupSizeAttr *ReqdWGS, int32_t *MinThreadsVal,
685 int32_t *MaxThreadsVal) {
686 unsigned Min = 0;
687 unsigned Max = 0;
688 if (FlatWGS) {
689 Min = FlatWGS->getMin()->EvaluateKnownConstInt(getContext()).getExtValue();
690 Max = FlatWGS->getMax()->EvaluateKnownConstInt(getContext()).getExtValue();
691 }
692 if (ReqdWGS && Min == 0 && Max == 0)
693 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
694
695 if (Min != 0) {
696 assert(Min <= Max && "Min must be less than or equal Max");
697
698 if (MinThreadsVal)
699 *MinThreadsVal = Min;
700 if (MaxThreadsVal)
701 *MaxThreadsVal = Max;
702 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
703 if (F)
704 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
705 } else
706 assert(Max == 0 && "Max must be zero");
707}
708
710 llvm::Function *F, const AMDGPUWavesPerEUAttr *Attr) {
711 unsigned Min =
712 Attr->getMin()->EvaluateKnownConstInt(getContext()).getExtValue();
713 unsigned Max =
714 Attr->getMax()
715 ? Attr->getMax()->EvaluateKnownConstInt(getContext()).getExtValue()
716 : 0;
717
718 if (Min != 0) {
719 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
720
721 std::string AttrVal = llvm::utostr(Min);
722 if (Max != 0)
723 AttrVal = AttrVal + "," + llvm::utostr(Max);
724 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
725 } else
726 assert(Max == 0 && "Max must be zero");
727}
728
729std::unique_ptr<TargetCodeGenInfo>
731 return std::make_unique<AMDGPUTargetCodeGenInfo>(CGM.getTypes());
732}
const Decl * D
Expr * E
static bool requiresAMDGPUProtectedVisibility(const Decl *D, llvm::GlobalValue *GV)
Definition: AMDGPU.cpp:327
#define X(type, name)
Definition: Value.h:144
Defines the clang::TargetOptions class.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTargetAddressSpace(LangAS AS) const
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6678
bool threadPrivateMemoryAtomicsAreUndefined() const
Return true if atomics operations targeting allocations in private memory are undefined.
Definition: Expr.h:6789
Attr - This represents one attribute.
Definition: Attr.h:43
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
static ABIArgInfo getIgnore()
static ABIArgInfo getDirect(llvm::Type *T=nullptr, unsigned Offset=0, llvm::Type *Padding=nullptr, bool CanBeFlattened=true, unsigned Align=0)
static ABIArgInfo getIndirectAliased(CharUnits Alignment, unsigned AddrSpace, bool Realign=false, llvm::Type *Padding=nullptr)
Pass this in memory using the IR byref attribute.
virtual bool isHomogeneousAggregateBaseType(QualType Ty) const
Definition: ABIInfo.cpp:47
virtual bool isHomogeneousAggregateSmallEnough(const Type *Base, uint64_t Members) const
Definition: ABIInfo.cpp:51
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:128
An aggregate value slot.
Definition: CGValue.h:504
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition: CGCXXABI.h:158
CGFunctionInfo - Class to encapsulate the information about a function definition.
unsigned getCallingConvention() const
getCallingConvention - Return the user specified calling convention, which has been translated into a...
CanQualType getReturnType() const
MutableArrayRef< ArgInfo > arguments()
unsigned getNumRequiredArgs() const
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
const TargetInfo & getTarget() const
llvm::LLVMContext & getLLVMContext()
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
void handleAMDGPUWavesPerEUAttr(llvm::Function *F, const AMDGPUWavesPerEUAttr *A)
Emit the IR encoding to attach the AMD GPU waves-per-eu attribute to F.
Definition: AMDGPU.cpp:709
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
void handleAMDGPUFlatWorkGroupSizeAttr(llvm::Function *F, const AMDGPUFlatWorkGroupSizeAttr *A, const ReqdWorkGroupSizeAttr *ReqdWGS=nullptr, int32_t *MinThreadsVal=nullptr, int32_t *MaxThreadsVal=nullptr)
Emit the IR encoding to attach the AMD GPU flat-work-group-size attribute to F.
Definition: AMDGPU.cpp:682
const llvm::DataLayout & getDataLayout() const
ASTContext & getContext() 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:2159
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
Definition: CodeGenTypes.h:54
DefaultABIInfo - The default implementation for ABI specific details.
Definition: ABIInfoImpl.h:21
ABIArgInfo classifyArgumentType(QualType RetTy) const
Definition: ABIInfoImpl.cpp:17
RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, AggValueSlot Slot) const override
EmitVAArg - Emit the target dependent code to load a value of.
Definition: ABIInfoImpl.cpp:75
ABIArgInfo classifyReturnType(QualType RetTy) const
Definition: ABIInfoImpl.cpp:46
void computeInfo(CGFunctionInfo &FI) const override
Definition: ABIInfoImpl.cpp:68
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:42
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
Definition: TargetInfo.h:47
virtual void setCUDAKernelCallingConvention(const FunctionType *&FT) const
Definition: TargetInfo.h:402
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
const T & getABIInfo() const
Definition: TargetInfo.h:57
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
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
Definition: TargetInfo.h:76
virtual bool shouldEmitDWARFBitFieldSeparators() const
Definition: TargetInfo.h:400
virtual llvm::Constant * getNullPointer(const CodeGen::CodeGenModule &CGM, llvm::PointerType *T, QualType QT) const
Get target specific null pointer.
Definition: TargetInfo.cpp:120
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
Definition: TargetInfo.h:316
virtual void setTargetAtomicMetadata(CodeGenFunction &CGF, llvm::Instruction &AtomicInst, const AtomicExpr *Expr=nullptr) const
Allow the target to apply other metadata to an atomic instruction.
Definition: TargetInfo.h:356
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 void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const
Provides a convenient hook to handle extra target-specific globals.
Definition: TargetInfo.h:86
virtual bool shouldEmitStaticExternCAliases() const
Definition: TargetInfo.h:395
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:576
bool hasAttr() const
Definition: DeclBase.h:580
This represents one expression.
Definition: Expr.h:110
Represents a member of a struct/union/class.
Definition: Decl.h:3033
Represents a function declaration or definition.
Definition: Decl.h:1935
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4547
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4655
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
A (possibly-)qualified type.
Definition: Type.h:929
Represents a struct/union/class.
Definition: Decl.h:4148
bool hasFlexibleArrayMember() const
Definition: Decl.h:4181
field_range fields() const
Definition: Decl.h:4354
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:311
virtual std::optional< LangAS > getConstantAddressSpace() const
Return an AST address space which can be used opportunistically for constant global memory.
Definition: TargetInfo.h:1654
bool allowAMDGPUUnsafeFPAtomics() const
Returns whether or not the AMDGPU unsafe floating point atomics are allowed.
Definition: TargetInfo.h:1054
llvm::CodeObjectVersionKind CodeObjectVersion
Code object version for AMDGPU.
Definition: TargetOptions.h:82
The base class of the type hierarchy.
Definition: Type.h:1828
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
Represents a variable declaration or definition.
Definition: Decl.h:882
Represents a GCC generic vector type.
Definition: Type.h:4034
ABIArgInfo classifyArgumentType(CodeGenModule &CGM, CanQualType type)
Classify the rules for how to pass a particular type.
CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, CGCXXABI &CXXABI)
bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, const ABIInfo &Info)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
Definition: AMDGPU.cpp:730
RValue emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType ValueTy, bool IsIndirect, TypeInfoChars ValueInfo, CharUnits SlotSizeAndAlign, bool AllowHigherAlign, AggValueSlot Slot, bool ForceRightAdjust=false)
Emit va_arg for a platform using the common void* representation, where arguments are simply emitted ...
bool isAggregateTypeForABI(QualType T)
Definition: ABIInfoImpl.cpp:94
const Type * isSingleElementStruct(QualType T, ASTContext &Context)
isSingleElementStruct - Determine if a structure is a "single element struct", i.e.
QualType useFirstFieldIfTransparentUnion(QualType Ty)
Pass transparent unions as if they were the type of the first element.
bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyRecord - Return true iff a structure contains only empty fields.
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2181
The JSON file list parser is used to communicate input to InstallAPI.
@ OpenCL
Definition: LangStandard.h:65
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:292
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:86
unsigned long uint64_t
unsigned int uint32_t