source: icGREP/icgrep-devel/icgrep/kernels/kernel.h @ 5422

Last change on this file since 5422 was 5422, checked in by cameron, 2 years ago

lz4d - LZ4 decompressor - initial check-in

File size: 15.7 KB
Line 
1/*
2 *  Copyright (c) 2016 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 */
5
6#ifndef KERNEL_BUILDER_H
7#define KERNEL_BUILDER_H
8
9#include "interface.h"      // for KernelInterface
10#include <boost/container/flat_map.hpp>
11#include <IR_Gen/idisa_builder.h>
12#include <kernels/pipeline.h>
13#include <llvm/IR/Constants.h>
14
15//#include <string>           // for string
16//#include <memory>           // for unique_ptr
17
18namespace llvm { class Function; }
19namespace llvm { class IntegerType; }
20namespace llvm { class LoadInst; }
21namespace llvm { class Type; }
22namespace llvm { class Value; }
23namespace parabix { class StreamSetBuffer; }
24
25namespace kernel {
26   
27class KernelBuilder : public KernelInterface {
28protected:
29    using KernelMap = boost::container::flat_map<std::string, unsigned>;
30    enum class Port { Input, Output };
31    using StreamPort = std::pair<Port, unsigned>;
32    using StreamMap = boost::container::flat_map<std::string, StreamPort>;
33    using StreamSetBuffers = std::vector<parabix::StreamSetBuffer *>;
34    using Kernels = std::vector<KernelBuilder *>;
35
36    friend void ::generateSegmentParallelPipeline(IDISA::IDISA_Builder *, const Kernels &);
37    friend void ::generatePipelineLoop(IDISA::IDISA_Builder *, const Kernels &);
38    friend void ::generateParallelPipeline(IDISA::IDISA_Builder *, const Kernels &);
39public:
40   
41    // Kernel Signatures and Module IDs
42    //
43    // A kernel signature uniquely identifies a kernel and its full functionality.
44    // In the event that a particular kernel instance is to be generated and compiled
45    // to produce object code, and we have a cached kernel object code instance with
46    // the same signature and targetting the same IDISA architecture, then the cached
47    // object code may safely be used to avoid recompilation.
48    //
49    // A kernel signature is a byte string of arbitrary length.
50    //
51    // Kernel developers should take responsibility for designing appropriate signature
52    // mechanisms that are short, inexpensive to compute and guarantee uniqueness
53    // based on the semantics of the kernel. 
54    //
55    // If no other mechanism is available, the default generateKernelSignature() method
56    // uses the full LLVM IR (before optimization) of the kernel instance.
57    //
58    // A kernel Module ID is short string that is used as a name for a particular kernel
59    // instance.  Kernel Module IDs are used to look up and retrieve cached kernel instances
60    // and so should be highly likely to uniquely identify a kernel instance.
61    //
62    // The ideal case is that a kernel Module ID serves as a full kernel signature thus
63    // guaranteeing uniqueness.  In this case, the moduleIDisUnique() method
64    // should return true.
65    //
66   
67    // Can the module ID itself serve as the unique signature?
68    virtual bool moduleIDisSignature() { return false; }
69   
70    virtual std::string generateKernelSignature(std::string moduleId);
71   
72    // Create a module stub for the kernel, populated only with its Module ID.     
73    //
74    void createKernelStub(const StreamSetBuffers & inputs, const StreamSetBuffers & outputs);
75
76    llvm::Module * getModule() const {
77        return mModule;
78    }
79
80    // Generate the Kernel to the current module (iBuilder->getModule()).
81    void generateKernel();
82   
83    llvm::Value * createInstance() final;
84
85    void initializeInstance() final;
86
87    void finalizeInstance() final;
88
89    llvm::Value * getProducedItemCount(const std::string & name, llvm::Value * doFinal = nullptr) const final;
90
91    void setProducedItemCount(const std::string & name, llvm::Value * value) const final;
92
93    llvm::Value * getProcessedItemCount(const std::string & name) const final;
94
95    void setProcessedItemCount(const std::string & name, llvm::Value * value) const final;
96
97    llvm::Value * getConsumedItemCount(const std::string & name) const final;
98
99    void setConsumedItemCount(const std::string & name, llvm::Value * value) const final;
100
101    bool hasNoTerminateAttribute() const {
102        return mNoTerminateAttribute;
103    }
104   
105    llvm::Value * getTerminationSignal() const final;
106
107    void setTerminationSignal() const final;
108
109    // Get the value of a scalar field for the current instance.
110    llvm::Value * getScalarFieldPtr(llvm::Value * index) const {
111        return getScalarFieldPtr(getInstance(), index);
112    }
113
114    llvm::Value * getScalarFieldPtr(const std::string & fieldName) const {
115        return getScalarFieldPtr(getInstance(), fieldName);
116    }
117
118    llvm::Value * getScalarField(const std::string & fieldName) const {
119        return iBuilder->CreateLoad(getScalarFieldPtr(fieldName), fieldName);
120    }
121
122//    llvm::Value * getScalarField(llvm::Value * index) const {
123//        return iBuilder->CreateLoad(getScalarFieldPtr(index));
124//    }
125
126    // Set the value of a scalar field for the current instance.
127    void setScalarField(const std::string & fieldName, llvm::Value * value) const {
128        iBuilder->CreateStore(value, getScalarFieldPtr(fieldName));
129    }
130
131//    void setScalarField(llvm::Value * index, llvm::Value * value) const {
132//        iBuilder->CreateStore(value, getScalarFieldPtr(index));
133//    }
134
135    // Synchronization actions for executing a kernel for a particular logical segment.
136    //
137    // Before the segment is processed, acquireLogicalSegmentNo must be used to load
138    // the segment number of the kernel state to ensure that the previous segment is
139    // complete (by checking that the acquired segment number is equal to the desired segment
140    // number).
141    // After all segment processing actions for the kernel are complete, and any necessary
142    // data has been extracted from the kernel for further pipeline processing, the
143    // segment number must be incremented and stored using releaseLogicalSegmentNo.
144    llvm::LoadInst * acquireLogicalSegmentNo() const;
145
146    void releaseLogicalSegmentNo(llvm::Value * nextSegNo) const;
147
148    llvm::Value * getConsumerState(const std::string & name) const;
149
150    // Get a parameter by name.
151    llvm::Argument * getParameter(llvm::Function * f, const std::string & name) const;
152
153    inline llvm::IntegerType * getSizeTy() const {
154        return getBuilder()->getSizeTy();
155    }
156
157    inline llvm::Type * getStreamTy(const unsigned FieldWidth = 1) {
158        return getBuilder()->getStreamTy(FieldWidth);
159    }
160   
161    inline llvm::Type * getStreamSetTy(const unsigned NumElements = 1, const unsigned FieldWidth = 1) {
162        return getBuilder()->getStreamSetTy(NumElements, FieldWidth);
163    }
164       
165    const StreamSetBuffers & getStreamSetInputBuffers() const { return mStreamSetInputBuffers; }
166
167    const parabix::StreamSetBuffer * getStreamSetInputBuffer(const unsigned i) const { return mStreamSetInputBuffers[i]; }
168
169    const StreamSetBuffers & getStreamSetOutputBuffers() const { return mStreamSetOutputBuffers; }
170
171    const parabix::StreamSetBuffer * getStreamSetOutputBuffer(const unsigned i) const { return mStreamSetOutputBuffers[i]; }
172
173    llvm::CallInst * createDoSegmentCall(const std::vector<llvm::Value *> & args) const;
174
175    llvm::Value * getAccumulator(const std::string & accumName) const;
176
177    virtual ~KernelBuilder() = 0;
178
179protected:
180
181    // Constructor
182    KernelBuilder(IDISA::IDISA_Builder * builder,
183                    std::string && kernelName,
184                    std::vector<Binding> && stream_inputs,
185                    std::vector<Binding> && stream_outputs,
186                    std::vector<Binding> && scalar_parameters,
187                    std::vector<Binding> && scalar_outputs,
188                    std::vector<Binding> && internal_scalars);
189
190    //
191    // Kernel builder subtypes define their logic of kernel construction
192    // in terms of 3 virtual methods for
193    // (a) preparing the Kernel state data structure
194    // (b) defining the logic of the doBlock function, and
195    // (c) defining the logic of the finalBlock function.
196    //
197    // Note: the kernel state data structure must only be finalized after
198    // all scalar fields have been added.   If there are no fields to
199    // be added, the default method for preparing kernel state may be used.
200   
201    void setNoTerminateAttribute(const bool noTerminate = true) {
202        mNoTerminateAttribute = noTerminate;
203    }
204
205    void prepareStreamSetNameMap();
206
207    virtual void prepareKernel();
208
209    virtual void generateInitializeMethod() { }
210   
211    virtual void generateDoSegmentMethod() = 0;
212
213    virtual void generateFinalizeMethod() { }
214
215    // Add an additional scalar field to the KernelState struct.
216    // Must occur before any call to addKernelDeclarations or createKernelModule.
217    unsigned addScalar(llvm::Type * type, const std::string & name);
218
219    unsigned addUnnamedScalar(llvm::Type * type);
220
221    // Run-time access of Kernel State and parameters of methods for
222    // use in implementing kernels.
223   
224    // Get the index of a named scalar field within the kernel state struct.
225    llvm::ConstantInt * getScalarIndex(const std::string & name) const;
226
227    llvm::Value * getInputStreamBlockPtr(const std::string & name, llvm::Value * streamIndex) const;
228
229    llvm::Value * loadInputStreamBlock(const std::string & name, llvm::Value * streamIndex) const;
230   
231    llvm::Value * getInputStreamPackPtr(const std::string & name, llvm::Value * streamIndex, llvm::Value * packIndex) const;
232   
233    llvm::Value * loadInputStreamPack(const std::string & name, llvm::Value * streamIndex, llvm::Value * packIndex) const;
234   
235    llvm::Value * getInputStreamSetCount(const std::string & name) const;
236
237    llvm::Value * getOutputStreamBlockPtr(const std::string & name, llvm::Value * streamIndex) const;
238   
239    void storeOutputStreamBlock(const std::string & name, llvm::Value * streamIndex, llvm::Value * toStore) const;
240   
241    llvm::Value * getOutputStreamPackPtr(const std::string & name, llvm::Value * streamIndex, llvm::Value * packIndex) const;
242   
243    void storeOutputStreamPack(const std::string & name, llvm::Value * streamIndex, llvm::Value * packIndex, llvm::Value * toStore) const;
244
245    llvm::Value * getOutputStreamSetCount(const std::string & name) const;
246
247    llvm::Value * getAdjustedInputStreamBlockPtr(llvm::Value * blockAdjustment, const std::string & name, llvm::Value * streamIndex) const;
248
249    llvm::Value * getRawInputPointer(const std::string & name, llvm::Value * streamIndex, llvm::Value * absolutePosition) const;
250
251    llvm::Value * getRawOutputPointer(const std::string & name, llvm::Value * streamIndex, llvm::Value * absolutePosition) const;
252
253    llvm::Value * getBaseAddress(const std::string & name) const;
254
255    void setBaseAddress(const std::string & name, llvm::Value * addr) const;
256
257    llvm::Value * getBufferedSize(const std::string & name) const;
258
259    void setBufferedSize(const std::string & name, llvm::Value * size) const;
260
261    void reserveBytes(const std::string & name, llvm::Value * requested) const;
262
263    llvm::Value * getAvailableItemCount(const std::string & name) const;
264
265    llvm::Value * getIsFinal() const {
266        return mIsFinal;
267    }
268
269
270    llvm::BasicBlock * CreateBasicBlock(std::string && name) const;
271
272    // Stream set helpers.
273
274    llvm::Value * getStreamSetBufferPtr(const std::string & name) const;
275
276    llvm::Value * getScalarFieldPtr(llvm::Value * const instance, llvm::Value * index) const {
277        assert ("instance cannot be null!" && instance);
278        return iBuilder->CreateGEP(getInstance(), {iBuilder->getInt32(0), index});
279    }
280
281    llvm::Value * getScalarFieldPtr(llvm::Value * const instance, const std::string & fieldName) const {
282        return getScalarFieldPtr(instance, getScalarIndex(fieldName));
283    }
284
285    void callGenerateInitializeMethod();
286
287    void callGenerateDoSegmentMethod();
288
289    void callGenerateFinalizeMethod();
290
291    StreamPort getStreamPort(const std::string & name) const;
292
293    const parabix::StreamSetBuffer * getInputStreamSetBuffer(const std::string & name) const {
294        const auto port = getStreamPort(name);
295        assert (port.first == Port::Input);
296        assert (port.second < mStreamSetInputBuffers.size());
297        return mStreamSetInputBuffers[port.second];
298    }
299
300    const parabix::StreamSetBuffer * getOutputStreamSetBuffer(const std::string & name) const {
301        const auto port = getStreamPort(name);
302        assert (port.first == Port::Output);
303        assert (port.second < mStreamSetOutputBuffers.size());
304        return mStreamSetOutputBuffers[port.second];
305    }
306
307    const parabix::StreamSetBuffer * getAnyStreamSetBuffer(const std::string & name) const {
308        unsigned index; Port port;
309        std::tie(port, index) = getStreamPort(name);
310        if (port == Port::Input) {
311            assert (index < mStreamSetInputBuffers.size());
312            return mStreamSetInputBuffers[index];
313        } else {
314            assert (index < mStreamSetOutputBuffers.size());
315            return mStreamSetOutputBuffers[index];
316        }
317    }
318
319private:
320
321    void setConsumerState(const std::string & name, llvm::Value * value) const;
322
323    llvm::Value * computeBlockIndex(const std::vector<Binding> & binding, const std::string & name, llvm::Value * itemCount) const;
324
325protected:
326
327    llvm::Module *                      mModule;
328    llvm::Function *                    mCurrentMethod;
329    bool                                mNoTerminateAttribute;
330    bool                                mIsGenerated;
331
332    llvm::Value *                       mIsFinal;
333    std::vector<llvm::Value *>          mAvailableItemCount;
334    llvm::Value *                       mOutputScalarResult;
335
336
337    std::vector<llvm::Type *>           mKernelFields;
338    KernelMap                           mKernelMap;
339    StreamMap                           mStreamMap;
340    StreamSetBuffers                    mStreamSetInputBuffers;
341    StreamSetBuffers                    mStreamSetOutputBuffers;
342
343};
344
345class SegmentOrientedKernel : public KernelBuilder {
346protected:
347
348    SegmentOrientedKernel(IDISA::IDISA_Builder * builder,
349                          std::string && kernelName,
350                          std::vector<Binding> && stream_inputs,
351                          std::vector<Binding> && stream_outputs,
352                          std::vector<Binding> && scalar_parameters,
353                          std::vector<Binding> && scalar_outputs,
354                          std::vector<Binding> && internal_scalars);
355
356};
357
358class BlockOrientedKernel : public KernelBuilder {
359protected:
360
361    void CreateDoBlockMethodCall();
362
363    // Each kernel builder subtype must provide its own logic for generating
364    // doBlock calls.
365    virtual void generateDoBlockMethod() = 0;
366
367    // Each kernel builder subtypre must also specify the logic for processing the
368    // final block of stream data, if there is any special processing required
369    // beyond simply calling the doBlock function.   In the case that the final block
370    // processing may be trivially implemented by dispatching to the doBlock method
371    // without additional preparation, the default generateFinalBlockMethod need
372    // not be overridden.
373
374    virtual void generateFinalBlockMethod(llvm::Value * remainingItems);
375
376    void generateDoSegmentMethod() override final;
377
378    BlockOrientedKernel(IDISA::IDISA_Builder * builder,
379                        std::string && kernelName,
380                        std::vector<Binding> && stream_inputs,
381                        std::vector<Binding> && stream_outputs,
382                        std::vector<Binding> && scalar_parameters,
383                        std::vector<Binding> && scalar_outputs,
384                        std::vector<Binding> && internal_scalars);
385
386private:
387
388    virtual bool useIndirectBr() const {
389        return iBuilder->supportsIndirectBr();
390    }
391
392    void writeDoBlockMethod();
393
394    void writeFinalBlockMethod(llvm::Value * remainingItems);
395
396private:
397
398    llvm::Function *        mDoBlockMethod;
399    llvm::BasicBlock *      mStrideLoopBody;
400    llvm::IndirectBrInst *  mStrideLoopBranch;
401    llvm::PHINode *         mStrideLoopTarget;
402};
403
404
405}
406#endif
Note: See TracBrowser for help on using the repository browser.