1/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7    http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15#include "tensorflow/contrib/lite/kernels/gemm_support.h"
16
17#include "tensorflow/contrib/lite/kernels/op_macros.h"
18
19namespace tflite {
20namespace gemm_support {
21
22struct RefCountedGemmContext {
23  gemmlowp::GemmContext* gemm_context_ = nullptr;
24  int num_references_ = 0;
25};
26
27void IncrementUsageCounter(TfLiteContext* context) {
28  auto* ptr = reinterpret_cast<RefCountedGemmContext*>(context->gemm_context);
29  if (ptr == nullptr) {
30    ptr = new RefCountedGemmContext;
31    ptr->gemm_context_ = new gemmlowp::GemmContext();
32    ptr->num_references_ = 0;
33    context->gemm_context = ptr;
34  }
35  ptr->num_references_++;
36}
37
38void DecrementUsageCounter(TfLiteContext* context) {
39  auto* ptr = reinterpret_cast<RefCountedGemmContext*>(context->gemm_context);
40  if (ptr == nullptr) {
41    TF_LITE_FATAL(
42        "Call to DecrementUsageCounter() not preceded by "
43        "IncrementUsageCounter()");
44  }
45  if (--ptr->num_references_ == 0) {
46    delete ptr->gemm_context_;
47    delete ptr;
48    context->gemm_context = nullptr;
49  }
50}
51
52gemmlowp::GemmContext* GetFromContext(TfLiteContext* context) {
53  auto* ptr = reinterpret_cast<RefCountedGemmContext*>(context->gemm_context);
54  if (ptr == nullptr) {
55    TF_LITE_FATAL(
56        "Call to GetFromContext() not preceded by IncrementUsageCounter()");
57  }
58  return ptr->gemm_context_;
59}
60
61void SetMaxNumThreads(TfLiteContext* context, int num_threads) {
62  IncrementUsageCounter(context);
63  GetFromContext(context)->set_max_num_threads(num_threads);
64  DecrementUsageCounter(context);
65}
66
67}  // namespace gemm_support
68}  // namespace tflite
69