-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathMTLDevice.cpp
More file actions
680 lines (593 loc) · 24.6 KB
/
MTLDevice.cpp
File metadata and controls
680 lines (593 loc) · 24.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
#define NS_PRIVATE_IMPLEMENTATION
#define CA_PRIVATE_IMPLEMENTATION
#define MTL_PRIVATE_IMPLEMENTATION
#include "Foundation/Foundation.hpp"
#include "Metal/Metal.hpp"
#include "QuartzCore/QuartzCore.hpp"
#define IR_RUNTIME_METALCPP
#define IR_PRIVATE_IMPLEMENTATION
#include "metal_irconverter_runtime.h"
#include "API/Device.h"
#include "Support/Pipeline.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace offloadtest;
static llvm::Error toError(NS::Error *Err) {
if (!Err)
return llvm::Error::success();
const std::error_code EC =
std::error_code(static_cast<int>(Err->code()), std::system_category());
llvm::SmallString<256> ErrMsg;
llvm::raw_svector_ostream OS(ErrMsg);
OS << Err->localizedDescription()->utf8String() << ": ";
OS << Err->localizedFailureReason()->utf8String();
return llvm::createStringError(EC, ErrMsg);
}
#define MTLFormats(FMT) \
if (Channels == 1) \
return MTL::PixelFormatR##FMT; \
if (Channels == 2) \
return MTL::PixelFormatRG##FMT; \
if (Channels == 4) \
return MTL::PixelFormatRGBA##FMT;
static MTL::PixelFormat getMTLFormat(DataFormat Format, int Channels) {
switch (Format) {
case DataFormat::Int32:
MTLFormats(32Sint) break;
case DataFormat::Float32:
MTLFormats(32Float) break;
default:
llvm_unreachable("Unsupported Resource format specified");
}
return MTL::PixelFormatInvalid;
}
#define MTLVTXFormats(Base) \
if (Channels == 1) \
return MTL::VertexFormat##Base; \
if (Channels == 2) \
return MTL::VertexFormat##Base##2; \
if (Channels == 3) \
return MTL::VertexFormat##Base##3; \
if (Channels == 4) \
return MTL::VertexFormat##Base##4;
static MTL::VertexFormat getMTLVertexFormat(DataFormat Format, int Channels) {
switch (Format) {
case DataFormat::Float32:
MTLVTXFormats(Float) break;
default:
llvm_unreachable("Unsupported Resource format specified");
}
return MTL::VertexFormatInvalid;
}
namespace {
class MTLQueue : public offloadtest::Queue {
public:
MTL::CommandQueue *Queue;
MTLQueue(MTL::CommandQueue *Queue) : Queue(Queue) {}
~MTLQueue() {
if (Queue)
Queue->release();
}
};
class MTLFence : public offloadtest::Fence {
public:
std::string Name;
MTL::SharedEvent *Event;
uint64_t getFenceValue() override { return Event->signaledValue(); }
llvm::Error waitForCompletion(uint64_t SignalValue) override {
if (!Event->waitUntilSignaledValue(SignalValue, UINT64_MAX))
return llvm::createStringError(std::errc::timed_out,
"Timed out waiting on shared event.");
return llvm::Error::success();
}
MTLFence(MTL::SharedEvent *Event, llvm::StringRef Name)
: Name(Name), Event(Event) {}
~MTLFence() {
if (Event)
Event->release();
}
};
class MTLBuffer : public offloadtest::Buffer {
public:
MTL::Buffer *Buf;
std::string Name;
BufferCreateDesc Desc;
size_t SizeInBytes;
MTLBuffer(MTL::Buffer *Buf, llvm::StringRef Name, BufferCreateDesc Desc,
size_t SizeInBytes)
: Buf(Buf), Name(Name), Desc(Desc), SizeInBytes(SizeInBytes) {}
~MTLBuffer() override {
if (Buf)
Buf->release();
}
};
class MTLDevice : public offloadtest::Device {
Capabilities Caps;
MTL::Device *Device;
MTLQueue GraphicsQueue;
struct InvocationState {
InvocationState() { Pool = NS::AutoreleasePool::alloc()->init(); }
~InvocationState() {
for (MTL::Texture *T : Textures)
T->release();
for (MTL::Buffer *B : Buffers)
B->release();
if (ComputePipeline)
ComputePipeline->release();
if (RenderPipeline)
RenderPipeline->release();
Pool->release();
}
NS::AutoreleasePool *Pool = nullptr;
MTL::ComputePipelineState *ComputePipeline = nullptr;
MTL::RenderPipelineState *RenderPipeline = nullptr;
MTL::Buffer *ArgBuffer;
MTL::Buffer *VertexBuffer;
MTL::VertexDescriptor *VertexDescriptor;
llvm::SmallVector<MTL::Texture *> Textures;
llvm::SmallVector<MTL::Buffer *> Buffers;
MTL::Texture *FrameBufferTexture = nullptr;
MTL::CommandBuffer *CmdBuffer = nullptr;
std::shared_ptr<offloadtest::Fence> Fence;
};
llvm::Error setupVertexShader(InvocationState &IS, const Pipeline &P,
MTL::Function *Fn) {
if (P.Bindings.VertexBufferPtr) {
NS::Array *FnAttrs = Fn->vertexAttributes();
// I'm not really sure if there's any valid case for a vertex shader with
// no vertex attributes, so we just error if that ever occurs.
if (!FnAttrs)
return llvm::createStringError(
std::errc::invalid_argument,
"Vertex shader has no vertex attributes.");
if (FnAttrs->count() != P.Bindings.VertexAttributes.size())
return llvm::createStringError(
std::errc::invalid_argument,
"Mismatch between vertex shader attribute count and pipeline "
"vertex input count.");
// Collect the attribute indices the shader expects so that we can map the
// specified attributes onto the correct indices.
llvm::StringMap<uint32_t> ShaderAttrIndices;
for (uint32_t Ai = 0; Ai < FnAttrs->count(); ++Ai) {
auto *A = static_cast<MTL::VertexAttribute *>(FnAttrs->object(Ai));
if (A && A->isActive()) {
ShaderAttrIndices.insert(std::make_pair(
llvm::StringRef(A->name()->utf8String()), A->attributeIndex()));
llvm::errs() << "Shader attr: " << A->name()->utf8String()
<< " at index " << A->attributeIndex() << "\n";
}
}
IS.VertexDescriptor = MTL::VertexDescriptor::alloc()->init();
const uint32_t Stride = P.Bindings.getVertexStride();
for (const VertexAttribute &VA : P.Bindings.VertexAttributes) {
llvm::SmallString<32> AttrName(VA.Name);
llvm::transform(AttrName, AttrName.begin(), tolower);
// Append a zero since we're only supporting one attribute per name.
// We'll need to revisit this if we ever support indexed attributes.
AttrName += "0";
MTL::VertexAttributeDescriptor *VADesc =
MTL::VertexAttributeDescriptor::alloc()->init();
VADesc->setBufferIndex(0);
VADesc->setOffset(VA.Offset);
VADesc->setFormat(getMTLVertexFormat(VA.Format, VA.Channels));
IS.VertexDescriptor->attributes()->setObject(
VADesc, ShaderAttrIndices[AttrName]);
}
MTL::VertexBufferLayoutDescriptor *LDesc =
MTL::VertexBufferLayoutDescriptor::alloc()->init();
LDesc->setStride(Stride);
LDesc->setStepRate(1);
LDesc->setStepFunction(MTL::VertexStepFunctionPerVertex);
IS.VertexDescriptor->layouts()->setObject(LDesc, 0);
}
return llvm::Error::success();
}
llvm::Error loadShaders(InvocationState &IS, const Pipeline &P) {
NS::Error *Error = nullptr;
if (P.isCompute()) {
// This is an arbitrary distinction that we could alter in the future.
if (P.Shaders.size() != 1)
return llvm::createStringError(
std::errc::invalid_argument,
"Compute pipeline must have exactly one compute shader.");
const llvm::StringRef Program = P.Shaders[0].Shader->getBuffer();
dispatch_data_t Data = dispatch_data_create(
Program.data(), Program.size(), dispatch_get_main_queue(),
^{
});
MTL::Library *Lib = Device->newLibrary(Data, &Error);
if (Error)
return toError(Error);
IS.Pool->addObject(Lib);
MTL::Function *Fn = Lib->newFunction(NS::String::string(
P.Shaders[0].Entry.c_str(), NS::UTF8StringEncoding));
IS.ComputePipeline = Device->newComputePipelineState(Fn, &Error);
if (Error)
return toError(Error);
IS.Pool->addObject(Fn);
} else {
MTL::RenderPipelineDescriptor *Desc =
MTL::RenderPipelineDescriptor::alloc()->init();
IS.Pool->addObject(Desc);
for (const auto &S : P.Shaders) {
const llvm::StringRef Program = S.Shader->getBuffer();
dispatch_data_t Data = dispatch_data_create(
Program.data(), Program.size(), dispatch_get_main_queue(),
^{
});
MTL::Library *Lib = Device->newLibrary(Data, &Error);
if (Error)
return toError(Error);
IS.Pool->addObject(Lib);
MTL::Function *Fn = Lib->newFunction(
NS::String::string(S.Entry.c_str(), NS::UTF8StringEncoding));
switch (S.Stage) {
case Stages::Vertex:
Desc->setVertexFunction(Fn);
if (llvm::Error Err = setupVertexShader(IS, P, Fn))
return Err;
Desc->setVertexDescriptor(IS.VertexDescriptor);
break;
case Stages::Pixel:
Desc->setFragmentFunction(Fn);
break;
case Stages::Compute:
return llvm::createStringError(
std::errc::not_supported,
"Metal: Compute shader invalid with render pipeline!");
}
if (Error)
return toError(Error);
IS.Pool->addObject(Fn);
}
// TODO: Add support for more shader stages and different pipeline shapes.
if (Desc->vertexFunction() == nullptr ||
Desc->fragmentFunction() == nullptr)
return llvm::createStringError(
std::errc::invalid_argument,
"Graphics pipeline requires both a vertex shader and a fragment "
"shader.");
if (P.Bindings.RTargetBufferPtr) {
// Configure the render target color attachment.
const MTL::PixelFormat PF =
getMTLFormat(P.Bindings.RTargetBufferPtr->Format,
P.Bindings.RTargetBufferPtr->Channels);
MTL::RenderPipelineColorAttachmentDescriptor *RPCA =
MTL::RenderPipelineColorAttachmentDescriptor::alloc()->init();
RPCA->setPixelFormat(PF);
Desc->colorAttachments()->setObject(RPCA, 0);
}
IS.RenderPipeline = Device->newRenderPipelineState(Desc, &Error);
if (Error)
return toError(Error);
}
return llvm::Error::success();
}
llvm::Error createDescriptor(Resource &R, InvocationState &IS,
const uint32_t HeapIdx) {
auto *TablePtr = (IRDescriptorTableEntry *)IS.ArgBuffer->contents();
assert(R.BufferPtr->ArraySize == 1 &&
"Resource arrays are not yet supported on Metal.");
if (R.isRaw()) {
MTL::Buffer *Buf =
Device->newBuffer(R.BufferPtr->Data.back().get(), R.size(),
MTL::ResourceStorageModeManaged);
IRBufferView View = {};
View.buffer = Buf;
View.bufferSize = R.size();
IRDescriptorTableSetBufferView(&TablePtr[HeapIdx], &View);
IS.Buffers.push_back(Buf);
} else {
const uint64_t Width = R.isTexture() ? R.BufferPtr->OutputProps.Width
: R.size() / R.getElementSize();
const uint64_t Height =
R.isTexture() ? R.BufferPtr->OutputProps.Height : 1;
MTL::TextureUsage UsageFlags = MTL::ResourceUsageRead;
if (R.isReadWrite())
UsageFlags |= MTL::ResourceUsageWrite;
MTL::TextureDescriptor *Desc = nullptr;
const MTL::PixelFormat Format =
getMTLFormat(R.BufferPtr->Format, R.BufferPtr->Channels);
switch (R.Kind) {
case ResourceKind::Buffer:
case ResourceKind::RWBuffer:
Desc = MTL::TextureDescriptor::textureBufferDescriptor(
Format, Width, MTL::ResourceStorageModeManaged, UsageFlags);
break;
case ResourceKind::Texture2D:
case ResourceKind::RWTexture2D:
Desc = MTL::TextureDescriptor::texture2DDescriptor(Format, Width,
Height, false);
break;
case ResourceKind::Sampler:
llvm_unreachable("Not implemented yet.");
case ResourceKind::SampledTexture2D:
llvm_unreachable("SampledTextures aren't supported in Metal.");
case ResourceKind::StructuredBuffer:
case ResourceKind::RWStructuredBuffer:
case ResourceKind::ByteAddressBuffer:
case ResourceKind::RWByteAddressBuffer:
case ResourceKind::ConstantBuffer:
llvm_unreachable("Raw is checked above");
}
MTL::Texture *NewTex = Device->newTexture(Desc);
NewTex->replaceRegion(MTL::Region(0, 0, Width, Height), 0,
R.BufferPtr->Data.back().get(),
Width * R.getElementSize());
IS.Textures.push_back(NewTex);
IRDescriptorTableSetTexture(&TablePtr[HeapIdx], NewTex, 0, 0);
}
return llvm::Error::success();
}
llvm::Error createBuffers(Pipeline &P, InvocationState &IS) {
const size_t ResourceCount = P.getDescriptorCount();
const size_t TableSize = sizeof(IRDescriptorTableEntry) * ResourceCount;
if (TableSize > 0) {
IS.ArgBuffer =
Device->newBuffer(TableSize, MTL::ResourceStorageModeManaged);
uint32_t HeapIndex = 0;
for (auto &D : P.Sets) {
for (auto &R : D.Resources) {
if (auto Err = createDescriptor(R, IS, HeapIndex++))
return Err;
}
}
IS.ArgBuffer->didModifyRange(NS::Range::Make(0, IS.ArgBuffer->length()));
}
if (P.isGraphics()) {
// Create and mark the vertex buffer as modified.
IS.VertexBuffer = Device->newBuffer(
P.Bindings.VertexBufferPtr->Data.back().get(),
P.Bindings.VertexBufferPtr->size(), MTL::ResourceStorageModeManaged);
IS.VertexBuffer->didModifyRange(
NS::Range::Make(0, IS.VertexBuffer->length()));
}
return llvm::Error::success();
}
llvm::Error createComputeCommands(Pipeline &P, InvocationState &IS) {
IS.CmdBuffer = GraphicsQueue.Queue->commandBuffer();
MTL::ComputeCommandEncoder *CmdEncoder =
IS.CmdBuffer->computeCommandEncoder();
CmdEncoder->setComputePipelineState(IS.ComputePipeline);
CmdEncoder->setBuffer(IS.ArgBuffer, 0, 2);
for (uint64_t I = 0; I < IS.Textures.size(); ++I)
CmdEncoder->useResource(IS.Textures[I],
MTL::ResourceUsageRead | MTL::ResourceUsageWrite);
for (uint64_t I = 0; I < IS.Buffers.size(); ++I)
CmdEncoder->useResource(IS.Buffers[I],
MTL::ResourceUsageRead | MTL::ResourceUsageWrite);
NS::UInteger TGS[3] = {IS.ComputePipeline->maxTotalThreadsPerThreadgroup(),
1, 1};
if (P.Shaders[0].Reflection) {
llvm::Expected<llvm::json::Value> E = llvm::json::parse(
llvm::StringRef(P.Shaders[0].Reflection->getBuffer()));
if (!E)
return E.takeError();
llvm::json::Value Reflection = *E;
const llvm::json::Object *ReflectionObj = Reflection.getAsObject();
if (!ReflectionObj)
return llvm::createStringError(
std::errc::invalid_argument,
"Shader reflection must be a JSON object.");
auto StateIt = ReflectionObj->find("state");
if (StateIt == ReflectionObj->end())
return llvm::createStringError(
std::errc::invalid_argument,
"Key 'state' not found in shader reflection.");
const llvm::json::Object *State = StateIt->second.getAsObject();
auto TGSize = State->find("tg_size");
if (TGSize == State->end())
return llvm::createStringError(
std::errc::invalid_argument,
"Key 'tg_size' not found in shader reflection.");
const llvm::json::Array *TGSizeArr = TGSize->second.getAsArray();
if (TGSizeArr->size() != 3)
return llvm::createStringError(
std::errc::invalid_argument,
"Threadgroup size in reflection must have three components.");
for (size_t I = 0; I < 3; ++I) {
auto OpVal = (*TGSizeArr)[I].getAsUINT64();
if (!OpVal)
return llvm::createStringError(std::errc::invalid_argument,
"Threadgroup size components in "
"reflection must be integers.");
TGS[I] = *OpVal;
}
}
const llvm::ArrayRef<int> DispatchSize =
llvm::ArrayRef<int>(P.Shaders[0].DispatchSize);
const MTL::Size GridSize =
MTL::Size(TGS[0] * DispatchSize[0], TGS[1] * DispatchSize[1],
TGS[2] * DispatchSize[2]);
const MTL::Size GroupSize(TGS[0], TGS[1], TGS[2]);
CmdEncoder->dispatchThreads(GridSize, GroupSize);
CmdEncoder->memoryBarrier(MTL::BarrierScopeBuffers);
CmdEncoder->endEncoding();
return llvm::Error::success();
}
llvm::Error createGraphicsCommands(Pipeline &P, InvocationState &IS) {
IS.CmdBuffer = GraphicsQueue.Queue->commandBuffer();
MTL::RenderPassDescriptor *Desc =
MTL::RenderPassDescriptor::alloc()->init();
// Setup the render target texture.
CPUBuffer *RTarget = P.Bindings.RTargetBufferPtr;
const MTL::PixelFormat Format =
getMTLFormat(RTarget->Format, RTarget->Channels);
const uint64_t Width = RTarget->OutputProps.Width;
const uint64_t Height = RTarget->OutputProps.Height;
MTL::TextureDescriptor *TDesc = MTL::TextureDescriptor::texture2DDescriptor(
Format, Width, Height, false);
// Create a shared texture used for both rendering and CPU readback.
MTL::TextureDescriptor *SharedDesc = TDesc->copy();
SharedDesc->setUsage(MTL::TextureUsageRenderTarget |
MTL::TextureUsageShaderRead |
MTL::TextureUsageShaderWrite);
SharedDesc->setStorageMode(MTL::StorageModeShared);
IS.FrameBufferTexture = Device->newTexture(SharedDesc);
auto *CADesc = MTL::RenderPassColorAttachmentDescriptor::alloc()->init();
CADesc->setTexture(IS.FrameBufferTexture);
CADesc->setLoadAction(MTL::LoadActionClear);
CADesc->setClearColor(MTL::ClearColor());
CADesc->setStoreAction(MTL::StoreActionStore);
Desc->colorAttachments()->setObject(CADesc, 0);
MTL::RenderCommandEncoder *CmdEncoder =
IS.CmdBuffer->renderCommandEncoder(Desc);
CmdEncoder->setRenderPipelineState(IS.RenderPipeline);
// Explicitly set viewport to texture dimensions.
CmdEncoder->setViewport(
MTL::Viewport{0.0, 0.0, (double)Width, (double)Height, 0.0, 1.0});
CmdEncoder->setCullMode(MTL::CullModeNone);
// Bind vertex buffer at slot 0 to match the vertex descriptor which
// references buffer index 0.
CmdEncoder->setVertexBuffer(IS.VertexBuffer, 0, 0);
CmdEncoder->drawPrimitives(MTL::PrimitiveTypeTriangle, NS::UInteger(0),
P.Bindings.getVertexCount());
CmdEncoder->endEncoding();
return llvm::Error::success();
}
llvm::Error executeCommands(InvocationState &IS) {
// This is a hack but it works since this is all single threaded code.
static uint64_t FenceCounter = 0;
const uint64_t CurrentCounter = FenceCounter + 1;
auto *F = static_cast<MTLFence *>(IS.Fence.get());
IS.CmdBuffer->encodeSignalEvent(F->Event, CurrentCounter);
IS.CmdBuffer->commit();
if (auto Err = IS.Fence->waitForCompletion(CurrentCounter))
return Err;
// Check and surface any errors that occurred during execution.
NS::Error *CBErr = IS.CmdBuffer->error();
if (CBErr)
return toError(CBErr);
FenceCounter = CurrentCounter;
return llvm::Error::success();
}
llvm::Error copyBack(Pipeline &P, InvocationState &IS) {
uint32_t TextureIndex = 0;
uint32_t BufferIndex = 0;
for (auto &D : P.Sets) {
for (auto &R : D.Resources) {
assert(R.BufferPtr->ArraySize == 1 &&
"Resource arrays are not yet supported on Metal.");
if (R.isReadOnly()) {
if (R.isRaw())
++BufferIndex;
else
++TextureIndex;
continue;
}
if (R.isRaw()) {
memcpy(R.BufferPtr->Data.back().get(),
IS.Buffers[BufferIndex++]->contents(), R.size());
continue;
}
const uint64_t Width = R.isTexture() ? R.BufferPtr->OutputProps.Width
: R.size() / R.getElementSize();
const uint64_t Height =
R.isTexture() ? R.BufferPtr->OutputProps.Height : 1;
IS.Textures[TextureIndex++]->getBytes(
R.BufferPtr->Data.back().get(), Width * R.getElementSize(),
MTL::Region(0, 0, Width, Height), 0);
}
}
if (P.isGraphics()) {
CPUBuffer *RTarget = P.Bindings.RTargetBufferPtr;
const uint64_t Width = RTarget->OutputProps.Width;
const uint64_t Height = RTarget->OutputProps.Height;
const size_t ElemSize = RTarget->getElementSize();
const size_t RowBytes = Width * ElemSize;
// Read the framebuffer one row at a time into the output buffer.
// Read rows from the texture bottom-to-top into the buffer top-to-bottom
// so the final image is upright.
unsigned char *Buf =
reinterpret_cast<unsigned char *>(RTarget->Data[0].get());
for (uint64_t R = 0; R < Height; ++R) {
const uint32_t SrcRow = (uint32_t)((Height - 1) - R);
unsigned char *Dst = Buf + R * RowBytes;
IS.FrameBufferTexture->getBytes(
Dst, RowBytes, MTL::Region(0, SrcRow, (uint32_t)Width, 1), 0);
}
}
return llvm::Error::success();
}
public:
MTLDevice(MTL::Device *D, MTL::CommandQueue *Q)
: Device(D), GraphicsQueue(MTLQueue(Q)) {
Description = Device->name()->utf8String();
}
const Capabilities &getCapabilities() override {
if (Caps.empty())
queryCapabilities();
return Caps;
}
llvm::StringRef getAPIName() const override { return "Metal"; };
GPUAPI getAPI() const override { return GPUAPI::Metal; };
Queue &getGraphicsQueue() override { return GraphicsQueue; }
llvm::Expected<std::unique_ptr<offloadtest::Fence>>
createFence(llvm::StringRef Name) override {
MTL::SharedEvent *Event = Device->newSharedEvent();
if (!Event)
return llvm::createStringError(std::errc::device_or_resource_busy,
"Failed to create shared event.");
return std::make_unique<MTLFence>(Event, Name);
}
llvm::Expected<std::shared_ptr<offloadtest::Buffer>>
createBuffer(std::string Name, BufferCreateDesc &Desc,
size_t SizeInBytes) override {
MTL::ResourceOptions StorageMode;
switch (Desc.Location) {
case MemoryLocation::GpuOnly:
StorageMode = MTL::ResourceStorageModePrivate;
break;
case MemoryLocation::CpuToGpu:
case MemoryLocation::GpuToCpu:
StorageMode = MTL::ResourceStorageModeManaged;
break;
}
MTL::Buffer *Buf = Device->newBuffer(SizeInBytes, StorageMode);
if (!Buf)
return llvm::createStringError(std::errc::not_enough_memory,
"Failed to create Metal buffer.");
return std::make_shared<MTLBuffer>(Buf, Name, Desc, SizeInBytes);
}
llvm::Error executeProgram(Pipeline &P) override {
InvocationState IS;
auto FenceOrErr = this->createFence("Fence");
if (!FenceOrErr)
return FenceOrErr.takeError();
IS.Fence = std::move(*FenceOrErr);
if (auto Err = createBuffers(P, IS))
return Err;
if (auto Err = loadShaders(IS, P))
return Err;
if (P.isCompute()) {
if (auto Err = createComputeCommands(P, IS))
return Err;
llvm::outs() << "Created compute commands.\n";
} else {
if (auto Err = createGraphicsCommands(P, IS))
return Err;
llvm::outs() << "Created graphics commands.\n";
}
if (auto Err = executeCommands(IS))
return Err;
if (auto Err = copyBack(P, IS))
return Err;
return llvm::Error::success();
}
virtual ~MTLDevice() {};
private:
void queryCapabilities() {}
};
} // namespace
llvm::Error offloadtest::initializeMetalDevices(
const DeviceConfig /*Config*/,
llvm::SmallVectorImpl<std::unique_ptr<Device>> &Devices) {
MTL::Device *MetalDevice = MTL::CreateSystemDefaultDevice();
MTL::CommandQueue *MetalQueue = MetalDevice->newCommandQueue();
auto DefaultDev = std::make_unique<MTLDevice>(MetalDevice, MetalQueue);
Devices.push_back(std::move(DefaultDev));
return llvm::Error::success();
}