rsCpuScript.cpp revision f218bf115af4ae4fd79adbb8842608b308a4cf07
1/*
2 * Copyright (C) 2011-2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17
18
19#include "rsCpuCore.h"
20
21#include "rsCpuScript.h"
22//#include "rsdRuntime.h"
23//#include "rsdAllocation.h"
24//#include "rsCpuIntrinsics.h"
25
26
27#include "utils/Vector.h"
28#include "utils/Timers.h"
29#include "utils/StopWatch.h"
30
31
32#include <bcc/BCCContext.h>
33#include <bcc/Renderscript/RSCompilerDriver.h>
34#include <bcc/Renderscript/RSExecutable.h>
35#include <bcc/Renderscript/RSInfo.h>
36
37namespace android {
38namespace renderscript {
39
40
41
42RsdCpuScriptImpl::RsdCpuScriptImpl(RsdCpuReferenceImpl *ctx, const Script *s) {
43    mCtx = ctx;
44    mScript = s;
45
46    mRoot = NULL;
47    mRootExpand = NULL;
48    mInit = NULL;
49    mFreeChildren = NULL;
50
51    mCompilerContext = NULL;
52    mCompilerDriver = NULL;
53    mExecutable = NULL;
54
55    mBoundAllocs = NULL;
56    mIntrinsicData = NULL;
57    mIsThreadable = true;
58}
59
60
61bool RsdCpuScriptImpl::init(char const *resName, char const *cacheDir,
62                            uint8_t const *bitcode, size_t bitcodeSize,
63                            uint32_t flags) {
64    //ALOGE("rsdScriptCreate %p %p %p %p %i %i %p", rsc, resName, cacheDir, bitcode, bitcodeSize, flags, lookupFunc);
65    //ALOGE("rsdScriptInit %p %p", rsc, script);
66
67    mCtx->lockMutex();
68
69    bcc::RSExecutable *exec;
70    const bcc::RSInfo *info;
71
72    mCompilerContext = NULL;
73    mCompilerDriver = NULL;
74    mExecutable = NULL;
75
76    mCompilerContext = new bcc::BCCContext();
77    if (mCompilerContext == NULL) {
78        ALOGE("bcc: FAILS to create compiler context (out of memory)");
79        mCtx->unlockMutex();
80        return false;
81    }
82
83    mCompilerDriver = new bcc::RSCompilerDriver();
84    if (mCompilerDriver == NULL) {
85        ALOGE("bcc: FAILS to create compiler driver (out of memory)");
86        mCtx->unlockMutex();
87        return false;
88    }
89
90    mCompilerDriver->setRSRuntimeLookupFunction(lookupRuntimeStub);
91    mCompilerDriver->setRSRuntimeLookupContext(this);
92
93    exec = mCompilerDriver->build(*mCompilerContext, cacheDir, resName,
94                                  (const char *)bitcode, bitcodeSize, NULL,
95                                  mCtx->getLinkRuntimeCallback());
96
97    if (exec == NULL) {
98        ALOGE("bcc: FAILS to prepare executable for '%s'", resName);
99        mCtx->unlockMutex();
100        return false;
101    }
102
103    mExecutable = exec;
104
105    exec->setThreadable(mIsThreadable);
106    if (!exec->syncInfo()) {
107        ALOGW("bcc: FAILS to synchronize the RS info file to the disk");
108    }
109
110    mRoot = reinterpret_cast<int (*)()>(exec->getSymbolAddress("root"));
111    mRootExpand =
112        reinterpret_cast<int (*)()>(exec->getSymbolAddress("root.expand"));
113    mInit = reinterpret_cast<void (*)()>(exec->getSymbolAddress("init"));
114    mFreeChildren =
115        reinterpret_cast<void (*)()>(exec->getSymbolAddress(".rs.dtor"));
116
117
118    info = &mExecutable->getInfo();
119    if (info->getExportVarNames().size()) {
120        mBoundAllocs = new Allocation *[info->getExportVarNames().size()];
121        memset(mBoundAllocs, 0, sizeof(void *) * info->getExportVarNames().size());
122    }
123
124    mCtx->unlockMutex();
125    return true;
126}
127
128void RsdCpuScriptImpl::populateScript(Script *script) {
129    const bcc::RSInfo *info = &mExecutable->getInfo();
130
131    // Copy info over to runtime
132    script->mHal.info.exportedFunctionCount = info->getExportFuncNames().size();
133    script->mHal.info.exportedVariableCount = info->getExportVarNames().size();
134    script->mHal.info.exportedPragmaCount = info->getPragmas().size();
135    script->mHal.info.exportedPragmaKeyList =
136        const_cast<const char**>(mExecutable->getPragmaKeys().array());
137    script->mHal.info.exportedPragmaValueList =
138        const_cast<const char**>(mExecutable->getPragmaValues().array());
139
140    if (mRootExpand) {
141        script->mHal.info.root = mRootExpand;
142    } else {
143        script->mHal.info.root = mRoot;
144    }
145}
146
147/*
148bool rsdInitIntrinsic(const Context *rsc, Script *s, RsScriptIntrinsicID iid, Element *e) {
149    pthread_mutex_lock(&rsdgInitMutex);
150
151    DrvScript *drv = (DrvScript *)calloc(1, sizeof(DrvScript));
152    if (drv == NULL) {
153        goto error;
154    }
155    s->mHal.drv = drv;
156    drv->mIntrinsicID = iid;
157    drv->mIntrinsicData = rsdIntrinsic_Init(rsc, s, iid, &drv->mIntrinsicFuncs);
158    s->mHal.info.isThreadable = true;
159
160    pthread_mutex_unlock(&rsdgInitMutex);
161    return true;
162
163error:
164    pthread_mutex_unlock(&rsdgInitMutex);
165    return false;
166}
167*/
168
169typedef void (*rs_t)(const void *, void *, const void *, uint32_t, uint32_t, uint32_t, uint32_t);
170
171void RsdCpuScriptImpl::forEachMtlsSetup(const Allocation * ain, Allocation * aout,
172                                        const void * usr, uint32_t usrLen,
173                                        const RsScriptCall *sc,
174                                        MTLaunchStruct *mtls) {
175
176    memset(mtls, 0, sizeof(MTLaunchStruct));
177
178    if (ain) {
179        mtls->fep.dimX = ain->getType()->getDimX();
180        mtls->fep.dimY = ain->getType()->getDimY();
181        mtls->fep.dimZ = ain->getType()->getDimZ();
182        //mtls->dimArray = ain->getType()->getDimArray();
183    } else if (aout) {
184        mtls->fep.dimX = aout->getType()->getDimX();
185        mtls->fep.dimY = aout->getType()->getDimY();
186        mtls->fep.dimZ = aout->getType()->getDimZ();
187        //mtls->dimArray = aout->getType()->getDimArray();
188    } else {
189        mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, "rsForEach called with null allocations");
190        return;
191    }
192
193    if (!sc || (sc->xEnd == 0)) {
194        mtls->xEnd = mtls->fep.dimX;
195    } else {
196        rsAssert(sc->xStart < mtls->fep.dimX);
197        rsAssert(sc->xEnd <= mtls->fep.dimX);
198        rsAssert(sc->xStart < sc->xEnd);
199        mtls->xStart = rsMin(mtls->fep.dimX, sc->xStart);
200        mtls->xEnd = rsMin(mtls->fep.dimX, sc->xEnd);
201        if (mtls->xStart >= mtls->xEnd) return;
202    }
203
204    if (!sc || (sc->yEnd == 0)) {
205        mtls->yEnd = mtls->fep.dimY;
206    } else {
207        rsAssert(sc->yStart < mtls->fep.dimY);
208        rsAssert(sc->yEnd <= mtls->fep.dimY);
209        rsAssert(sc->yStart < sc->yEnd);
210        mtls->yStart = rsMin(mtls->fep.dimY, sc->yStart);
211        mtls->yEnd = rsMin(mtls->fep.dimY, sc->yEnd);
212        if (mtls->yStart >= mtls->yEnd) return;
213    }
214
215    if (!sc || (sc->zEnd == 0)) {
216        mtls->zEnd = mtls->fep.dimZ;
217    } else {
218        rsAssert(sc->zStart < mtls->fep.dimZ);
219        rsAssert(sc->zEnd <= mtls->fep.dimZ);
220        rsAssert(sc->zStart < sc->zEnd);
221        mtls->zStart = rsMin(mtls->fep.dimZ, sc->zStart);
222        mtls->zEnd = rsMin(mtls->fep.dimZ, sc->zEnd);
223        if (mtls->zStart >= mtls->zEnd) return;
224    }
225
226    mtls->xEnd = rsMax((uint32_t)1, mtls->xEnd);
227    mtls->yEnd = rsMax((uint32_t)1, mtls->yEnd);
228    mtls->zEnd = rsMax((uint32_t)1, mtls->zEnd);
229    mtls->arrayEnd = rsMax((uint32_t)1, mtls->arrayEnd);
230
231    rsAssert(!ain || (ain->getType()->getDimZ() == 0));
232
233    mtls->rsc = mCtx;
234    mtls->ain = ain;
235    mtls->aout = aout;
236    mtls->fep.usr = usr;
237    mtls->fep.usrLen = usrLen;
238    mtls->mSliceSize = 1;
239    mtls->mSliceNum = 0;
240
241    mtls->fep.ptrIn = NULL;
242    mtls->fep.eStrideIn = 0;
243    mtls->isThreadable = mIsThreadable;
244
245    if (ain) {
246        mtls->fep.ptrIn = (const uint8_t *)ain->mHal.drvState.lod[0].mallocPtr;
247        mtls->fep.eStrideIn = ain->getType()->getElementSizeBytes();
248        mtls->fep.yStrideIn = ain->mHal.drvState.lod[0].stride;
249    }
250
251    mtls->fep.ptrOut = NULL;
252    mtls->fep.eStrideOut = 0;
253    if (aout) {
254        mtls->fep.ptrOut = (uint8_t *)aout->mHal.drvState.lod[0].mallocPtr;
255        mtls->fep.eStrideOut = aout->getType()->getElementSizeBytes();
256        mtls->fep.yStrideOut = aout->mHal.drvState.lod[0].stride;
257    }
258}
259
260
261void RsdCpuScriptImpl::invokeForEach(uint32_t slot,
262                                     const Allocation * ain,
263                                     Allocation * aout,
264                                     const void * usr,
265                                     uint32_t usrLen,
266                                     const RsScriptCall *sc) {
267
268    MTLaunchStruct mtls;
269    forEachMtlsSetup(ain, aout, usr, usrLen, sc, &mtls);
270    forEachKernelSetup(slot, &mtls);
271
272    RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
273    mCtx->launchThreads(ain, aout, sc, &mtls);
274    mCtx->setTLS(oldTLS);
275}
276
277void RsdCpuScriptImpl::forEachKernelSetup(uint32_t slot, MTLaunchStruct *mtls) {
278
279    mtls->script = this;
280    mtls->fep.slot = slot;
281
282    rsAssert(slot < mExecutable->getExportForeachFuncAddrs().size());
283    mtls->kernel = reinterpret_cast<ForEachFunc_t>(
284                      mExecutable->getExportForeachFuncAddrs()[slot]);
285    rsAssert(mtls->kernel != NULL);
286    mtls->sig = mExecutable->getInfo().getExportForeachFuncs()[slot].second;
287}
288
289int RsdCpuScriptImpl::invokeRoot() {
290    RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
291    int ret = mRoot();
292    mCtx->setTLS(oldTLS);
293    return ret;
294}
295
296void RsdCpuScriptImpl::invokeInit() {
297    if (mInit) {
298        mInit();
299    }
300}
301
302void RsdCpuScriptImpl::invokeFreeChildren() {
303    if (mFreeChildren) {
304        mFreeChildren();
305    }
306}
307
308void RsdCpuScriptImpl::invokeFunction(uint32_t slot, const void *params,
309                                      size_t paramLength) {
310    //ALOGE("invoke %p %p %i %p %i", dc, script, slot, params, paramLength);
311
312    RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
313    reinterpret_cast<void (*)(const void *, uint32_t)>(
314        mExecutable->getExportFuncAddrs()[slot])(params, paramLength);
315    mCtx->setTLS(oldTLS);
316}
317
318void RsdCpuScriptImpl::setGlobalVar(uint32_t slot, const void *data, size_t dataLength) {
319    //rsAssert(!script->mFieldIsObject[slot]);
320    //ALOGE("setGlobalVar %p %p %i %p %i", dc, script, slot, data, dataLength);
321
322    //if (mIntrinsicID) {
323        //mIntrinsicFuncs.setVar(dc, script, drv->mIntrinsicData, slot, data, dataLength);
324        //return;
325    //}
326
327    int32_t *destPtr = reinterpret_cast<int32_t *>(
328                          mExecutable->getExportVarAddrs()[slot]);
329    if (!destPtr) {
330        //ALOGV("Calling setVar on slot = %i which is null", slot);
331        return;
332    }
333
334    memcpy(destPtr, data, dataLength);
335}
336
337void RsdCpuScriptImpl::setGlobalVarWithElemDims(uint32_t slot, const void *data, size_t dataLength,
338                                                const Element *elem,
339                                                const size_t *dims, size_t dimLength) {
340
341    int32_t *destPtr = reinterpret_cast<int32_t *>(
342        mExecutable->getExportVarAddrs()[slot]);
343    if (!destPtr) {
344        //ALOGV("Calling setVar on slot = %i which is null", slot);
345        return;
346    }
347
348    // We want to look at dimension in terms of integer components,
349    // but dimLength is given in terms of bytes.
350    dimLength /= sizeof(int);
351
352    // Only a single dimension is currently supported.
353    rsAssert(dimLength == 1);
354    if (dimLength == 1) {
355        // First do the increment loop.
356        size_t stride = elem->getSizeBytes();
357        const char *cVal = reinterpret_cast<const char *>(data);
358        for (size_t i = 0; i < dims[0]; i++) {
359            elem->incRefs(cVal);
360            cVal += stride;
361        }
362
363        // Decrement loop comes after (to prevent race conditions).
364        char *oldVal = reinterpret_cast<char *>(destPtr);
365        for (size_t i = 0; i < dims[0]; i++) {
366            elem->decRefs(oldVal);
367            oldVal += stride;
368        }
369    }
370
371    memcpy(destPtr, data, dataLength);
372}
373
374void RsdCpuScriptImpl::setGlobalBind(uint32_t slot, Allocation *data) {
375
376    //rsAssert(!script->mFieldIsObject[slot]);
377    //ALOGE("setGlobalBind %p %p %i %p", dc, script, slot, data);
378
379    int32_t *destPtr = reinterpret_cast<int32_t *>(
380                          mExecutable->getExportVarAddrs()[slot]);
381    if (!destPtr) {
382        //ALOGV("Calling setVar on slot = %i which is null", slot);
383        return;
384    }
385
386    void *ptr = NULL;
387    mBoundAllocs[slot] = data;
388    if(data) {
389        ptr = data->mHal.drvState.lod[0].mallocPtr;
390    }
391    memcpy(destPtr, &ptr, sizeof(void *));
392}
393
394void RsdCpuScriptImpl::setGlobalObj(uint32_t slot, ObjectBase *data) {
395
396    //rsAssert(script->mFieldIsObject[slot]);
397    //ALOGE("setGlobalObj %p %p %i %p", dc, script, slot, data);
398
399    //if (mIntrinsicID) {
400        //mIntrinsicFuncs.setVarObj(dc, script, drv->mIntrinsicData, slot, alloc);
401        //return;
402    //}
403
404    int32_t *destPtr = reinterpret_cast<int32_t *>(
405                          mExecutable->getExportVarAddrs()[slot]);
406    if (!destPtr) {
407        //ALOGV("Calling setVar on slot = %i which is null", slot);
408        return;
409    }
410
411    rsrSetObject(mCtx->getContext(), (ObjectBase **)destPtr, data);
412}
413
414RsdCpuScriptImpl::~RsdCpuScriptImpl() {
415
416    if (mExecutable) {
417        Vector<void *>::const_iterator var_addr_iter =
418            mExecutable->getExportVarAddrs().begin();
419        Vector<void *>::const_iterator var_addr_end =
420            mExecutable->getExportVarAddrs().end();
421
422        bcc::RSInfo::ObjectSlotListTy::const_iterator is_object_iter =
423            mExecutable->getInfo().getObjectSlots().begin();
424        bcc::RSInfo::ObjectSlotListTy::const_iterator is_object_end =
425            mExecutable->getInfo().getObjectSlots().end();
426
427        while ((var_addr_iter != var_addr_end) &&
428               (is_object_iter != is_object_end)) {
429            // The field address can be NULL if the script-side has optimized
430            // the corresponding global variable away.
431            ObjectBase **obj_addr =
432                reinterpret_cast<ObjectBase **>(*var_addr_iter);
433            if (*is_object_iter) {
434                if (*var_addr_iter != NULL) {
435                    rsrClearObject(mCtx->getContext(), obj_addr);
436                }
437            }
438            var_addr_iter++;
439            is_object_iter++;
440        }
441    }
442
443    if (mCompilerContext) {
444        delete mCompilerContext;
445    }
446    if (mCompilerDriver) {
447        delete mCompilerDriver;
448    }
449    if (mExecutable) {
450        delete mExecutable;
451    }
452    if (mBoundAllocs) {
453        delete[] mBoundAllocs;
454    }
455}
456
457Allocation * RsdCpuScriptImpl::getAllocationForPointer(const void *ptr) const {
458    if (!ptr) {
459        return NULL;
460    }
461
462    for (uint32_t ct=0; ct < mScript->mHal.info.exportedVariableCount; ct++) {
463        Allocation *a = mBoundAllocs[ct];
464        if (!a) continue;
465        if (a->mHal.drvState.lod[0].mallocPtr == ptr) {
466            return a;
467        }
468    }
469    ALOGE("rsGetAllocation, failed to find %p", ptr);
470    return NULL;
471}
472
473
474}
475}
476