Repository: tensorflow/tensorflow (language: cpp)

Issue:
bazel build aot armeabi-v7a so failed
<em>Please make sure that this is a build/installation issue. As per our [GitHub Policy](https://github.com/tensorflow/tensorflow/blob/master/ISSUES.md), we only address code/doc bugs, performance issues, feature requests and build/installation issues on GitHub. tag:build_template</em>

**System information**
- OS Platform and Distribution (e.g., Linux Ubuntu 16.04):
macOS 10.13.6
- Mobile device (e.g. iPhone 8, Pixel 2, Samsung Galaxy) if the issue happens on mobile device:
- TensorFlow installed from (source or binary):
binary
- TensorFlow version:
1.12.0
- Python version:
3.6.2
- Installed using virtualenv? pip? conda?:
conda
- Bazel version (if compiling from source):
0.21.0
- ndk version
14b
- GCC/Compiler version (if compiling from source):
- CUDA/cuDNN version:
no
- GPU model and memory:



**Describe the problem**

I have tried to perform a simple demo in //tensorflow/compiler/aot/test/test_graph_tfmatmul.pb by using this command:
bazel build //tensorflow/compiler/aot/tests:my_library
and have succeeded in the building procedure.

However, when I tried to generate a .so file for an android project I got failed. The command I used is as below:
```text
bazel build --crosstool_top=@androidndk//:default_crosstool  --cpu=armeabi-v7a  --host_crosstool_top=@bazel_tools//tools/cpp:toolchain --cxxopt="-std=c++11" //tensorflow/compiler/aot/tests:my_library
```
I don't know how to fix the problem. Please help.  The error message is as below:


```text
/private/var/tmp/_bazel_sunday/7a01d1437f77ea8b21ffc614971e2517/external/mkl_dnn/BUILD.bazel:71:1: C++ compilation of rule '@mkl_dnn//:mkldnn_single_threaded' failed (Exit 1)
In file included from external/mkl_dnn/src/common/utils.cpp:22:
In file included from external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/xmmintrin.h:27:
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:47:5: error: use of undeclared identifier '__builtin_ia32_emms'; did you mean '__builtin_isless'?
    __builtin_ia32_emms();
    ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:47:5: note: '__builtin_isless' declared here
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:47:25: error: too few arguments to function call, expected 2, have 0
    __builtin_ia32_emms();
                        ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:64:19: error: use of undeclared identifier '__builtin_ia32_vec_init_v2si'
    return (__m64)__builtin_ia32_vec_init_v2si(__i, 0);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:81:12: error: use of undeclared identifier '__builtin_ia32_vec_ext_v2si'
    return __builtin_ia32_vec_ext_v2si((__v2si)__m, 0);
           ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:143:19: error: use of undeclared identifier '__builtin_ia32_packsswb'
    return (__m64)__builtin_ia32_packsswb((__v4hi)__m1, (__v4hi)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:173:19: error: use of undeclared identifier '__builtin_ia32_packssdw'
    return (__m64)__builtin_ia32_packssdw((__v2si)__m1, (__v2si)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:203:19: error: use of undeclared identifier '__builtin_ia32_packuswb'
    return (__m64)__builtin_ia32_packuswb((__v4hi)__m1, (__v4hi)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:230:19: error: use of undeclared identifier '__builtin_ia32_punpckhbw'
    return (__m64)__builtin_ia32_punpckhbw((__v8qi)__m1, (__v8qi)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:253:19: error: use of undeclared identifier '__builtin_ia32_punpckhwd'
    return (__m64)__builtin_ia32_punpckhwd((__v4hi)__m1, (__v4hi)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:274:19: error: use of undeclared identifier '__builtin_ia32_punpckhdq'
    return (__m64)__builtin_ia32_punpckhdq((__v2si)__m1, (__v2si)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:301:19: error: use of undeclared identifier '__builtin_ia32_punpcklbw'
    return (__m64)__builtin_ia32_punpcklbw((__v8qi)__m1, (__v8qi)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:324:19: error: use of undeclared identifier '__builtin_ia32_punpcklwd'
    return (__m64)__builtin_ia32_punpcklwd((__v4hi)__m1, (__v4hi)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:345:19: error: use of undeclared identifier '__builtin_ia32_punpckldq'
    return (__m64)__builtin_ia32_punpckldq((__v2si)__m1, (__v2si)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:366:19: error: use of undeclared identifier '__builtin_ia32_paddb'; did you mean '__builtin_arm_qadd'?
    return (__m64)__builtin_ia32_paddb((__v8qi)__m1, (__v8qi)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:366:19: note: '__builtin_arm_qadd' declared here
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:366:40: error: cannot initialize a parameter of type 'int' with an rvalue of type '__v8qi' (vector of 8 'char' values)
    return (__m64)__builtin_ia32_paddb((__v8qi)__m1, (__v8qi)__m2);
                                       ^~~~~~~~~~~~
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:387:19: error: use of undeclared identifier '__builtin_ia32_paddw'; did you mean '__builtin_arm_qadd'?
    return (__m64)__builtin_ia32_paddw((__v4hi)__m1, (__v4hi)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:366:19: note: '__builtin_arm_qadd' declared here
    return (__m64)__builtin_ia32_paddb((__v8qi)__m1, (__v8qi)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:387:40: error: cannot initialize a parameter of type 'int' with an rvalue of type '__v4hi' (vector of 4 'short' values)
    return (__m64)__builtin_ia32_paddw((__v4hi)__m1, (__v4hi)__m2);
                                       ^~~~~~~~~~~~
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:408:19: error: use of undeclared identifier '__builtin_ia32_paddd'; did you mean '__builtin_arm_qadd'?
    return (__m64)__builtin_ia32_paddd((__v2si)__m1, (__v2si)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:366:19: note: '__builtin_arm_qadd' declared here
    return (__m64)__builtin_ia32_paddb((__v8qi)__m1, (__v8qi)__m2);
                  ^
external/androidndk/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib64/clang/3.8.275480/include/mmintrin.h:408:40: error: cannot initialize a parameter of type 'int' with an rvalue of type '__v2si' (vector of 2 'int' values)
    return (__m64)__builtin_ia32_paddd((__v2si)__m1, (__v2si)__m2);
                                       ^~~~~~~~~~~~
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
Target //tensorflow/compiler/aot/tests:my_library failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 1.407s, Critical Path: 0.28s
INFO: 0 processes.
FAILED: Build did NOT complete successfully
```
the content of the bazel BUILD file:
```text
load("//tensorflow/compiler/aot:tfcompile.bzl", "tf_library")

tf_library(
    name = "test_graph_tfmatmul",
    cpp_class = "foo::bar::MatMulComp",
    graph = "test_graph_tfmatmul.pb",
    config = "test_graph_tfmatmul.config.pbtxt",
)

cc_library(
    name = "my_library",
    srcs = [
        "my_code.cc",  # include test_graph_tfmatmul.h to access the generated header
    ],
    hdrs = ["my_code.h"],
    deps = [
        ":test_graph_tfmatmul",  # link in the generated object file
        "//third_party/eigen3",
    ],
    linkopts = [
        "-lpthread",
    ]
)
```

**Provide the exact sequence of commands / steps that you executed before running into the problem**


**Any other info / logs**
Include any logs or source code that would be helpful to diagnose the problem. If including tracebacks, please include the full traceback. Large logs and files should be attached.



Discussion / hints:
@sundayxcn Could you provide more details on the context and the issue? Thanks!
> @sundayxcn Could you provide more details on the context and the issue? Thanks!


@jvishnuvardhan 

At first I pulled the tensorflow source code from the branch master
The demo file is from the path of  /tensorflow/compiler/aot/tests

Step 1:  Run python make_simple.py and generate the .pb file
```python
import argparse
import os
import sys

from tensorflow.core.protobuf import saver_pb2
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import function
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import app
from tensorflow.python.training import saver as saver_lib

FLAGS = None

def tfmatmul(_):
  x = array_ops.placeholder(dtypes.float32, name='x_hold')
  y = array_ops.placeholder(dtypes.float32, name='y_hold')
  math_ops.matmul(x, y, name='x_y_prod')

def tfmatmulandadd(_):
  
  x = array_ops.placeholder(dtypes.float32, name='x_hold')
  y = array_ops.placeholder(dtypes.float32, name='y_hold')
  math_ops.matmul(x, y, name='x_y_prod')
  math_ops.add(x, y, name='x_y_sum')

def write_graph(build_graph, out_dir):
  """Build a graph using build_graph and write it out."""
  g = ops.Graph()
  with g.as_default():
    build_graph(out_dir)
    filename = os.path.join(out_dir, 'test_graph_%s.pb' % build_graph.__name__)
    with open(filename, 'wb') as f:
      f.write(g.as_graph_def().SerializeToString())

def main(_):
  write_graph(tfmatmul, FLAGS.out_dir)

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.register('type', 'bool', lambda v: v.lower() == 'true')
  parser.add_argument(
      '--out_dir',
      type=str,
      default='',
      help='Output directory for graphs, checkpoints and savers.')
  FLAGS, unparsed = parser.parse_known_args()
  app.run(main=main, argv=[sys.argv[0]] + unparsed)
```

step 2:( After running step1 the test_graph_tfmatmul.pb file is obtained)

 Step 2.1 
I create files of my_code.cc and my_code.h
my_code.cc
```C++
#define EIGEN_USE_THREADS
#define EIGEN_USE_CUSTOM_THREAD_POOL

#include <iostream>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/compiler/aot/tests/test_graph_tfmatmul.h" // generated
#include "my_code.h"

int my_code::compare(){
    Eigen::ThreadPool tp(2);  // Size the thread pool as appropriate.
    Eigen::ThreadPoolDevice device(&tp, tp.NumThreads());

    foo::bar::MatMulComp matmul;
    matmul.set_thread_pool(&device);

    // Set up args and run the computation.
    const float args[15] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15};
    std::copy(args + 0, args + 6, matmul.arg0_data());
    std::copy(args + 6, args + 12, matmul.arg1_data());
    matmul.Run();

    // Check result
    if (matmul.result0(0, 0) == 58) {
        std::cout << "Success" << std::endl;
    } else {
        std::cout << "Failed. Expected value 58 at 0,0. Got:"
                    << matmul.result0(0, 0) << std::endl;
    }

    return 0;
}
```

my_code.h
```C++
class my_code
{
public:
    int compare();
}
```

step 2.2:
 I changed the BUILD File as follows:
```text
load("//tensorflow/compiler/aot:tfcompile.bzl", "tf_library")

tf_library(
name = "test_graph_tfmatmul",
cpp_class = "foo::bar::MatMulComp",
graph = "test_graph_tfmatmul.pb",
config = "test_graph_tfmatmul.config.pbtxt",
)

cc_library(
name = "my_library",
srcs = [
"my_code.cc", # include test_graph_tfmatmul.h to access the generated header
],
hdrs = ["my_code.h"],
deps = [
":test_graph_tfmatmul", # link in the generated object file
"//third_party/eigen3",
],
linkopts = [
"-lpthread",
]
)
```

Step3: Run the bazel build to generate the .so file
```text
bazel build --crosstool_top=@androidndk//:default_crosstool --cpu=armeabi-v7a --host_crosstool_top=@bazel_tools//tools/cpp:toolchain --cxxopt="-std=c++11" //tensorflow/compiler/aot/tests:my_library
```
the error message hints about mkl_dnn as you can see in my first post. I added --config=mkl in the command 

```text
bazel build --crosstool_top=@androidndk//:default_crosstool --cpu=armeabi-v7a --host_crosstool_top=@bazel_tools//tools/cpp:toolchain --cxxopt="-std=c++11" --config=mkl //tensorflow/compiler/aot/tests:my_library 
```
but got failed again:

```text
INFO: Invocation ID: c9afb568-3d69-4fb3-bae5-27dd141e2357
INFO: Build options have changed, discarding analysis cache.
INFO: Analysed target //tensorflow/compiler/aot/tests:my_library (96 packages loaded, 11819 targets configured).
INFO: Found 1 target...
ERROR: /Users/apple/tmp/tensorflow/tensorflow/compiler/xla/service/cpu/BUILD:525:1: C++ compilation of rule '//tensorflow/compiler/xla/service/cpu:runtime_conv2d' failed (Exit 1)
In file included from tensorflow/compiler/xla/service/cpu/runtime_conv2d.cc:21:
In file included from ./tensorflow/compiler/xla/service/cpu/runtime_conv2d_impl.h:18:
In file included from ./third_party/eigen3/unsupported/Eigen/CXX11/Tensor:1:
In file included from external/eigen_archive/unsupported/Eigen/CXX11/Tensor:111:
external/eigen_archive/unsupported/Eigen/CXX11/src/Tensor/TensorDimensions.h:340:167: error: non-constant-expression cannot be narrowed from type 'long long' to 'int' in initializer list [-Wc++11-narrowing]
  EIGEN_STRONG_INLINE explicit DSizes(DenseIndex firstDimension, DenseIndex secondDimension, IndexTypes... otherDimensions) : Base({{firstDimension, secondDimension, otherDimensions...}}) {
                                                                                                                                                                      ^~~~~~~~~~~~~~~
external/eigen_archive/unsupported/Eigen/CXX11/src/Tensor/TensorMap.h:69:131: note: in instantiation of function template specialization 'Eigen::DSizes<int, 4>::DSizes<long long, long long>' requested here
    EIGEN_STRONG_INLINE TensorMap(PointerArgType dataPtr, Index firstDimension, IndexTypes... otherDimensions) : m_data(dataPtr), m_dimensions(firstDimension, otherDimensions...) {
                                                                                                                                  ^
./tensorflow/compiler/xla/service/cpu/runtime_conv2d_impl.h:40:7: note: in instantiation of function template specialization 'Eigen::TensorMap<Eigen::Tensor<const float, 4, 1, int>, 16, MakePointer>::TensorMap<long long, long long, long long>' requested here
      input(lhs, input_batch, input_rows, input_cols, input_channels);
      ^
tensorflow/compiler/xla/service/cpu/runtime_conv2d.cc:37:20: note: in instantiation of function template specialization 'tensorflow::xla::EigenConvImpl<Eigen::ThreadPoolDevice, float>' requested here
  tensorflow::xla::EigenConvImpl(
                   ^
external/eigen_archive/unsupported/Eigen/CXX11/src/Tensor/TensorDimensions.h:340:167: note: insert an explicit cast to silence this issue
  EIGEN_STRONG_INLINE explicit DSizes(DenseIndex firstDimension, DenseIndex secondDimension, IndexTypes... otherDimensions) : Base({{firstDimension, secondDimension, otherDimensions...}}) {
                                                                                                                                                                      ^~~~~~~~~~~~~~~
                                                                                                                                                                      static_cast<int>( )
external/eigen_archive/unsupported/Eigen/CXX11/src/Tensor/TensorDimensions.h:340:167: error: non-constant-expression cannot be narrowed from type 'long long' to 'int' in initializer list [-Wc++11-narrowing]
  EIGEN_STRONG_INLINE explicit DSizes(DenseIndex firstDimension, DenseIndex secondDimension, IndexTypes... otherDimensions) : Base({{firstDimension, secondDimension, otherDimensions...}}) {
                                                                                                                                                                      ^~~~~~~~~~~~~~~
external/eigen_archive/unsupported/Eigen/CXX11/src/Tensor/TensorDimensions.h:340:167: note: insert an explicit cast to silence this issue
  EIGEN_STRONG_INLINE explicit DSizes(DenseIndex firstDimension, DenseIndex secondDimension, IndexTypes... otherDimensions) : Base({{firstDimension, secondDimension, otherDimensions...}}) {
                                                                                                                                                                      ^~~~~~~~~~~~~~~
                                                                                                                                                                      static_cast<int>( )
2 errors generated.
Target //tensorflow/compiler/aot/tests:my_library failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 51.010s, Critical Path: 12.17s
INFO: 20 processes: 20 local.
FAILED: Build did NOT complete successfully
```

@jvishnuvardhan  
I have't found any document on how to build an android project to support .so file (containing a pre-trained model ) on tensorflow aot guide.  The command I found is from [bazel guide](
https://docs.bazel.build/versions/master/android-ndk.html)

and I tried to implement a helloword.cc (just return "hellowolrd") which was successful. However, when I tried to embed the pre-trained model test_graph_tfmatmul I got failed. I guess the tensorflow configure should be changed in some way but I can't figure it out.

Thank you very much!          
     
@sundayxcn Try
```
bazel build --config android_arm \
--cxxopt=-std=c++11 --cxxopt=-Wno-c++11-narrowing \
//tensorflow/compiler/aot/tests:my_library
```
Howeverr, `cc_library()` is for creating static libraries (.a), to create .so you should use [`cc_binary()`](https://docs.bazel.build/versions/master/be/c-cpp.html#cc_binary), it should be something like,
```
cc_binary(
    name = "libmylib.so",
    linkshared=True,
    srcs = [
        "my_code.cc", 
        "my_code.h", 
    ],
    deps = [
        ":test_graph_tfmatmul",
        "//third_party/eigen3",
    ],
)
```

@freedomtan , Hi, thanks for your quick reply. I have adopted your suggestions and built the .so library successfully a moment ago. However, while I am trying calling the **compare** method mentioned, see above **step 2.1** in before attached script. The Android Studio gives the error traceback like following:
```text
  Process: com.example.sunday.ndkdemo, PID: 28571
    java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "ceilf" referenced by "/data/app/com.example.sunday.ndkdemo-B05bPAF3wQDe9L865kV88Q==/lib/arm/libmylib.so"...
        at java.lang.Runtime.loadLibrary0(Runtime.java:1016)
        at java.lang.System.loadLibrary(System.java:1672)
        at com.example.sunday.ndkdemo.MainActivity.<clinit>(MainActivity.java:11)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
```
I believe this is caused by the lack of **ceilf** method in my .so library.  But in the **compare** method, I only easy imported ''foo::bar::MatMulComp matmul'' and did some simple calculations. Now, I am confused why there were concerned about the **ceilf** in my library.  PS: Also, the resulted .so library is around 30mb+, after imported and built in Android APK, it has been converted to 600KB only in APK!!?? 
Could you help me to check this problem. please? Hope to hear from you soon! Thanks in advance!
`ceilf()` is a standard C library function, should be in `libm`. Add something like `linkopts="-lm"` to your `cc_binary(....)` could help. Add `-s` to your bazel build command:
```
bazel build --config android_arm \
--cxxopt=-std=c++11 --cxxopt=-Wno-c++11-narrowing \
//tensorflow/compiler/aot/tests:my_library -s
```
Then you can learn why you got a huge .so.
> `ceilf()` is a standard C library function, should be in `libm`. Add something like `linkopts="-lm"` to your `cc_binary(....)` could help. Add `-s` to your bazel build command:
> 
> ```
> bazel build --config android_arm \
> --cxxopt=-std=c++11 --cxxopt=-Wno-c++11-narrowing \
> //tensorflow/compiler/aot/tests:my_library -s
> ```
> Then you can learn why you got a huge .so.
@freedomtan  According to your advice, i change the cc_binary,
```text
cc_binary(
    name = "libmy_library.so",
    linkshared=True,
    srcs = [
        "my_code.cc", 
        "my_code.h", 
    ],
    deps = [
        ":test_graph_tfmatmul",
        "//third_party/eigen3",
    ],
    linkopts=["-lm"],
)
```

There are different error:
```text
java.lang.UnsatisfiedLinkError: dlopen failed: library "../../../../src/main/jniLibs/armeabi/libmy_library.so" not found
        at java.lang.Runtime.loadLibrary0(Runtime.java:989)
        at java.lang.System.loadLibrary(System.java:1562)
        at com.example.sunday.ndkdemo.MainActivity.<clinit>(MainActivity.java:12)
        at java.lang.Class.newInstance(Native Method)
```
but my android project  configuration files still unchanged,only change the libmy_library.so . 
( i check the apk. the package include libmy_library.so.)
I tested it several times. if i remove linkopts=["-lm"], 
errmsg:
```text
java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "ceilf" referenced by "/data/app/com.example.sunday.ndkdemo-B05bPAF3wQDe9L865kV88Q==/lib/arm/libmylib.so"...
```
if i restore linkopts=["-lm"], 
errmsg:
```text
java.lang.UnsatisfiedLinkError: dlopen failed: library "../../../../src/main/jniLibs/armeabi/libmy_library.so" not found
```
so I'm sure there's still a problem about so. Please check it for me. thank you...




Are there any additional logcat messages surrounding the dlopen failure?
@jdduke @freedomtan 
the dlopen message has no more message. and i change the bazel command :
```text
bazel build --crosstool_top=//external:android/crosstool --cpu=armeabi-v7a --host_crosstool_top=@bazel_tools//tools/cpp:toolchain --cxxopt=-std=c++11 --cxxopt=-Wno-c++11-narrowing //tensorflow/compiler/aot/tests:my_library
```
show linking error:
```text
note: 'CFURLCreateDataAndPropertiesFromResource' has been explicitly marked deprecated here
Boolean CFURLCreateDataAndPropertiesFromResource(CFAllocatorRef alloc, CFURLRef url, CFDataRef *resourceData, CFDictionaryRef *properties, CFArrayRef desiredProperties, SInt32 *errorCode) API_DEPRECATED("For resource data, use the CFReadStream API. For file resource properties, use CFURLCopyResourcePropertiesForKeys.", macos(10.0,10.9), ios(2.0,7.0), watchos(2.0,2.0), tvos(9.0,9.0));
        ^
1 warning generated.
INFO: From Linking external/curl/libcurl.a [for host]:
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/asyn-ares.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/curl_multibyte.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/curl_rtmp.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/curl_sspi.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/curl_threads.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/hostasyn.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/hostcheck.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/hostip4.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/inet_pton.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/krb5.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/md4.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/memdebug.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/nwlib.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/nwos.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/security.o has no symbols
/Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/strtok.o has no symbols
INFO: From Compiling tensorflow/core/grappler/optimizers/pin_to_host_optimizer.cc [for host]:
In file included from tensorflow/core/grappler/optimizers/pin_to_host_optimizer.cc:16:
./tensorflow/core/grappler/optimizers/pin_to_host_optimizer.h:56:26: warning: private field 'opt_level_' is not used [-Wunused-private-field]
  RewriterConfig::Toggle opt_level_;
                         ^
1 warning generated.
INFO: From Linking tensorflow/compiler/aot/tfcompile [for host]:
ld: warning: text-based stub file /System/Library/Frameworks//IOKit.framework/IOKit.tbd and library file /System/Library/Frameworks//IOKit.framework/IOKit are out of sync. Falling back to library file for linking.
ld: warning: text-based stub file /System/Library/Frameworks//CoreFoundation.framework/CoreFoundation.tbd and library file /System/Library/Frameworks//CoreFoundation.framework/CoreFoundation are out of sync. Falling back to library file for linking.
ld: warning: text-based stub file /System/Library/Frameworks//Security.framework/Security.tbd and library file /System/Library/Frameworks//Security.framework/Security are out of sync. Falling back to library file for linking.
INFO: From Executing genrule //tensorflow/compiler/aot/tests:gen_test_graph_tfmatmul:
2019-02-18 13:19:30.705553: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.2 AVX
ERROR: /Users/sunday/tensorflow/tensorflow/compiler/aot/tests/BUILD:15:1: Linking of rule '//tensorflow/compiler/aot/tests:my_library' failed (Exit 1)
clang: error: no such file or directory: 'libmy_library.so'
Target //tensorflow/compiler/aot/tests:my_library failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 1399.023s, Critical Path: 231.09s
INFO: 2563 processes: 2563 local.

```
but the tensorflow binary is from resource code compile 
```text
bazel build  --copt=-msse4.1 --copt=-msse4.2 --copt=-mavx --copt=-mavx2 //tensorflow/tools/pip_package:build_pip_package
```


apparently, it failed because of this line
```
java.lang.UnsatisfiedLinkError: dlopen failed: library "../../../../src/main/jniLibs/armeabi/libmy_library.so" not found
```
This probably is caused by some link flag which wrote `../../../../src/main/jniLibs/armeabi/libmy_library.so` into your `libmy_library.so`. You may want to check what link flags are used (with `-s` in bazel command) and inspect your `libmy_library.so` (by something like `readelf -a`) before using it. If you don't how to do these, you may want to check with your local compile / tool chain expert to get quick response.
@freedomtan  @jdduke please help my check my latest action,thank you !!

the message  
```text
2019-02-18 13:19:30.705553: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.2 AVX 
```
is that mean the aot cant support arm-v7a?

> ```
> bazel build --crosstool_top=//external:android/crosstool --cpu=armeabi-v7a --host_crosstool_top=@bazel_tools//tools/cpp:toolchain --cxxopt=-std=c++11 --cxxopt=-Wno-c++11-narrowing //tensorflow/compiler/aot/tests:my_library
> ```
> show linking error:
> 
> ```
> note: 'CFURLCreateDataAndPropertiesFromResource' has been explicitly marked deprecated here
> Boolean CFURLCreateDataAndPropertiesFromResource(CFAllocatorRef alloc, CFURLRef url, CFDataRef *resourceData, CFDictionaryRef *properties, CFArrayRef desiredProperties, SInt32 *errorCode) API_DEPRECATED("For resource data, use the CFReadStream API. For file resource properties, use CFURLCopyResourcePropertiesForKeys.", macos(10.0,10.9), ios(2.0,7.0), watchos(2.0,2.0), tvos(9.0,9.0));
>         ^
> 1 warning generated.
> INFO: From Linking external/curl/libcurl.a [for host]:
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/asyn-ares.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/curl_multibyte.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/curl_rtmp.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/curl_sspi.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/curl_threads.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/hostasyn.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/hostcheck.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/hostip4.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/inet_pton.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/krb5.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/md4.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/memdebug.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/nwlib.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/nwos.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/security.o has no symbols
> /Library/Developer/CommandLineTools/usr/bin/libtool: file: bazel-out/host/bin/external/curl/_objs/curl/strtok.o has no symbols
> INFO: From Compiling tensorflow/core/grappler/optimizers/pin_to_host_optimizer.cc [for host]:
> In file included from tensorflow/core/grappler/optimizers/pin_to_host_optimizer.cc:16:
> ./tensorflow/core/grappler/optimizers/pin_to_host_optimizer.h:56:26: warning: private field 'opt_level_' is not used [-Wunused-private-field]
>   RewriterConfig::Toggle opt_level_;
>                          ^
> 1 warning generated.
> INFO: From Linking tensorflow/compiler/aot/tfcompile [for host]:
> ld: warning: text-based stub file /System/Library/Frameworks//IOKit.framework/IOKit.tbd and library file /System/Library/Frameworks//IOKit.framework/IOKit are out of sync. Falling back to library file for linking.
> ld: warning: text-based stub file /System/Library/Frameworks//CoreFoundation.framework/CoreFoundation.tbd and library file /System/Library/Frameworks//CoreFoundation.framework/CoreFoundation are out of sync. Falling back to library file for linking.
> ld: warning: text-based stub file /System/Library/Frameworks//Security.framework/Security.tbd and library file /System/Library/Frameworks//Security.framework/Security are out of sync. Falling back to library file for linking.
> INFO: From Executing genrule //tensorflow/compiler/aot/tests:gen_test_graph_tfmatmul:
> 2019-02-18 13:19:30.705553: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.2 AVX
> ERROR: /Users/sunday/tensorflow/tensorflow/compiler/aot/tests/BUILD:15:1: Linking of rule '//tensorflow/compiler/aot/tests:my_library' failed (Exit 1)
> clang: error: no such file or directory: 'libmy_library.so'
> Target //tensorflow/compiler/aot/tests:my_library failed to build
> Use --verbose_failures to see the command lines of failed build steps.
> INFO: Elapsed time: 1399.023s, Critical Path: 231.09s
> INFO: 2563 processes: 2563 local.
> ```
> but the tensorflow binary is from resource code compile
> 
> ```
> bazel build  --copt=-msse4.1 --copt=-msse4.2 --copt=-mavx --copt=-mavx2 //tensorflow/tools/pip_package:build_pip_package
> ```


> bazel build --crosstool_top=//external:android/crosstool --cpu=armeabi-v7a --host_crosstool_top=@bazel_tools//tools/cpp:toolchain --cxxopt=-std=c++11 --cxxopt=-Wno-c++11-narrowing //tensorflow/compiler/aot/tests:my_library

Have you run `./configure` and located the Android toolchain from your root checkout directory?

> clang: error: no such file or directory: 'libmy_library.so'

This looks like an issue with your build rule, are you referring to the .so directly or indirectly from the .so target itself?



@sundayxcn I checked output .so of bazel, it won't cause
```
java.lang.UnsatisfiedLinkError: dlopen failed: library "../../../../src/main/jniLibs/armeabi/libmy_library.so" not found

```
Should be caused by your settings when you built your .so in Android Studio. Surely you won't find ``` "../../../../src/main/jniLibs/armeabi/libmy_library.so"``` on your Android devices. The path is supposed to be used during linking time on your host machine only.

Fix patch:
diff --git a/third_party/xla/xla/service/gpu/transforms/double_buffer_loop_unrolling.cc b/third_party/xla/xla/service/gpu/transforms/double_buffer_loop_unrolling.cc
index 16646269eb7563..8641cc733dcce3 100644
--- a/third_party/xla/xla/service/gpu/transforms/double_buffer_loop_unrolling.cc
+++ b/third_party/xla/xla/service/gpu/transforms/double_buffer_loop_unrolling.cc
@@ -519,6 +519,21 @@ absl::StatusOr<bool> DoubleBufferingUnroll(HloInstruction* while_instr,
 
   WhileLoopBackendConfig new_config;
   new_config.mutable_known_trip_count()->set_n(exact_trip_count / 2);
+
+  // Keep known induction variable metadata if it was present before.
+  if (config.has_known_induction_variable()) {
+    *new_config.mutable_known_induction_variable() =
+        config.known_induction_variable();
+  }
+
+  // Update the init/step metadata if it was present before.
+  if (config.has_known_init_step()) {
+    int64_t step = config.known_init_step().step();
+    new_config.mutable_known_init_step()->set_step(step * 2);
+    new_config.mutable_known_init_step()->set_init(
+        config.known_init_step().init() + (peel_one_iteration ? step : 0));
+  }
+
   TF_RETURN_IF_ERROR(while_instr->set_backend_config(new_config));
   return true;  // changed
 }


Test patch:
diff --git a/third_party/xla/xla/service/gpu/transforms/double_buffer_loop_unrolling_test.cc b/third_party/xla/xla/service/gpu/transforms/double_buffer_loop_unrolling_test.cc
index 565b00fe4e5cd0..8252b1508b2fd9 100644
--- a/third_party/xla/xla/service/gpu/transforms/double_buffer_loop_unrolling_test.cc
+++ b/third_party/xla/xla/service/gpu/transforms/double_buffer_loop_unrolling_test.cc
@@ -92,7 +92,9 @@ ENTRY main {
   param_0 = f32[] parameter(0)
   param_2 = s32[] constant(0)
   tuple = (f32[], s32[]) tuple(param_0, param_2)
-  ROOT while = (f32[], s32[]) while(tuple), condition=condition, body=body, backend_config={"known_trip_count":{"n":"10"}}
+  ROOT while = (f32[], s32[]) while(tuple), condition=condition, body=body,
+      backend_config={"known_trip_count":{"n":"10"},
+                      "known_induction_variable":{"tuple_index":"1"}}
 })";
 
   TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::HloModule> module,
@@ -110,6 +112,7 @@ ENTRY main {
       WhileLoopBackendConfig config,
       while_instruction->backend_config<WhileLoopBackendConfig>());
   EXPECT_EQ(config.known_trip_count().n(), 5);
+  EXPECT_EQ(config.known_induction_variable().tuple_index(), 1);
   EXPECT_EQ(CountInstructions((*while_instruction->while_body()),
                               HloOpcode::kAllReduceStart),
             2);
@@ -1397,6 +1400,94 @@ ENTRY main {
   EXPECT_THAT(double_buffer.Run(module.get()), IsOkAndHolds(false));
 }
 
+TEST_F(GpuLoopDoubleBufferTransformerTest, UpdateInitStepOddTripCount) {
+  absl::string_view kModuleString = R"(
+    HloModule m
+      condition {
+      input_tuple = (s32[]) parameter(0)
+      iter = s32[] get-tuple-element(input_tuple), index=0
+      c12 = s32[] constant(12)
+      ROOT continue = pred[] compare(iter, c12), direction=LT
+    }
+
+    body {
+      input_tuple = (s32[]) parameter(0)
+      iter = s32[] get-tuple-element(input_tuple), index=0
+      c2 = s32[] constant(2)
+      next_iter = s32[] add(iter, c2)
+      ROOT output_tuple = (s32[]) tuple(next_iter)
+    }
+
+    ENTRY main {
+      c3 = s32[] constant(3)
+      tuple = (s32[]) tuple(c3)
+      // Values: 3, 5, 7, 9, 11
+      ROOT while = (s32[]) while(tuple), condition=condition, body=body,
+        backend_config={"known_trip_count":{"n":"5"},
+                        "known_init_step":{"init":"3","step":"2"}}
+    })";
+
+  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::HloModule> module,
+                          ParseAndReturnVerifiedModule(kModuleString));
+  DoubleBufferLoopUnrolling unroller(
+      DoubleBufferLoopUnrolling::UnrollStrategy::kDoubleBuffer);
+  TF_ASSERT_OK_AND_ASSIGN(bool changed, unroller.Run(module.get()));
+  EXPECT_TRUE(changed);
+
+  HloInstruction* while_instruction = hlo_query::GetFirstInstructionWithOpcode(
+      *module->entry_computation(), HloOpcode::kWhile);
+  TF_ASSERT_OK_AND_ASSIGN(
+      WhileLoopBackendConfig config,
+      while_instruction->backend_config<WhileLoopBackendConfig>());
+  EXPECT_EQ(config.known_trip_count().n(), 2);
+  EXPECT_EQ(config.known_init_step().init(), 5);
+  EXPECT_EQ(config.known_init_step().step(), 4);
+}
+
+TEST_F(GpuLoopDoubleBufferTransformerTest, UpdateInitStepEvenTripCount) {
+  absl::string_view kModuleString = R"(
+    HloModule m
+      condition {
+      input_tuple = (s32[]) parameter(0)
+      iter = s32[] get-tuple-element(input_tuple), index=0
+      c14 = s32[] constant(14)
+      ROOT continue = pred[] compare(iter, c14), direction=LT
+    }
+
+    body {
+      input_tuple = (s32[]) parameter(0)
+      iter = s32[] get-tuple-element(input_tuple), index=0
+      c2 = s32[] constant(2)
+      next_iter = s32[] add(iter, c2)
+      ROOT output_tuple = (s32[]) tuple(next_iter)
+    }
+
+    ENTRY main {
+      c3 = s32[] constant(3)
+      tuple = (s32[]) tuple(c3)
+      // Values: 3, 5, 7, 9, 11, 13
+      ROOT while = (s32[]) while(tuple), condition=condition, body=body,
+        backend_config={"known_trip_count":{"n":"6"},
+                        "known_init_step":{"init":"3","step":"2"}}
+    })";
+
+  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::HloModule> module,
+                          ParseAndReturnVerifiedModule(kModuleString));
+  DoubleBufferLoopUnrolling unroller(
+      DoubleBufferLoopUnrolling::UnrollStrategy::kDoubleBuffer);
+  TF_ASSERT_OK_AND_ASSIGN(bool changed, unroller.Run(module.get()));
+  EXPECT_TRUE(changed);
+
+  HloInstruction* while_instruction = hlo_query::GetFirstInstructionWithOpcode(
+      *module->entry_computation(), HloOpcode::kWhile);
+  TF_ASSERT_OK_AND_ASSIGN(
+      WhileLoopBackendConfig config,
+      while_instruction->backend_config<WhileLoopBackendConfig>());
+  EXPECT_EQ(config.known_trip_count().n(), 3);
+  EXPECT_EQ(config.known_init_step().init(), 3);
+  EXPECT_EQ(config.known_init_step().step(), 4);
+}
+
 }  // namespace
 }  // namespace gpu
 }  // namespace xla