1 //===- CBuffer.cpp - HLSL constant buffer handling ------------------------===//
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 "llvm/Frontend/HLSL/CBuffer.h"
10 #include "llvm/Frontend/HLSL/HLSLResource.h"
11 #include "llvm/IR/DerivedTypes.h"
12 #include "llvm/IR/Metadata.h"
13 #include "llvm/IR/Module.h"
14
15 using namespace llvm;
16 using namespace llvm::hlsl;
17
getMemberOffset(GlobalVariable * Handle,size_t Index)18 static size_t getMemberOffset(GlobalVariable *Handle, size_t Index) {
19 auto *HandleTy = cast<TargetExtType>(Handle->getValueType());
20 assert(HandleTy->getName().ends_with(".CBuffer") && "Not a cbuffer type");
21 assert(HandleTy->getNumTypeParameters() == 1 && "Expected layout type");
22
23 auto *LayoutTy = cast<TargetExtType>(HandleTy->getTypeParameter(0));
24 assert(LayoutTy->getName().ends_with(".Layout") && "Not a layout type");
25
26 // Skip the "size" parameter.
27 size_t ParamIndex = Index + 1;
28 assert(LayoutTy->getNumIntParameters() > ParamIndex &&
29 "Not enough parameters");
30
31 return LayoutTy->getIntParameter(ParamIndex);
32 }
33
get(Module & M)34 std::optional<CBufferMetadata> CBufferMetadata::get(Module &M) {
35 NamedMDNode *CBufMD = M.getNamedMetadata("hlsl.cbs");
36 if (!CBufMD)
37 return std::nullopt;
38
39 std::optional<CBufferMetadata> Result({CBufMD});
40
41 for (const MDNode *MD : CBufMD->operands()) {
42 assert(MD->getNumOperands() && "Invalid cbuffer metadata");
43
44 auto *Handle = cast<GlobalVariable>(
45 cast<ValueAsMetadata>(MD->getOperand(0))->getValue());
46 CBufferMapping &Mapping = Result->Mappings.emplace_back(Handle);
47
48 for (int I = 1, E = MD->getNumOperands(); I < E; ++I) {
49 Metadata *OpMD = MD->getOperand(I);
50 // Some members may be null if they've been optimized out.
51 if (!OpMD)
52 continue;
53 auto *V = cast<GlobalVariable>(cast<ValueAsMetadata>(OpMD)->getValue());
54 Mapping.Members.emplace_back(V, getMemberOffset(Handle, I - 1));
55 }
56 }
57
58 return Result;
59 }
60
eraseFromModule()61 void CBufferMetadata::eraseFromModule() {
62 // Remove the cbs named metadata
63 MD->eraseFromParent();
64 }
65
translateCBufArrayOffset(const DataLayout & DL,APInt Offset,ArrayType * Ty)66 APInt hlsl::translateCBufArrayOffset(const DataLayout &DL, APInt Offset,
67 ArrayType *Ty) {
68 int64_t TypeSize = DL.getTypeSizeInBits(Ty->getElementType()) / 8;
69 int64_t RoundUp = alignTo(TypeSize, Align(CBufferRowSizeInBytes));
70 return Offset.udiv(TypeSize) * RoundUp;
71 }
72