Refactor cache writing out from internalCompile().

Add public writeCache() interface in bcc::Script.

Change-Id: If7b8ce56f7197e379613976c71c568ca0c019876
diff --git a/lib/ExecutionEngine/Script.cpp b/lib/ExecutionEngine/Script.cpp
index 14d38bf..4d882e1 100644
--- a/lib/ExecutionEngine/Script.cpp
+++ b/lib/ExecutionEngine/Script.cpp
@@ -197,6 +197,11 @@
   int status = internalCompile(option);
   if (status != 0) {
     ALOGE("LLVM error message: %s\n", getCompilerErrorMessage());
+    return status;
+  }
+  status = writeCache();
+  if (status != 0) {
+    ALOGE("Failed to write the cache for %s\n", cacheName);
   }
   return status;
 }
@@ -232,16 +237,22 @@
   if (status != 0) {
     CompilerOption option;
     status = internalCompile(option);
-  }
 
-  if (status != 0) {
-    ALOGE("LLVM error message: %s\n", getCompilerErrorMessage());
+    if (status != 0) {
+      ALOGE("LLVM error message: %s\n", getCompilerErrorMessage());
+      return status;
+    }
+
+    status = writeCache();
+    if (status != 0) {
+      ALOGE("Failed to write the cache for %s\n", cacheName);
+      return status;
+    }
   }
 
   // FIXME: Registration can be conditional on the presence of debug metadata
-  if (status == 0) {
-    registerObjectWithGDB(getELF(), getELFSize()); // thread-safe registration
-  }
+  registerObjectWithGDB(getELF(), getELFSize()); // thread-safe registration
+
   return status;
 }
 
@@ -386,6 +397,15 @@
     return 1;
   }
 
+  return 0;
+}
+
+int Script::writeCache() {
+  // Not compiled script or encouter error during the compilation.
+  if ((mStatus != ScriptStatus::Compiled) ||
+      (getCompilerErrorMessage() == NULL))
+    return 1;
+
 #if USE_CACHE
   // Note: If we re-compile the script because the cached context slot not
   // available, then we don't have to write the cache.
diff --git a/lib/ExecutionEngine/Script.h b/lib/ExecutionEngine/Script.h
index 870d354..73a2ce1 100644
--- a/lib/ExecutionEngine/Script.h
+++ b/lib/ExecutionEngine/Script.h
@@ -165,6 +165,7 @@
     int prepareExecutable(char const *cacheDir,
                           char const *cacheName,
                           unsigned long flags);
+    int writeCache();
 
     /*
      * Link the given bitcodes in mSourceList to shared object (.so).