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

Last change on this file since 5425 was 5425, checked in by nmedfort, 2 years ago

Changes towards separate compilation

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