Merge "ART: Fix the simplifier for add/sub"
diff --git a/build/Android.gtest.mk b/build/Android.gtest.mk
index 4850e6c..63ad9cf 100644
--- a/build/Android.gtest.mk
+++ b/build/Android.gtest.mk
@@ -165,7 +165,6 @@
   runtime/base/hex_dump_test.cc \
   runtime/base/histogram_test.cc \
   runtime/base/mutex_test.cc \
-  runtime/base/out_test.cc \
   runtime/base/scoped_flock_test.cc \
   runtime/base/stringprintf_test.cc \
   runtime/base/time_utils_test.cc \
diff --git a/build/Android.oat.mk b/build/Android.oat.mk
index 0c0c3df..3a3cb99 100644
--- a/build/Android.oat.mk
+++ b/build/Android.oat.mk
@@ -23,11 +23,17 @@
 
 include art/build/Android.common_build.mk
 
+LOCAL_DEX2OAT_HOST_INSTRUCTION_SET_FEATURES_OPTION :=
 ifeq ($(DEX2OAT_HOST_INSTRUCTION_SET_FEATURES),)
-  DEX2OAT_HOST_INSTRUCTION_SET_FEATURES := default
+  LOCAL_DEX2OAT_HOST_INSTRUCTION_SET_FEATURES_OPTION := --instruction-set-features=default
+else
+  LOCAL_DEX2OAT_HOST_INSTRUCTION_SET_FEATURES_OPTION := --instruction-set-features=$(DEX2OAT_HOST_INSTRUCTION_SET_FEATURES)
 endif
+LOCAL_$(HOST_2ND_ARCH_VAR_PREFIX)DEX2OAT_HOST_INSTRUCTION_SET_FEATURES_OPTION :=
 ifeq ($($(HOST_2ND_ARCH_VAR_PREFIX)DEX2OAT_HOST_INSTRUCTION_SET_FEATURES),)
-  $(HOST_2ND_ARCH_VAR_PREFIX)DEX2OAT_HOST_INSTRUCTION_SET_FEATURES := default
+  LOCAL_$(HOST_2ND_ARCH_VAR_PREFIX)DEX2OAT_HOST_INSTRUCTION_SET_FEATURES_OPTION := --instruction-set-features=default
+else
+  LOCAL_$(HOST_2ND_ARCH_VAR_PREFIX)DEX2OAT_HOST_INSTRUCTION_SET_FEATURES_OPTION := --instruction-set-features=$($(HOST_2ND_ARCH_VAR_PREFIX)DEX2OAT_HOST_INSTRUCTION_SET_FEATURES)
 endif
 
 # Use dex2oat debug version for better error reporting
@@ -116,7 +122,7 @@
 	  $$(addprefix --dex-location=,$$(HOST_CORE_DEX_LOCATIONS)) --oat-file=$$(PRIVATE_CORE_OAT_NAME) \
 	  --oat-location=$$(PRIVATE_CORE_OAT_NAME) --image=$$(PRIVATE_CORE_IMG_NAME) \
 	  --base=$$(LIBART_IMG_HOST_BASE_ADDRESS) --instruction-set=$$($(3)ART_HOST_ARCH) \
-	  --instruction-set-features=$$($(3)DEX2OAT_HOST_INSTRUCTION_SET_FEATURES) \
+	  $$(LOCAL_$(3)DEX2OAT_HOST_INSTRUCTION_SET_FEATURES_OPTION) \
 	  --host --android-root=$$(HOST_OUT) --include-patch-information --generate-debug-info \
 	  $$(PRIVATE_CORE_COMPILE_OPTIONS)
 
diff --git a/compiler/Android.mk b/compiler/Android.mk
index 3947078..4944915 100644
--- a/compiler/Android.mk
+++ b/compiler/Android.mk
@@ -171,6 +171,7 @@
   dex/quick/mips/mips_lir.h \
   dex/quick/resource_mask.h \
   dex/compiler_enums.h \
+  dex/dex_to_dex_compiler.h \
   dex/global_value_numbering.h \
   dex/pass_me.h \
   driver/compiler_driver.h \
diff --git a/compiler/dex/dex_to_dex_compiler.cc b/compiler/dex/dex_to_dex_compiler.cc
index 4b56b69..603130a 100644
--- a/compiler/dex/dex_to_dex_compiler.cc
+++ b/compiler/dex/dex_to_dex_compiler.cc
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include "dex_to_dex_compiler.h"
+
 #include "art_field-inl.h"
 #include "art_method-inl.h"
 #include "base/logging.h"
@@ -65,7 +67,7 @@
   }
 
   bool PerformOptimizations() const {
-    return dex_to_dex_compilation_level_ >= kOptimize;
+    return dex_to_dex_compilation_level_ >= DexToDexCompilationLevel::kOptimize;
   }
 
   // Compiles a RETURN-VOID into a RETURN-VOID-BARRIER within a constructor where
@@ -108,7 +110,7 @@
 };
 
 void DexCompiler::Compile() {
-  DCHECK_GE(dex_to_dex_compilation_level_, kRequired);
+  DCHECK_GE(dex_to_dex_compilation_level_, DexToDexCompilationLevel::kRequired);
   const DexFile::CodeItem* code_item = unit_.GetCodeItem();
   const uint16_t* insns = code_item->insns_;
   const uint32_t insns_size = code_item->insns_size_in_code_units_;
@@ -310,21 +312,22 @@
   }
 }
 
-extern "C" CompiledMethod* ArtCompileDEX(
-    art::CompilerDriver& driver,
-    const art::DexFile::CodeItem* code_item,
+CompiledMethod* ArtCompileDEX(
+    CompilerDriver* driver,
+    const DexFile::CodeItem* code_item,
     uint32_t access_flags,
-    art::InvokeType invoke_type ATTRIBUTE_UNUSED,
+    InvokeType invoke_type ATTRIBUTE_UNUSED,
     uint16_t class_def_idx,
     uint32_t method_idx,
     jobject class_loader,
-    const art::DexFile& dex_file,
-    art::DexToDexCompilationLevel dex_to_dex_compilation_level) {
-  if (dex_to_dex_compilation_level != art::kDontDexToDexCompile) {
+    const DexFile& dex_file,
+    DexToDexCompilationLevel dex_to_dex_compilation_level) {
+  DCHECK(driver != nullptr);
+  if (dex_to_dex_compilation_level != DexToDexCompilationLevel::kDontDexToDexCompile) {
     art::DexCompilationUnit unit(nullptr, class_loader, art::Runtime::Current()->GetClassLinker(),
                                  dex_file, code_item, class_def_idx, method_idx, access_flags,
-                                 driver.GetVerifiedMethod(&dex_file, method_idx));
-    art::optimizer::DexCompiler dex_compiler(driver, unit, dex_to_dex_compilation_level);
+                                 driver->GetVerifiedMethod(&dex_file, method_idx));
+    art::optimizer::DexCompiler dex_compiler(*driver, unit, dex_to_dex_compilation_level);
     dex_compiler.Compile();
     if (dex_compiler.GetQuickenedInfo().empty()) {
       // No need to create a CompiledMethod if there are no quickened opcodes.
@@ -337,13 +340,13 @@
       builder.PushBackUnsigned(info.dex_pc);
       builder.PushBackUnsigned(info.dex_member_index);
     }
-    InstructionSet instruction_set = driver.GetInstructionSet();
+    InstructionSet instruction_set = driver->GetInstructionSet();
     if (instruction_set == kThumb2) {
       // Don't use the thumb2 instruction set to avoid the one off code delta.
       instruction_set = kArm;
     }
     return CompiledMethod::SwapAllocCompiledMethod(
-        &driver,
+        driver,
         instruction_set,
         ArrayRef<const uint8_t>(),                   // no code
         0,
diff --git a/compiler/dex/dex_to_dex_compiler.h b/compiler/dex/dex_to_dex_compiler.h
new file mode 100644
index 0000000..3fad6d4
--- /dev/null
+++ b/compiler/dex/dex_to_dex_compiler.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ART_COMPILER_DEX_DEX_TO_DEX_COMPILER_H_
+#define ART_COMPILER_DEX_DEX_TO_DEX_COMPILER_H_
+
+#include "jni.h"
+
+#include "dex_file.h"
+#include "invoke_type.h"
+
+namespace art {
+
+class CompiledMethod;
+class CompilerDriver;
+
+namespace optimizer {
+
+enum class DexToDexCompilationLevel {
+  kDontDexToDexCompile,   // Only meaning wrt image time interpretation.
+  kRequired,              // Dex-to-dex compilation required for correctness.
+  kOptimize               // Perform required transformation and peep-hole optimizations.
+};
+std::ostream& operator<<(std::ostream& os, const DexToDexCompilationLevel& rhs);
+
+CompiledMethod* ArtCompileDEX(CompilerDriver* driver,
+                              const DexFile::CodeItem* code_item,
+                              uint32_t access_flags,
+                              InvokeType invoke_type,
+                              uint16_t class_def_idx,
+                              uint32_t method_idx,
+                              jobject class_loader,
+                              const DexFile& dex_file,
+                              DexToDexCompilationLevel dex_to_dex_compilation_level);
+
+}  // namespace optimizer
+
+}  // namespace art
+
+#endif  // ART_COMPILER_DEX_DEX_TO_DEX_COMPILER_H_
diff --git a/compiler/driver/compiler_driver.cc b/compiler/driver/compiler_driver.cc
index affa52a..299b995 100644
--- a/compiler/driver/compiler_driver.cc
+++ b/compiler/driver/compiler_driver.cc
@@ -39,6 +39,7 @@
 #include "compiler_driver-inl.h"
 #include "dex_compilation_unit.h"
 #include "dex_file-inl.h"
+#include "dex/dex_to_dex_compiler.h"
 #include "dex/verification_results.h"
 #include "dex/verified_method.h"
 #include "dex/quick/dex_file_method_inliner.h"
@@ -334,16 +335,6 @@
   DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
 };
 
-
-extern "C" art::CompiledMethod* ArtCompileDEX(art::CompilerDriver& compiler,
-                                              const art::DexFile::CodeItem* code_item,
-                                              uint32_t access_flags,
-                                              art::InvokeType invoke_type,
-                                              uint16_t class_def_idx,
-                                              uint32_t method_idx,
-                                              jobject class_loader,
-                                              const art::DexFile& dex_file);
-
 CompilerDriver::CompilerDriver(const CompilerOptions* compiler_options,
                                VerificationResults* verification_results,
                                DexFileToMethodInlinerMap* method_inliner_map,
@@ -394,8 +385,6 @@
   DCHECK(verification_results_ != nullptr);
   DCHECK(method_inliner_map_ != nullptr);
 
-  dex_to_dex_compiler_ = reinterpret_cast<DexToDexCompilerFn>(ArtCompileDEX);
-
   compiler_->Init();
 
   CHECK_EQ(image_, image_classes_.get() != nullptr);
@@ -508,13 +497,14 @@
   }
 }
 
-DexToDexCompilationLevel CompilerDriver::GetDexToDexCompilationlevel(
-    Thread* self, Handle<mirror::ClassLoader> class_loader, const DexFile& dex_file,
-    const DexFile::ClassDef& class_def) {
+static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
+    Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
+    const DexFile& dex_file, const DexFile::ClassDef& class_def)
+    SHARED_REQUIRES(Locks::mutator_lock_) {
   auto* const runtime = Runtime::Current();
-  if (runtime->UseJit() || GetCompilerOptions().VerifyAtRuntime()) {
+  if (runtime->UseJit() || driver.GetCompilerOptions().VerifyAtRuntime()) {
     // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
-    return kDontDexToDexCompile;
+    return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
   }
   const char* descriptor = dex_file.GetClassDescriptor(class_def);
   ClassLinker* class_linker = runtime->GetClassLinker();
@@ -522,7 +512,7 @@
   if (klass == nullptr) {
     CHECK(self->IsExceptionPending());
     self->ClearException();
-    return kDontDexToDexCompile;
+    return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
   }
   // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
   // references with actual offsets. We cannot re-verify such instructions.
@@ -532,14 +522,142 @@
   // optimize when a class has been fully verified before.
   if (klass->IsVerified()) {
     // Class is verified so we can enable DEX-to-DEX compilation for performance.
-    return kOptimize;
+    return optimizer::DexToDexCompilationLevel::kOptimize;
   } else if (klass->IsCompileTimeVerified()) {
     // Class verification has soft-failed. Anyway, ensure at least correctness.
     DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
-    return kRequired;
+    return optimizer::DexToDexCompilationLevel::kRequired;
   } else {
     // Class verification has failed: do not run DEX-to-DEX compilation.
-    return kDontDexToDexCompile;
+    return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
+  }
+}
+
+static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
+    Thread* self,
+    const CompilerDriver& driver,
+    jobject jclass_loader,
+    const DexFile& dex_file,
+    const DexFile::ClassDef& class_def) {
+  ScopedObjectAccess soa(self);
+  StackHandleScope<1> hs(soa.Self());
+  Handle<mirror::ClassLoader> class_loader(
+      hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
+  return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
+}
+
+// Does the runtime for the InstructionSet provide an implementation returned by
+// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
+static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
+  switch (isa) {
+    case kArm:
+    case kArm64:
+    case kThumb2:
+    case kMips:
+    case kMips64:
+    case kX86:
+    case kX86_64: return true;
+    default: return false;
+  }
+}
+
+static void CompileMethod(Thread* self,
+                          CompilerDriver* driver,
+                          const DexFile::CodeItem* code_item,
+                          uint32_t access_flags,
+                          InvokeType invoke_type,
+                          uint16_t class_def_idx,
+                          uint32_t method_idx,
+                          jobject class_loader,
+                          const DexFile& dex_file,
+                          optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
+                          bool compilation_enabled)
+    REQUIRES(!driver->compiled_methods_lock_) {
+  DCHECK(driver != nullptr);
+  CompiledMethod* compiled_method = nullptr;
+  uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
+  MethodReference method_ref(&dex_file, method_idx);
+
+  if ((access_flags & kAccNative) != 0) {
+    // Are we interpreting only and have support for generic JNI down calls?
+    if (!driver->GetCompilerOptions().IsCompilationEnabled() &&
+        InstructionSetHasGenericJniStub(driver->GetInstructionSet())) {
+      // Leaving this empty will trigger the generic JNI version
+    } else {
+      compiled_method = driver->GetCompiler()->JniCompile(access_flags, method_idx, dex_file);
+      CHECK(compiled_method != nullptr);
+    }
+  } else if ((access_flags & kAccAbstract) != 0) {
+    // Abstract methods don't have code.
+  } else {
+    bool has_verified_method = driver->GetVerificationResults()
+        ->GetVerifiedMethod(method_ref) != nullptr;
+    bool compile = compilation_enabled &&
+        // Basic checks, e.g., not <clinit>.
+        driver->GetVerificationResults()
+            ->IsCandidateForCompilation(method_ref, access_flags) &&
+        // Did not fail to create VerifiedMethod metadata.
+        has_verified_method &&
+        // Is eligable for compilation by methods-to-compile filter.
+        driver->IsMethodToCompile(method_ref);
+    if (compile) {
+      // NOTE: if compiler declines to compile this method, it will return null.
+      compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
+                                                       class_def_idx, method_idx, class_loader,
+                                                       dex_file);
+    }
+    if (compiled_method == nullptr &&
+        dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
+      // TODO: add a command-line option to disable DEX-to-DEX compilation ?
+      // Do not optimize if a VerifiedMethod is missing. SafeCast elision, for example, relies on
+      // it.
+      compiled_method = optimizer::ArtCompileDEX(
+          driver,
+          code_item,
+          access_flags,
+          invoke_type,
+          class_def_idx,
+          method_idx,
+          class_loader,
+          dex_file,
+          has_verified_method
+              ? dex_to_dex_compilation_level
+              : optimizer::DexToDexCompilationLevel::kRequired);
+    }
+  }
+  if (kTimeCompileMethod) {
+    uint64_t duration_ns = NanoTime() - start_ns;
+    if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
+      LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
+                   << " took " << PrettyDuration(duration_ns);
+    }
+  }
+
+  if (compiled_method != nullptr) {
+    // Count non-relative linker patches.
+    size_t non_relative_linker_patch_count = 0u;
+    for (const LinkerPatch& patch : compiled_method->GetPatches()) {
+      if (!patch.IsPcRelative()) {
+        ++non_relative_linker_patch_count;
+      }
+    }
+    bool compile_pic = driver->GetCompilerOptions().GetCompilePic();  // Off by default
+    // When compiling with PIC, there should be zero non-relative linker patches
+    CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
+
+    driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
+  }
+
+  // Done compiling, delete the verified method to reduce native memory usage. Do not delete in
+  // optimizing compiler, which may need the verified method again for inlining.
+  if (driver->GetCompilerKind() != Compiler::kOptimizing) {
+    driver->GetVerificationResults()->RemoveVerifiedMethod(method_ref);
+  }
+
+  if (self->IsExceptionPending()) {
+    ScopedObjectAccess soa(self);
+    LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
+        << self->GetException()->Dump();
   }
 }
 
@@ -570,24 +688,30 @@
   PreCompile(jclass_loader, dex_files, thread_pool.get(), timings);
 
   // Can we run DEX-to-DEX compiler on this class ?
-  DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
-  {
-    ScopedObjectAccess soa(self);
-    const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
-    StackHandleScope<1> hs(soa.Self());
-    Handle<mirror::ClassLoader> class_loader(
-        hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
-    dex_to_dex_compilation_level = GetDexToDexCompilationlevel(self, class_loader, *dex_file,
-                                                               class_def);
-  }
-  CompileMethod(self, code_item, access_flags, invoke_type, class_def_idx, method_idx,
-                jclass_loader, *dex_file, dex_to_dex_compilation_level, true);
+  optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
+      GetDexToDexCompilationLevel(self,
+                                  *this,
+                                  jclass_loader,
+                                  *dex_file,
+                                  dex_file->GetClassDef(class_def_idx));
+
+  CompileMethod(self,
+                this,
+                code_item,
+                access_flags,
+                invoke_type,
+                class_def_idx,
+                method_idx,
+                jclass_loader,
+                *dex_file,
+                dex_to_dex_compilation_level,
+                true);
 
   self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
   self->TransitionFromSuspendedToRunnable();
 }
 
-CompiledMethod* CompilerDriver::CompileMethod(Thread* self, ArtMethod* method) {
+CompiledMethod* CompilerDriver::CompileArtMethod(Thread* self, ArtMethod* method) {
   const uint32_t method_idx = method->GetDexMethodIndex();
   const uint32_t access_flags = method->GetAccessFlags();
   const InvokeType invoke_type = method->GetInvokeType();
@@ -598,12 +722,21 @@
   const DexFile* dex_file = method->GetDexFile();
   const uint16_t class_def_idx = method->GetClassDefIndex();
   const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
-  DexToDexCompilationLevel dex_to_dex_compilation_level =
-      GetDexToDexCompilationlevel(self, class_loader, *dex_file, class_def);
+  optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
+      GetDexToDexCompilationLevel(self, *this, class_loader, *dex_file, class_def);
   const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
   self->TransitionFromRunnableToSuspended(kNative);
-  CompileMethod(self, code_item, access_flags, invoke_type, class_def_idx, method_idx,
-                jclass_loader, *dex_file, dex_to_dex_compilation_level, true);
+  CompileMethod(self,
+                this,
+                code_item,
+                access_flags,
+                invoke_type,
+                class_def_idx,
+                method_idx,
+                jclass_loader,
+                *dex_file,
+                dex_to_dex_compilation_level,
+                true);
   auto* compiled_method = GetCompiledMethod(MethodReference(dex_file, method_idx));
   self->TransitionFromSuspendedToRunnable();
   return compiled_method;
@@ -2237,15 +2370,9 @@
     CompilerDriver* const driver = manager_->GetCompiler();
 
     // Can we run DEX-to-DEX compiler on this class ?
-    DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
-    {
-      ScopedObjectAccess soa(self);
-      StackHandleScope<1> hs(soa.Self());
-      Handle<mirror::ClassLoader> class_loader(
-          hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
-      dex_to_dex_compilation_level = driver->GetDexToDexCompilationlevel(
-          soa.Self(), class_loader, dex_file, class_def);
-    }
+    optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
+        GetDexToDexCompilationLevel(self, *driver, jclass_loader, dex_file, class_def);
+
     ClassDataItemIterator it(dex_file, class_data);
     // Skip fields
     while (it.HasNextStaticField()) {
@@ -2269,10 +2396,10 @@
         continue;
       }
       previous_direct_method_idx = method_idx;
-      driver->CompileMethod(self, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
-                            it.GetMethodInvokeType(class_def), class_def_index,
-                            method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
-                            compilation_enabled);
+      CompileMethod(self, driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
+                    it.GetMethodInvokeType(class_def), class_def_index,
+                    method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
+                    compilation_enabled);
       it.Next();
     }
     // Compile virtual methods
@@ -2286,10 +2413,10 @@
         continue;
       }
       previous_virtual_method_idx = method_idx;
-      driver->CompileMethod(self, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
-                            it.GetMethodInvokeType(class_def), class_def_index,
-                            method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
-                            compilation_enabled);
+      CompileMethod(self, driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
+                    it.GetMethodInvokeType(class_def), class_def_index,
+                    method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
+                    compilation_enabled);
       it.Next();
     }
     DCHECK(!it.HasNext());
@@ -2309,112 +2436,18 @@
   context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count_);
 }
 
-// Does the runtime for the InstructionSet provide an implementation returned by
-// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
-static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
-  switch (isa) {
-    case kArm:
-    case kArm64:
-    case kThumb2:
-    case kMips:
-    case kMips64:
-    case kX86:
-    case kX86_64: return true;
-    default: return false;
+void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
+                                       CompiledMethod* const compiled_method,
+                                       size_t non_relative_linker_patch_count) {
+  DCHECK(GetCompiledMethod(method_ref) == nullptr)
+      << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
+  {
+    MutexLock mu(Thread::Current(), compiled_methods_lock_);
+    compiled_methods_.Put(method_ref, compiled_method);
+    non_relative_linker_patch_count_ += non_relative_linker_patch_count;
   }
-}
-
-void CompilerDriver::CompileMethod(Thread* self, const DexFile::CodeItem* code_item,
-                                   uint32_t access_flags, InvokeType invoke_type,
-                                   uint16_t class_def_idx, uint32_t method_idx,
-                                   jobject class_loader, const DexFile& dex_file,
-                                   DexToDexCompilationLevel dex_to_dex_compilation_level,
-                                   bool compilation_enabled) {
-  CompiledMethod* compiled_method = nullptr;
-  uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
-  MethodReference method_ref(&dex_file, method_idx);
-
-  if ((access_flags & kAccNative) != 0) {
-    // Are we interpreting only and have support for generic JNI down calls?
-    if (!compiler_options_->IsCompilationEnabled() &&
-        InstructionSetHasGenericJniStub(instruction_set_)) {
-      // Leaving this empty will trigger the generic JNI version
-    } else {
-      compiled_method = compiler_->JniCompile(access_flags, method_idx, dex_file);
-      CHECK(compiled_method != nullptr);
-    }
-  } else if ((access_flags & kAccAbstract) != 0) {
-    // Abstract methods don't have code.
-  } else {
-    bool has_verified_method = verification_results_->GetVerifiedMethod(method_ref) != nullptr;
-    bool compile = compilation_enabled &&
-                   // Basic checks, e.g., not <clinit>.
-                   verification_results_->IsCandidateForCompilation(method_ref, access_flags) &&
-                   // Did not fail to create VerifiedMethod metadata.
-                   has_verified_method &&
-                   // Is eligable for compilation by methods-to-compile filter.
-                   IsMethodToCompile(method_ref);
-    if (compile) {
-      // NOTE: if compiler declines to compile this method, it will return null.
-      compiled_method = compiler_->Compile(code_item, access_flags, invoke_type, class_def_idx,
-                                           method_idx, class_loader, dex_file);
-    }
-    if (compiled_method == nullptr && dex_to_dex_compilation_level != kDontDexToDexCompile) {
-      // TODO: add a command-line option to disable DEX-to-DEX compilation ?
-      // Do not optimize if a VerifiedMethod is missing. SafeCast elision, for example, relies on
-      // it.
-      compiled_method = (*dex_to_dex_compiler_)(
-          *this,
-          code_item,
-          access_flags,
-          invoke_type,
-          class_def_idx,
-          method_idx,
-          class_loader,
-          dex_file,
-          has_verified_method ? dex_to_dex_compilation_level : kRequired);
-    }
-  }
-  if (kTimeCompileMethod) {
-    uint64_t duration_ns = NanoTime() - start_ns;
-    if (duration_ns > MsToNs(compiler_->GetMaximumCompilationTimeBeforeWarning())) {
-      LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
-                   << " took " << PrettyDuration(duration_ns);
-    }
-  }
-
-  if (compiled_method != nullptr) {
-    // Count non-relative linker patches.
-    size_t non_relative_linker_patch_count = 0u;
-    for (const LinkerPatch& patch : compiled_method->GetPatches()) {
-      if (!patch.IsPcRelative()) {
-        ++non_relative_linker_patch_count;
-      }
-    }
-    bool compile_pic = GetCompilerOptions().GetCompilePic();  // Off by default
-    // When compiling with PIC, there should be zero non-relative linker patches
-    CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
-
-    DCHECK(GetCompiledMethod(method_ref) == nullptr) << PrettyMethod(method_idx, dex_file);
-    {
-      MutexLock mu(self, compiled_methods_lock_);
-      compiled_methods_.Put(method_ref, compiled_method);
-      non_relative_linker_patch_count_ += non_relative_linker_patch_count;
-    }
-    DCHECK(GetCompiledMethod(method_ref) != nullptr) << PrettyMethod(method_idx, dex_file);
-  }
-
-  // Done compiling, delete the verified method to reduce native memory usage. Do not delete in
-  // optimizing compiler, which may need the verified method again for inlining.
-  if (compiler_kind_ != Compiler::kOptimizing) {
-    verification_results_->RemoveVerifiedMethod(method_ref);
-  }
-
-  if (self->IsExceptionPending()) {
-    ScopedObjectAccess soa(self);
-    LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
-        << self->GetException()->Dump();
-  }
+  DCHECK(GetCompiledMethod(method_ref) != nullptr)
+      << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
 }
 
 void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
diff --git a/compiler/driver/compiler_driver.h b/compiler/driver/compiler_driver.h
index 88e03a2..4de9c73 100644
--- a/compiler/driver/compiler_driver.h
+++ b/compiler/driver/compiler_driver.h
@@ -80,13 +80,6 @@
   kQuickAbi
 };
 
-enum DexToDexCompilationLevel {
-  kDontDexToDexCompile,   // Only meaning wrt image time interpretation.
-  kRequired,              // Dex-to-dex compilation required for correctness.
-  kOptimize               // Perform required transformation and peep-hole optimizations.
-};
-std::ostream& operator<<(std::ostream& os, const DexToDexCompilationLevel& rhs);
-
 static constexpr bool kUseMurmur3Hash = true;
 
 class CompilerDriver {
@@ -116,7 +109,7 @@
                   TimingLogger* timings)
       REQUIRES(!Locks::mutator_lock_, !compiled_classes_lock_);
 
-  CompiledMethod* CompileMethod(Thread* self, ArtMethod*)
+  CompiledMethod* CompileArtMethod(Thread* self, ArtMethod*)
       SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!compiled_methods_lock_) WARN_UNUSED;
 
   // Compile a single Method.
@@ -185,6 +178,11 @@
   size_t GetNonRelativeLinkerPatchCount() const
       REQUIRES(!compiled_methods_lock_);
 
+  // Add a compiled method.
+  void AddCompiledMethod(const MethodReference& method_ref,
+                         CompiledMethod* const compiled_method,
+                         size_t non_relative_linker_patch_count)
+      REQUIRES(!compiled_methods_lock_);
   // Remove and delete a compiled method.
   void RemoveCompiledMethod(const MethodReference& method_ref) REQUIRES(!compiled_methods_lock_);
 
@@ -476,6 +474,10 @@
     had_hard_verifier_failure_ = true;
   }
 
+  Compiler::Kind GetCompilerKind() {
+    return compiler_kind_;
+  }
+
  private:
   // Return whether the declaring class of `resolved_member` is
   // available to `referrer_class` for read or write access using two
@@ -546,10 +548,6 @@
       SHARED_REQUIRES(Locks::mutator_lock_);
 
  private:
-  DexToDexCompilationLevel GetDexToDexCompilationlevel(
-      Thread* self, Handle<mirror::ClassLoader> class_loader, const DexFile& dex_file,
-      const DexFile::ClassDef& class_def) SHARED_REQUIRES(Locks::mutator_lock_);
-
   void PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
                   ThreadPool* thread_pool, TimingLogger* timings)
       REQUIRES(!Locks::mutator_lock_, !compiled_classes_lock_);
@@ -599,12 +597,6 @@
                       const std::vector<const DexFile*>& dex_files,
                       ThreadPool* thread_pool, TimingLogger* timings)
       REQUIRES(!Locks::mutator_lock_);
-  void CompileMethod(Thread* self, const DexFile::CodeItem* code_item, uint32_t access_flags,
-                     InvokeType invoke_type, uint16_t class_def_idx, uint32_t method_idx,
-                     jobject class_loader, const DexFile& dex_file,
-                     DexToDexCompilationLevel dex_to_dex_compilation_level,
-                     bool compilation_enabled)
-      REQUIRES(!compiled_methods_lock_);
 
   // Swap pool and allocator used for native allocations. May be file-backed. Needs to be first
   // as other fields rely on this.
@@ -634,8 +626,13 @@
   ClassTable compiled_classes_ GUARDED_BY(compiled_classes_lock_);
 
   typedef SafeMap<const MethodReference, CompiledMethod*, MethodReferenceComparator> MethodTable;
-  // All method references that this compiler has compiled.
+
+ public:
+  // Lock is public so that non-members can have lock annotations.
   mutable Mutex compiled_methods_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
+
+ private:
+  // All method references that this compiler has compiled.
   MethodTable compiled_methods_ GUARDED_BY(compiled_methods_lock_);
   // Number of non-relative patches in all compiled methods. These patches need space
   // in the .oat_patches ELF section if requested in the compiler options.
@@ -675,15 +672,6 @@
   typedef void (*CompilerCallbackFn)(CompilerDriver& driver);
   typedef MutexLock* (*CompilerMutexLockFn)(CompilerDriver& driver);
 
-  typedef CompiledMethod* (*DexToDexCompilerFn)(
-      CompilerDriver& driver,
-      const DexFile::CodeItem* code_item,
-      uint32_t access_flags, InvokeType invoke_type,
-      uint32_t class_dex_idx, uint32_t method_idx,
-      jobject class_loader, const DexFile& dex_file,
-      DexToDexCompilationLevel dex_to_dex_compilation_level);
-  DexToDexCompilerFn dex_to_dex_compiler_;
-
   void* compiler_context_;
 
   bool support_boot_image_fixup_;
diff --git a/compiler/image_writer.cc b/compiler/image_writer.cc
index 17d75a3..b85a129 100644
--- a/compiler/image_writer.cc
+++ b/compiler/image_writer.cc
@@ -141,7 +141,7 @@
     return false;
   }
   std::string error_msg;
-  oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, nullptr, outof(error_msg));
+  oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, nullptr, &error_msg);
   if (oat_file_ == nullptr) {
     PLOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
         << ": " << error_msg;
@@ -719,7 +719,7 @@
     }
     // InternImageString allows us to intern while holding the heap bitmap lock. This is safe since
     // we are guaranteed to not have GC during image writing.
-    mirror::String* const interned = Runtime::Current()->GetInternTable()->InternImageString(
+    mirror::String* const interned = Runtime::Current()->GetInternTable()->InternStrongImageString(
         obj->AsString());
     if (obj != interned) {
       if (!IsImageBinSlotAssigned(interned)) {
@@ -825,35 +825,68 @@
         field_offset = MemberOffset(field_offset.Uint32Value() +
                                     sizeof(mirror::HeapReference<mirror::Object>));
       }
-      // Visit and assign offsets for fields.
+      // Visit and assign offsets for fields and field arrays.
       auto* as_klass = h_obj->AsClass();
-      ArtField* fields[] = { as_klass->GetSFields(), as_klass->GetIFields() };
-      size_t num_fields[] = { as_klass->NumStaticFields(), as_klass->NumInstanceFields() };
-      for (size_t i = 0; i < 2; ++i) {
-        for (size_t j = 0; j < num_fields[i]; ++j) {
-          auto* field = fields[i] + j;
-          auto it = native_object_reloc_.find(field);
-          CHECK(it == native_object_reloc_.end()) << "Field at index " << i << ":" << j
-              << " already assigned " << PrettyField(field);
-          native_object_reloc_.emplace(
-              field, NativeObjectReloc { bin_slot_sizes_[kBinArtField], kBinArtField });
-          bin_slot_sizes_[kBinArtField] += sizeof(ArtField);
+      LengthPrefixedArray<ArtField>* fields[] = {
+          as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
+      };
+      for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
+        // Total array length including header.
+        if (cur_fields != nullptr) {
+          const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
+          // Forward the entire array at once.
+          auto it = native_object_relocations_.find(cur_fields);
+          CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
+                                                  << " already forwarded";
+          size_t& offset = bin_slot_sizes_[kBinArtField];
+          native_object_relocations_.emplace(
+              cur_fields, NativeObjectRelocation {
+                  offset, kNativeObjectRelocationTypeArtFieldArray });
+          offset += header_size;
+          // Forward individual fields so that we can quickly find where they belong.
+          for (size_t i = 0, count = cur_fields->Length(); i < count; ++i) {
+            // Need to forward arrays separate of fields.
+            ArtField* field = &cur_fields->At(i);
+            auto it2 = native_object_relocations_.find(field);
+            CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
+                << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
+            native_object_relocations_.emplace(
+                field, NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtField });
+            offset += sizeof(ArtField);
+          }
         }
       }
       // Visit and assign offsets for methods.
-      IterationRange<StrideIterator<ArtMethod>> method_arrays[] = {
-          as_klass->GetDirectMethods(target_ptr_size_),
-          as_klass->GetVirtualMethods(target_ptr_size_)
+      LengthPrefixedArray<ArtMethod>* method_arrays[] = {
+          as_klass->GetDirectMethodsPtr(), as_klass->GetVirtualMethodsPtr(),
       };
-      for (auto& array : method_arrays) {
+      for (LengthPrefixedArray<ArtMethod>* array : method_arrays) {
+        if (array == nullptr) {
+          continue;
+        }
         bool any_dirty = false;
         size_t count = 0;
-        for (auto& m : array) {
+        const size_t method_size = ArtMethod::ObjectSize(target_ptr_size_);
+        auto iteration_range = MakeIterationRangeFromLengthPrefixedArray(array, method_size);
+        for (auto& m : iteration_range) {
           any_dirty = any_dirty || WillMethodBeDirty(&m);
           ++count;
         }
-        for (auto& m : array) {
-          AssignMethodOffset(&m, any_dirty ? kBinArtMethodDirty : kBinArtMethodClean);
+        NativeObjectRelocationType type = any_dirty ? kNativeObjectRelocationTypeArtMethodDirty :
+            kNativeObjectRelocationTypeArtMethodClean;
+        Bin bin_type = BinTypeForNativeRelocationType(type);
+        // Forward the entire array at once, but header first.
+        const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0, method_size);
+        auto it = native_object_relocations_.find(array);
+        CHECK(it == native_object_relocations_.end()) << "Method array " << array
+            << " already forwarded";
+        size_t& offset = bin_slot_sizes_[bin_type];
+        native_object_relocations_.emplace(array, NativeObjectRelocation { offset,
+            any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty :
+                kNativeObjectRelocationTypeArtMethodArrayClean });
+        offset += header_size;
+        for (auto& m : iteration_range) {
+          AssignMethodOffset(&m, type);
         }
         (any_dirty ? dirty_methods_ : clean_methods_) += count;
       }
@@ -871,12 +904,13 @@
   }
 }
 
-void ImageWriter::AssignMethodOffset(ArtMethod* method, Bin bin) {
-  auto it = native_object_reloc_.find(method);
-  CHECK(it == native_object_reloc_.end()) << "Method " << method << " already assigned "
+void ImageWriter::AssignMethodOffset(ArtMethod* method, NativeObjectRelocationType type) {
+  auto it = native_object_relocations_.find(method);
+  CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
       << PrettyMethod(method);
-  native_object_reloc_.emplace(method, NativeObjectReloc { bin_slot_sizes_[bin], bin });
-  bin_slot_sizes_[bin] += ArtMethod::ObjectSize(target_ptr_size_);
+  size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
+  native_object_relocations_.emplace(method, NativeObjectRelocation { offset, type });
+  offset += ArtMethod::ObjectSize(target_ptr_size_);
 }
 
 void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
@@ -930,10 +964,20 @@
       runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
   image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
       runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
+
+  // Add room for fake length prefixed array.
+  const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
+  auto it = native_object_relocations_.find(&image_method_array_);
+  CHECK(it == native_object_relocations_.end());
+  size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
+  native_object_relocations_.emplace(&image_method_array_,
+                                     NativeObjectRelocation { offset, image_method_type });
+  CHECK_EQ(sizeof(image_method_array_), 8u);
+  offset += sizeof(image_method_array_);
   for (auto* m : image_methods_) {
     CHECK(m != nullptr);
     CHECK(m->IsRuntimeMethod());
-    AssignMethodOffset(m, kBinArtMethodDirty);
+    AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean);
   }
 
   // Calculate cumulative bin slot sizes.
@@ -953,10 +997,10 @@
   image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
 
   // Update the native relocations by adding their bin sums.
-  for (auto& pair : native_object_reloc_) {
-    auto& native_reloc = pair.second;
-    native_reloc.offset += image_objects_offset_begin_ +
-        bin_slot_previous_sizes_[native_reloc.bin_type];
+  for (auto& pair : native_object_relocations_) {
+    NativeObjectRelocation& relocation = pair.second;
+    Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
+    relocation.offset += image_objects_offset_begin_ + bin_slot_previous_sizes_[bin_type];
   }
 
   // Calculate how big the intern table will be after being serialized.
@@ -1025,8 +1069,8 @@
 }
 
 ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
-  auto it = native_object_reloc_.find(method);
-  CHECK(it != native_object_reloc_.end()) << PrettyMethod(method) << " @ " << method;
+  auto it = native_object_relocations_.find(method);
+  CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
   CHECK_GE(it->second.offset, image_end_) << "ArtMethods should be after Objects";
   return reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
 }
@@ -1064,20 +1108,34 @@
 
 void ImageWriter::CopyAndFixupNativeData() {
   // Copy ArtFields and methods to their locations and update the array for convenience.
-  for (auto& pair : native_object_reloc_) {
-    auto& native_reloc = pair.second;
-    if (native_reloc.bin_type == kBinArtField) {
-      auto* dest = image_->Begin() + native_reloc.offset;
-      DCHECK_GE(dest, image_->Begin() + image_end_);
-      memcpy(dest, pair.first, sizeof(ArtField));
-      reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
-          GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
-    } else {
-      CHECK(IsArtMethodBin(native_reloc.bin_type)) << native_reloc.bin_type;
-      auto* dest = image_->Begin() + native_reloc.offset;
-      DCHECK_GE(dest, image_->Begin() + image_end_);
-      CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
-                         reinterpret_cast<ArtMethod*>(dest));
+  for (auto& pair : native_object_relocations_) {
+    NativeObjectRelocation& relocation = pair.second;
+    auto* dest = image_->Begin() + relocation.offset;
+    DCHECK_GE(dest, image_->Begin() + image_end_);
+    switch (relocation.type) {
+      case kNativeObjectRelocationTypeArtField: {
+        memcpy(dest, pair.first, sizeof(ArtField));
+        reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
+            GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
+        break;
+      }
+      case kNativeObjectRelocationTypeArtMethodClean:
+      case kNativeObjectRelocationTypeArtMethodDirty: {
+        CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
+                           reinterpret_cast<ArtMethod*>(dest));
+        break;
+      }
+      // For arrays, copy just the header since the elements will get copied by their corresponding
+      // relocations.
+      case kNativeObjectRelocationTypeArtFieldArray: {
+        memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
+        break;
+      }
+      case kNativeObjectRelocationTypeArtMethodArrayClean:
+      case kNativeObjectRelocationTypeArtMethodArrayDirty: {
+        memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0));
+        break;
+      }
     }
   }
   // Fixup the image method roots.
@@ -1086,12 +1144,12 @@
   for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
     auto* m = image_methods_[i];
     CHECK(m != nullptr);
-    auto it = native_object_reloc_.find(m);
-    CHECK(it != native_object_reloc_.end()) << "No fowarding for " << PrettyMethod(m);
-    auto& native_reloc = it->second;
-    CHECK(methods_section.Contains(native_reloc.offset)) << native_reloc.offset << " not in "
+    auto it = native_object_relocations_.find(m);
+    CHECK(it != native_object_relocations_.end()) << "No fowarding for " << PrettyMethod(m);
+    NativeObjectRelocation& relocation = it->second;
+    CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
         << methods_section;
-    CHECK(IsArtMethodBin(native_reloc.bin_type)) << native_reloc.bin_type;
+    CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
     auto* dest = reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
     image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), dest);
   }
@@ -1143,9 +1201,9 @@
   for (size_t i = 0, count = num_elements; i < count; ++i) {
     auto* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
     if (elem != nullptr) {
-      auto it = native_object_reloc_.find(elem);
-      if (it == native_object_reloc_.end()) {
-        if (IsArtMethodBin(array_type)) {
+      auto it = native_object_relocations_.find(elem);
+      if (it == native_object_relocations_.end()) {
+        if (true) {
           auto* method = reinterpret_cast<ArtMethod*>(elem);
           LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
               << method << " idx=" << i << "/" << num_elements << " with declaring class "
@@ -1237,51 +1295,38 @@
   }
 };
 
+void* ImageWriter::NativeLocationInImage(void* obj) {
+  if (obj == nullptr) {
+    return nullptr;
+  }
+  auto it = native_object_relocations_.find(obj);
+  const NativeObjectRelocation& relocation = it->second;
+  CHECK(it != native_object_relocations_.end()) << obj;
+  return reinterpret_cast<void*>(image_begin_ + relocation.offset);
+}
+
 void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
-  // Copy and fix up ArtFields in the class.
-  ArtField* fields[2] = { orig->GetSFields(), orig->GetIFields() };
-  size_t num_fields[2] = { orig->NumStaticFields(), orig->NumInstanceFields() };
   // Update the field arrays.
-  for (size_t i = 0; i < 2; ++i) {
-    if (num_fields[i] == 0) {
-      CHECK(fields[i] == nullptr);
-      continue;
-    }
-    auto it = native_object_reloc_.find(fields[i]);
-    CHECK(it != native_object_reloc_.end()) << PrettyClass(orig) << " : " << PrettyField(fields[i]);
-    auto* image_fields = reinterpret_cast<ArtField*>(image_begin_ + it->second.offset);
-    if (i == 0) {
-      copy->SetSFieldsUnchecked(image_fields);
-    } else {
-      copy->SetIFieldsUnchecked(image_fields);
-    }
-  }
-  // Update direct / virtual method arrays.
-  auto* direct_methods = orig->GetDirectMethodsPtr();
-  if (direct_methods != nullptr) {
-    auto it = native_object_reloc_.find(direct_methods);
-    CHECK(it != native_object_reloc_.end()) << PrettyClass(orig);
-    copy->SetDirectMethodsPtrUnchecked(
-        reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset));
-  }
-  auto* virtual_methods = orig->GetVirtualMethodsPtr();
-  if (virtual_methods != nullptr) {
-    auto it = native_object_reloc_.find(virtual_methods);
-    CHECK(it != native_object_reloc_.end()) << PrettyClass(orig);
-    copy->SetVirtualMethodsPtr(
-        reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset));
-  }
+  copy->SetSFieldsPtrUnchecked(reinterpret_cast<LengthPrefixedArray<ArtField>*>(
+      NativeLocationInImage(orig->GetSFieldsPtr())));
+  copy->SetIFieldsPtrUnchecked(reinterpret_cast<LengthPrefixedArray<ArtField>*>(
+      NativeLocationInImage(orig->GetIFieldsPtr())));
+  // Update direct and virtual method arrays.
+  copy->SetDirectMethodsPtrUnchecked(reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
+      NativeLocationInImage(orig->GetDirectMethodsPtr())));
+  copy->SetVirtualMethodsPtr(reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
+      NativeLocationInImage(orig->GetVirtualMethodsPtr())));
   // Fix up embedded tables.
   if (orig->ShouldHaveEmbeddedImtAndVTable()) {
     for (int32_t i = 0; i < orig->GetEmbeddedVTableLength(); ++i) {
-      auto it = native_object_reloc_.find(orig->GetEmbeddedVTableEntry(i, target_ptr_size_));
-      CHECK(it != native_object_reloc_.end()) << PrettyClass(orig);
+      auto it = native_object_relocations_.find(orig->GetEmbeddedVTableEntry(i, target_ptr_size_));
+      CHECK(it != native_object_relocations_.end()) << PrettyClass(orig);
       copy->SetEmbeddedVTableEntryUnchecked(
           i, reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset), target_ptr_size_);
     }
     for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
-      auto it = native_object_reloc_.find(orig->GetEmbeddedImTableEntry(i, target_ptr_size_));
-      CHECK(it != native_object_reloc_.end()) << PrettyClass(orig);
+      auto it = native_object_relocations_.find(orig->GetEmbeddedImTableEntry(i, target_ptr_size_));
+      CHECK(it != native_object_relocations_.end()) << PrettyClass(orig);
       copy->SetEmbeddedImTableEntry(
           i, reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset), target_ptr_size_);
     }
@@ -1322,9 +1367,9 @@
       auto* dest = down_cast<mirror::AbstractMethod*>(copy);
       auto* src = down_cast<mirror::AbstractMethod*>(orig);
       ArtMethod* src_method = src->GetArtMethod();
-      auto it = native_object_reloc_.find(src_method);
-      CHECK(it != native_object_reloc_.end()) << "Missing relocation for AbstractMethod.artMethod "
-          << PrettyMethod(src_method);
+      auto it = native_object_relocations_.find(src_method);
+      CHECK(it != native_object_relocations_.end())
+          << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
       dest->SetArtMethod(
           reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset));
     }
@@ -1504,4 +1549,19 @@
       bin_slot_sizes_[kBinArtMethodClean] + intern_table_bytes_, kPageSize);
 }
 
+ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
+  switch (type) {
+    case kNativeObjectRelocationTypeArtField:
+    case kNativeObjectRelocationTypeArtFieldArray:
+      return kBinArtField;
+    case kNativeObjectRelocationTypeArtMethodClean:
+    case kNativeObjectRelocationTypeArtMethodArrayClean:
+      return kBinArtMethodClean;
+    case kNativeObjectRelocationTypeArtMethodDirty:
+    case kNativeObjectRelocationTypeArtMethodArrayDirty:
+      return kBinArtMethodDirty;
+  }
+  UNREACHABLE();
+}
+
 }  // namespace art
diff --git a/compiler/image_writer.h b/compiler/image_writer.h
index cabd918..eb6aa6f 100644
--- a/compiler/image_writer.h
+++ b/compiler/image_writer.h
@@ -30,6 +30,7 @@
 #include "base/macros.h"
 #include "driver/compiler_driver.h"
 #include "gc/space/space.h"
+#include "length_prefixed_array.h"
 #include "lock_word.h"
 #include "mem_map.h"
 #include "oat_file.h"
@@ -54,7 +55,8 @@
         quick_to_interpreter_bridge_offset_(0), compile_pic_(compile_pic),
         target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
         bin_slot_sizes_(), bin_slot_previous_sizes_(), bin_slot_count_(),
-        intern_table_bytes_(0u), dirty_methods_(0u), clean_methods_(0u) {
+        intern_table_bytes_(0u), image_method_array_(ImageHeader::kImageMethodsCount),
+        dirty_methods_(0u), clean_methods_(0u) {
     CHECK_NE(image_begin, 0U);
     std::fill(image_methods_, image_methods_ + arraysize(image_methods_), nullptr);
   }
@@ -129,9 +131,18 @@
     // Number of bins which are for mirror objects.
     kBinMirrorCount = kBinArtField,
   };
-
   friend std::ostream& operator<<(std::ostream& stream, const Bin& bin);
 
+  enum NativeObjectRelocationType {
+    kNativeObjectRelocationTypeArtField,
+    kNativeObjectRelocationTypeArtFieldArray,
+    kNativeObjectRelocationTypeArtMethodClean,
+    kNativeObjectRelocationTypeArtMethodArrayClean,
+    kNativeObjectRelocationTypeArtMethodDirty,
+    kNativeObjectRelocationTypeArtMethodArrayDirty,
+  };
+  friend std::ostream& operator<<(std::ostream& stream, const NativeObjectRelocationType& type);
+
   static constexpr size_t kBinBits = MinimumBitsToStore<uint32_t>(kBinMirrorCount - 1);
   // uint32 = typeof(lockword_)
   // Subtract read barrier bits since we want these to remain 0, or else it may result in DCHECK
@@ -204,10 +215,6 @@
     return offset == 0u ? nullptr : oat_data_begin_ + offset;
   }
 
-  static bool IsArtMethodBin(Bin bin) {
-    return bin == kBinArtMethodClean || bin == kBinArtMethodDirty;
-  }
-
   // Returns true if the class was in the original requested image classes list.
   bool IsImageClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_);
 
@@ -284,7 +291,12 @@
   bool WillMethodBeDirty(ArtMethod* m) const SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Assign the offset for an ArtMethod.
-  void AssignMethodOffset(ArtMethod* method, Bin bin) SHARED_REQUIRES(Locks::mutator_lock_);
+  void AssignMethodOffset(ArtMethod* method, NativeObjectRelocationType type)
+      SHARED_REQUIRES(Locks::mutator_lock_);
+
+  static Bin BinTypeForNativeRelocationType(NativeObjectRelocationType type);
+
+  void* NativeLocationInImage(void* obj);
 
   const CompilerDriver& compiler_driver_;
 
@@ -356,14 +368,21 @@
   // ArtField, ArtMethod relocating map. These are allocated as array of structs but we want to
   // have one entry per art field for convenience. ArtFields are placed right after the end of the
   // image objects (aka sum of bin_slot_sizes_). ArtMethods are placed right after the ArtFields.
-  struct NativeObjectReloc {
+  struct NativeObjectRelocation {
     uintptr_t offset;
-    Bin bin_type;
+    NativeObjectRelocationType type;
+
+    bool IsArtMethodRelocation() const {
+      return type == kNativeObjectRelocationTypeArtMethodClean ||
+          type == kNativeObjectRelocationTypeArtMethodDirty;
+    }
   };
-  std::unordered_map<void*, NativeObjectReloc> native_object_reloc_;
+  std::unordered_map<void*, NativeObjectRelocation> native_object_relocations_;
 
   // Runtime ArtMethods which aren't reachable from any Class but need to be copied into the image.
   ArtMethod* image_methods_[ImageHeader::kImageMethodsCount];
+  // Fake length prefixed array for image methods.
+  LengthPrefixedArray<ArtMethod> image_method_array_;
 
   // Counters for measurements, used for logging only.
   uint64_t dirty_methods_;
diff --git a/compiler/jit/jit_compiler.cc b/compiler/jit/jit_compiler.cc
index c95bac2..4215f3c 100644
--- a/compiler/jit/jit_compiler.cc
+++ b/compiler/jit/jit_compiler.cc
@@ -153,7 +153,7 @@
   CompiledMethod* compiled_method = nullptr;
   {
     TimingLogger::ScopedTiming t2("Compiling", &logger);
-    compiled_method = compiler_driver_->CompileMethod(self, method);
+    compiled_method = compiler_driver_->CompileArtMethod(self, method);
   }
   {
     TimingLogger::ScopedTiming t2("TrimMaps", &logger);
diff --git a/compiler/oat_test.cc b/compiler/oat_test.cc
index 05a33d7..88dc29e 100644
--- a/compiler/oat_test.cc
+++ b/compiler/oat_test.cc
@@ -16,7 +16,6 @@
 
 #include "arch/instruction_set_features.h"
 #include "art_method-inl.h"
-#include "base/out.h"
 #include "class_linker.h"
 #include "common_compiler_test.h"
 #include "compiled_method.h"
@@ -84,7 +83,7 @@
 
   std::string error_msg;
   std::unique_ptr<const InstructionSetFeatures> insn_features(
-      InstructionSetFeatures::FromVariant(insn_set, "default", outof(error_msg)));
+      InstructionSetFeatures::FromVariant(insn_set, "default", &error_msg));
   ASSERT_TRUE(insn_features.get() != nullptr) << error_msg;
   compiler_options_.reset(new CompilerOptions);
   verification_results_.reset(new VerificationResults(compiler_options_.get()));
@@ -124,7 +123,7 @@
     compiler_driver_->CompileAll(class_loader, class_linker->GetBootClassPath(), &timings);
   }
   std::unique_ptr<OatFile> oat_file(OatFile::Open(tmp.GetFilename(), tmp.GetFilename(), nullptr,
-                                                  nullptr, false, nullptr, outof(error_msg)));
+                                                  nullptr, false, nullptr, &error_msg));
   ASSERT_TRUE(oat_file.get() != nullptr) << error_msg;
   const OatHeader& oat_header = oat_file->GetOatHeader();
   ASSERT_TRUE(oat_header.IsValid());
@@ -191,7 +190,7 @@
     InstructionSet insn_set = kX86;
     std::string error_msg;
     std::unique_ptr<const InstructionSetFeatures> insn_features(
-        InstructionSetFeatures::FromVariant(insn_set, "default", outof(error_msg)));
+        InstructionSetFeatures::FromVariant(insn_set, "default", &error_msg));
     ASSERT_TRUE(insn_features.get() != nullptr) << error_msg;
     std::vector<const DexFile*> dex_files;
     uint32_t image_file_location_oat_checksum = 0;
diff --git a/oatdump/oatdump.cc b/oatdump/oatdump.cc
index 99140d4..b61cfc9 100644
--- a/oatdump/oatdump.cc
+++ b/oatdump/oatdump.cc
@@ -159,7 +159,7 @@
 
   void WalkOatDexFile(const OatFile::OatDexFile* oat_dex_file, Callback callback) {
     std::string error_msg;
-    std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(outof(error_msg)));
+    std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
     if (dex_file.get() == nullptr) {
       return;
     }
@@ -504,7 +504,7 @@
       const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
       CHECK(oat_dex_file != nullptr);
       std::string error_msg;
-      std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(outof(error_msg)));
+      std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
       if (dex_file.get() == nullptr) {
         LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
             << "': " << error_msg;
@@ -533,7 +533,7 @@
       const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
       CHECK(oat_dex_file != nullptr);
       std::string error_msg;
-      std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(outof(error_msg)));
+      std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
       if (dex_file.get() == nullptr) {
         LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
             << "': " << error_msg;
@@ -593,7 +593,7 @@
     // Create the verifier early.
 
     std::string error_msg;
-    std::unique_ptr<const DexFile> dex_file(oat_dex_file.OpenDexFile(outof(error_msg)));
+    std::unique_ptr<const DexFile> dex_file(oat_dex_file.OpenDexFile(&error_msg));
     if (dex_file.get() == nullptr) {
       os << "NOT FOUND: " << error_msg << "\n\n";
       os << std::flush;
@@ -638,7 +638,7 @@
     std::string error_msg;
     std::string dex_file_location = oat_dex_file.GetDexFileLocation();
 
-    std::unique_ptr<const DexFile> dex_file(oat_dex_file.OpenDexFile(outof(error_msg)));
+    std::unique_ptr<const DexFile> dex_file(oat_dex_file.OpenDexFile(&error_msg));
     if (dex_file == nullptr) {
       os << "Failed to open dex file '" << dex_file_location << "': " << error_msg;
       return false;
@@ -1553,7 +1553,7 @@
     if (oat_file == nullptr) {
       oat_file = OatFile::Open(oat_location, oat_location,
                                nullptr, nullptr, false, nullptr,
-                               outof(error_msg));
+                               &error_msg);
       if (oat_file == nullptr) {
         os << "NOT FOUND: " << error_msg << "\n";
         return false;
@@ -1615,16 +1615,12 @@
           // TODO: Dump fields.
           // Dump methods after.
           const auto& methods_section = image_header_.GetMethodsSection();
-          const auto pointer_size =
+          const size_t pointer_size =
               InstructionSetPointerSize(oat_dumper_->GetOatInstructionSet());
-          const auto method_size = ArtMethod::ObjectSize(pointer_size);
-          for (size_t pos = 0; pos < methods_section.Size(); pos += method_size) {
-            auto* method = reinterpret_cast<ArtMethod*>(
-                image_space->Begin() + pos + methods_section.Offset());
-            indent_os << method << " " << " ArtMethod: " << PrettyMethod(method) << "\n";
-            DumpMethod(method, this, indent_os);
-            indent_os << "\n";
-          }
+          DumpArtMethodVisitor visitor(this);
+          methods_section.VisitPackedArtMethods(&visitor,
+                                                image_space->Begin(),
+                                                ArtMethod::ObjectSize(pointer_size));
         }
       }
       // Dump the large objects separately.
@@ -1663,6 +1659,21 @@
   }
 
  private:
+  class DumpArtMethodVisitor : public ArtMethodVisitor {
+   public:
+    explicit DumpArtMethodVisitor(ImageDumper* image_dumper) : image_dumper_(image_dumper) {}
+
+    virtual void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
+      std::ostream& indent_os = image_dumper_->vios_.Stream();
+      indent_os << method << " " << " ArtMethod: " << PrettyMethod(method) << "\n";
+      image_dumper_->DumpMethod(method, image_dumper_, indent_os);
+      indent_os << "\n";
+    }
+
+   private:
+    ImageDumper* const image_dumper_;
+  };
+
   static void PrettyObjectValue(std::ostream& os, mirror::Class* type, mirror::Object* value)
       SHARED_REQUIRES(Locks::mutator_lock_) {
     CHECK(type != nullptr);
@@ -1739,9 +1750,8 @@
     if (super != nullptr) {
       DumpFields(os, obj, super);
     }
-    ArtField* fields = klass->GetIFields();
-    for (size_t i = 0, count = klass->NumInstanceFields(); i < count; i++) {
-      PrintField(os, &fields[i], obj);
+    for (ArtField& field : klass->GetIFields()) {
+      PrintField(os, &field, obj);
     }
   }
 
@@ -1837,13 +1847,11 @@
       }
     } else if (obj->IsClass()) {
       mirror::Class* klass = obj->AsClass();
-      ArtField* sfields = klass->GetSFields();
-      const size_t num_fields = klass->NumStaticFields();
-      if (num_fields != 0) {
+      if (klass->NumStaticFields() != 0) {
         os << "STATICS:\n";
         ScopedIndentation indent2(&state->vios_);
-        for (size_t i = 0; i < num_fields; i++) {
-          PrintField(os, &sfields[i], sfields[i].GetDeclaringClass());
+        for (ArtField& field : klass->GetSFields()) {
+          PrintField(os, &field, field.GetDeclaringClass());
         }
       }
     } else {
@@ -2321,7 +2329,7 @@
   std::vector<std::unique_ptr<const DexFile>> dex_files;
   for (const OatFile::OatDexFile* odf : oat_file->GetOatDexFiles()) {
     std::string error_msg;
-    std::unique_ptr<const DexFile> dex_file = odf->OpenDexFile(outof(error_msg));
+    std::unique_ptr<const DexFile> dex_file = odf->OpenDexFile(&error_msg);
     CHECK(dex_file != nullptr) << error_msg;
     class_linker->RegisterDexFile(*dex_file);
     dex_files.push_back(std::move(dex_file));
@@ -2361,7 +2369,7 @@
                    std::ostream* os) {
   std::string error_msg;
   OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, nullptr, nullptr, false,
-                                    nullptr, outof(error_msg));
+                                    nullptr, &error_msg);
   if (oat_file == nullptr) {
     fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
     return EXIT_FAILURE;
@@ -2377,7 +2385,7 @@
 static int SymbolizeOat(const char* oat_filename, std::string& output_name) {
   std::string error_msg;
   OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, nullptr, nullptr, false,
-                                    nullptr, outof(error_msg));
+                                    nullptr, &error_msg);
   if (oat_file == nullptr) {
     fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
     return EXIT_FAILURE;
diff --git a/patchoat/patchoat.cc b/patchoat/patchoat.cc
index 1ed6597..283eea9 100644
--- a/patchoat/patchoat.cc
+++ b/patchoat/patchoat.cc
@@ -419,24 +419,44 @@
   return true;
 }
 
-void PatchOat::PatchArtFields(const ImageHeader* image_header) {
-  const auto& section = image_header->GetImageSection(ImageHeader::kSectionArtFields);
-  for (size_t pos = 0; pos < section.Size(); pos += sizeof(ArtField)) {
-    auto* src = reinterpret_cast<ArtField*>(heap_->Begin() + section.Offset() + pos);
-    auto* dest = RelocatedCopyOf(src);
-    dest->SetDeclaringClass(RelocatedAddressOfPointer(src->GetDeclaringClass()));
+class PatchOatArtFieldVisitor : public ArtFieldVisitor {
+ public:
+  explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
+
+  void Visit(ArtField* field) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
+    ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
+    dest->SetDeclaringClass(patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass()));
   }
+
+ private:
+  PatchOat* const patch_oat_;
+};
+
+void PatchOat::PatchArtFields(const ImageHeader* image_header) {
+  PatchOatArtFieldVisitor visitor(this);
+  const auto& section = image_header->GetImageSection(ImageHeader::kSectionArtFields);
+  section.VisitPackedArtFields(&visitor, heap_->Begin());
 }
 
+class PatchOatArtMethodVisitor : public ArtMethodVisitor {
+ public:
+  explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
+
+  void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
+    ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
+    patch_oat_->FixupMethod(method, dest);
+  }
+
+ private:
+  PatchOat* const patch_oat_;
+};
+
 void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
   const auto& section = image_header->GetMethodsSection();
   const size_t pointer_size = InstructionSetPointerSize(isa_);
-  size_t method_size = ArtMethod::ObjectSize(pointer_size);
-  for (size_t pos = 0; pos < section.Size(); pos += method_size) {
-    auto* src = reinterpret_cast<ArtMethod*>(heap_->Begin() + section.Offset() + pos);
-    auto* dest = RelocatedCopyOf(src);
-    FixupMethod(src, dest);
-  }
+  const size_t method_size = ArtMethod::ObjectSize(pointer_size);
+  PatchOatArtMethodVisitor visitor(this);
+  section.VisitPackedArtMethods(&visitor, heap_->Begin(), method_size);
 }
 
 class FixupRootVisitor : public RootVisitor {
@@ -601,8 +621,8 @@
   if (object->IsClass<kVerifyNone>()) {
     auto* klass = object->AsClass();
     auto* copy_klass = down_cast<mirror::Class*>(copy);
-    copy_klass->SetSFieldsUnchecked(RelocatedAddressOfPointer(klass->GetSFields()));
-    copy_klass->SetIFieldsUnchecked(RelocatedAddressOfPointer(klass->GetIFields()));
+    copy_klass->SetSFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetSFieldsPtr()));
+    copy_klass->SetIFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetIFieldsPtr()));
     copy_klass->SetDirectMethodsPtrUnchecked(
         RelocatedAddressOfPointer(klass->GetDirectMethodsPtr()));
     copy_klass->SetVirtualMethodsPtr(RelocatedAddressOfPointer(klass->GetVirtualMethodsPtr()));
diff --git a/patchoat/patchoat.h b/patchoat/patchoat.h
index 466dacb..43cdaea 100644
--- a/patchoat/patchoat.h
+++ b/patchoat/patchoat.h
@@ -207,6 +207,8 @@
   TimingLogger* timings_;
 
   friend class FixupRootVisitor;
+  friend class PatchOatArtFieldVisitor;
+  friend class PatchOatArtMethodVisitor;
   DISALLOW_IMPLICIT_CONSTRUCTORS(PatchOat);
 };
 
diff --git a/runtime/arch/stub_test.cc b/runtime/arch/stub_test.cc
index 195b3b3..e6710ed 100644
--- a/runtime/arch/stub_test.cc
+++ b/runtime/arch/stub_test.cc
@@ -2063,37 +2063,34 @@
   // Play with it...
 
   // Static fields.
-  ArtField* fields = c->GetSFields();
-  size_t num_fields = c->NumStaticFields();
-  for (size_t i = 0; i < num_fields; ++i) {
-    ArtField* f = &fields[i];
-    Primitive::Type type = f->GetTypeAsPrimitiveType();
+  for (ArtField& f : c->GetSFields()) {
+    Primitive::Type type = f.GetTypeAsPrimitiveType();
     if (test_type != type) {
      continue;
     }
     switch (type) {
       case Primitive::Type::kPrimBoolean:
-        GetSetBooleanStatic(f, self, m, test);
+        GetSetBooleanStatic(&f, self, m, test);
         break;
       case Primitive::Type::kPrimByte:
-        GetSetByteStatic(f, self, m, test);
+        GetSetByteStatic(&f, self, m, test);
         break;
       case Primitive::Type::kPrimChar:
-        GetSetCharStatic(f, self, m, test);
+        GetSetCharStatic(&f, self, m, test);
         break;
       case Primitive::Type::kPrimShort:
-        GetSetShortStatic(f, self, m, test);
+        GetSetShortStatic(&f, self, m, test);
         break;
       case Primitive::Type::kPrimInt:
-        GetSet32Static(f, self, m, test);
+        GetSet32Static(&f, self, m, test);
         break;
       case Primitive::Type::kPrimLong:
-        GetSet64Static(f, self, m, test);
+        GetSet64Static(&f, self, m, test);
         break;
       case Primitive::Type::kPrimNot:
         // Don't try array.
-        if (f->GetTypeDescriptor()[0] != '[') {
-          GetSetObjStatic(f, self, m, test);
+        if (f.GetTypeDescriptor()[0] != '[') {
+          GetSetObjStatic(&f, self, m, test);
         }
         break;
       default:
@@ -2102,37 +2099,34 @@
   }
 
   // Instance fields.
-  fields = c->GetIFields();
-  num_fields = c->NumInstanceFields();
-  for (size_t i = 0; i < num_fields; ++i) {
-    ArtField* f = &fields[i];
-    Primitive::Type type = f->GetTypeAsPrimitiveType();
+  for (ArtField& f : c->GetIFields()) {
+    Primitive::Type type = f.GetTypeAsPrimitiveType();
     if (test_type != type) {
       continue;
     }
     switch (type) {
       case Primitive::Type::kPrimBoolean:
-        GetSetBooleanInstance(&obj, f, self, m, test);
+        GetSetBooleanInstance(&obj, &f, self, m, test);
         break;
       case Primitive::Type::kPrimByte:
-        GetSetByteInstance(&obj, f, self, m, test);
+        GetSetByteInstance(&obj, &f, self, m, test);
         break;
       case Primitive::Type::kPrimChar:
-        GetSetCharInstance(&obj, f, self, m, test);
+        GetSetCharInstance(&obj, &f, self, m, test);
         break;
       case Primitive::Type::kPrimShort:
-        GetSetShortInstance(&obj, f, self, m, test);
+        GetSetShortInstance(&obj, &f, self, m, test);
         break;
       case Primitive::Type::kPrimInt:
-        GetSet32Instance(&obj, f, self, m, test);
+        GetSet32Instance(&obj, &f, self, m, test);
         break;
       case Primitive::Type::kPrimLong:
-        GetSet64Instance(&obj, f, self, m, test);
+        GetSet64Instance(&obj, &f, self, m, test);
         break;
       case Primitive::Type::kPrimNot:
         // Don't try array.
-        if (f->GetTypeDescriptor()[0] != '[') {
-          GetSetObjInstance(&obj, f, self, m, test);
+        if (f.GetTypeDescriptor()[0] != '[') {
+          GetSetObjInstance(&obj, &f, self, m, test);
         }
         break;
       default:
diff --git a/runtime/art_field.cc b/runtime/art_field.cc
index e4a5834..3737e0d 100644
--- a/runtime/art_field.cc
+++ b/runtime/art_field.cc
@@ -49,10 +49,9 @@
 
 ArtField* ArtField::FindInstanceFieldWithOffset(mirror::Class* klass, uint32_t field_offset) {
   DCHECK(klass != nullptr);
-  auto* instance_fields = klass->GetIFields();
-  for (size_t i = 0, count = klass->NumInstanceFields(); i < count; ++i) {
-    if (instance_fields[i].GetOffset().Uint32Value() == field_offset) {
-      return &instance_fields[i];
+  for (ArtField& field : klass->GetIFields()) {
+    if (field.GetOffset().Uint32Value() == field_offset) {
+      return &field;
     }
   }
   // We did not find field in the class: look into superclass.
@@ -62,10 +61,9 @@
 
 ArtField* ArtField::FindStaticFieldWithOffset(mirror::Class* klass, uint32_t field_offset) {
   DCHECK(klass != nullptr);
-  auto* static_fields = klass->GetSFields();
-  for (size_t i = 0, count = klass->NumStaticFields(); i < count; ++i) {
-    if (static_fields[i].GetOffset().Uint32Value() == field_offset) {
-      return &static_fields[i];
+  for (ArtField& field : klass->GetSFields()) {
+    if (field.GetOffset().Uint32Value() == field_offset) {
+      return &field;
     }
   }
   return nullptr;
diff --git a/runtime/art_method.cc b/runtime/art_method.cc
index f37e040..17c9fe4 100644
--- a/runtime/art_method.cc
+++ b/runtime/art_method.cc
@@ -19,7 +19,6 @@
 #include "arch/context.h"
 #include "art_field-inl.h"
 #include "art_method-inl.h"
-#include "base/out.h"
 #include "base/stringpiece.h"
 #include "dex_file-inl.h"
 #include "dex_instruction.h"
@@ -566,7 +565,7 @@
 const uint8_t* ArtMethod::GetQuickenedInfo() {
   bool found = false;
   OatFile::OatMethod oat_method =
-      Runtime::Current()->GetClassLinker()->FindOatMethodFor(this, outof(found));
+      Runtime::Current()->GetClassLinker()->FindOatMethodFor(this, &found);
   if (!found || (oat_method.GetQuickCode() != nullptr)) {
     return nullptr;
   }
diff --git a/runtime/asm_support.h b/runtime/asm_support.h
index 350a0d4..35acd42 100644
--- a/runtime/asm_support.h
+++ b/runtime/asm_support.h
@@ -141,10 +141,10 @@
 #define MIRROR_CLASS_ACCESS_FLAGS_OFFSET (36 + MIRROR_OBJECT_HEADER_SIZE)
 ADD_TEST_EQ(MIRROR_CLASS_ACCESS_FLAGS_OFFSET,
             art::mirror::Class::AccessFlagsOffset().Int32Value())
-#define MIRROR_CLASS_OBJECT_SIZE_OFFSET (112 + MIRROR_OBJECT_HEADER_SIZE)
+#define MIRROR_CLASS_OBJECT_SIZE_OFFSET (96 + MIRROR_OBJECT_HEADER_SIZE)
 ADD_TEST_EQ(MIRROR_CLASS_OBJECT_SIZE_OFFSET,
             art::mirror::Class::ObjectSizeOffset().Int32Value())
-#define MIRROR_CLASS_STATUS_OFFSET (124 + MIRROR_OBJECT_HEADER_SIZE)
+#define MIRROR_CLASS_STATUS_OFFSET (108 + MIRROR_OBJECT_HEADER_SIZE)
 ADD_TEST_EQ(MIRROR_CLASS_STATUS_OFFSET,
             art::mirror::Class::StatusOffset().Int32Value())
 
diff --git a/runtime/barrier.h b/runtime/barrier.h
index 02f9f58..94977fb 100644
--- a/runtime/barrier.h
+++ b/runtime/barrier.h
@@ -51,7 +51,7 @@
   // to sleep, resulting in a deadlock.
 
   // Increment the count by delta, wait on condition if count is non zero.
-  void Increment(Thread* self, int delta) REQUIRES(!lock_);;
+  void Increment(Thread* self, int delta) REQUIRES(!lock_);
 
   // Increment the count by delta, wait on condition if count is non zero, with a timeout. Returns
   // true if time out occurred.
diff --git a/runtime/base/iteration_range.h b/runtime/base/iteration_range.h
index 6a0ef1f..cf02d32 100644
--- a/runtime/base/iteration_range.h
+++ b/runtime/base/iteration_range.h
@@ -49,6 +49,11 @@
   return IterationRange<Iter>(begin_it, end_it);
 }
 
+template <typename Iter>
+static inline IterationRange<Iter> MakeEmptyIterationRange(const Iter& it) {
+  return IterationRange<Iter>(it, it);
+}
+
 }  // namespace art
 
 #endif  // ART_RUNTIME_BASE_ITERATION_RANGE_H_
diff --git a/runtime/base/mutex.h b/runtime/base/mutex.h
index d0504d9..2801fb7 100644
--- a/runtime/base/mutex.h
+++ b/runtime/base/mutex.h
@@ -332,36 +332,40 @@
   bool IsExclusiveHeld(const Thread* self) const;
 
   // Assert the current thread has exclusive access to the ReaderWriterMutex.
-  void AssertExclusiveHeld(const Thread* self) {
+  void AssertExclusiveHeld(const Thread* self) ASSERT_CAPABILITY(this) {
     if (kDebugLocking && (gAborting == 0)) {
       CHECK(IsExclusiveHeld(self)) << *this;
     }
   }
-  void AssertWriterHeld(const Thread* self) { AssertExclusiveHeld(self); }
+  void AssertWriterHeld(const Thread* self) ASSERT_CAPABILITY(this) { AssertExclusiveHeld(self); }
 
   // Assert the current thread doesn't have exclusive access to the ReaderWriterMutex.
-  void AssertNotExclusiveHeld(const Thread* self) {
+  void AssertNotExclusiveHeld(const Thread* self) ASSERT_CAPABILITY(!this) {
     if (kDebugLocking && (gAborting == 0)) {
       CHECK(!IsExclusiveHeld(self)) << *this;
     }
   }
-  void AssertNotWriterHeld(const Thread* self) { AssertNotExclusiveHeld(self); }
+  void AssertNotWriterHeld(const Thread* self) ASSERT_CAPABILITY(!this) {
+    AssertNotExclusiveHeld(self);
+  }
 
   // Is the current thread a shared holder of the ReaderWriterMutex.
   bool IsSharedHeld(const Thread* self) const;
 
   // Assert the current thread has shared access to the ReaderWriterMutex.
-  void AssertSharedHeld(const Thread* self) {
+  void AssertSharedHeld(const Thread* self) ASSERT_SHARED_CAPABILITY(this) {
     if (kDebugLocking && (gAborting == 0)) {
       // TODO: we can only assert this well when self != null.
       CHECK(IsSharedHeld(self) || self == nullptr) << *this;
     }
   }
-  void AssertReaderHeld(const Thread* self) { AssertSharedHeld(self); }
+  void AssertReaderHeld(const Thread* self) ASSERT_SHARED_CAPABILITY(this) {
+    AssertSharedHeld(self);
+  }
 
   // Assert the current thread doesn't hold this ReaderWriterMutex either in shared or exclusive
   // mode.
-  void AssertNotHeld(const Thread* self) {
+  void AssertNotHeld(const Thread* self) ASSERT_SHARED_CAPABILITY(!this) {
     if (kDebugLocking && (gAborting == 0)) {
       CHECK(!IsSharedHeld(self)) << *this;
     }
@@ -679,6 +683,7 @@
 
 class Roles {
  public:
+  // Uninterruptible means that the thread may not become suspended.
   static Uninterruptible uninterruptible_;
 };
 
diff --git a/runtime/base/out.h b/runtime/base/out.h
deleted file mode 100644
index 7b4bc12..0000000
--- a/runtime/base/out.h
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ART_RUNTIME_BASE_OUT_H_
-#define ART_RUNTIME_BASE_OUT_H_
-
-#include <base/macros.h>
-#include <base/logging.h>
-
-#include <memory>
-// A zero-overhead abstraction marker that means this value is meant to be used as an out
-// parameter for functions. It mimics semantics of a pointer that the function will
-// dereference and output its value into.
-//
-// Inspired by the 'out' language keyword in C#.
-//
-// Declaration example:
-//   int do_work(size_t args, out<int> result);
-//               // returns 0 on success, sets result, otherwise error code
-//
-// Use-site example:
-// // (1) -- out of a local variable or field
-//   int res;
-//   if (do_work(1, outof(res)) {
-//     cout << "success: " << res;
-//   }
-// // (2) -- out of an iterator
-//   std::vector<int> list = {1};
-//   std::vector<int>::iterator it = list.begin();
-//   if (do_work(2, outof_iterator(*it)) {
-//     cout << "success: " << list[0];
-//   }
-// // (3) -- out of a pointer
-//   int* array = &some_other_value;
-//   if (do_work(3, outof_ptr(array))) {
-//     cout << "success: " << *array;
-//   }
-//
-// The type will also automatically decay into a C-style pointer for compatibility
-// with calling legacy code that expect pointers.
-//
-// Declaration example:
-//   void write_data(int* res) { *res = 5; }
-//
-// Use-site example:
-//   int data;
-//   write_data(outof(res));
-//   // data is now '5'
-// (The other outof_* functions can be used analogously when the target is a C-style pointer).
-//
-// ---------------
-//
-// Other typical pointer operations such as addition, subtraction, etc are banned
-// since there is exactly one value being output.
-//
-namespace art {
-
-// Forward declarations. See below for specific functions.
-template <typename T>
-struct out_convertible;  // Implicitly converts to out<T> or T*.
-
-// Helper function that automatically infers 'T'
-//
-// Returns a type that is implicitly convertible to either out<T> or T* depending
-// on the call site.
-//
-// Example:
-//   int do_work(size_t args, out<int> result);
-//               // returns 0 on success, sets result, otherwise error code
-//
-// Usage:
-//   int res;
-//   if (do_work(1, outof(res)) {
-//     cout << "success: " << res;
-//   }
-template <typename T>
-out_convertible<T> outof(T& param) ALWAYS_INLINE;
-
-// Helper function that automatically infers 'T' from a container<T>::iterator.
-// To use when the argument is already inside an iterator.
-//
-// Returns a type that is implicitly convertible to either out<T> or T* depending
-// on the call site.
-//
-// Example:
-//   int do_work(size_t args, out<int> result);
-//               // returns 0 on success, sets result, otherwise error code
-//
-// Usage:
-//   std::vector<int> list = {1};
-//   std::vector<int>::iterator it = list.begin();
-//   if (do_work(2, outof_iterator(*it)) {
-//     cout << "success: " << list[0];
-//   }
-template <typename It>
-auto ALWAYS_INLINE outof_iterator(It iter)
-    -> out_convertible<typename std::remove_reference<decltype(*iter)>::type>;
-
-// Helper function that automatically infers 'T'.
-// To use when the argument is already a pointer.
-//
-// ptr must be not-null, else a DCHECK failure will occur.
-//
-// Returns a type that is implicitly convertible to either out<T> or T* depending
-// on the call site.
-//
-// Example:
-//   int do_work(size_t args, out<int> result);
-//               // returns 0 on success, sets result, otherwise error code
-//
-// Usage:
-//   int* array = &some_other_value;
-//   if (do_work(3, outof_ptr(array))) {
-//     cout << "success: " << *array;
-//   }
-template <typename T>
-out_convertible<T> outof_ptr(T* ptr) ALWAYS_INLINE;
-
-// Zero-overhead wrapper around a non-null non-const pointer meant to be used to output
-// the result of parameters. There are no other extra guarantees.
-//
-// The most common use case is to treat this like a typical pointer argument, for example:
-//
-// void write_out_5(out<int> x) {
-//   *x = 5;
-// }
-//
-// The following operations are supported:
-//   operator* -> use like a pointer (guaranteed to be non-null)
-//   == and != -> compare against other pointers for (in)equality
-//   begin/end -> use in standard C++ algorithms as if it was an iterator
-template <typename T>
-struct out {
-  // Has to be mutable lref. Otherwise how would you write something as output into it?
-  explicit inline out(T& param)
-    : param_(param) {}
-
-  // Model a single-element iterator (or pointer) to the parameter.
-  inline T& operator *() {
-    return param_;
-  }
-
-  // Model dereferencing fields/methods on a pointer.
-  inline T* operator->() {
-    return std::addressof(param_);
-  }
-
-  //
-  // Comparison against this or other pointers.
-  //
-  template <typename T2>
-  inline bool operator==(const T2* other) const {
-    return std::addressof(param_) == other;
-  }
-
-  template <typename T2>
-  inline bool operator==(const out<T>& other) const {
-    return std::addressof(param_) == std::addressof(other.param_);
-  }
-
-  // An out-parameter is never null.
-  inline bool operator==(std::nullptr_t) const {
-    return false;
-  }
-
-  template <typename T2>
-  inline bool operator!=(const T2* other) const {
-    return std::addressof(param_) != other;
-  }
-
-  template <typename T2>
-  inline bool operator!=(const out<T>& other) const {
-    return std::addressof(param_) != std::addressof(other.param_);
-  }
-
-  // An out-parameter is never null.
-  inline bool operator!=(std::nullptr_t) const {
-    return true;
-  }
-
-  //
-  // Iterator interface implementation. Use with standard algorithms.
-  // TODO: (add items in iterator_traits if this is truly useful).
-  //
-
-  inline T* begin() {
-    return std::addressof(param_);
-  }
-
-  inline const T* begin() const {
-    return std::addressof(param_);
-  }
-
-  inline T* end() {
-    return std::addressof(param_) + 1;
-  }
-
-  inline const T* end() const {
-    return std::addressof(param_) + 1;
-  }
-
- private:
-  T& param_;
-};
-
-//
-// IMPLEMENTATION DETAILS
-//
-
-//
-// This intermediate type should not be used directly by user code.
-//
-// It enables 'outof(x)' to be passed into functions that expect either
-// an out<T> **or** a regular C-style pointer (T*).
-//
-template <typename T>
-struct out_convertible {
-  explicit inline out_convertible(T& param)
-    : param_(param) {
-  }
-
-  // Implicitly convert into an out<T> for standard usage.
-  inline operator out<T>() {
-    return out<T>(param_);
-  }
-
-  // Implicitly convert into a '*' for legacy usage.
-  inline operator T*() {
-    return std::addressof(param_);
-  }
- private:
-  T& param_;
-};
-
-// Helper function that automatically infers 'T'
-template <typename T>
-inline out_convertible<T> outof(T& param) {
-  return out_convertible<T>(param);
-}
-
-// Helper function that automatically infers 'T'.
-// To use when the argument is already inside an iterator.
-template <typename It>
-inline auto outof_iterator(It iter)
-    -> out_convertible<typename std::remove_reference<decltype(*iter)>::type> {
-  return outof(*iter);
-}
-
-// Helper function that automatically infers 'T'.
-// To use when the argument is already a pointer.
-template <typename T>
-inline out_convertible<T> outof_ptr(T* ptr) {
-  DCHECK(ptr != nullptr);
-  return outof(*ptr);
-}
-
-// Helper function that automatically infers 'T'.
-// Forwards an out parameter from one function into another.
-template <typename T>
-inline out_convertible<T> outof_forward(out<T>& out_param) {
-  T& param = *out_param;
-  return out_convertible<T>(param);
-}
-
-}  // namespace art
-#endif  // ART_RUNTIME_BASE_OUT_H_
diff --git a/runtime/base/out_fwd.h b/runtime/base/out_fwd.h
deleted file mode 100644
index 6b2f926..0000000
--- a/runtime/base/out_fwd.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ART_RUNTIME_BASE_OUT_FWD_H_
-#define ART_RUNTIME_BASE_OUT_FWD_H_
-
-// Forward declaration for "out<T>". See <out.h> for more information.
-// Other headers use only the forward declaration.
-
-// Callers of functions that take an out<T> parameter should #include <out.h> to get outof_.
-// which constructs out<T> through type inference.
-namespace art {
-template <typename T>
-struct out;
-}  // namespace art
-
-#endif  // ART_RUNTIME_BASE_OUT_FWD_H_
diff --git a/runtime/base/out_test.cc b/runtime/base/out_test.cc
deleted file mode 100644
index 4274200..0000000
--- a/runtime/base/out_test.cc
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "out.h"
-
-#include <algorithm>
-#include <gtest/gtest.h>
-
-namespace art {
-
-struct OutTest : public testing::Test {
-  // Multiplies values less than 10 by two, stores the result and returns 0.
-  // Returns -1 if the original value was not multiplied by two.
-  static int multiply_small_values_by_two(size_t args, out<int> result) {
-    if (args < 10) {
-      *result = args * 2;
-      return 0;
-    } else {
-      return -1;
-    }
-  }
-};
-
-extern "C" int multiply_small_values_by_two_legacy(size_t args, int* result) {
-  if (args < 10) {
-    *result = args * 2;
-    return 0;
-  } else {
-    return -1;
-  }
-}
-
-TEST_F(OutTest, TraditionalCall) {
-  // For calling traditional C++ functions.
-  int res;
-  EXPECT_EQ(multiply_small_values_by_two(1, outof(res)), 0);
-  EXPECT_EQ(2, res);
-}
-
-TEST_F(OutTest, LegacyCall) {
-  // For calling legacy, e.g. C-style functions.
-  int res2;
-  EXPECT_EQ(0, multiply_small_values_by_two_legacy(1, outof(res2)));
-  EXPECT_EQ(2, res2);
-}
-
-TEST_F(OutTest, CallFromIterator) {
-  // For calling a function with a parameter originating as an iterator.
-  std::vector<int> list = {1, 2, 3};  // NOLINT [whitespace/labels] [4]
-  std::vector<int>::iterator it = list.begin();
-
-  EXPECT_EQ(0, multiply_small_values_by_two(2, outof_iterator(it)));
-  EXPECT_EQ(4, list[0]);
-}
-
-TEST_F(OutTest, CallFromPointer) {
-  // For calling a function with a parameter originating as a C-pointer.
-  std::vector<int> list = {1, 2, 3};  // NOLINT [whitespace/labels] [4]
-
-  int* list_ptr = &list[2];  // 3
-
-  EXPECT_EQ(0, multiply_small_values_by_two(2, outof_ptr(list_ptr)));
-  EXPECT_EQ(4, list[2]);
-}
-
-TEST_F(OutTest, OutAsIterator) {
-  // For using the out<T> parameter as an iterator inside of the callee.
-  std::vector<int> list;
-  int x = 100;
-  out<int> out_from_x = outof(x);
-
-  for (const int& val : out_from_x) {
-    list.push_back(val);
-  }
-
-  ASSERT_EQ(1u, list.size());
-  EXPECT_EQ(100, list[0]);
-
-  // A more typical use-case would be to use std algorithms
-  EXPECT_NE(out_from_x.end(),
-            std::find(out_from_x.begin(),
-                      out_from_x.end(),
-                      100));  // Search for '100' in out.
-}
-
-}  // namespace art
diff --git a/runtime/class_linker-inl.h b/runtime/class_linker-inl.h
index c08417f..11901b3 100644
--- a/runtime/class_linker-inl.h
+++ b/runtime/class_linker-inl.h
@@ -117,10 +117,8 @@
   return resolved_method;
 }
 
-inline ArtMethod* ClassLinker::ResolveMethod(Thread* self,
-                                             uint32_t method_idx,
-                                             ArtMethod* referrer,
-                                             InvokeType type) {
+inline ArtMethod* ClassLinker::ResolveMethod(Thread* self, uint32_t method_idx,
+                                             ArtMethod* referrer, InvokeType type) {
   ArtMethod* resolved_method = GetResolvedMethod(method_idx, referrer);
   if (UNLIKELY(resolved_method == nullptr)) {
     mirror::Class* declaring_class = referrer->GetDeclaringClass();
@@ -145,8 +143,7 @@
   return GetResolvedField(field_idx, field_declaring_class->GetDexCache());
 }
 
-inline ArtField* ClassLinker::ResolveField(uint32_t field_idx,
-                                           ArtMethod* referrer,
+inline ArtField* ClassLinker::ResolveField(uint32_t field_idx, ArtMethod* referrer,
                                            bool is_static) {
   mirror::Class* declaring_class = referrer->GetDeclaringClass();
   ArtField* resolved_field = GetResolvedField(field_idx, declaring_class);
diff --git a/runtime/class_linker.cc b/runtime/class_linker.cc
index 82cf7af..a306c30 100644
--- a/runtime/class_linker.cc
+++ b/runtime/class_linker.cc
@@ -30,7 +30,6 @@
 #include "base/arena_allocator.h"
 #include "base/casts.h"
 #include "base/logging.h"
-#include "base/out.h"
 #include "base/scoped_arena_containers.h"
 #include "base/scoped_flock.h"
 #include "base/stl_util.h"
@@ -199,7 +198,7 @@
     return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
   }
 };
-using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
+typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
 
 // Adds largest aligned gaps to queue of gaps.
 static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
@@ -776,13 +775,12 @@
                           // be from multidex, which resolves correctly).
 };
 
-static void AddDexFilesFromOat(const OatFile* oat_file,
-                               bool already_loaded,
+static void AddDexFilesFromOat(const OatFile* oat_file, bool already_loaded,
                                std::priority_queue<DexFileAndClassPair>* heap) {
   const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
   for (const OatDexFile* oat_dex_file : oat_dex_files) {
     std::string error;
-    std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(outof(error));
+    std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
     if (dex_file.get() == nullptr) {
       LOG(WARNING) << "Could not create dex file from oat file: " << error;
     } else {
@@ -838,7 +836,7 @@
 // against the following top element. If the descriptor is the same, it is now checked whether
 // the two elements agree on whether their dex file was from an already-loaded oat-file or the
 // new oat file. Any disagreement indicates a collision.
-bool ClassLinker::HasCollisions(const OatFile* oat_file, out<std::string> error_msg) {
+bool ClassLinker::HasCollisions(const OatFile* oat_file, std::string* error_msg) {
   if (!kDuplicateClassesCheck) {
     return false;
   }
@@ -903,9 +901,10 @@
 }
 
 std::vector<std::unique_ptr<const DexFile>> ClassLinker::OpenDexFilesFromOat(
-    const char* dex_location,
-    const char* oat_location,
-    out<std::vector<std::string>> error_msgs) {
+    const char* dex_location, const char* oat_location,
+    std::vector<std::string>* error_msgs) {
+  CHECK(error_msgs != nullptr);
+
   // Verify we aren't holding the mutator lock, which could starve GC if we
   // have to generate or relocate an oat file.
   Locks::mutator_lock_->AssertNotHeld(Thread::Current());
@@ -947,7 +946,7 @@
     std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
     if (oat_file.get() != nullptr) {
       // Take the file only if it has no collisions, or we must take it because of preopting.
-      bool accept_oat_file = !HasCollisions(oat_file.get(), outof(error_msg));
+      bool accept_oat_file = !HasCollisions(oat_file.get(), &error_msg);
       if (!accept_oat_file) {
         // Failed the collision check. Print warning.
         if (Runtime::Current()->IsDexFileFallbackEnabled()) {
@@ -981,7 +980,8 @@
   if (source_oat_file != nullptr) {
     dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
     if (dex_files.empty()) {
-      error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
+      error_msgs->push_back("Failed to open dex files from "
+          + source_oat_file->GetLocation());
     }
   }
 
@@ -1017,8 +1017,7 @@
   return nullptr;
 }
 
-static void SanityCheckArtMethod(ArtMethod* m,
-                                 mirror::Class* expected_class,
+static void SanityCheckArtMethod(ArtMethod* m, mirror::Class* expected_class,
                                  gc::space::ImageSpace* space)
     SHARED_REQUIRES(Locks::mutator_lock_) {
   if (m->IsRuntimeMethod()) {
@@ -1036,11 +1035,9 @@
   }
 }
 
-static void SanityCheckArtMethodPointerArray(mirror::PointerArray* arr,
-                                             mirror::Class* expected_class,
-                                             size_t pointer_size,
-                                             gc::space::ImageSpace* space)
-    SHARED_REQUIRES(Locks::mutator_lock_) {
+static void SanityCheckArtMethodPointerArray(
+    mirror::PointerArray* arr, mirror::Class* expected_class, size_t pointer_size,
+    gc::space::ImageSpace* space) SHARED_REQUIRES(Locks::mutator_lock_) {
   CHECK(arr != nullptr);
   for (int32_t j = 0; j < arr->GetLength(); ++j) {
     auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size);
@@ -1061,12 +1058,11 @@
   CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
   if (obj->IsClass()) {
     auto klass = obj->AsClass();
-    ArtField* fields[2] = { klass->GetSFields(), klass->GetIFields() };
-    size_t num_fields[2] = { klass->NumStaticFields(), klass->NumInstanceFields() };
-    for (size_t i = 0; i < 2; ++i) {
-      for (size_t j = 0; j < num_fields[i]; ++j) {
-        CHECK_EQ(fields[i][j].GetDeclaringClass(), klass);
-      }
+    for (ArtField& field : klass->GetIFields()) {
+      CHECK_EQ(field.GetDeclaringClass(), klass);
+    }
+    for (ArtField& field : klass->GetSFields()) {
+      CHECK_EQ(field.GetDeclaringClass(), klass);
     }
     auto* runtime = Runtime::Current();
     auto* image_space = runtime->GetHeap()->GetImageSpace();
@@ -1101,6 +1097,28 @@
   }
 }
 
+// Set image methods' entry point to interpreter.
+class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
+ public:
+  explicit SetInterpreterEntrypointArtMethodVisitor(size_t image_pointer_size)
+    : image_pointer_size_(image_pointer_size) {}
+
+  void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
+    if (kIsDebugBuild && !method->IsRuntimeMethod()) {
+      CHECK(method->GetDeclaringClass() != nullptr);
+    }
+    if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
+      method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
+                                                        image_pointer_size_);
+    }
+  }
+
+ private:
+  const size_t image_pointer_size_;
+
+  DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
+};
+
 void ClassLinker::InitFromImage() {
   VLOG(startup) << "ClassLinker::InitFromImage entering";
   CHECK(!init_done_);
@@ -1146,7 +1164,7 @@
                                                                      nullptr);
     CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
     std::string error_msg;
-    std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(outof(error_msg));
+    std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
     if (dex_file.get() == nullptr) {
       LOG(FATAL) << "Failed to open dex file " << dex_file_location
                  << " from within oat file " << oat_file.GetLocation()
@@ -1191,19 +1209,11 @@
 
   // Set entry point to interpreter if in InterpretOnly mode.
   if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
-    const auto& header = space->GetImageHeader();
-    const auto& methods = header.GetMethodsSection();
-    const auto art_method_size = ArtMethod::ObjectSize(image_pointer_size_);
-    for (uintptr_t pos = 0; pos < methods.Size(); pos += art_method_size) {
-      auto* method = reinterpret_cast<ArtMethod*>(space->Begin() + pos + methods.Offset());
-      if (kIsDebugBuild && !method->IsRuntimeMethod()) {
-        CHECK(method->GetDeclaringClass() != nullptr);
-      }
-      if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
-        method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
-                                                          image_pointer_size_);
-      }
-    }
+    const ImageHeader& header = space->GetImageHeader();
+    const ImageSection& methods = header.GetMethodsSection();
+    const size_t art_method_size = ArtMethod::ObjectSize(image_pointer_size_);
+    SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
+    methods.VisitPackedArtMethods(&visitor, space->Begin(), art_method_size);
   }
 
   // reinit class_roots_
@@ -1506,8 +1516,7 @@
   return dex_cache.Get();
 }
 
-mirror::Class* ClassLinker::AllocClass(Thread* self,
-                                       mirror::Class* java_lang_Class,
+mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
                                        uint32_t class_size) {
   DCHECK_GE(class_size, sizeof(mirror::Class));
   gc::Heap* heap = Runtime::Current()->GetHeap();
@@ -1526,14 +1535,13 @@
   return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
 }
 
-mirror::ObjectArray<mirror::StackTraceElement>*
-ClassLinker::AllocStackTraceElementArray(Thread* self, size_t length) {
+mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
+    Thread* self, size_t length) {
   return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
       self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
 }
 
-mirror::Class* ClassLinker::EnsureResolved(Thread* self,
-                                           const char* descriptor,
+mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
                                            mirror::Class* klass) {
   DCHECK(klass != nullptr);
 
@@ -1592,8 +1600,7 @@
 
 // Search a collection of DexFiles for a descriptor
 ClassPathEntry FindInClassPath(const char* descriptor,
-                               size_t hash,
-                               const std::vector<const DexFile*>& class_path) {
+                               size_t hash, const std::vector<const DexFile*>& class_path) {
   for (const DexFile* dex_file : class_path) {
     const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
     if (dex_class_def != nullptr) {
@@ -1612,17 +1619,16 @@
 }
 
 bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
-                                             Thread* self,
-                                             const char* descriptor,
+                                             Thread* self, const char* descriptor,
                                              size_t hash,
                                              Handle<mirror::ClassLoader> class_loader,
-                                             out<mirror::Class*> result) {
+                                             mirror::Class** result) {
   // Termination case: boot class-loader.
   if (IsBootClassLoader(soa, class_loader.Get())) {
     // The boot class loader, search the boot class path.
     ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
     if (pair.second != nullptr) {
-      mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr /* no classloader */);
+      mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
       if (klass != nullptr) {
         *result = EnsureResolved(self, descriptor, klass);
       } else {
@@ -1724,8 +1730,7 @@
   return true;
 }
 
-mirror::Class* ClassLinker::FindClass(Thread* self,
-                                      const char* descriptor,
+mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
                                       Handle<mirror::ClassLoader> class_loader) {
   DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
   DCHECK(self != nullptr);
@@ -1761,7 +1766,7 @@
   } else {
     ScopedObjectAccessUnchecked soa(self);
     mirror::Class* cp_klass;
-    if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, outof(cp_klass))) {
+    if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) {
       // The chain was understood. So the value in cp_klass is either the class we were looking
       // for, or not found.
       if (cp_klass != nullptr) {
@@ -1814,9 +1819,7 @@
   UNREACHABLE();
 }
 
-mirror::Class* ClassLinker::DefineClass(Thread* self,
-                                        const char* descriptor,
-                                        size_t hash,
+mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
                                         Handle<mirror::ClassLoader> class_loader,
                                         const DexFile& dex_file,
                                         const DexFile::ClassDef& dex_class_def) {
@@ -1902,7 +1905,7 @@
   auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
 
   MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
-  if (!LinkClass(self, descriptor, klass, interfaces, outof(h_new_class))) {
+  if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
     // Linking failed.
     if (!klass->IsErroneous()) {
       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
@@ -1985,9 +1988,8 @@
                                          image_pointer_size_);
 }
 
-OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file,
-                                            uint16_t class_def_idx,
-                                            out<bool> found) {
+OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
+                                            bool* found) {
   DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
   const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
   if (oat_dex_file == nullptr) {
@@ -1998,8 +2000,7 @@
   return oat_dex_file->GetOatClass(class_def_idx);
 }
 
-static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file,
-                                                 uint16_t class_def_idx,
+static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
                                                  uint32_t method_idx) {
   const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
   const uint8_t* class_data = dex_file.GetClassData(class_def);
@@ -2033,7 +2034,7 @@
   UNREACHABLE();
 }
 
-const OatFile::OatMethod ClassLinker::FindOatMethodFor(ArtMethod* method, out<bool> found) {
+const OatFile::OatMethod ClassLinker::FindOatMethodFor(ArtMethod* method, bool* found) {
   // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
   // method for direct methods (or virtual methods made direct).
   mirror::Class* declaring_class = method->GetDeclaringClass();
@@ -2065,7 +2066,7 @@
                                              method->GetDexMethodIndex()));
   OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
                                              declaring_class->GetDexClassDefIndex(),
-                                             outof_forward(found));
+                                             found);
   if (!(*found)) {
     return OatFile::OatMethod::Invalid();
   }
@@ -2079,7 +2080,7 @@
     return GetQuickProxyInvokeHandler();
   }
   bool found;
-  OatFile::OatMethod oat_method = FindOatMethodFor(method, outof(found));
+  OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
   if (found) {
     auto* code = oat_method.GetQuickCode();
     if (code != nullptr) {
@@ -2105,7 +2106,7 @@
     return nullptr;
   }
   bool found;
-  OatFile::OatMethod oat_method = FindOatMethodFor(method, outof(found));
+  OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
   if (found) {
     return oat_method.GetQuickCode();
   }
@@ -2119,11 +2120,10 @@
   return nullptr;
 }
 
-const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file,
-                                            uint16_t class_def_idx,
+const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
                                             uint32_t method_idx) {
   bool found;
-  OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, outof(found));
+  OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
   if (!found) {
     return nullptr;
   }
@@ -2174,7 +2174,7 @@
   }
   bool has_oat_class;
   OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
-                                             outof(has_oat_class));
+                                             &has_oat_class);
   // Link the code of methods skipped by LinkCode.
   for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
     ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
@@ -2202,8 +2202,7 @@
   // Ignore virtual methods on the iterator.
 }
 
-void ClassLinker::LinkCode(ArtMethod* method,
-                           const OatFile::OatClass* oat_class,
+void ClassLinker::LinkCode(ArtMethod* method, const OatFile::OatClass* oat_class,
                            uint32_t class_def_method_index) {
   Runtime* const runtime = Runtime::Current();
   if (runtime->IsAotCompiler()) {
@@ -2255,10 +2254,8 @@
   }
 }
 
-void ClassLinker::SetupClass(const DexFile& dex_file,
-                             const DexFile::ClassDef& dex_class_def,
-                             Handle<mirror::Class> klass,
-                             mirror::ClassLoader* class_loader) {
+void ClassLinker::SetupClass(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
+                             Handle<mirror::Class> klass, mirror::ClassLoader* class_loader) {
   CHECK(klass.Get() != nullptr);
   CHECK(klass->GetDexCache() != nullptr);
   CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
@@ -2278,8 +2275,7 @@
   CHECK(klass->GetDexCacheStrings() != nullptr);
 }
 
-void ClassLinker::LoadClass(Thread* self,
-                            const DexFile& dex_file,
+void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
                             const DexFile::ClassDef& dex_class_def,
                             Handle<mirror::Class> klass) {
   const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
@@ -2289,7 +2285,7 @@
   bool has_oat_class = false;
   if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
     OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
-                                               outof(has_oat_class));
+                                               &has_oat_class);
     if (has_oat_class) {
       LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
     }
@@ -2299,27 +2295,34 @@
   }
 }
 
-ArtField* ClassLinker::AllocArtFieldArray(Thread* self, size_t length) {
-  auto* const la = Runtime::Current()->GetLinearAlloc();
-  auto* ptr = reinterpret_cast<ArtField*>(la->AllocArray<ArtField>(self, length));
-  CHECK(ptr!= nullptr);
-  std::uninitialized_fill_n(ptr, length, ArtField());
-  return ptr;
-}
-
-ArtMethod* ClassLinker::AllocArtMethodArray(Thread* self, size_t length) {
-  const size_t method_size = ArtMethod::ObjectSize(image_pointer_size_);
-  uintptr_t ptr = reinterpret_cast<uintptr_t>(
-      Runtime::Current()->GetLinearAlloc()->Alloc(self, method_size * length));
-  CHECK_NE(ptr, 0u);
-  for (size_t i = 0; i < length; ++i) {
-    new(reinterpret_cast<void*>(ptr + i * method_size)) ArtMethod;
+LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self, size_t length) {
+  if (length == 0) {
+    return nullptr;
   }
-  return reinterpret_cast<ArtMethod*>(ptr);
+  auto* ret = new(Runtime::Current()->GetLinearAlloc()->Alloc(
+      self, LengthPrefixedArray<ArtField>::ComputeSize(length))) LengthPrefixedArray<ArtField>(
+          length);
+  CHECK(ret != nullptr);
+  std::uninitialized_fill_n(&ret->At(0), length, ArtField());
+  return ret;
 }
 
-void ClassLinker::LoadClassMembers(Thread* self,
-                                   const DexFile& dex_file,
+LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self, size_t length) {
+  if (length == 0) {
+    return nullptr;
+  }
+  const size_t method_size = ArtMethod::ObjectSize(image_pointer_size_);
+  auto* ret = new (Runtime::Current()->GetLinearAlloc()->Alloc(
+      self, LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size)))
+          LengthPrefixedArray<ArtMethod>(length);
+  CHECK(ret != nullptr);
+  for (size_t i = 0; i < length; ++i) {
+    new(reinterpret_cast<void*>(&ret->At(i, method_size))) ArtMethod;
+  }
+  return ret;
+}
+
+void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
                                    const uint8_t* class_data,
                                    Handle<mirror::Class> klass,
                                    const OatFile::OatClass* oat_class) {
@@ -2331,8 +2334,7 @@
     // We allow duplicate definitions of the same field in a class_data_item
     // but ignore the repeated indexes here, b/21868015.
     ClassDataItemIterator it(dex_file, class_data);
-    ArtField* sfields =
-        it.NumStaticFields() != 0 ? AllocArtFieldArray(self, it.NumStaticFields()) : nullptr;
+    LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, it.NumStaticFields());
     size_t num_sfields = 0;
     uint32_t last_field_idx = 0u;
     for (; it.HasNextStaticField(); it.Next()) {
@@ -2340,17 +2342,15 @@
       DCHECK_GE(field_idx, last_field_idx);  // Ordering enforced by DexFileVerifier.
       if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
         DCHECK_LT(num_sfields, it.NumStaticFields());
-        LoadField(it, klass, &sfields[num_sfields]);
+        LoadField(it, klass, &sfields->At(num_sfields));
         ++num_sfields;
         last_field_idx = field_idx;
       }
     }
-    klass->SetSFields(sfields);
-    klass->SetNumStaticFields(num_sfields);
+    klass->SetSFieldsPtr(sfields);
     DCHECK_EQ(klass->NumStaticFields(), num_sfields);
     // Load instance fields.
-    ArtField* ifields =
-        it.NumInstanceFields() != 0 ? AllocArtFieldArray(self, it.NumInstanceFields()) : nullptr;
+    LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self, it.NumInstanceFields());
     size_t num_ifields = 0u;
     last_field_idx = 0u;
     for (; it.HasNextInstanceField(); it.Next()) {
@@ -2358,7 +2358,7 @@
       DCHECK_GE(field_idx, last_field_idx);  // Ordering enforced by DexFileVerifier.
       if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
         DCHECK_LT(num_ifields, it.NumInstanceFields());
-        LoadField(it, klass, &ifields[num_ifields]);
+        LoadField(it, klass, &ifields->At(num_ifields));
         ++num_ifields;
         last_field_idx = field_idx;
       }
@@ -2370,18 +2370,11 @@
           << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
       // NOTE: Not shrinking the over-allocated sfields/ifields.
     }
-    klass->SetIFields(ifields);
-    klass->SetNumInstanceFields(num_ifields);
+    klass->SetIFieldsPtr(ifields);
     DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
     // Load methods.
-    if (it.NumDirectMethods() != 0) {
-      klass->SetDirectMethodsPtr(AllocArtMethodArray(self, it.NumDirectMethods()));
-    }
-    klass->SetNumDirectMethods(it.NumDirectMethods());
-    if (it.NumVirtualMethods() != 0) {
-      klass->SetVirtualMethodsPtr(AllocArtMethodArray(self, it.NumVirtualMethods()));
-    }
-    klass->SetNumVirtualMethods(it.NumVirtualMethods());
+    klass->SetDirectMethodsPtr(AllocArtMethodArray(self, it.NumDirectMethods()));
+    klass->SetVirtualMethodsPtr(AllocArtMethodArray(self, it.NumVirtualMethods()));
     size_t class_def_method_index = 0;
     uint32_t last_dex_method_index = DexFile::kDexNoIndex;
     size_t last_class_def_method_index = 0;
@@ -2414,8 +2407,7 @@
   self->AllowThreadSuspension();
 }
 
-void ClassLinker::LoadField(const ClassDataItemIterator& it,
-                            Handle<mirror::Class> klass,
+void ClassLinker::LoadField(const ClassDataItemIterator& it, Handle<mirror::Class> klass,
                             ArtField* dst) {
   const uint32_t field_idx = it.GetMemberIndex();
   dst->SetDexFieldIndex(field_idx);
@@ -2423,11 +2415,8 @@
   dst->SetAccessFlags(it.GetFieldAccessFlags());
 }
 
-void ClassLinker::LoadMethod(Thread* self,
-                             const DexFile& dex_file,
-                             const ClassDataItemIterator& it,
-                             Handle<mirror::Class> klass,
-                             ArtMethod* dst) {
+void ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file, const ClassDataItemIterator& it,
+                             Handle<mirror::Class> klass, ArtMethod* dst) {
   uint32_t dex_method_idx = it.GetMemberIndex();
   const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
   const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
@@ -2627,9 +2616,7 @@
 // array class; that always comes from the base element class.
 //
 // Returns null with an exception raised on failure.
-mirror::Class* ClassLinker::CreateArrayClass(Thread* self,
-                                             const char* descriptor,
-                                             size_t hash,
+mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
                                              Handle<mirror::ClassLoader> class_loader) {
   // Identify the underlying component type
   CHECK_EQ('[', descriptor[0]);
@@ -2832,12 +2819,9 @@
 }
 
 void ClassLinker::UpdateClassVirtualMethods(mirror::Class* klass,
-                                            ArtMethod* new_methods,
-                                            size_t new_num_methods) {
-  // TODO: Fix the race condition here. b/22832610
-  klass->SetNumVirtualMethods(new_num_methods);
+                                            LengthPrefixedArray<ArtMethod>* new_methods) {
   klass->SetVirtualMethodsPtr(new_methods);
-  // Need to mark the card so that the remembered sets and mod union tables get update.
+  // Need to mark the card so that the remembered sets and mod union tables get updated.
   Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
 }
 
@@ -2847,9 +2831,7 @@
   return class_table != nullptr && class_table->Remove(descriptor);
 }
 
-mirror::Class* ClassLinker::LookupClass(Thread* self,
-                                        const char* descriptor,
-                                        size_t hash,
+mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
                                         mirror::ClassLoader* class_loader) {
   {
     ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
@@ -2953,9 +2935,7 @@
   return nullptr;
 }
 
-void ClassLinker::LookupClasses(const char* descriptor,
-                                out<std::vector<mirror::Class*>> out_result) {
-  std::vector<mirror::Class*>& result = *out_result;
+void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
   result.clear();
   if (dex_cache_image_class_lookup_required_) {
     MoveImageClassesToClassTable();
@@ -3132,8 +3112,7 @@
   }
 }
 
-bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
-                                          mirror::Class* klass,
+bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
                                           mirror::Class::Status& oat_file_class_status) {
   // If we're compiling, we can only verify the class using the oat file if
   // we are not compiling the image or if the class we're verifying is not part of
@@ -3255,12 +3234,9 @@
   }
 }
 
-mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
-                                             jstring name,
-                                             jobjectArray interfaces,
-                                             jobject loader,
-                                             jobjectArray methods,
-                                             jobjectArray throws) {
+mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
+                                             jobjectArray interfaces, jobject loader,
+                                             jobjectArray methods, jobjectArray throws) {
   Thread* self = soa.Self();
   StackHandleScope<10> hs(self);
   MutableHandle<mirror::Class> klass(hs.NewHandle(
@@ -3290,25 +3266,24 @@
 
   // Instance fields are inherited, but we add a couple of static fields...
   const size_t num_fields = 2;
-  ArtField* sfields = AllocArtFieldArray(self, num_fields);
-  klass->SetSFields(sfields);
-  klass->SetNumStaticFields(num_fields);
+  LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, num_fields);
+  klass->SetSFieldsPtr(sfields);
 
   // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
   // our proxy, so Class.getInterfaces doesn't return the flattened set.
-  ArtField* interfaces_sfield = &sfields[0];
-  interfaces_sfield->SetDexFieldIndex(0);
-  interfaces_sfield->SetDeclaringClass(klass.Get());
-  interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
+  ArtField& interfaces_sfield = sfields->At(0);
+  interfaces_sfield.SetDexFieldIndex(0);
+  interfaces_sfield.SetDeclaringClass(klass.Get());
+  interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
 
   // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
-  ArtField* throws_sfield = &sfields[1];
-  throws_sfield->SetDexFieldIndex(1);
-  throws_sfield->SetDeclaringClass(klass.Get());
-  throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
+  ArtField& throws_sfield = sfields->At(1);
+  throws_sfield.SetDexFieldIndex(1);
+  throws_sfield.SetDeclaringClass(klass.Get());
+  throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
 
   // Proxies have 1 direct method, the constructor
-  auto* directs = AllocArtMethodArray(self, 1);
+  LengthPrefixedArray<ArtMethod>* directs = AllocArtMethodArray(self, 1);
   // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
   // want to throw OOM in the future.
   if (UNLIKELY(directs == nullptr)) {
@@ -3316,13 +3291,12 @@
     return nullptr;
   }
   klass->SetDirectMethodsPtr(directs);
-  klass->SetNumDirectMethods(1u);
   CreateProxyConstructor(klass, klass->GetDirectMethodUnchecked(0, image_pointer_size_));
 
   // Create virtual method using specified prototypes.
   auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>*>(methods));
   DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
-    << PrettyClass(h_methods->GetClass());
+      << PrettyClass(h_methods->GetClass());
   const size_t num_virtual_methods = h_methods->GetLength();
   auto* virtuals = AllocArtMethodArray(self, num_virtual_methods);
   // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
@@ -3332,7 +3306,6 @@
     return nullptr;
   }
   klass->SetVirtualMethodsPtr(virtuals);
-  klass->SetNumVirtualMethods(num_virtual_methods);
   for (size_t i = 0; i < num_virtual_methods; ++i) {
     auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
     auto* prototype = h_methods->Get(i)->GetArtMethod();
@@ -3355,7 +3328,7 @@
     // The new class will replace the old one in the class table.
     Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
         hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
-    if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, outof(new_class))) {
+    if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
       return nullptr;
     }
@@ -3364,12 +3337,12 @@
   CHECK_NE(klass.Get(), new_class.Get());
   klass.Assign(new_class.Get());
 
-  CHECK_EQ(interfaces_sfield->GetDeclaringClass(), klass.Get());
-  interfaces_sfield->SetObject<false>(klass.Get(),
-                                      soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
-  CHECK_EQ(throws_sfield->GetDeclaringClass(), klass.Get());
-  throws_sfield->SetObject<false>(klass.Get(),
-      soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
+  CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
+  interfaces_sfield.SetObject<false>(klass.Get(),
+                                     soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
+  CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
+  throws_sfield.SetObject<false>(
+      klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
 
   {
     // Lock on klass is released. Lock new class object.
@@ -3379,7 +3352,7 @@
 
   // sanity checks
   if (kIsDebugBuild) {
-    CHECK(klass->GetIFields() == nullptr);
+    CHECK(klass->GetIFieldsPtr() == nullptr);
     CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
 
     for (size_t i = 0; i < num_virtual_methods; ++i) {
@@ -3460,8 +3433,7 @@
   DCHECK(constructor->IsPublic());
 }
 
-void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass,
-                                    ArtMethod* prototype,
+void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
                                     ArtMethod* out) {
   // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
   // prototype method
@@ -3507,8 +3479,7 @@
   CHECK_EQ(np->GetReturnType(), prototype->GetReturnType());
 }
 
-bool ClassLinker::CanWeInitializeClass(mirror::Class* klass,
-                                       bool can_init_statics,
+bool ClassLinker::CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
                                        bool can_init_parents) {
   if (can_init_statics && can_init_parents) {
     return true;
@@ -3538,10 +3509,8 @@
   return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
 }
 
-bool ClassLinker::InitializeClass(Thread* self,
-                                  Handle<mirror::Class> klass,
-                                  bool can_init_statics,
-                                  bool can_init_parents) {
+bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
+                                  bool can_init_statics, bool can_init_parents) {
   // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
 
   // Are we already initialized and therefore done?
@@ -3610,7 +3579,7 @@
         return true;
       }
       // No. That's fine. Wait for another thread to finish initializing.
-      return WaitForInitializeClass(klass, self, &lock);
+      return WaitForInitializeClass(klass, self, lock);
     }
 
     if (!ValidateSuperClassDescriptors(klass)) {
@@ -3744,16 +3713,13 @@
   return success;
 }
 
-bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
-                                         Thread* self,
-                                         ObjectLock<mirror::Class>* lock)
+bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
+                                         ObjectLock<mirror::Class>& lock)
     SHARED_REQUIRES(Locks::mutator_lock_) {
-  DCHECK(lock != nullptr);
-
   while (true) {
     self->AssertNoPendingException();
     CHECK(!klass->IsInitialized());
-    lock->WaitIgnoringInterrupts();
+    lock.WaitIgnoringInterrupts();
 
     // When we wake up, repeat the test for init-in-progress.  If
     // there's an exception pending (only possible if
@@ -3816,8 +3782,7 @@
                                                    Handle<mirror::Class> super_klass,
                                                    ArtMethod* method,
                                                    ArtMethod* m,
-                                                   uint32_t index,
-                                                   uint32_t arg_type_idx)
+                                                   uint32_t index, uint32_t arg_type_idx)
     SHARED_REQUIRES(Locks::mutator_lock_) {
   DCHECK(Thread::Current()->IsExceptionPending());
   DCHECK(!m->IsProxyMethod());
@@ -3979,8 +3944,7 @@
   return true;
 }
 
-bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c,
-                                    bool can_init_fields,
+bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
                                     bool can_init_parents) {
   DCHECK(c.Get() != nullptr);
   if (c->IsInitialized()) {
@@ -4000,19 +3964,17 @@
 
 void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class,
                                                mirror::Class* new_class) {
-  ArtField* fields = new_class->GetIFields();
   DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
-  for (size_t i = 0, count = new_class->NumInstanceFields(); i < count; i++) {
-    if (fields[i].GetDeclaringClass() == temp_class) {
-      fields[i].SetDeclaringClass(new_class);
+  for (ArtField& field : new_class->GetIFields()) {
+    if (field.GetDeclaringClass() == temp_class) {
+      field.SetDeclaringClass(new_class);
     }
   }
 
-  fields = new_class->GetSFields();
   DCHECK_EQ(temp_class->NumStaticFields(), 0u);
-  for (size_t i = 0, count = new_class->NumStaticFields(); i < count; i++) {
-    if (fields[i].GetDeclaringClass() == temp_class) {
-      fields[i].SetDeclaringClass(new_class);
+  for (ArtField& field : new_class->GetSFields()) {
+    if (field.GetDeclaringClass() == temp_class) {
+      field.SetDeclaringClass(new_class);
     }
   }
 
@@ -4054,11 +4016,9 @@
   return nullptr;
 }
 
-bool ClassLinker::LinkClass(Thread* self,
-                            const char* descriptor,
-                            Handle<mirror::Class> klass,
+bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
                             Handle<mirror::ObjectArray<mirror::Class>> interfaces,
-                            out<MutableHandle<mirror::Class>> h_new_class_out) {
+                            MutableHandle<mirror::Class>* h_new_class_out) {
   CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
 
   if (!LinkSuperClass(klass)) {
@@ -4066,14 +4026,14 @@
   }
   ArtMethod* imt[mirror::Class::kImtSize];
   std::fill_n(imt, arraysize(imt), Runtime::Current()->GetImtUnimplementedMethod());
-  if (!LinkMethods(self, klass, interfaces, outof(imt))) {
+  if (!LinkMethods(self, klass, interfaces, imt)) {
     return false;
   }
   if (!LinkInstanceFields(self, klass)) {
     return false;
   }
   size_t class_size;
-  if (!LinkStaticFields(self, klass, outof(class_size))) {
+  if (!LinkStaticFields(self, klass, &class_size)) {
     return false;
   }
   CreateReferenceInstanceOffsets(klass);
@@ -4101,10 +4061,10 @@
     // same ArtFields with the same If this occurs, it causes bugs in remembered sets since the GC
     // may not see any references to the from space and clean the card. Though there was references
     // to the from space that got marked by the first class.
-    klass->SetNumDirectMethods(0);
-    klass->SetNumVirtualMethods(0);
-    klass->SetNumStaticFields(0);
-    klass->SetNumInstanceFields(0);
+    klass->SetDirectMethodsPtrUnchecked(nullptr);
+    klass->SetVirtualMethodsPtr(nullptr);
+    klass->SetSFieldsPtrUnchecked(nullptr);
+    klass->SetIFieldsPtrUnchecked(nullptr);
     if (UNLIKELY(h_new_class.Get() == nullptr)) {
       self->AssertPendingOOMException();
       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
@@ -4149,31 +4109,30 @@
   return true;
 }
 
-static void CountMethodsAndFields(ClassDataItemIterator* dex_data,
-                                  out<size_t> virtual_methods,
-                                  out<size_t> direct_methods,
-                                  out<size_t> static_fields,
-                                  out<size_t> instance_fields) {
-  DCHECK(dex_data != nullptr);
+static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
+                                  size_t* virtual_methods,
+                                  size_t* direct_methods,
+                                  size_t* static_fields,
+                                  size_t* instance_fields) {
   *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
 
-  while (dex_data->HasNextStaticField()) {
-    dex_data->Next();
+  while (dex_data.HasNextStaticField()) {
+    dex_data.Next();
     (*static_fields)++;
   }
-  while (dex_data->HasNextInstanceField()) {
-    dex_data->Next();
+  while (dex_data.HasNextInstanceField()) {
+    dex_data.Next();
     (*instance_fields)++;
   }
-  while (dex_data->HasNextDirectMethod()) {
+  while (dex_data.HasNextDirectMethod()) {
     (*direct_methods)++;
-    dex_data->Next();
+    dex_data.Next();
   }
-  while (dex_data->HasNextVirtualMethod()) {
+  while (dex_data.HasNextVirtualMethod()) {
     (*virtual_methods)++;
-    dex_data->Next();
+    dex_data.Next();
   }
-  DCHECK(!dex_data->HasNext());
+  DCHECK(!dex_data.HasNext());
 }
 
 static void DumpClass(std::ostream& os,
@@ -4207,10 +4166,8 @@
   }
 }
 
-static std::string DumpClasses(const DexFile& dex_file1,
-                               const DexFile::ClassDef& dex_class_def1,
-                               const DexFile& dex_file2,
-                               const DexFile::ClassDef& dex_class_def2) {
+static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
+                               const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
   std::ostringstream os;
   DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
   DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
@@ -4220,28 +4177,20 @@
 
 // Very simple structural check on whether the classes match. Only compares the number of
 // methods and fields.
-static bool SimpleStructuralCheck(const DexFile& dex_file1,
-                                  const DexFile::ClassDef& dex_class_def1,
-                                  const DexFile& dex_file2,
-                                  const DexFile::ClassDef& dex_class_def2,
+static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
+                                  const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
                                   std::string* error_msg) {
   ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
   ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
 
   // Counters for current dex file.
   size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
-  CountMethodsAndFields(&dex_data1,
-                        outof(dex_virtual_methods1),
-                        outof(dex_direct_methods1),
-                        outof(dex_static_fields1),
-                        outof(dex_instance_fields1));
+  CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
+                        &dex_instance_fields1);
   // Counters for compile-time dex file.
   size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
-  CountMethodsAndFields(&dex_data2,
-                        outof(dex_virtual_methods2),
-                        outof(dex_direct_methods2),
-                        outof(dex_static_fields2),
-                        outof(dex_instance_fields2));
+  CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
+                        &dex_instance_fields2);
 
   if (dex_virtual_methods1 != dex_virtual_methods2) {
     std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
@@ -4444,10 +4393,9 @@
 }
 
 // Populate the class vtable and itable. Compute return type indices.
-bool ClassLinker::LinkMethods(Thread* self,
-                              Handle<mirror::Class> klass,
+bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
                               Handle<mirror::ObjectArray<mirror::Class>> interfaces,
-                              out<ArtMethod* [mirror::Class::kImtSize]> out_imt) {
+                              ArtMethod** out_imt) {
   self->AllowThreadSuspension();
   if (klass->IsInterface()) {
     // No vtable.
@@ -4462,10 +4410,7 @@
   } else if (!LinkVirtualMethods(self, klass)) {  // Link virtual methods first.
     return false;
   }
-  return LinkInterfaceMethods(self,
-                              klass,
-                              interfaces,
-                              outof_forward(out_imt));  // Link interface method last.
+  return LinkInterfaceMethods(self, klass, interfaces, out_imt);  // Link interface method last.
 }
 
 // Comparator for name and signature of a method, used in finding overriding methods. Implementation
@@ -4518,9 +4463,7 @@
 
 class LinkVirtualHashTable {
  public:
-  LinkVirtualHashTable(Handle<mirror::Class> klass,
-                       size_t hash_size,
-                       uint32_t* hash_table,
+  LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table,
                        size_t image_pointer_size)
      : klass_(klass), hash_size_(hash_size), hash_table_(hash_table),
        image_pointer_size_(image_pointer_size) {
@@ -4724,12 +4667,9 @@
   return true;
 }
 
-bool ClassLinker::LinkInterfaceMethods(Thread* self,
-                                       Handle<mirror::Class> klass,
+bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
                                        Handle<mirror::ObjectArray<mirror::Class>> interfaces,
-                                       out<ArtMethod* [mirror::Class::kImtSize]> out_imt_array) {
-  auto& out_imt = *out_imt_array;
-
+                                       ArtMethod** out_imt) {
   StackHandleScope<3> hs(self);
   Runtime* const runtime = Runtime::Current();
   const bool has_superclass = klass->HasSuperClass();
@@ -4917,7 +4857,7 @@
     }
   }
 
-  const char* old_cause = self->StartAssertNoThreadSuspension(
+  auto* old_cause = self->StartAssertNoThreadSuspension(
       "Copying ArtMethods for LinkInterfaceMethods");
   for (size_t i = 0; i < ifcount; ++i) {
     size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
@@ -4927,7 +4867,7 @@
       const bool super_interface = is_super && extend_super_iftable;
       auto method_array(hs2.NewHandle(iftable->GetMethodArray(i)));
 
-      ArtMethod* input_virtual_methods = nullptr;
+      LengthPrefixedArray<ArtMethod>* input_virtual_methods = nullptr;
       Handle<mirror::PointerArray> input_vtable_array = NullHandle<mirror::PointerArray>();
       int32_t input_array_length = 0;
       if (super_interface) {
@@ -4962,8 +4902,7 @@
         // matter which direction we go.  We walk it backward anyway.)
         for (k = input_array_length - 1; k >= 0; --k) {
           ArtMethod* vtable_method = input_virtual_methods != nullptr ?
-              reinterpret_cast<ArtMethod*>(
-                  reinterpret_cast<uintptr_t>(input_virtual_methods) + method_size * k) :
+              &input_virtual_methods->At(k, method_size) :
               input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
           ArtMethod* vtable_method_for_name_comparison =
               vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
@@ -5019,13 +4958,17 @@
     const size_t old_method_count = klass->NumVirtualMethods();
     const size_t new_method_count = old_method_count + miranda_methods.size();
     // Attempt to realloc to save RAM if possible.
-    ArtMethod* old_virtuals = klass->GetVirtualMethodsPtr();
+    LengthPrefixedArray<ArtMethod>* old_virtuals = klass->GetVirtualMethodsPtr();
     // The Realloced virtual methods aren't visiblef from the class roots, so there is no issue
     // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
     // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
     // CopyFrom has internal read barriers.
-    auto* virtuals = reinterpret_cast<ArtMethod*>(runtime->GetLinearAlloc()->Realloc(
-        self, old_virtuals, old_method_count * method_size, new_method_count * method_size));
+    const size_t old_size = old_virtuals != nullptr ?
+        LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count, method_size) : 0u;
+    const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
+                                                                        method_size);
+    auto* virtuals = new(runtime->GetLinearAlloc()->Realloc(
+        self, old_virtuals, old_size, new_size))LengthPrefixedArray<ArtMethod>(new_method_count);
     if (UNLIKELY(virtuals == nullptr)) {
       self->AssertPendingOOMException();
       self->EndAssertNoThreadSuspension(old_cause);
@@ -5034,7 +4977,7 @@
     ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table(allocator.Adapter());
     if (virtuals != old_virtuals) {
       // Maps from heap allocated miranda method to linear alloc miranda method.
-      StrideIterator<ArtMethod> out(reinterpret_cast<uintptr_t>(virtuals), method_size);
+      StrideIterator<ArtMethod> out = virtuals->Begin(method_size);
       // Copy over the old methods + miranda methods.
       for (auto& m : klass->GetVirtualMethods(image_pointer_size_)) {
         move_table.emplace(&m, &*out);
@@ -5044,8 +4987,7 @@
         ++out;
       }
     }
-    StrideIterator<ArtMethod> out(
-        reinterpret_cast<uintptr_t>(virtuals) + old_method_count * method_size, method_size);
+    StrideIterator<ArtMethod> out(virtuals->Begin(method_size) + old_method_count);
     // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
     // we want the roots of the miranda methods to get visited.
     for (ArtMethod* mir_method : miranda_methods) {
@@ -5054,7 +4996,7 @@
       move_table.emplace(mir_method, &*out);
       ++out;
     }
-    UpdateClassVirtualMethods(klass.Get(), virtuals, new_method_count);
+    UpdateClassVirtualMethods(klass.Get(), virtuals);
     // Done copying methods, they are all roots in the class now, so we can end the no thread
     // suspension assert.
     self->EndAssertNoThreadSuspension(old_cause);
@@ -5067,8 +5009,7 @@
       self->AssertPendingOOMException();
       return false;
     }
-    out = StrideIterator<ArtMethod>(
-        reinterpret_cast<uintptr_t>(virtuals) + old_method_count * method_size, method_size);
+    out = StrideIterator<ArtMethod>(virtuals->Begin(method_size) + old_method_count);
     size_t vtable_pos = old_vtable_count;
     for (size_t i = old_method_count; i < new_method_count; ++i) {
       // Leave the declaring class alone as type indices are relative to it
@@ -5122,7 +5063,7 @@
     }
     // Put some random garbage in old virtuals to help find stale pointers.
     if (virtuals != old_virtuals) {
-      memset(old_virtuals, 0xFEu, ArtMethod::ObjectSize(image_pointer_size_) * old_method_count);
+      memset(old_virtuals, 0xFEu, old_size);
     }
   } else {
     self->EndAssertNoThreadSuspension(old_cause);
@@ -5138,16 +5079,12 @@
 
 bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
   CHECK(klass.Get() != nullptr);
-  size_t class_size_dont_care;
-  UNUSED(class_size_dont_care);  // This doesn't get set for instance fields.
-  return LinkFields(self, klass, false, outof(class_size_dont_care));
+  return LinkFields(self, klass, false, nullptr);
 }
 
-bool ClassLinker::LinkStaticFields(Thread* self,
-                                   Handle<mirror::Class> klass,
-                                   out<size_t> class_size) {
+bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
   CHECK(klass.Get() != nullptr);
-  return LinkFields(self, klass, true, outof_forward(class_size));
+  return LinkFields(self, klass, true, class_size);
 }
 
 struct LinkFieldsComparator {
@@ -5184,13 +5121,12 @@
   }
 };
 
-bool ClassLinker::LinkFields(Thread* self,
-                             Handle<mirror::Class> klass,
-                             bool is_static,
-                             out<size_t> class_size) {
+bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
+                             size_t* class_size) {
   self->AllowThreadSuspension();
   const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
-  ArtField* const fields = is_static ? klass->GetSFields() : klass->GetIFields();
+  LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
+      klass->GetIFieldsPtr();
 
   // Initialize field_offset
   MemberOffset field_offset(0);
@@ -5213,7 +5149,7 @@
   const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
       "Naked ArtField references in deque");
   for (size_t i = 0; i < num_fields; i++) {
-    grouped_and_sorted_fields.push_back(&fields[i]);
+    grouped_and_sorted_fields.push_back(&fields->At(i));
   }
   std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
             LinkFieldsComparator());
@@ -5258,7 +5194,8 @@
     // We know there are no non-reference fields in the Reference classes, and we know
     // that 'referent' is alphabetically last, so this is easy...
     CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
-    CHECK_STREQ(fields[num_fields - 1].GetName(), "referent") << PrettyClass(klass.Get());
+    CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
+        << PrettyClass(klass.Get());
     --num_reference_fields;
   }
 
@@ -5292,15 +5229,15 @@
                                     sizeof(mirror::HeapReference<mirror::Object>));
     MemberOffset current_ref_offset = start_ref_offset;
     for (size_t i = 0; i < num_fields; i++) {
-      ArtField* field = &fields[i];
+      ArtField* field = &fields->At(i);
       VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
           << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
           << field->GetOffsetDuringLinking();
       if (i != 0) {
-        ArtField* const prev_field = &fields[i - 1];
+        ArtField* const prev_field = &fields->At(i - 1);
         // NOTE: The field names can be the same. This is not possible in the Java language
         // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
-        CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
+        DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
       }
       Primitive::Type type = field->GetTypeAsPrimitiveType();
       bool is_primitive = type != Primitive::kPrimNot;
@@ -5358,8 +5295,7 @@
   klass->SetReferenceInstanceOffsets(reference_offsets);
 }
 
-mirror::String* ClassLinker::ResolveString(const DexFile& dex_file,
-                                           uint32_t string_idx,
+mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
                                            Handle<mirror::DexCache> dex_cache) {
   DCHECK(dex_cache.Get() != nullptr);
   mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
@@ -5373,8 +5309,7 @@
   return string;
 }
 
-mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
-                                        uint16_t type_idx,
+mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
                                         mirror::Class* referrer) {
   StackHandleScope<2> hs(Thread::Current());
   Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
@@ -5382,8 +5317,7 @@
   return ResolveType(dex_file, type_idx, dex_cache, class_loader);
 }
 
-mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
-                                        uint16_t type_idx,
+mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
                                         Handle<mirror::DexCache> dex_cache,
                                         Handle<mirror::ClassLoader> class_loader) {
   DCHECK(dex_cache.Get() != nullptr);
@@ -5416,8 +5350,7 @@
   return resolved;
 }
 
-ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
-                                      uint32_t method_idx,
+ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
                                       Handle<mirror::DexCache> dex_cache,
                                       Handle<mirror::ClassLoader> class_loader,
                                       ArtMethod* referrer, InvokeType type) {
@@ -5574,11 +5507,9 @@
   }
 }
 
-ArtField* ClassLinker::ResolveField(const DexFile& dex_file,
-                                    uint32_t field_idx,
+ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
                                     Handle<mirror::DexCache> dex_cache,
-                                    Handle<mirror::ClassLoader> class_loader,
-                                    bool is_static) {
+                                    Handle<mirror::ClassLoader> class_loader, bool is_static) {
   DCHECK(dex_cache.Get() != nullptr);
   ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
   if (resolved != nullptr) {
@@ -5617,8 +5548,7 @@
   return resolved;
 }
 
-ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
-                                       uint32_t field_idx,
+ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, uint32_t field_idx,
                                        Handle<mirror::DexCache> dex_cache,
                                        Handle<mirror::ClassLoader> class_loader) {
   DCHECK(dex_cache.Get() != nullptr);
@@ -5648,8 +5578,7 @@
   return resolved;
 }
 
-const char* ClassLinker::MethodShorty(uint32_t method_idx,
-                                      ArtMethod* referrer,
+const char* ClassLinker::MethodShorty(uint32_t method_idx, ArtMethod* referrer,
                                       uint32_t* length) {
   mirror::Class* declaring_class = referrer->GetDeclaringClass();
   mirror::DexCache* dex_cache = declaring_class->GetDexCache();
@@ -5856,8 +5785,7 @@
   }
 }
 
-jobject ClassLinker::CreatePathClassLoader(Thread* self,
-                                           const std::vector<const DexFile*>& dex_files) {
+jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
   // SOAAlreadyRunnable is protected, and we need something to add a global reference.
   // We could move the jobject to the callers, but all call-sites do this...
   ScopedObjectAccessUnchecked soa(self);
@@ -5947,7 +5875,8 @@
 }
 
 ArtMethod* ClassLinker::CreateRuntimeMethod() {
-  ArtMethod* method = AllocArtMethodArray(Thread::Current(), 1);
+  const size_t method_size = ArtMethod::ObjectSize(image_pointer_size_);
+  ArtMethod* method = &AllocArtMethodArray(Thread::Current(), 1)->At(0, method_size);
   CHECK(method != nullptr);
   method->SetDexMethodIndex(DexFile::kDexNoIndex);
   CHECK(method->IsRuntimeMethod());
diff --git a/runtime/class_linker.h b/runtime/class_linker.h
index 54f1f3d..17d6be6 100644
--- a/runtime/class_linker.h
+++ b/runtime/class_linker.h
@@ -25,7 +25,6 @@
 #include "base/hash_set.h"
 #include "base/macros.h"
 #include "base/mutex.h"
-#include "base/out_fwd.h"
 #include "class_table.h"
 #include "dex_file.h"
 #include "gc_root.h"
@@ -109,19 +108,16 @@
 
   // Initialize class linker by bootstraping from dex files.
   void InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   // Initialize class linker from one or more images.
   void InitFromImage() SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   // Finds a class by its descriptor, loading it if necessary.
   // If class_loader is null, searches boot_class_path_.
-  mirror::Class* FindClass(Thread* self,
-                           const char* descriptor,
+  mirror::Class* FindClass(Thread* self, const char* descriptor,
                            Handle<mirror::ClassLoader> class_loader)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   // Finds a class in the path class loader, loading it if necessary without using JNI. Hash
   // function is supposed to be ComputeModifiedUtf8Hash(descriptor). Returns true if the
@@ -129,24 +125,19 @@
   // was encountered while walking the parent chain (currently only BootClassLoader and
   // PathClassLoader are supported).
   bool FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
-                                  Thread* self,
-                                  const char* descriptor,
-                                  size_t hash,
+                                  Thread* self, const char* descriptor, size_t hash,
                                   Handle<mirror::ClassLoader> class_loader,
-                                  out<mirror::Class*> result)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+                                  mirror::Class** result)
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   // Finds a class by its descriptor using the "system" class loader, ie by searching the
   // boot_class_path_.
   mirror::Class* FindSystemClass(Thread* self, const char* descriptor)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   // Finds the array class given for the element class.
-  mirror::Class* FindArrayClass(Thread* self, /* in parameter */ mirror::Class** element_class)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+  mirror::Class* FindArrayClass(Thread* self, mirror::Class** element_class)
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   // Returns true if the class linker is initialized.
   bool IsInitialized() const {
@@ -154,27 +145,20 @@
   }
 
   // Define a new a class based on a ClassDef from a DexFile
-  mirror::Class* DefineClass(Thread* self,
-                             const char* descriptor,
-                             size_t hash,
+  mirror::Class* DefineClass(Thread* self, const char* descriptor, size_t hash,
                              Handle<mirror::ClassLoader> class_loader,
-                             const DexFile& dex_file,
-                             const DexFile::ClassDef& dex_class_def)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+                             const DexFile& dex_file, const DexFile::ClassDef& dex_class_def)
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   // Finds a class by its descriptor, returning null if it isn't wasn't loaded
   // by the given 'class_loader'.
-  mirror::Class* LookupClass(Thread* self,
-                             const char* descriptor,
-                             size_t hash,
-                             mirror::ClassLoader*
-                             class_loader)
+  mirror::Class* LookupClass(Thread* self, const char* descriptor, size_t hash,
+                             mirror::ClassLoader* class_loader)
       REQUIRES(!Locks::classlinker_classes_lock_)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Finds all the classes with the given descriptor, regardless of ClassLoader.
-  void LookupClasses(const char* descriptor, out<std::vector<mirror::Class*>> classes)
+  void LookupClasses(const char* descriptor, std::vector<mirror::Class*>& classes)
       REQUIRES(!Locks::classlinker_classes_lock_)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
@@ -182,21 +166,17 @@
 
   // General class unloading is not supported, this is used to prune
   // unwanted classes during image writing.
-  bool RemoveClass(const char* descriptor,
-                   mirror::ClassLoader* class_loader)
-      REQUIRES(!Locks::classlinker_classes_lock_)
-      SHARED_REQUIRES(Locks::mutator_lock_);
+  bool RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader)
+      REQUIRES(!Locks::classlinker_classes_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
 
   void DumpAllClasses(int flags)
-      REQUIRES(!Locks::classlinker_classes_lock_)
-      SHARED_REQUIRES(Locks::mutator_lock_);
+      REQUIRES(!Locks::classlinker_classes_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
 
   void DumpForSigQuit(std::ostream& os)
       REQUIRES(!Locks::classlinker_classes_lock_);
 
   size_t NumLoadedClasses()
-      REQUIRES(!Locks::classlinker_classes_lock_)
-      SHARED_REQUIRES(Locks::mutator_lock_);
+      REQUIRES(!Locks::classlinker_classes_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Resolve a String with the given index from the DexFile, storing the
   // result in the DexCache. The referrer is used to identify the
@@ -206,95 +186,75 @@
 
   // Resolve a String with the given index from the DexFile, storing the
   // result in the DexCache.
-  mirror::String* ResolveString(const DexFile& dex_file,
-                                uint32_t string_idx,
+  mirror::String* ResolveString(const DexFile& dex_file, uint32_t string_idx,
                                 Handle<mirror::DexCache> dex_cache)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Resolve a Type with the given index from the DexFile, storing the
   // result in the DexCache. The referrer is used to identity the
   // target DexCache and ClassLoader to use for resolution.
-  mirror::Class* ResolveType(const DexFile& dex_file,
-                             uint16_t type_idx,
-                             mirror::Class* referrer)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+  mirror::Class* ResolveType(const DexFile& dex_file, uint16_t type_idx, mirror::Class* referrer)
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
   // Resolve a Type with the given index from the DexFile, storing the
   // result in the DexCache. The referrer is used to identify the
   // target DexCache and ClassLoader to use for resolution.
-  mirror::Class* ResolveType(uint16_t type_idx,
-                             ArtMethod* referrer)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+  mirror::Class* ResolveType(uint16_t type_idx, ArtMethod* referrer)
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
-  mirror::Class* ResolveType(uint16_t type_idx,
-                             ArtField* referrer)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+  mirror::Class* ResolveType(uint16_t type_idx, ArtField* referrer)
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
   // Resolve a type with the given ID from the DexFile, storing the
   // result in DexCache. The ClassLoader is used to search for the
   // type, since it may be referenced from but not contained within
   // the given DexFile.
-  mirror::Class* ResolveType(const DexFile& dex_file,
-                             uint16_t type_idx,
+  mirror::Class* ResolveType(const DexFile& dex_file, uint16_t type_idx,
                              Handle<mirror::DexCache> dex_cache,
                              Handle<mirror::ClassLoader> class_loader)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
   // Resolve a method with a given ID from the DexFile, storing the
   // result in DexCache. The ClassLinker and ClassLoader are used as
   // in ResolveType. What is unique is the method type argument which
   // is used to determine if this method is a direct, static, or
   // virtual method.
-  ArtMethod* ResolveMethod(const DexFile& dex_file,
-                           uint32_t method_idx,
+  ArtMethod* ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
                            Handle<mirror::DexCache> dex_cache,
-                           Handle<mirror::ClassLoader> class_loader,
-                           ArtMethod* referrer,
+                           Handle<mirror::ClassLoader> class_loader, ArtMethod* referrer,
                            InvokeType type)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
   ArtMethod* GetResolvedMethod(uint32_t method_idx, ArtMethod* referrer)
       SHARED_REQUIRES(Locks::mutator_lock_);
   ArtMethod* ResolveMethod(Thread* self, uint32_t method_idx, ArtMethod* referrer, InvokeType type)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
   ArtField* GetResolvedField(uint32_t field_idx, mirror::Class* field_declaring_class)
       SHARED_REQUIRES(Locks::mutator_lock_);
   ArtField* GetResolvedField(uint32_t field_idx, mirror::DexCache* dex_cache)
       SHARED_REQUIRES(Locks::mutator_lock_);
   ArtField* ResolveField(uint32_t field_idx, ArtMethod* referrer, bool is_static)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
   // Resolve a field with a given ID from the DexFile, storing the
   // result in DexCache. The ClassLinker and ClassLoader are used as
   // in ResolveType. What is unique is the is_static argument which is
   // used to determine if we are resolving a static or non-static
   // field.
-  ArtField* ResolveField(const DexFile& dex_file,
-                         uint32_t field_idx,
+  ArtField* ResolveField(const DexFile& dex_file, uint32_t field_idx,
                          Handle<mirror::DexCache> dex_cache,
-                         Handle<mirror::ClassLoader> class_loader,
-                         bool is_static)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+                         Handle<mirror::ClassLoader> class_loader, bool is_static)
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
   // Resolve a field with a given ID from the DexFile, storing the
   // result in DexCache. The ClassLinker and ClassLoader are used as
   // in ResolveType. No is_static argument is provided so that Java
   // field resolution semantics are followed.
-  ArtField* ResolveFieldJLS(const DexFile& dex_file,
-                            uint32_t field_idx,
+  ArtField* ResolveFieldJLS(const DexFile& dex_file, uint32_t field_idx,
                             Handle<mirror::DexCache> dex_cache,
                             Handle<mirror::ClassLoader> class_loader)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
   // Get shorty from method index without resolution. Used to do handlerization.
   const char* MethodShorty(uint32_t method_idx, ArtMethod* referrer, uint32_t* length)
@@ -303,12 +263,9 @@
   // Returns true on success, false if there's an exception pending.
   // can_run_clinit=false allows the compiler to attempt to init a class,
   // given the restriction that no <clinit> execution is possible.
-  bool EnsureInitialized(Thread* self,
-                         Handle<mirror::Class> c,
-                         bool can_init_fields,
+  bool EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
                          bool can_init_parents)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
   // Initializes classes that have instances in the image but that have
   // <clinit> methods so they could not be initialized by the compiler.
@@ -332,33 +289,26 @@
       REQUIRES(!dex_lock_);
 
   void VisitClasses(ClassVisitor* visitor)
-      REQUIRES(!Locks::classlinker_classes_lock_)
-      SHARED_REQUIRES(Locks::mutator_lock_);
+      REQUIRES(!Locks::classlinker_classes_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Less efficient variant of VisitClasses that copies the class_table_ into secondary storage
   // so that it can visit individual classes without holding the doesn't hold the
   // Locks::classlinker_classes_lock_. As the Locks::classlinker_classes_lock_ isn't held this code
   // can race with insertion and deletion of classes while the visitor is being called.
   void VisitClassesWithoutClassesLock(ClassVisitor* visitor)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   void VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags)
-      REQUIRES(!Locks::classlinker_classes_lock_)
-      SHARED_REQUIRES(Locks::mutator_lock_);
+      REQUIRES(!Locks::classlinker_classes_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
   void VisitRoots(RootVisitor* visitor, VisitRootFlags flags)
-      REQUIRES(!dex_lock_)
-      SHARED_REQUIRES(Locks::mutator_lock_);
+      REQUIRES(!dex_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
 
   mirror::DexCache* FindDexCache(const DexFile& dex_file)
-      REQUIRES(!dex_lock_)
-      SHARED_REQUIRES(Locks::mutator_lock_);
+      REQUIRES(!dex_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
   bool IsDexFileRegistered(const DexFile& dex_file)
-      REQUIRES(!dex_lock_)
-      SHARED_REQUIRES(Locks::mutator_lock_);
+      REQUIRES(!dex_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
   void FixupDexCaches(ArtMethod* resolution_method)
-      REQUIRES(!dex_lock_)
-      SHARED_REQUIRES(Locks::mutator_lock_);
+      REQUIRES(!dex_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Finds or creates the oat file holding dex_location. Then loads and returns
   // all corresponding dex files (there may be more than one dex file loaded
@@ -374,75 +324,58 @@
   // This method should not be called with the mutator_lock_ held, because it
   // could end up starving GC if we need to generate or relocate any oat
   // files.
-  std::vector<std::unique_ptr<const DexFile>> OpenDexFilesFromOat(const char* dex_location,
-                                                                  const char* oat_location,
-                                                                  out<std::vector<std::string>>
-                                                                      error_msgs)
+  std::vector<std::unique_ptr<const DexFile>> OpenDexFilesFromOat(
+      const char* dex_location, const char* oat_location,
+      std::vector<std::string>* error_msgs)
       REQUIRES(!dex_lock_, !Locks::mutator_lock_);
 
   // Allocate an instance of a java.lang.Object.
-  mirror::Object* AllocObject(Thread* self)
-      SHARED_REQUIRES(Locks::mutator_lock_)
+  mirror::Object* AllocObject(Thread* self) SHARED_REQUIRES(Locks::mutator_lock_)
       REQUIRES(!Roles::uninterruptible_);
 
   // TODO: replace this with multiple methods that allocate the correct managed type.
   template <class T>
   mirror::ObjectArray<T>* AllocObjectArray(Thread* self, size_t length)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
 
   mirror::ObjectArray<mirror::Class>* AllocClassArray(Thread* self, size_t length)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
 
   mirror::ObjectArray<mirror::String>* AllocStringArray(Thread* self, size_t length)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
 
-  ArtField* AllocArtFieldArray(Thread* self, size_t length);
+  LengthPrefixedArray<ArtField>* AllocArtFieldArray(Thread* self, size_t length);
 
-  ArtMethod* AllocArtMethodArray(Thread* self, size_t length);
+  LengthPrefixedArray<ArtMethod>* AllocArtMethodArray(Thread* self, size_t length);
 
   mirror::PointerArray* AllocPointerArray(Thread* self, size_t length)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
 
   mirror::IfTable* AllocIfTable(Thread* self, size_t ifcount)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
 
-  mirror::ObjectArray<mirror::StackTraceElement>* AllocStackTraceElementArray(Thread* self,
-                                                                              size_t length)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+  mirror::ObjectArray<mirror::StackTraceElement>* AllocStackTraceElementArray(
+      Thread* self, size_t length) SHARED_REQUIRES(Locks::mutator_lock_)
+          REQUIRES(!Roles::uninterruptible_);
 
   void VerifyClass(Thread* self, Handle<mirror::Class> klass)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
-  bool VerifyClassUsingOatFile(const DexFile& dex_file,
-                               mirror::Class* klass,
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
+  bool VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
                                mirror::Class::Status& oat_file_class_status)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
   void ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
                                          Handle<mirror::Class> klass)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
   void ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, ArtMethod* klass)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
-  mirror::Class* CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
-                                  jstring name,
-                                  jobjectArray interfaces,
-                                  jobject loader,
-                                  jobjectArray methods,
+  mirror::Class* CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
+                                  jobjectArray interfaces, jobject loader, jobjectArray methods,
                                   jobjectArray throws)
       SHARED_REQUIRES(Locks::mutator_lock_);
   std::string GetDescriptorForProxy(mirror::Class* proxy_class)
       SHARED_REQUIRES(Locks::mutator_lock_);
-  ArtMethod* FindMethodForProxy(mirror::Class* proxy_class,
-                                ArtMethod* proxy_method)
+  ArtMethod* FindMethodForProxy(mirror::Class* proxy_class, ArtMethod* proxy_method)
       REQUIRES(!dex_lock_)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
@@ -451,8 +384,7 @@
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Get the oat code for a method from a method index.
-  const void* GetQuickOatCodeFor(const DexFile& dex_file,
-                                 uint16_t class_def_idx,
+  const void* GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
                                  uint32_t method_idx)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
@@ -462,7 +394,7 @@
   const void* GetOatMethodQuickCodeFor(ArtMethod* method)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  const OatFile::OatMethod FindOatMethodFor(ArtMethod* method, out<bool> found)
+  const OatFile::OatMethod FindOatMethodFor(ArtMethod* method, bool* found)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   pid_t GetClassesLockOwner();  // For SignalCatcher.
@@ -519,14 +451,12 @@
 
   // Returns true if the method can be called with its direct code pointer, false otherwise.
   bool MayBeCalledWithDirectCodePointer(ArtMethod* m)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   // Creates a GlobalRef PathClassLoader that can be used to load classes from the given dex files.
   // Note: the objects are not completely set up. Do not use this outside of tests and the compiler.
-  jobject CreatePathClassLoader(Thread* self, const std::vector<const DexFile*>& dex_files)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+  jobject CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files)
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   size_t GetImagePointerSize() const {
     DCHECK(ValidPointerSize(image_pointer_size_)) << image_pointer_size_;
@@ -573,39 +503,29 @@
 
   // For early bootstrapping by Init
   mirror::Class* AllocClass(Thread* self, mirror::Class* java_lang_Class, uint32_t class_size)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
 
   // Alloc* convenience functions to avoid needing to pass in mirror::Class*
   // values that are known to the ClassLinker such as
   // kObjectArrayClass and kJavaLangString etc.
   mirror::Class* AllocClass(Thread* self, uint32_t class_size)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
   mirror::DexCache* AllocDexCache(Thread* self, const DexFile& dex_file)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
 
   mirror::Class* CreatePrimitiveClass(Thread* self, Primitive::Type type)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
   mirror::Class* InitializePrimitiveClass(mirror::Class* primitive_class, Primitive::Type type)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
 
-  mirror::Class* CreateArrayClass(Thread* self,
-                                  const char* descriptor,
-                                  size_t hash,
+  mirror::Class* CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
                                   Handle<mirror::ClassLoader> class_loader)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_, !Roles::uninterruptible_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_, !Roles::uninterruptible_);
 
   void AppendToBootClassPath(Thread* self, const DexFile& dex_file)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
   void AppendToBootClassPath(const DexFile& dex_file, Handle<mirror::DexCache> dex_cache)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   // Precomputes size needed for Class, in the case of a non-temporary class this size must be
   // sufficient to hold all static fields.
@@ -614,41 +534,30 @@
 
   // Setup the classloader, class def index, type idx so that we can insert this class in the class
   // table.
-  void SetupClass(const DexFile& dex_file,
-                  const DexFile::ClassDef& dex_class_def,
-                  Handle<mirror::Class> klass,
-                  mirror::ClassLoader* class_loader)
+  void SetupClass(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
+                  Handle<mirror::Class> klass, mirror::ClassLoader* class_loader)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  void LoadClass(Thread* self,
-                 const DexFile& dex_file,
-                 const DexFile::ClassDef& dex_class_def,
+  void LoadClass(Thread* self, const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
                  Handle<mirror::Class> klass)
       SHARED_REQUIRES(Locks::mutator_lock_);
-  void LoadClassMembers(Thread* self,
-                        const DexFile& dex_file,
-                        const uint8_t* class_data,
-                        Handle<mirror::Class> klass,
-                        const OatFile::OatClass* oat_class)
+  void LoadClassMembers(Thread* self, const DexFile& dex_file, const uint8_t* class_data,
+                        Handle<mirror::Class> klass, const OatFile::OatClass* oat_class)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  void LoadField(const ClassDataItemIterator& it,
-                 Handle<mirror::Class> klass,
+  void LoadField(const ClassDataItemIterator& it, Handle<mirror::Class> klass,
                  ArtField* dst)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  void LoadMethod(Thread* self,
-                  const DexFile& dex_file,
-                  const ClassDataItemIterator& it,
-                  Handle<mirror::Class> klass,
-                  ArtMethod* dst)
+  void LoadMethod(Thread* self, const DexFile& dex_file, const ClassDataItemIterator& it,
+                  Handle<mirror::Class> klass, ArtMethod* dst)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   void FixupStaticTrampolines(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Finds the associated oat class for a dex_file and descriptor. Returns an invalid OatClass on
   // error and sets found to false.
-  OatFile::OatClass FindOatClass(const DexFile& dex_file, uint16_t class_def_idx, out<bool> found)
+  OatFile::OatClass FindOatClass(const DexFile& dex_file, uint16_t class_def_idx, bool* found)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   void RegisterDexFileLocked(const DexFile& dex_file, Handle<mirror::DexCache> dex_cache)
@@ -656,70 +565,55 @@
   bool IsDexFileRegisteredLocked(const DexFile& dex_file)
       SHARED_REQUIRES(dex_lock_, Locks::mutator_lock_);
 
-  bool InitializeClass(Thread* self,
-                       Handle<mirror::Class> klass,
-                       bool can_run_clinit,
+  bool InitializeClass(Thread* self, Handle<mirror::Class> klass, bool can_run_clinit,
                        bool can_init_parents)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
-  bool WaitForInitializeClass(Handle<mirror::Class> klass,
-                              Thread* self,
-                              ObjectLock<mirror::Class>* lock);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
+  bool WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
+                              ObjectLock<mirror::Class>& lock);
   bool ValidateSuperClassDescriptors(Handle<mirror::Class> klass)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  bool IsSameDescriptorInDifferentClassContexts(Thread* self,
-                                                const char* descriptor,
+  bool IsSameDescriptorInDifferentClassContexts(Thread* self, const char* descriptor,
                                                 Handle<mirror::ClassLoader> class_loader1,
                                                 Handle<mirror::ClassLoader> class_loader2)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  bool IsSameMethodSignatureInDifferentClassContexts(Thread* self,
-                                                     ArtMethod* method,
-                                                     mirror::Class* klass1,
-                                                     mirror::Class* klass2)
+  bool IsSameMethodSignatureInDifferentClassContexts(Thread* self, ArtMethod* method,
+                                                     mirror::Class* klass1, mirror::Class* klass2)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  bool LinkClass(Thread* self,
-                 const char* descriptor,
-                 Handle<mirror::Class> klass,
+  bool LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
                  Handle<mirror::ObjectArray<mirror::Class>> interfaces,
-                 out<MutableHandle<mirror::Class>> h_new_class_out)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!Locks::classlinker_classes_lock_);
+                 MutableHandle<mirror::Class>* h_new_class_out)
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Locks::classlinker_classes_lock_);
 
   bool LinkSuperClass(Handle<mirror::Class> klass)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   bool LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file)
-      SHARED_REQUIRES(Locks::mutator_lock_)
-      REQUIRES(!dex_lock_);
+      SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
 
   bool LinkMethods(Thread* self,
                    Handle<mirror::Class> klass,
                    Handle<mirror::ObjectArray<mirror::Class>> interfaces,
-                   out<ArtMethod* [mirror::Class::kImtSize]> out_imt)
+                   ArtMethod** out_imt)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   bool LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  bool LinkInterfaceMethods(Thread* self,
-                            Handle<mirror::Class> klass,
+  bool LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
                             Handle<mirror::ObjectArray<mirror::Class>> interfaces,
-                            out<ArtMethod* [mirror::Class::kImtSize]> out_imt)
+                            ArtMethod** out_imt)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  bool LinkStaticFields(Thread* self,
-                        Handle<mirror::Class> klass,
-                        out<size_t> class_size)
+  bool LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size)
       SHARED_REQUIRES(Locks::mutator_lock_);
   bool LinkInstanceFields(Thread* self, Handle<mirror::Class> klass)
       SHARED_REQUIRES(Locks::mutator_lock_);
-  bool LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static, out<size_t> class_size)
+  bool LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static, size_t* class_size)
       SHARED_REQUIRES(Locks::mutator_lock_);
-  void LinkCode(ArtMethod* method,
-                const OatFile::OatClass* oat_class,
+  void LinkCode(ArtMethod* method, const OatFile::OatClass* oat_class,
                 uint32_t class_def_method_index)
       SHARED_REQUIRES(Locks::mutator_lock_);
   void CreateReferenceInstanceOffsets(Handle<mirror::Class> klass)
@@ -792,7 +686,7 @@
       REQUIRES(!dex_lock_);
 
   // Check for duplicate class definitions of the given oat file against all open oat files.
-  bool HasCollisions(const OatFile* oat_file, out<std::string> error_msg) REQUIRES(!dex_lock_);
+  bool HasCollisions(const OatFile* oat_file, std::string* error_msg) REQUIRES(!dex_lock_);
 
   bool HasInitWithString(Thread* self, const char* descriptor)
       SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!dex_lock_);
@@ -801,8 +695,7 @@
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   void UpdateClassVirtualMethods(mirror::Class* klass,
-                                 ArtMethod* new_methods,
-                                 size_t new_num_methods)
+                                 LengthPrefixedArray<ArtMethod>* new_methods)
       SHARED_REQUIRES(Locks::mutator_lock_)
       REQUIRES(!Locks::classlinker_classes_lock_);
 
diff --git a/runtime/class_linker_test.cc b/runtime/class_linker_test.cc
index 3f8259a..4212dda 100644
--- a/runtime/class_linker_test.cc
+++ b/runtime/class_linker_test.cc
@@ -500,14 +500,10 @@
     addOffset(OFFSETOF_MEMBER(mirror::Class, ifields_), "iFields");
     addOffset(OFFSETOF_MEMBER(mirror::Class, iftable_), "ifTable");
     addOffset(OFFSETOF_MEMBER(mirror::Class, name_), "name");
-    addOffset(OFFSETOF_MEMBER(mirror::Class, num_direct_methods_), "numDirectMethods");
-    addOffset(OFFSETOF_MEMBER(mirror::Class, num_instance_fields_), "numInstanceFields");
     addOffset(OFFSETOF_MEMBER(mirror::Class, num_reference_instance_fields_),
               "numReferenceInstanceFields");
     addOffset(OFFSETOF_MEMBER(mirror::Class, num_reference_static_fields_),
               "numReferenceStaticFields");
-    addOffset(OFFSETOF_MEMBER(mirror::Class, num_static_fields_), "numStaticFields");
-    addOffset(OFFSETOF_MEMBER(mirror::Class, num_virtual_methods_), "numVirtualMethods");
     addOffset(OFFSETOF_MEMBER(mirror::Class, object_size_), "objectSize");
     addOffset(OFFSETOF_MEMBER(mirror::Class, primitive_type_), "primitiveType");
     addOffset(OFFSETOF_MEMBER(mirror::Class, reference_instance_offsets_),
@@ -841,21 +837,21 @@
   NullHandle<mirror::ClassLoader> class_loader;
   mirror::Class* c;
   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Boolean;", class_loader);
-  EXPECT_STREQ("value", c->GetIFields()[0].GetName());
+  EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Byte;", class_loader);
-  EXPECT_STREQ("value", c->GetIFields()[0].GetName());
+  EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Character;", class_loader);
-  EXPECT_STREQ("value", c->GetIFields()[0].GetName());
+  EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Double;", class_loader);
-  EXPECT_STREQ("value", c->GetIFields()[0].GetName());
+  EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Float;", class_loader);
-  EXPECT_STREQ("value", c->GetIFields()[0].GetName());
+  EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Integer;", class_loader);
-  EXPECT_STREQ("value", c->GetIFields()[0].GetName());
+  EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Long;", class_loader);
-  EXPECT_STREQ("value", c->GetIFields()[0].GetName());
+  EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Short;", class_loader);
-  EXPECT_STREQ("value", c->GetIFields()[0].GetName());
+  EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
 }
 
 TEST_F(ClassLinkerTest, TwoClassLoadersOneClass) {
diff --git a/runtime/class_table.h b/runtime/class_table.h
index 252a47d..4182954 100644
--- a/runtime/class_table.h
+++ b/runtime/class_table.h
@@ -107,13 +107,14 @@
       return item.IsNull();
     }
   };
-  // hash set which hashes class descriptor, and compares descriptors nad class loaders. Results
+  // hash set which hashes class descriptor, and compares descriptors and class loaders. Results
   // should be compared for a matching Class descriptor and class loader.
   typedef HashSet<GcRoot<mirror::Class>, GcRootEmptyFn, ClassDescriptorHashEquals,
       ClassDescriptorHashEquals, TrackingAllocator<GcRoot<mirror::Class>, kAllocatorTagClassTable>>
       ClassSet;
 
   // TODO: shard lock to have one per class loader.
+  // We have a vector to help prevent dirty pages after the zygote forks by calling FreezeSnapshot.
   std::vector<ClassSet> classes_ GUARDED_BY(Locks::classlinker_classes_lock_);
 };
 
diff --git a/runtime/debugger.cc b/runtime/debugger.cc
index 1865516..8e60814 100644
--- a/runtime/debugger.cc
+++ b/runtime/debugger.cc
@@ -24,7 +24,6 @@
 #include "art_field-inl.h"
 #include "art_method-inl.h"
 #include "base/time_utils.h"
-#include "base/out.h"
 #include "class_linker.h"
 #include "class_linker-inl.h"
 #include "dex_file-inl.h"
@@ -1001,7 +1000,7 @@
 
 void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
   std::vector<mirror::Class*> classes;
-  Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, outof(classes));
+  Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
   ids->clear();
   for (size_t i = 0; i < classes.size(); ++i) {
     ids->push_back(gRegistry->Add(classes[i]));
@@ -2094,7 +2093,7 @@
     case kWaitingInMainDebuggerLoop:
     case kWaitingInMainSignalCatcherLoop:
     case kWaitingPerformingGc:
-    case kWaitingWeakRootRead:
+    case kWaitingWeakGcRootRead:
     case kWaiting:
       return JDWP::TS_WAIT;
       // Don't add a 'default' here so the compiler can spot incompatible enum changes.
diff --git a/runtime/gc/accounting/mod_union_table.cc b/runtime/gc/accounting/mod_union_table.cc
index 157f609..b9e8925 100644
--- a/runtime/gc/accounting/mod_union_table.cc
+++ b/runtime/gc/accounting/mod_union_table.cc
@@ -101,28 +101,34 @@
   // Extra parameters are required since we use this same visitor signature for checking objects.
   void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
       SHARED_REQUIRES(Locks::mutator_lock_) {
-    // Only add the reference if it is non null and fits our criteria.
-    mirror::HeapReference<Object>* const obj_ptr = obj->GetFieldObjectReferenceAddr(offset);
-    mirror::Object* ref = obj_ptr->AsMirrorPtr();
-    if (ref != nullptr && !from_space_->HasAddress(ref) && !immune_space_->HasAddress(ref)) {
-      *contains_reference_to_other_space_ = true;
-      visitor_->MarkHeapReference(obj_ptr);
-    }
+    MarkReference(obj->GetFieldObjectReferenceAddr(offset));
   }
 
   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
       SHARED_REQUIRES(Locks::mutator_lock_) {
-    if (kIsDebugBuild && !root->IsNull()) {
-      VisitRoot(root);
-    }
+    VisitRoot(root);
   }
 
   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
       SHARED_REQUIRES(Locks::mutator_lock_) {
-    DCHECK(from_space_->HasAddress(root->AsMirrorPtr()));
+    MarkReference(root);
   }
 
  private:
+  template<bool kPoisonReferences>
+  void MarkReference(mirror::ObjectReference<kPoisonReferences, mirror::Object>* obj_ptr) const
+      SHARED_REQUIRES(Locks::mutator_lock_) {
+    // Only add the reference if it is non null and fits our criteria.
+    mirror::Object* ref = obj_ptr->AsMirrorPtr();
+    if (ref != nullptr && !from_space_->HasAddress(ref) && !immune_space_->HasAddress(ref)) {
+      *contains_reference_to_other_space_ = true;
+      mirror::Object* new_object = visitor_->MarkObject(ref);
+      if (ref != new_object) {
+        obj_ptr->Assign(new_object);
+      }
+    }
+  }
+
   MarkObjectVisitor* const visitor_;
   // Space which we are scanning
   space::ContinuousSpace* const from_space_;
diff --git a/runtime/gc/accounting/space_bitmap.cc b/runtime/gc/accounting/space_bitmap.cc
index 7914b66..b43f77f 100644
--- a/runtime/gc/accounting/space_bitmap.cc
+++ b/runtime/gc/accounting/space_bitmap.cc
@@ -195,11 +195,9 @@
     WalkInstanceFields(visited, callback, obj, super, arg);
   }
   // Walk instance fields
-  auto* fields = klass->GetIFields();
-  for (size_t i = 0, count = klass->NumInstanceFields(); i < count; ++i) {
-    ArtField* field = &fields[i];
-    if (!field->IsPrimitiveType()) {
-      mirror::Object* value = field->GetObj(obj);
+  for (ArtField& field : klass->GetIFields()) {
+    if (!field.IsPrimitiveType()) {
+      mirror::Object* value = field.GetObj(obj);
       if (value != nullptr) {
         WalkFieldsInOrder(visited, callback, value, arg);
       }
@@ -222,11 +220,9 @@
   WalkInstanceFields(visited, callback, obj, klass, arg);
   // Walk static fields of a Class
   if (obj->IsClass()) {
-    auto* sfields = klass->GetSFields();
-    for (size_t i = 0, count = klass->NumStaticFields(); i < count; ++i) {
-      ArtField* field = &sfields[i];
-      if (!field->IsPrimitiveType()) {
-        mirror::Object* value = field->GetObj(nullptr);
+    for (ArtField& field : klass->GetSFields()) {
+      if (!field.IsPrimitiveType()) {
+        mirror::Object* value = field.GetObj(nullptr);
         if (value != nullptr) {
           WalkFieldsInOrder(visited, callback, value, arg);
         }
diff --git a/runtime/gc/heap.cc b/runtime/gc/heap.cc
index 5f617bd..59e39df 100644
--- a/runtime/gc/heap.cc
+++ b/runtime/gc/heap.cc
@@ -2912,14 +2912,10 @@
           if (!obj->IsObjectArray()) {
             mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
             CHECK(klass != nullptr);
-            auto* fields = is_static ? klass->GetSFields() : klass->GetIFields();
-            auto num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
-            CHECK_EQ(fields == nullptr, num_fields == 0u);
-            for (size_t i = 0; i < num_fields; ++i) {
-              ArtField* cur = &fields[i];
-              if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
+            for (ArtField& field : is_static ? klass->GetSFields() : klass->GetIFields()) {
+              if (field.GetOffset().Int32Value() == offset.Int32Value()) {
                 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
-                          << PrettyField(cur);
+                           << PrettyField(&field);
                 break;
               }
             }
diff --git a/runtime/gc/space/image_space.cc b/runtime/gc/space/image_space.cc
index aba32a0..1923d24 100644
--- a/runtime/gc/space/image_space.cc
+++ b/runtime/gc/space/image_space.cc
@@ -25,7 +25,6 @@
 
 #include "art_method.h"
 #include "base/macros.h"
-#include "base/out.h"
 #include "base/stl_util.h"
 #include "base/scoped_flock.h"
 #include "base/time_utils.h"
@@ -208,7 +207,7 @@
   // Note: we do not generate a fully debuggable boot image so we do not pass the
   // compiler flag --debuggable here.
 
-  Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(outof(arg_vector));
+  Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
   CHECK_EQ(image_isa, kRuntimeISA)
       << "We should always be generating an image for the current isa.";
 
@@ -790,13 +789,10 @@
 
   CHECK(image_header.GetOatDataBegin() != nullptr);
 
-  OatFile* oat_file = OatFile::Open(oat_filename,
-                                    oat_filename,
-                                    image_header.GetOatDataBegin(),
+  OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, image_header.GetOatDataBegin(),
                                     image_header.GetOatFileBegin(),
                                     !Runtime::Current()->IsAotCompiler(),
-                                    nullptr /* no abs dex location */,
-                                    outof_ptr(error_msg));
+                                    nullptr, error_msg);
   if (oat_file == nullptr) {
     *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
                               oat_filename.c_str(), GetName(), error_msg->c_str());
diff --git a/runtime/gc/weak_root_state.h b/runtime/gc/weak_root_state.h
index b66f19d..e3cefc4 100644
--- a/runtime/gc/weak_root_state.h
+++ b/runtime/gc/weak_root_state.h
@@ -28,6 +28,8 @@
   // Need to wait until we can read weak roots.
   kWeakRootStateNoReadsOrWrites,
   // Need to mark new weak roots to make sure they don't get swept.
+  // kWeakRootStateMarkNewRoots is currently unused but I was planning on using to allow adding new
+  // weak roots during the CMS reference processing phase.
   kWeakRootStateMarkNewRoots,
 };
 
diff --git a/runtime/image.cc b/runtime/image.cc
index 44193da..ba1e58b 100644
--- a/runtime/image.cc
+++ b/runtime/image.cc
@@ -24,7 +24,7 @@
 namespace art {
 
 const uint8_t ImageHeader::kImageMagic[] = { 'a', 'r', 't', '\n' };
-const uint8_t ImageHeader::kImageVersion[] = { '0', '1', '7', '\0' };
+const uint8_t ImageHeader::kImageVersion[] = { '0', '1', '8', '\0' };
 
 ImageHeader::ImageHeader(uint32_t image_begin,
                          uint32_t image_size,
@@ -147,4 +147,26 @@
   return os << "size=" << section.Size() << " range=" << section.Offset() << "-" << section.End();
 }
 
+void ImageSection::VisitPackedArtFields(ArtFieldVisitor* visitor, uint8_t* base) const {
+  for (size_t pos = 0; pos < Size(); ) {
+    auto* array = reinterpret_cast<LengthPrefixedArray<ArtField>*>(base + Offset() + pos);
+    for (size_t i = 0; i < array->Length(); ++i) {
+      visitor->Visit(&array->At(i, sizeof(ArtField)));
+    }
+    pos += array->ComputeSize(array->Length(), sizeof(ArtField));
+  }
+}
+
+void ImageSection::VisitPackedArtMethods(ArtMethodVisitor* visitor,
+                                         uint8_t* base,
+                                         size_t method_size) const {
+  for (size_t pos = 0; pos < Size(); ) {
+    auto* array = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(base + Offset() + pos);
+    for (size_t i = 0; i < array->Length(); ++i) {
+      visitor->Visit(&array->At(i, method_size));
+    }
+    pos += array->ComputeSize(array->Length(), method_size);
+  }
+}
+
 }  // namespace art
diff --git a/runtime/image.h b/runtime/image.h
index cc98ba6..eb26f7f 100644
--- a/runtime/image.h
+++ b/runtime/image.h
@@ -24,6 +24,23 @@
 
 namespace art {
 
+class ArtField;
+class ArtMethod;
+
+class ArtMethodVisitor {
+ public:
+  virtual ~ArtMethodVisitor() {}
+
+  virtual void Visit(ArtMethod* method) = 0;
+};
+
+class ArtFieldVisitor {
+ public:
+  virtual ~ArtFieldVisitor() {}
+
+  virtual void Visit(ArtField* method) = 0;
+};
+
 class PACKED(4) ImageSection {
  public:
   ImageSection() : offset_(0), size_(0) { }
@@ -47,6 +64,12 @@
     return offset - offset_ < size_;
   }
 
+  // Visit ArtMethods in the section starting at base.
+  void VisitPackedArtMethods(ArtMethodVisitor* visitor, uint8_t* base, size_t method_size) const;
+
+  // Visit ArtMethods in the section starting at base.
+  void VisitPackedArtFields(ArtFieldVisitor* visitor, uint8_t* base) const;
+
  private:
   uint32_t offset_;
   uint32_t size_;
diff --git a/runtime/intern_table.cc b/runtime/intern_table.cc
index ae521b1..2be570a 100644
--- a/runtime/intern_table.cc
+++ b/runtime/intern_table.cc
@@ -90,7 +90,6 @@
 }
 
 mirror::String* InternTable::LookupWeak(mirror::String* s) {
-  // TODO: Return only if marked.
   return weak_interns_.Find(s);
 }
 
@@ -229,7 +228,7 @@
 
 void InternTable::WaitUntilAccessible(Thread* self) {
   Locks::intern_table_lock_->ExclusiveUnlock(self);
-  self->TransitionFromRunnableToSuspended(kWaitingWeakRootRead);
+  self->TransitionFromRunnableToSuspended(kWaitingWeakGcRootRead);
   Locks::intern_table_lock_->ExclusiveLock(self);
   while (weak_root_state_ == gc::kWeakRootStateNoReadsOrWrites) {
     weak_intern_condition_.Wait(self);
@@ -250,24 +249,35 @@
     CHECK_EQ(2u, self->NumberOfHeldMutexes()) << "may only safely hold the mutator lock";
   }
   while (true) {
+    if (holding_locks) {
+      if (!kUseReadBarrier) {
+        CHECK_EQ(weak_root_state_, gc::kWeakRootStateNormal);
+      } else {
+        CHECK(self->GetWeakRefAccessEnabled());
+      }
+    }
     // Check the strong table for a match.
     mirror::String* strong = LookupStrong(s);
     if (strong != nullptr) {
       return strong;
     }
+    if ((!kUseReadBarrier && weak_root_state_ != gc::kWeakRootStateNoReadsOrWrites) ||
+        (kUseReadBarrier && self->GetWeakRefAccessEnabled())) {
+      break;
+    }
     // weak_root_state_ is set to gc::kWeakRootStateNoReadsOrWrites in the GC pause but is only
     // cleared after SweepSystemWeaks has completed. This is why we need to wait until it is
     // cleared.
-    if (weak_root_state_ != gc::kWeakRootStateNoReadsOrWrites) {
-      break;
-    }
     CHECK(!holding_locks);
     StackHandleScope<1> hs(self);
     auto h = hs.NewHandleWrapper(&s);
     WaitUntilAccessible(self);
   }
-  CHECK_NE(weak_root_state_, gc::kWeakRootStateNoReadsOrWrites);
-  DCHECK_NE(weak_root_state_, gc::kWeakRootStateMarkNewRoots) << "Unsupported";
+  if (!kUseReadBarrier) {
+    CHECK_EQ(weak_root_state_, gc::kWeakRootStateNormal);
+  } else {
+    CHECK(self->GetWeakRefAccessEnabled());
+  }
   // There is no match in the strong table, check the weak table.
   mirror::String* weak = LookupWeak(s);
   if (weak != nullptr) {
@@ -298,7 +308,7 @@
   return InternStrong(mirror::String::AllocFromModifiedUtf8(Thread::Current(), utf8_data));
 }
 
-mirror::String* InternTable::InternImageString(mirror::String* s) {
+mirror::String* InternTable::InternStrongImageString(mirror::String* s) {
   // May be holding the heap bitmap lock.
   return Insert(s, true, true);
 }
@@ -319,8 +329,6 @@
 void InternTable::SweepInternTableWeaks(IsMarkedVisitor* visitor) {
   MutexLock mu(Thread::Current(), *Locks::intern_table_lock_);
   weak_interns_.SweepWeaks(visitor);
-  // Done sweeping, back to a normal state.
-  ChangeWeakRootStateLocked(gc::kWeakRootStateNormal);
 }
 
 void InternTable::AddImageInternTable(gc::space::ImageSpace* image_space) {
diff --git a/runtime/intern_table.h b/runtime/intern_table.h
index 0be6675..ae9f7a7 100644
--- a/runtime/intern_table.h
+++ b/runtime/intern_table.h
@@ -61,8 +61,10 @@
       SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_);
 
   // Only used by image writer. Special version that may not cause thread suspension since the GC
-  // can not be running while we are doing image writing.
-  mirror::String* InternImageString(mirror::String* s) SHARED_REQUIRES(Locks::mutator_lock_);
+  // can not be running while we are doing image writing. Maybe be called while while holding a
+  // lock since there will not be thread suspension.
+  mirror::String* InternStrongImageString(mirror::String* s)
+      SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Interns a potentially new string in the 'strong' table. May cause thread suspension.
   mirror::String* InternStrong(const char* utf8_data) SHARED_REQUIRES(Locks::mutator_lock_)
@@ -184,7 +186,9 @@
     UnorderedSet post_zygote_table_;
   };
 
-  // Insert if non null, otherwise return null.
+  // Insert if non null, otherwise return null. Must be called holding the mutator lock.
+  // If holding_locks is true, then we may also hold other locks. If holding_locks is true, then we
+  // require GC is not running since it is not safe to wait while holding locks.
   mirror::String* Insert(mirror::String* s, bool is_strong, bool holding_locks)
       REQUIRES(!Locks::intern_table_lock_) SHARED_REQUIRES(Locks::mutator_lock_);
 
diff --git a/runtime/interpreter/interpreter_common.cc b/runtime/interpreter/interpreter_common.cc
index 9de9e8a..f923b84 100644
--- a/runtime/interpreter/interpreter_common.cc
+++ b/runtime/interpreter/interpreter_common.cc
@@ -884,7 +884,7 @@
 
 // Explicit DoCall template function declarations.
 #define EXPLICIT_DO_CALL_TEMPLATE_DECL(_is_range, _do_assignability_check)                      \
-  template SHARED_REQUIRES(Locks::mutator_lock_)                                          \
+  template SHARED_REQUIRES(Locks::mutator_lock_)                                                \
   bool DoCall<_is_range, _do_assignability_check>(ArtMethod* method, Thread* self,              \
                                                   ShadowFrame& shadow_frame,                    \
                                                   const Instruction* inst, uint16_t inst_data,  \
@@ -897,7 +897,7 @@
 
 // Explicit DoLambdaCall template function declarations.
 #define EXPLICIT_DO_LAMBDA_CALL_TEMPLATE_DECL(_is_range, _do_assignability_check)               \
-  template SHARED_REQUIRES(Locks::mutator_lock_)                                          \
+  template SHARED_REQUIRES(Locks::mutator_lock_)                                                \
   bool DoLambdaCall<_is_range, _do_assignability_check>(ArtMethod* method, Thread* self,        \
                                                         ShadowFrame& shadow_frame,              \
                                                         const Instruction* inst,                \
@@ -911,7 +911,7 @@
 
 // Explicit DoFilledNewArray template function declarations.
 #define EXPLICIT_DO_FILLED_NEW_ARRAY_TEMPLATE_DECL(_is_range_, _check, _transaction_active)       \
-  template SHARED_REQUIRES(Locks::mutator_lock_)                                            \
+  template SHARED_REQUIRES(Locks::mutator_lock_)                                                  \
   bool DoFilledNewArray<_is_range_, _check, _transaction_active>(const Instruction* inst,         \
                                                                  const ShadowFrame& shadow_frame, \
                                                                  Thread* self, JValue* result)
diff --git a/runtime/interpreter/interpreter_common.h b/runtime/interpreter/interpreter_common.h
index a6cccef..2486a98 100644
--- a/runtime/interpreter/interpreter_common.h
+++ b/runtime/interpreter/interpreter_common.h
@@ -553,7 +553,7 @@
   ArtMethod* unboxed_closure = nullptr;
   // Raise an exception if unboxing fails.
   if (!Runtime::Current()->GetLambdaBoxTable()->UnboxLambda(boxed_closure_object,
-                                                            outof(unboxed_closure))) {
+                                                            &unboxed_closure)) {
     CHECK(self->IsExceptionPending());
     return false;
   }
diff --git a/runtime/interpreter/unstarted_runtime.cc b/runtime/interpreter/unstarted_runtime.cc
index 22701ac..c559389 100644
--- a/runtime/interpreter/unstarted_runtime.cc
+++ b/runtime/interpreter/unstarted_runtime.cc
@@ -229,20 +229,16 @@
   mirror::Class* klass = shadow_frame->GetVRegReference(arg_offset)->AsClass();
   mirror::String* name2 = shadow_frame->GetVRegReference(arg_offset + 1)->AsString();
   ArtField* found = nullptr;
-  ArtField* fields = klass->GetIFields();
-  for (int32_t i = 0, count = klass->NumInstanceFields(); i < count; ++i) {
-    ArtField* f = &fields[i];
-    if (name2->Equals(f->GetName())) {
-      found = f;
+  for (ArtField& field : klass->GetIFields()) {
+    if (name2->Equals(field.GetName())) {
+      found = &field;
       break;
     }
   }
   if (found == nullptr) {
-    fields = klass->GetSFields();
-    for (int32_t i = 0, count = klass->NumStaticFields(); i < count; ++i) {
-      ArtField* f = &fields[i];
-      if (name2->Equals(f->GetName())) {
-        found = f;
+    for (ArtField& field : klass->GetSFields()) {
+      if (name2->Equals(field.GetName())) {
+        found = &field;
         break;
       }
     }
diff --git a/runtime/jdwp/jdwp.h b/runtime/jdwp/jdwp.h
index f5ac9d0..ae02fe6 100644
--- a/runtime/jdwp/jdwp.h
+++ b/runtime/jdwp/jdwp.h
@@ -128,6 +128,9 @@
    * the debugger.
    *
    * Returns a newly-allocated JdwpState struct on success, or nullptr on failure.
+   *
+   * NO_THREAD_SAFETY_ANALYSIS since we can't annotate that we do not have
+   * state->thread_start_lock_ held.
    */
   static JdwpState* Create(const JdwpOptions* options)
       REQUIRES(!Locks::mutator_lock_) NO_THREAD_SAFETY_ANALYSIS;
diff --git a/runtime/jdwp/jdwp_handler.cc b/runtime/jdwp/jdwp_handler.cc
index f449406..7776f8f 100644
--- a/runtime/jdwp/jdwp_handler.cc
+++ b/runtime/jdwp/jdwp_handler.cc
@@ -1391,7 +1391,7 @@
     // heap requirements is probably more valuable than the efficiency.
     CHECK_GT(replyLen, 0);
     memcpy(expandBufAddSpace(pReply, replyLen), replyBuf, replyLen);
-    free(replyBuf);
+    delete[] replyBuf;
   }
   return ERR_NONE;
 }
diff --git a/runtime/jit/jit_code_cache_test.cc b/runtime/jit/jit_code_cache_test.cc
index cd123b9..555ad7c 100644
--- a/runtime/jit/jit_code_cache_test.cc
+++ b/runtime/jit/jit_code_cache_test.cc
@@ -50,7 +50,7 @@
   ASSERT_TRUE(code_cache->ContainsCodePtr(reserved_code));
   ASSERT_EQ(code_cache->NumMethods(), 1u);
   ClassLinker* const cl = Runtime::Current()->GetClassLinker();
-  auto* method = cl->AllocArtMethodArray(soa.Self(), 1);
+  ArtMethod* method = &cl->AllocArtMethodArray(soa.Self(), 1)->At(0, 0);
   ASSERT_FALSE(code_cache->ContainsMethod(method));
   method->SetEntryPointFromQuickCompiledCode(reserved_code);
   ASSERT_TRUE(code_cache->ContainsMethod(method));
diff --git a/runtime/lambda/box_table.cc b/runtime/lambda/box_table.cc
index 22cc820..64a6076 100644
--- a/runtime/lambda/box_table.cc
+++ b/runtime/lambda/box_table.cc
@@ -94,7 +94,8 @@
   return method_as_object;
 }
 
-bool BoxTable::UnboxLambda(mirror::Object* object, out<ClosureType> out_closure) {
+bool BoxTable::UnboxLambda(mirror::Object* object, ClosureType* out_closure) {
+  DCHECK(object != nullptr);
   *out_closure = nullptr;
 
   // Note that we do not need to access lambda_table_lock_ here
diff --git a/runtime/lambda/box_table.h b/runtime/lambda/box_table.h
index c6d3d0c..312d811 100644
--- a/runtime/lambda/box_table.h
+++ b/runtime/lambda/box_table.h
@@ -18,7 +18,6 @@
 
 #include "base/allocator.h"
 #include "base/hash_map.h"
-#include "base/out.h"
 #include "gc_root.h"
 #include "base/macros.h"
 #include "base/mutex.h"
@@ -52,7 +51,7 @@
       SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Locks::lambda_table_lock_);
 
   // Unboxes an object back into the lambda. Returns false and throws an exception on failure.
-  bool UnboxLambda(mirror::Object* object, out<ClosureType> out_closure)
+  bool UnboxLambda(mirror::Object* object, ClosureType* out_closure)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Sweep weak references to lambda boxes. Update the addresses if the objects have been
diff --git a/runtime/length_prefixed_array.h b/runtime/length_prefixed_array.h
new file mode 100644
index 0000000..82176e3
--- /dev/null
+++ b/runtime/length_prefixed_array.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ART_RUNTIME_LENGTH_PREFIXED_ARRAY_H_
+#define ART_RUNTIME_LENGTH_PREFIXED_ARRAY_H_
+
+#include <stddef.h>  // for offsetof()
+
+#include "linear_alloc.h"
+#include "stride_iterator.h"
+#include "base/iteration_range.h"
+
+namespace art {
+
+template<typename T>
+class LengthPrefixedArray {
+ public:
+  explicit LengthPrefixedArray(uint64_t length) : length_(length) {}
+
+  T& At(size_t index, size_t element_size = sizeof(T)) {
+    DCHECK_LT(index, length_);
+    return *reinterpret_cast<T*>(&data_[0] + index * element_size);
+  }
+
+  StrideIterator<T> Begin(size_t element_size = sizeof(T)) {
+    return StrideIterator<T>(reinterpret_cast<T*>(&data_[0]), element_size);
+  }
+
+  StrideIterator<T> End(size_t element_size = sizeof(T)) {
+    return StrideIterator<T>(reinterpret_cast<T*>(&data_[0] + element_size * length_),
+                             element_size);
+  }
+
+  static size_t OffsetOfElement(size_t index, size_t element_size = sizeof(T)) {
+    return offsetof(LengthPrefixedArray<T>, data_) + index * element_size;
+  }
+
+  static size_t ComputeSize(size_t num_elements, size_t element_size = sizeof(T)) {
+    return sizeof(LengthPrefixedArray<T>) + num_elements * element_size;
+  }
+
+  uint64_t Length() const {
+    return length_;
+  }
+
+ private:
+  uint64_t length_;  // 64 bits for padding reasons.
+  uint8_t data_[0];
+};
+
+// Returns empty iteration range if the array is null.
+template<typename T>
+IterationRange<StrideIterator<T>> MakeIterationRangeFromLengthPrefixedArray(
+    LengthPrefixedArray<T>* arr, size_t element_size) {
+  return arr != nullptr ?
+      MakeIterationRange(arr->Begin(element_size), arr->End(element_size)) :
+      MakeEmptyIterationRange(StrideIterator<T>(nullptr, 0));
+}
+
+}  // namespace art
+
+#endif  // ART_RUNTIME_LENGTH_PREFIXED_ARRAY_H_
diff --git a/runtime/linear_alloc.h b/runtime/linear_alloc.h
index 743ee77..1b21527 100644
--- a/runtime/linear_alloc.h
+++ b/runtime/linear_alloc.h
@@ -33,7 +33,7 @@
   // Realloc never frees the input pointer, it is the caller's job to do this if necessary.
   void* Realloc(Thread* self, void* ptr, size_t old_size, size_t new_size) REQUIRES(!lock_);
 
-  // Allocate and construct an array of structs of type T.
+  // Allocate an array of structs of type T.
   template<class T>
   T* AllocArray(Thread* self, size_t elements) REQUIRES(!lock_) {
     return reinterpret_cast<T*>(Alloc(self, elements * sizeof(T)));
diff --git a/runtime/mirror/class-inl.h b/runtime/mirror/class-inl.h
index 6568487..887e204 100644
--- a/runtime/mirror/class-inl.h
+++ b/runtime/mirror/class-inl.h
@@ -28,6 +28,7 @@
 #include "dex_file.h"
 #include "gc/heap-inl.h"
 #include "iftable.h"
+#include "length_prefixed_array.h"
 #include "object_array-inl.h"
 #include "read_barrier-inl.h"
 #include "reference-inl.h"
@@ -61,25 +62,28 @@
   return GetFieldObject<DexCache, kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_));
 }
 
-inline ArtMethod* Class::GetDirectMethodsPtr() {
+inline LengthPrefixedArray<ArtMethod>* Class::GetDirectMethodsPtr() {
   DCHECK(IsLoaded() || IsErroneous());
   return GetDirectMethodsPtrUnchecked();
 }
 
-inline ArtMethod* Class::GetDirectMethodsPtrUnchecked() {
-  return reinterpret_cast<ArtMethod*>(GetField64(OFFSET_OF_OBJECT_MEMBER(Class, direct_methods_)));
+inline LengthPrefixedArray<ArtMethod>* Class::GetDirectMethodsPtrUnchecked() {
+  return reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
+      GetField64(OFFSET_OF_OBJECT_MEMBER(Class, direct_methods_)));
 }
 
-inline ArtMethod* Class::GetVirtualMethodsPtrUnchecked() {
-  return reinterpret_cast<ArtMethod*>(GetField64(OFFSET_OF_OBJECT_MEMBER(Class, virtual_methods_)));
+inline LengthPrefixedArray<ArtMethod>* Class::GetVirtualMethodsPtrUnchecked() {
+  return reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
+      GetField64(OFFSET_OF_OBJECT_MEMBER(Class, virtual_methods_)));
 }
 
-inline void Class::SetDirectMethodsPtr(ArtMethod* new_direct_methods) {
+inline void Class::SetDirectMethodsPtr(LengthPrefixedArray<ArtMethod>* new_direct_methods) {
   DCHECK(GetDirectMethodsPtrUnchecked() == nullptr);
   SetDirectMethodsPtrUnchecked(new_direct_methods);
 }
 
-inline void Class::SetDirectMethodsPtrUnchecked(ArtMethod* new_direct_methods) {
+inline void Class::SetDirectMethodsPtrUnchecked(
+    LengthPrefixedArray<ArtMethod>* new_direct_methods) {
   SetField64<false>(OFFSET_OF_OBJECT_MEMBER(Class, direct_methods_),
                     reinterpret_cast<uint64_t>(new_direct_methods));
 }
@@ -88,25 +92,23 @@
   CheckPointerSize(pointer_size);
   auto* methods = GetDirectMethodsPtrUnchecked();
   DCHECK(methods != nullptr);
-  return reinterpret_cast<ArtMethod*>(reinterpret_cast<uintptr_t>(methods) +
-      ArtMethod::ObjectSize(pointer_size) * i);
+  return &methods->At(i, ArtMethod::ObjectSize(pointer_size));
 }
 
 inline ArtMethod* Class::GetDirectMethod(size_t i, size_t pointer_size) {
   CheckPointerSize(pointer_size);
   auto* methods = GetDirectMethodsPtr();
   DCHECK(methods != nullptr);
-  return reinterpret_cast<ArtMethod*>(reinterpret_cast<uintptr_t>(methods) +
-      ArtMethod::ObjectSize(pointer_size) * i);
+  return &methods->At(i, ArtMethod::ObjectSize(pointer_size));
 }
 
 template<VerifyObjectFlags kVerifyFlags>
-inline ArtMethod* Class::GetVirtualMethodsPtr() {
+inline LengthPrefixedArray<ArtMethod>* Class::GetVirtualMethodsPtr() {
   DCHECK(IsLoaded<kVerifyFlags>() || IsErroneous<kVerifyFlags>());
   return GetVirtualMethodsPtrUnchecked();
 }
 
-inline void Class::SetVirtualMethodsPtr(ArtMethod* new_virtual_methods) {
+inline void Class::SetVirtualMethodsPtr(LengthPrefixedArray<ArtMethod>* new_virtual_methods) {
   // TODO: we reassign virtual methods to grow the table for miranda
   // methods.. they should really just be assigned once.
   SetField64<false>(OFFSET_OF_OBJECT_MEMBER(Class, virtual_methods_),
@@ -129,10 +131,9 @@
 
 inline ArtMethod* Class::GetVirtualMethodUnchecked(size_t i, size_t pointer_size) {
   CheckPointerSize(pointer_size);
-  auto* methods = GetVirtualMethodsPtrUnchecked();
+  LengthPrefixedArray<ArtMethod>* methods = GetVirtualMethodsPtrUnchecked();
   DCHECK(methods != nullptr);
-  return reinterpret_cast<ArtMethod*>(reinterpret_cast<uintptr_t>(methods) +
-      ArtMethod::ObjectSize(pointer_size) * i);
+  return &methods->At(i, ArtMethod::ObjectSize(pointer_size));
 }
 
 inline PointerArray* Class::GetVTable() {
@@ -423,9 +424,9 @@
   SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, iftable_), new_iftable);
 }
 
-inline ArtField* Class::GetIFields() {
+inline LengthPrefixedArray<ArtField>* Class::GetIFieldsPtr() {
   DCHECK(IsLoaded() || IsErroneous());
-  return GetFieldPtr<ArtField*>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
+  return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
 }
 
 inline MemberOffset Class::GetFirstReferenceInstanceFieldOffset() {
@@ -458,46 +459,44 @@
   return MemberOffset(base);
 }
 
-inline void Class::SetIFields(ArtField* new_ifields) {
-  DCHECK(GetIFieldsUnchecked() == nullptr);
+inline void Class::SetIFieldsPtr(LengthPrefixedArray<ArtField>* new_ifields) {
+  DCHECK(GetIFieldsPtrUnchecked() == nullptr);
   return SetFieldPtr<false>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_), new_ifields);
 }
 
-inline void Class::SetIFieldsUnchecked(ArtField* new_ifields) {
+inline void Class::SetIFieldsPtrUnchecked(LengthPrefixedArray<ArtField>* new_ifields) {
   SetFieldPtr<false, true, kVerifyNone>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_), new_ifields);
 }
 
-inline ArtField* Class::GetSFieldsUnchecked() {
-  return GetFieldPtr<ArtField*>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_));
+inline LengthPrefixedArray<ArtField>* Class::GetSFieldsPtrUnchecked() {
+  return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_));
 }
 
-inline ArtField* Class::GetIFieldsUnchecked() {
-  return GetFieldPtr<ArtField*>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
+inline LengthPrefixedArray<ArtField>* Class::GetIFieldsPtrUnchecked() {
+  return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
 }
 
-inline ArtField* Class::GetSFields() {
+inline LengthPrefixedArray<ArtField>* Class::GetSFieldsPtr() {
   DCHECK(IsLoaded() || IsErroneous()) << GetStatus();
-  return GetSFieldsUnchecked();
+  return GetSFieldsPtrUnchecked();
 }
 
-inline void Class::SetSFields(ArtField* new_sfields) {
+inline void Class::SetSFieldsPtr(LengthPrefixedArray<ArtField>* new_sfields) {
   DCHECK((IsRetired() && new_sfields == nullptr) ||
          GetFieldPtr<ArtField*>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_)) == nullptr);
   SetFieldPtr<false>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_), new_sfields);
 }
 
-inline void Class::SetSFieldsUnchecked(ArtField* new_sfields) {
+inline void Class::SetSFieldsPtrUnchecked(LengthPrefixedArray<ArtField>* new_sfields) {
   SetFieldPtr<false, true, kVerifyNone>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_), new_sfields);
 }
 
 inline ArtField* Class::GetStaticField(uint32_t i) {
-  DCHECK_LT(i, NumStaticFields());
-  return &GetSFields()[i];
+  return &GetSFieldsPtr()->At(i);
 }
 
 inline ArtField* Class::GetInstanceField(uint32_t i) {
-  DCHECK_LT(i, NumInstanceFields());
-  return &GetIFields()[i];
+  return &GetIFieldsPtr()->At(i);
 }
 
 template<VerifyObjectFlags kVerifyFlags>
@@ -813,85 +812,54 @@
 
 template<class Visitor>
 void mirror::Class::VisitNativeRoots(Visitor& visitor, size_t pointer_size) {
-  ArtField* const sfields = GetSFieldsUnchecked();
-  // Since we visit class roots while we may be writing these fields, check against null.
-  if (sfields != nullptr) {
-    for (size_t i = 0, count = NumStaticFields(); i < count; ++i) {
-      auto* f = &sfields[i];
-      // Visit roots first in case the declaring class gets moved.
-      f->VisitRoots(visitor);
-      if (kIsDebugBuild && IsResolved()) {
-        CHECK_EQ(f->GetDeclaringClass(), this) << GetStatus();
-      }
+  for (ArtField& field : GetSFieldsUnchecked()) {
+    // Visit roots first in case the declaring class gets moved.
+    field.VisitRoots(visitor);
+    if (kIsDebugBuild && IsResolved()) {
+      CHECK_EQ(field.GetDeclaringClass(), this) << GetStatus();
     }
   }
-  ArtField* const ifields = GetIFieldsUnchecked();
-  if (ifields != nullptr) {
-    for (size_t i = 0, count = NumInstanceFields(); i < count; ++i) {
-      auto* f = &ifields[i];
-      // Visit roots first in case the declaring class gets moved.
-      f->VisitRoots(visitor);
-      if (kIsDebugBuild && IsResolved()) {
-        CHECK_EQ(f->GetDeclaringClass(), this) << GetStatus();
-      }
+  for (ArtField& field : GetIFieldsUnchecked()) {
+    // Visit roots first in case the declaring class gets moved.
+    field.VisitRoots(visitor);
+    if (kIsDebugBuild && IsResolved()) {
+      CHECK_EQ(field.GetDeclaringClass(), this) << GetStatus();
     }
   }
-  // We may see GetDirectMethodsPtr() == null with NumDirectMethods() != 0 if the root marking
-  // thread reads a null DirectMethodsBegin() but a non null DirectMethodsBegin() due to a race
-  // SetDirectMethodsPtr from class linking. Same for virtual methods.
-  // In this case, it is safe to avoid marking the roots since we must be either the CC or CMS. If
-  // we are CMS then the roots are already marked through other sources, otherwise the roots are
-  // already marked due to the to-space invariant.
-  // Unchecked versions since we may visit roots of classes that aren't yet loaded.
-  if (GetDirectMethodsPtrUnchecked() != nullptr) {
-    for (auto& m : GetDirectMethods(pointer_size)) {
-      m.VisitRoots(visitor);
-    }
+  for (ArtMethod& method : GetDirectMethods(pointer_size)) {
+    method.VisitRoots(visitor);
   }
-  if (GetVirtualMethodsPtrUnchecked() != nullptr) {
-    for (auto& m : GetVirtualMethods(pointer_size)) {
-      m.VisitRoots(visitor);
-    }
+  for (ArtMethod& method : GetVirtualMethods(pointer_size)) {
+    method.VisitRoots(visitor);
   }
 }
 
-inline StrideIterator<ArtMethod> Class::DirectMethodsBegin(size_t pointer_size)  {
-  CheckPointerSize(pointer_size);
-  auto* methods = GetDirectMethodsPtrUnchecked();
-  auto stride = ArtMethod::ObjectSize(pointer_size);
-  return StrideIterator<ArtMethod>(reinterpret_cast<uintptr_t>(methods), stride);
-}
-
-inline StrideIterator<ArtMethod> Class::DirectMethodsEnd(size_t pointer_size) {
-  CheckPointerSize(pointer_size);
-  auto* methods = GetDirectMethodsPtrUnchecked();
-  auto stride = ArtMethod::ObjectSize(pointer_size);
-  auto count = NumDirectMethods();
-  return StrideIterator<ArtMethod>(reinterpret_cast<uintptr_t>(methods) + stride * count, stride);
-}
-
 inline IterationRange<StrideIterator<ArtMethod>> Class::GetDirectMethods(size_t pointer_size) {
   CheckPointerSize(pointer_size);
-  return MakeIterationRange(DirectMethodsBegin(pointer_size), DirectMethodsEnd(pointer_size));
-}
-
-inline StrideIterator<ArtMethod> Class::VirtualMethodsBegin(size_t pointer_size)  {
-  CheckPointerSize(pointer_size);
-  auto* methods = GetVirtualMethodsPtrUnchecked();
-  auto stride = ArtMethod::ObjectSize(pointer_size);
-  return StrideIterator<ArtMethod>(reinterpret_cast<uintptr_t>(methods), stride);
-}
-
-inline StrideIterator<ArtMethod> Class::VirtualMethodsEnd(size_t pointer_size) {
-  CheckPointerSize(pointer_size);
-  auto* methods = GetVirtualMethodsPtrUnchecked();
-  auto stride = ArtMethod::ObjectSize(pointer_size);
-  auto count = NumVirtualMethods();
-  return StrideIterator<ArtMethod>(reinterpret_cast<uintptr_t>(methods) + stride * count, stride);
+  return MakeIterationRangeFromLengthPrefixedArray(GetDirectMethodsPtrUnchecked(),
+                                                   ArtMethod::ObjectSize(pointer_size));
 }
 
 inline IterationRange<StrideIterator<ArtMethod>> Class::GetVirtualMethods(size_t pointer_size) {
-  return MakeIterationRange(VirtualMethodsBegin(pointer_size), VirtualMethodsEnd(pointer_size));
+  CheckPointerSize(pointer_size);
+  return MakeIterationRangeFromLengthPrefixedArray(GetVirtualMethodsPtrUnchecked(),
+                                                   ArtMethod::ObjectSize(pointer_size));
+}
+
+inline IterationRange<StrideIterator<ArtField>> Class::GetIFields() {
+  return MakeIterationRangeFromLengthPrefixedArray(GetIFieldsPtr(), sizeof(ArtField));
+}
+
+inline IterationRange<StrideIterator<ArtField>> Class::GetSFields() {
+  return MakeIterationRangeFromLengthPrefixedArray(GetSFieldsPtr(), sizeof(ArtField));
+}
+
+inline IterationRange<StrideIterator<ArtField>> Class::GetIFieldsUnchecked() {
+  return MakeIterationRangeFromLengthPrefixedArray(GetIFieldsPtrUnchecked(), sizeof(ArtField));
+}
+
+inline IterationRange<StrideIterator<ArtField>> Class::GetSFieldsUnchecked() {
+  return MakeIterationRangeFromLengthPrefixedArray(GetSFieldsPtrUnchecked(), sizeof(ArtField));
 }
 
 inline MemberOffset Class::EmbeddedImTableOffset(size_t pointer_size) {
@@ -940,6 +908,26 @@
   }
 }
 
+inline uint32_t Class::NumDirectMethods() {
+  LengthPrefixedArray<ArtMethod>* arr = GetDirectMethodsPtrUnchecked();
+  return arr != nullptr ? arr->Length() : 0u;
+}
+
+inline uint32_t Class::NumVirtualMethods() {
+  LengthPrefixedArray<ArtMethod>* arr = GetVirtualMethodsPtrUnchecked();
+  return arr != nullptr ? arr->Length() : 0u;
+}
+
+inline uint32_t Class::NumInstanceFields() {
+  LengthPrefixedArray<ArtField>* arr = GetIFieldsPtrUnchecked();
+  return arr != nullptr ? arr->Length() : 0u;
+}
+
+inline uint32_t Class::NumStaticFields() {
+  LengthPrefixedArray<ArtField>* arr = GetSFieldsPtrUnchecked();
+  return arr != nullptr ? arr->Length() : 0u;
+}
+
 }  // namespace mirror
 }  // namespace art
 
diff --git a/runtime/mirror/class.h b/runtime/mirror/class.h
index d95bcd8..f138936 100644
--- a/runtime/mirror/class.h
+++ b/runtime/mirror/class.h
@@ -41,7 +41,7 @@
 class ArtMethod;
 struct ClassOffsets;
 template<class T> class Handle;
-template<class T> class Handle;
+template<typename T> class LengthPrefixedArray;
 class Signature;
 class StringPiece;
 template<size_t kNumReferences> class PACKED(4) StackHandleScope;
@@ -656,21 +656,15 @@
   // Also updates the dex_cache_strings_ variable from new_dex_cache.
   void SetDexCache(DexCache* new_dex_cache) SHARED_REQUIRES(Locks::mutator_lock_);
 
-  ALWAYS_INLINE StrideIterator<ArtMethod> DirectMethodsBegin(size_t pointer_size)
-      SHARED_REQUIRES(Locks::mutator_lock_);
-
-  ALWAYS_INLINE StrideIterator<ArtMethod> DirectMethodsEnd(size_t pointer_size)
-      SHARED_REQUIRES(Locks::mutator_lock_);
-
   ALWAYS_INLINE IterationRange<StrideIterator<ArtMethod>> GetDirectMethods(size_t pointer_size)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  ArtMethod* GetDirectMethodsPtr() SHARED_REQUIRES(Locks::mutator_lock_);
+  LengthPrefixedArray<ArtMethod>* GetDirectMethodsPtr() SHARED_REQUIRES(Locks::mutator_lock_);
 
-  void SetDirectMethodsPtr(ArtMethod* new_direct_methods)
+  void SetDirectMethodsPtr(LengthPrefixedArray<ArtMethod>* new_direct_methods)
       SHARED_REQUIRES(Locks::mutator_lock_);
   // Used by image writer.
-  void SetDirectMethodsPtrUnchecked(ArtMethod* new_direct_methods)
+  void SetDirectMethodsPtrUnchecked(LengthPrefixedArray<ArtMethod>* new_direct_methods)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   ALWAYS_INLINE ArtMethod* GetDirectMethod(size_t i, size_t pointer_size)
@@ -683,35 +677,20 @@
         SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Returns the number of static, private, and constructor methods.
-  ALWAYS_INLINE uint32_t NumDirectMethods() SHARED_REQUIRES(Locks::mutator_lock_) {
-    return GetField32(OFFSET_OF_OBJECT_MEMBER(Class, num_direct_methods_));
-  }
-  void SetNumDirectMethods(uint32_t num) SHARED_REQUIRES(Locks::mutator_lock_) {
-    return SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, num_direct_methods_), num);
-  }
+  ALWAYS_INLINE uint32_t NumDirectMethods() SHARED_REQUIRES(Locks::mutator_lock_);
 
   template<VerifyObjectFlags kVerifyFlags = kDefaultVerifyFlags>
-  ALWAYS_INLINE ArtMethod* GetVirtualMethodsPtr() SHARED_REQUIRES(Locks::mutator_lock_);
-
-  ALWAYS_INLINE StrideIterator<ArtMethod> VirtualMethodsBegin(size_t pointer_size)
-      SHARED_REQUIRES(Locks::mutator_lock_);
-
-  ALWAYS_INLINE StrideIterator<ArtMethod> VirtualMethodsEnd(size_t pointer_size)
+  ALWAYS_INLINE LengthPrefixedArray<ArtMethod>* GetVirtualMethodsPtr()
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   ALWAYS_INLINE IterationRange<StrideIterator<ArtMethod>> GetVirtualMethods(size_t pointer_size)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  void SetVirtualMethodsPtr(ArtMethod* new_virtual_methods)
+  void SetVirtualMethodsPtr(LengthPrefixedArray<ArtMethod>* new_virtual_methods)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Returns the number of non-inherited virtual methods.
-  ALWAYS_INLINE uint32_t NumVirtualMethods() SHARED_REQUIRES(Locks::mutator_lock_) {
-    return GetField32(OFFSET_OF_OBJECT_MEMBER(Class, num_virtual_methods_));
-  }
-  void SetNumVirtualMethods(uint32_t num) SHARED_REQUIRES(Locks::mutator_lock_) {
-    return SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, num_virtual_methods_), num);
-  }
+  ALWAYS_INLINE uint32_t NumVirtualMethods() SHARED_REQUIRES(Locks::mutator_lock_);
 
   template<VerifyObjectFlags kVerifyFlags = kDefaultVerifyFlags>
   ArtMethod* GetVirtualMethod(size_t i, size_t pointer_size)
@@ -859,21 +838,19 @@
   ALWAYS_INLINE void SetIfTable(IfTable* new_iftable) SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Get instance fields of the class (See also GetSFields).
-  ArtField* GetIFields() SHARED_REQUIRES(Locks::mutator_lock_);
+  LengthPrefixedArray<ArtField>* GetIFieldsPtr() SHARED_REQUIRES(Locks::mutator_lock_);
 
-  void SetIFields(ArtField* new_ifields) SHARED_REQUIRES(Locks::mutator_lock_);
+  ALWAYS_INLINE IterationRange<StrideIterator<ArtField>> GetIFields()
+      SHARED_REQUIRES(Locks::mutator_lock_);
+
+  void SetIFieldsPtr(LengthPrefixedArray<ArtField>* new_ifields)
+      SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Unchecked edition has no verification flags.
-  void SetIFieldsUnchecked(ArtField* new_sfields) SHARED_REQUIRES(Locks::mutator_lock_);
+  void SetIFieldsPtrUnchecked(LengthPrefixedArray<ArtField>* new_sfields)
+      SHARED_REQUIRES(Locks::mutator_lock_);
 
-  uint32_t NumInstanceFields() SHARED_REQUIRES(Locks::mutator_lock_) {
-    return GetField32(OFFSET_OF_OBJECT_MEMBER(Class, num_instance_fields_));
-  }
-
-  void SetNumInstanceFields(uint32_t num) SHARED_REQUIRES(Locks::mutator_lock_) {
-    return SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, num_instance_fields_), num);
-  }
-
+  uint32_t NumInstanceFields() SHARED_REQUIRES(Locks::mutator_lock_);
   ArtField* GetInstanceField(uint32_t i) SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Returns the number of instance fields containing reference types.
@@ -927,20 +904,18 @@
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Gets the static fields of the class.
-  ArtField* GetSFields() SHARED_REQUIRES(Locks::mutator_lock_);
+  LengthPrefixedArray<ArtField>* GetSFieldsPtr() SHARED_REQUIRES(Locks::mutator_lock_);
+  ALWAYS_INLINE IterationRange<StrideIterator<ArtField>> GetSFields()
+      SHARED_REQUIRES(Locks::mutator_lock_);
 
-  void SetSFields(ArtField* new_sfields) SHARED_REQUIRES(Locks::mutator_lock_);
+  void SetSFieldsPtr(LengthPrefixedArray<ArtField>* new_sfields)
+      SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Unchecked edition has no verification flags.
-  void SetSFieldsUnchecked(ArtField* new_sfields) SHARED_REQUIRES(Locks::mutator_lock_);
+  void SetSFieldsPtrUnchecked(LengthPrefixedArray<ArtField>* new_sfields)
+      SHARED_REQUIRES(Locks::mutator_lock_);
 
-  uint32_t NumStaticFields() SHARED_REQUIRES(Locks::mutator_lock_) {
-    return GetField32(OFFSET_OF_OBJECT_MEMBER(Class, num_static_fields_));
-  }
-
-  void SetNumStaticFields(uint32_t num) SHARED_REQUIRES(Locks::mutator_lock_) {
-    return SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, num_static_fields_), num);
-  }
+  uint32_t NumStaticFields() SHARED_REQUIRES(Locks::mutator_lock_);
 
   // TODO: uint16_t
   ArtField* GetStaticField(uint32_t i) SHARED_REQUIRES(Locks::mutator_lock_);
@@ -1129,10 +1104,10 @@
     return pointer_size;
   }
 
-  ALWAYS_INLINE ArtMethod* GetDirectMethodsPtrUnchecked()
+  ALWAYS_INLINE LengthPrefixedArray<ArtMethod>* GetDirectMethodsPtrUnchecked()
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  ALWAYS_INLINE ArtMethod* GetVirtualMethodsPtrUnchecked()
+  ALWAYS_INLINE LengthPrefixedArray<ArtMethod>* GetVirtualMethodsPtrUnchecked()
       SHARED_REQUIRES(Locks::mutator_lock_);
 
  private:
@@ -1154,8 +1129,12 @@
   void CheckObjectAlloc() SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Unchecked editions is for root visiting.
-  ArtField* GetSFieldsUnchecked() SHARED_REQUIRES(Locks::mutator_lock_);
-  ArtField* GetIFieldsUnchecked() SHARED_REQUIRES(Locks::mutator_lock_);
+  LengthPrefixedArray<ArtField>* GetSFieldsPtrUnchecked() SHARED_REQUIRES(Locks::mutator_lock_);
+  IterationRange<StrideIterator<ArtField>> GetSFieldsUnchecked()
+      SHARED_REQUIRES(Locks::mutator_lock_);
+  LengthPrefixedArray<ArtField>* GetIFieldsPtrUnchecked() SHARED_REQUIRES(Locks::mutator_lock_);
+  IterationRange<StrideIterator<ArtField>> GetIFieldsUnchecked()
+      SHARED_REQUIRES(Locks::mutator_lock_);
 
   bool ProxyDescriptorEquals(const char* match) SHARED_REQUIRES(Locks::mutator_lock_);
 
@@ -1216,7 +1195,7 @@
   // Note: Shuffled back.
   uint32_t access_flags_;
 
-  // static, private, and <init> methods. Pointer to an ArtMethod array.
+  // static, private, and <init> methods. Pointer to an ArtMethod length-prefixed array.
   uint64_t direct_methods_;
 
   // instance fields
@@ -1229,10 +1208,11 @@
   // ArtField arrays are allocated as an array of fields, and not an array of fields pointers.
   uint64_t ifields_;
 
-  // Static fields
+  // Static fields length-prefixed array.
   uint64_t sfields_;
 
-  // Virtual methods defined in this class; invoked through vtable. Pointer to an ArtMethod array.
+  // Virtual methods defined in this class; invoked through vtable. Pointer to an ArtMethod
+  // length-prefixed array.
   uint64_t virtual_methods_;
 
   // Total size of the Class instance; used when allocating storage on gc heap.
@@ -1250,24 +1230,12 @@
   // TODO: really 16bits
   int32_t dex_type_idx_;
 
-  // Number of direct fields.
-  uint32_t num_direct_methods_;
-
-  // Number of instance fields.
-  uint32_t num_instance_fields_;
-
   // Number of instance fields that are object refs.
   uint32_t num_reference_instance_fields_;
 
   // Number of static fields that are object refs,
   uint32_t num_reference_static_fields_;
 
-  // Number of static fields.
-  uint32_t num_static_fields_;
-
-  // Number of virtual methods.
-  uint32_t num_virtual_methods_;
-
   // Total object size; used when allocating storage on gc heap.
   // (For interfaces and abstract classes this will be zero.)
   // See also class_size_.
diff --git a/runtime/mirror/field.cc b/runtime/mirror/field.cc
index 02e4484..ff6847c 100644
--- a/runtime/mirror/field.cc
+++ b/runtime/mirror/field.cc
@@ -61,10 +61,10 @@
     DCHECK_EQ(declaring_class->NumStaticFields(), 2U);
     // 0 == Class[] interfaces; 1 == Class[][] throws;
     if (GetDexFieldIndex() == 0) {
-      return &declaring_class->GetSFields()[0];
+      return &declaring_class->GetSFieldsPtr()->At(0);
     } else {
       DCHECK_EQ(GetDexFieldIndex(), 1U);
-      return &declaring_class->GetSFields()[1];
+      return &declaring_class->GetSFieldsPtr()->At(1);
     }
   }
   mirror::DexCache* const dex_cache = declaring_class->GetDexCache();
diff --git a/runtime/mirror/object.cc b/runtime/mirror/object.cc
index 80decaa..87fb5ba 100644
--- a/runtime/mirror/object.cc
+++ b/runtime/mirror/object.cc
@@ -208,15 +208,13 @@
     return;
   }
   for (Class* cur = c; cur != nullptr; cur = cur->GetSuperClass()) {
-    ArtField* fields = cur->GetIFields();
-    for (size_t i = 0, count = cur->NumInstanceFields(); i < count; ++i) {
+    for (ArtField& field : cur->GetIFields()) {
       StackHandleScope<1> hs(Thread::Current());
       Handle<Object> h_object(hs.NewHandle(new_value));
-      ArtField* field = &fields[i];
-      if (field->GetOffset().Int32Value() == field_offset.Int32Value()) {
-        CHECK_NE(field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
+      if (field.GetOffset().Int32Value() == field_offset.Int32Value()) {
+        CHECK_NE(field.GetTypeAsPrimitiveType(), Primitive::kPrimNot);
         // TODO: resolve the field type for moving GC.
-        mirror::Class* field_type = field->GetType<!kMovingCollector>();
+        mirror::Class* field_type = field.GetType<!kMovingCollector>();
         if (field_type != nullptr) {
           CHECK(field_type->IsAssignableFrom(new_value->GetClass()));
         }
@@ -229,13 +227,11 @@
     return;
   }
   if (IsClass()) {
-    ArtField* fields = AsClass()->GetSFields();
-    for (size_t i = 0, count = AsClass()->NumStaticFields(); i < count; ++i) {
-      ArtField* field = &fields[i];
-      if (field->GetOffset().Int32Value() == field_offset.Int32Value()) {
-        CHECK_NE(field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
+    for (ArtField& field : AsClass()->GetSFields()) {
+      if (field.GetOffset().Int32Value() == field_offset.Int32Value()) {
+        CHECK_NE(field.GetTypeAsPrimitiveType(), Primitive::kPrimNot);
         // TODO: resolve the field type for moving GC.
-        mirror::Class* field_type = field->GetType<!kMovingCollector>();
+        mirror::Class* field_type = field.GetType<!kMovingCollector>();
         if (field_type != nullptr) {
           CHECK(field_type->IsAssignableFrom(new_value->GetClass()));
         }
diff --git a/runtime/native/dalvik_system_DexFile.cc b/runtime/native/dalvik_system_DexFile.cc
index 1b210bb..4f97d20 100644
--- a/runtime/native/dalvik_system_DexFile.cc
+++ b/runtime/native/dalvik_system_DexFile.cc
@@ -17,7 +17,6 @@
 #include "dalvik_system_DexFile.h"
 
 #include "base/logging.h"
-#include "base/out.h"
 #include "base/stl_util.h"
 #include "base/stringprintf.h"
 #include "class_linker.h"
@@ -165,8 +164,7 @@
   std::vector<std::unique_ptr<const DexFile>> dex_files;
   std::vector<std::string> error_msgs;
 
-  dex_files =
-      linker->OpenDexFilesFromOat(sourceName.c_str(), outputName.c_str(), outof(error_msgs));
+  dex_files = linker->OpenDexFilesFromOat(sourceName.c_str(), outputName.c_str(), &error_msgs);
 
   if (!dex_files.empty()) {
     jlongArray array = ConvertNativeToJavaArray(env, dex_files);
diff --git a/runtime/native/java_lang_Class.cc b/runtime/native/java_lang_Class.cc
index eddb2d1..1ca98e5 100644
--- a/runtime/native/java_lang_Class.cc
+++ b/runtime/native/java_lang_Class.cc
@@ -110,20 +110,18 @@
     Thread* self, mirror::Class* klass, bool public_only, bool force_resolve)
       SHARED_REQUIRES(Locks::mutator_lock_) {
   StackHandleScope<1> hs(self);
-  auto* ifields = klass->GetIFields();
-  auto* sfields = klass->GetSFields();
-  const auto num_ifields = klass->NumInstanceFields();
-  const auto num_sfields = klass->NumStaticFields();
-  size_t array_size = num_ifields + num_sfields;
+  IterationRange<StrideIterator<ArtField>> ifields = klass->GetIFields();
+  IterationRange<StrideIterator<ArtField>> sfields = klass->GetSFields();
+  size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
   if (public_only) {
     // Lets go subtract all the non public fields.
-    for (size_t i = 0; i < num_ifields; ++i) {
-      if (!ifields[i].IsPublic()) {
+    for (ArtField& field : ifields) {
+      if (!field.IsPublic()) {
         --array_size;
       }
     }
-    for (size_t i = 0; i < num_sfields; ++i) {
-      if (!sfields[i].IsPublic()) {
+    for (ArtField& field : sfields) {
+      if (!field.IsPublic()) {
         --array_size;
       }
     }
@@ -134,34 +132,32 @@
   if (object_array.Get() == nullptr) {
     return nullptr;
   }
-  for (size_t i = 0; i < num_ifields; ++i) {
-    auto* art_field = &ifields[i];
-    if (!public_only || art_field->IsPublic()) {
-      auto* field = mirror::Field::CreateFromArtField(self, art_field, force_resolve);
-      if (field == nullptr) {
+  for (ArtField& field : ifields) {
+    if (!public_only || field.IsPublic()) {
+      auto* reflect_field = mirror::Field::CreateFromArtField(self, &field, force_resolve);
+      if (reflect_field == nullptr) {
         if (kIsDebugBuild) {
           self->AssertPendingException();
         }
         // Maybe null due to OOME or type resolving exception.
         return nullptr;
       }
-      object_array->SetWithoutChecks<false>(array_idx++, field);
+      object_array->SetWithoutChecks<false>(array_idx++, reflect_field);
     }
   }
-  for (size_t i = 0; i < num_sfields; ++i) {
-    auto* art_field = &sfields[i];
-    if (!public_only || art_field->IsPublic()) {
-      auto* field = mirror::Field::CreateFromArtField(self, art_field, force_resolve);
-      if (field == nullptr) {
+  for (ArtField& field : sfields) {
+    if (!public_only || field.IsPublic()) {
+      auto* reflect_field = mirror::Field::CreateFromArtField(self, &field, force_resolve);
+      if (reflect_field == nullptr) {
         if (kIsDebugBuild) {
           self->AssertPendingException();
         }
         return nullptr;
       }
-      object_array->SetWithoutChecks<false>(array_idx++, field);
+      object_array->SetWithoutChecks<false>(array_idx++, reflect_field);
     }
   }
-  CHECK_EQ(array_idx, array_size);
+  DCHECK_EQ(array_idx, array_size);
   return object_array.Get();
 }
 
@@ -188,16 +184,19 @@
 // the dex cache for lookups? I think CompareModifiedUtf8ToUtf16AsCodePointValues should be fairly
 // fast.
 ALWAYS_INLINE static inline ArtField* FindFieldByName(
-    Thread* self ATTRIBUTE_UNUSED, mirror::String* name, ArtField* fields, size_t num_fields)
+    Thread* self ATTRIBUTE_UNUSED, mirror::String* name, LengthPrefixedArray<ArtField>* fields)
     SHARED_REQUIRES(Locks::mutator_lock_) {
+  if (fields == nullptr) {
+    return nullptr;
+  }
   size_t low = 0;
-  size_t high = num_fields;
+  size_t high = fields->Length();
   const uint16_t* const data = name->GetValue();
   const size_t length = name->GetLength();
   while (low < high) {
     auto mid = (low + high) / 2;
-    ArtField* const field = &fields[mid];
-    int result = CompareModifiedUtf8ToUtf16AsCodePointValues(field->GetName(), data, length);
+    ArtField& field = fields->At(mid);
+    int result = CompareModifiedUtf8ToUtf16AsCodePointValues(field.GetName(), data, length);
     // Alternate approach, only a few % faster at the cost of more allocations.
     // int result = field->GetStringName(self, true)->CompareTo(name);
     if (result < 0) {
@@ -205,12 +204,12 @@
     } else if (result > 0) {
       high = mid;
     } else {
-      return field;
+      return &field;
     }
   }
   if (kIsDebugBuild) {
-    for (size_t i = 0; i < num_fields; ++i) {
-      CHECK_NE(fields[i].GetName(), name->ToModifiedUtf8());
+    for (ArtField& field : MakeIterationRangeFromLengthPrefixedArray(fields, sizeof(ArtField))) {
+      CHECK_NE(field.GetName(), name->ToModifiedUtf8());
     }
   }
   return nullptr;
@@ -219,13 +218,11 @@
 ALWAYS_INLINE static inline mirror::Field* GetDeclaredField(
     Thread* self, mirror::Class* c, mirror::String* name)
     SHARED_REQUIRES(Locks::mutator_lock_) {
-  auto* instance_fields = c->GetIFields();
-  auto* art_field = FindFieldByName(self, name, instance_fields, c->NumInstanceFields());
+  ArtField* art_field = FindFieldByName(self, name, c->GetIFieldsPtr());
   if (art_field != nullptr) {
     return mirror::Field::CreateFromArtField(self, art_field, true);
   }
-  auto* static_fields = c->GetSFields();
-  art_field = FindFieldByName(self, name, static_fields, c->NumStaticFields());
+  art_field = FindFieldByName(self, name, c->GetSFieldsPtr());
   if (art_field != nullptr) {
     return mirror::Field::CreateFromArtField(self, art_field, true);
   }
diff --git a/runtime/native/java_lang_Thread.cc b/runtime/native/java_lang_Thread.cc
index b40d94a..7118f36 100644
--- a/runtime/native/java_lang_Thread.cc
+++ b/runtime/native/java_lang_Thread.cc
@@ -90,7 +90,7 @@
     case kWaitingInMainSignalCatcherLoop: return kJavaWaiting;
     case kWaitingForMethodTracingStart:   return kJavaWaiting;
     case kWaitingForVisitObjects:         return kJavaWaiting;
-    case kWaitingWeakRootRead:            return kJavaWaiting;
+    case kWaitingWeakGcRootRead:          return kJavaWaiting;
     case kSuspended:                      return kJavaRunnable;
     // Don't add a 'default' here so the compiler can spot incompatible enum changes.
   }
diff --git a/runtime/native/java_lang_VMClassLoader.cc b/runtime/native/java_lang_VMClassLoader.cc
index 62a0b76..1515630 100644
--- a/runtime/native/java_lang_VMClassLoader.cc
+++ b/runtime/native/java_lang_VMClassLoader.cc
@@ -16,7 +16,6 @@
 
 #include "java_lang_VMClassLoader.h"
 
-#include "base/out.h"
 #include "class_linker.h"
 #include "jni_internal.h"
 #include "mirror/class_loader.h"
@@ -46,7 +45,7 @@
     // Try the common case.
     StackHandleScope<1> hs(soa.Self());
     cl->FindClassInPathClassLoader(soa, soa.Self(), descriptor.c_str(), descriptor_hash,
-                                   hs.NewHandle(loader), outof(c));
+                                   hs.NewHandle(loader), &c);
     if (c != nullptr) {
       return soa.AddLocalReference<jclass>(c);
     }
diff --git a/runtime/oat_file.cc b/runtime/oat_file.cc
index 80fc7fa..a23d94d 100644
--- a/runtime/oat_file.cc
+++ b/runtime/oat_file.cc
@@ -32,7 +32,6 @@
 #endif
 
 #include "art_method-inl.h"
-#include "base/out.h"
 #include "base/bit_vector.h"
 #include "base/stl_util.h"
 #include "base/unix_file/fd_file.h"
@@ -89,16 +88,16 @@
 OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
                                   const std::string& location,
                                   const char* abs_dex_location,
-                                  out<std::string> error_msg) {
+                                  std::string* error_msg) {
   std::unique_ptr<OatFile> oat_file(new OatFile(location, false));
   oat_file->elf_file_.reset(elf_file);
   uint64_t offset, size;
-  bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", outof(offset), outof(size));
+  bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
   CHECK(has_section);
   oat_file->begin_ = elf_file->Begin() + offset;
   oat_file->end_ = elf_file->Begin() + size + offset;
   // Ignore the optional .bss section when opening non-executable.
-  return oat_file->Setup(abs_dex_location, outof_forward(error_msg)) ? oat_file.release() : nullptr;
+  return oat_file->Setup(abs_dex_location, error_msg) ? oat_file.release() : nullptr;
 }
 
 OatFile* OatFile::Open(const std::string& filename,
@@ -107,7 +106,7 @@
                        uint8_t* oat_file_begin,
                        bool executable,
                        const char* abs_dex_location,
-                       out<std::string> error_msg) {
+                       std::string* error_msg) {
   CHECK(!filename.empty()) << location;
   CheckLocation(location);
   std::unique_ptr<OatFile> ret;
@@ -155,34 +154,27 @@
   return ret.release();
 }
 
-OatFile* OatFile::OpenWritable(File* file,
-                               const std::string& location,
+OatFile* OatFile::OpenWritable(File* file, const std::string& location,
                                const char* abs_dex_location,
-                               out<std::string> error_msg) {
+                               std::string* error_msg) {
   CheckLocation(location);
-  return OpenElfFile(file, location, nullptr, nullptr, true, false, abs_dex_location,
-                     outof_forward(error_msg));
+  return OpenElfFile(file, location, nullptr, nullptr, true, false, abs_dex_location, error_msg);
 }
 
-OatFile* OatFile::OpenReadable(File* file,
-                               const std::string& location,
+OatFile* OatFile::OpenReadable(File* file, const std::string& location,
                                const char* abs_dex_location,
-                               out<std::string> error_msg) {
+                               std::string* error_msg) {
   CheckLocation(location);
-  return OpenElfFile(file, location, nullptr, nullptr, false, false, abs_dex_location,
-                     outof_forward(error_msg));
+  return OpenElfFile(file, location, nullptr, nullptr, false, false, abs_dex_location, error_msg);
 }
 
 OatFile* OatFile::OpenDlopen(const std::string& elf_filename,
                              const std::string& location,
                              uint8_t* requested_base,
                              const char* abs_dex_location,
-                             out<std::string> error_msg) {
+                             std::string* error_msg) {
   std::unique_ptr<OatFile> oat_file(new OatFile(location, true));
-  bool success = oat_file->Dlopen(elf_filename,
-                                  requested_base,
-                                  abs_dex_location,
-                                  outof_forward(error_msg));
+  bool success = oat_file->Dlopen(elf_filename, requested_base, abs_dex_location, error_msg);
   if (!success) {
     return nullptr;
   }
@@ -196,10 +188,10 @@
                               bool writable,
                               bool executable,
                               const char* abs_dex_location,
-                              out<std::string> error_msg) {
+                              std::string* error_msg) {
   std::unique_ptr<OatFile> oat_file(new OatFile(location, executable));
   bool success = oat_file->ElfFileOpen(file, requested_base, oat_file_begin, writable, executable,
-                                       abs_dex_location, outof_forward(error_msg));
+                                       abs_dex_location, error_msg);
   if (!success) {
     CHECK(!error_msg->empty());
     return nullptr;
@@ -208,13 +200,8 @@
 }
 
 OatFile::OatFile(const std::string& location, bool is_executable)
-    : location_(location),
-      begin_(nullptr),
-      end_(nullptr),
-      bss_begin_(nullptr),
-      bss_end_(nullptr),
-      is_executable_(is_executable),
-      dlopen_handle_(nullptr),
+    : location_(location), begin_(nullptr), end_(nullptr), bss_begin_(nullptr), bss_end_(nullptr),
+      is_executable_(is_executable), dlopen_handle_(nullptr),
       secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
   CHECK(!location_.empty());
 }
@@ -226,10 +213,8 @@
   }
 }
 
-bool OatFile::Dlopen(const std::string& elf_filename,
-                     uint8_t* requested_base,
-                     const char* abs_dex_location,
-                     out<std::string> error_msg) {
+bool OatFile::Dlopen(const std::string& elf_filename, uint8_t* requested_base,
+                     const char* abs_dex_location, std::string* error_msg) {
 #ifdef __APPLE__
   // The dl_iterate_phdr syscall is missing.  There is similar API on OSX,
   // but let's fallback to the custom loading code for the time being.
@@ -334,28 +319,22 @@
     LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but can not find its mmaps.";
   }
 
-  return Setup(abs_dex_location, outof_forward(error_msg));
+  return Setup(abs_dex_location, error_msg);
 #endif  // __APPLE__
 }
 
-bool OatFile::ElfFileOpen(File* file,
-                          uint8_t* requested_base,
-                          uint8_t* oat_file_begin,
-                          bool writable,
-                          bool executable,
+bool OatFile::ElfFileOpen(File* file, uint8_t* requested_base, uint8_t* oat_file_begin,
+                          bool writable, bool executable,
                           const char* abs_dex_location,
-                          out<std::string> error_msg) {
+                          std::string* error_msg) {
   // TODO: rename requested_base to oat_data_begin
-  elf_file_.reset(ElfFile::Open(file,
-                                writable,
-                                /*program_header_only*/true,
-                                outof_forward(error_msg),
+  elf_file_.reset(ElfFile::Open(file, writable, /*program_header_only*/true, error_msg,
                                 oat_file_begin));
   if (elf_file_ == nullptr) {
     DCHECK(!error_msg->empty());
     return false;
   }
-  bool loaded = elf_file_->Load(executable, outof_forward(error_msg));
+  bool loaded = elf_file_->Load(executable, error_msg);
   if (!loaded) {
     DCHECK(!error_msg->empty());
     return false;
@@ -396,10 +375,10 @@
     bss_end_ += sizeof(uint32_t);
   }
 
-  return Setup(abs_dex_location, outof_forward(error_msg));
+  return Setup(abs_dex_location, error_msg);
 }
 
-bool OatFile::Setup(const char* abs_dex_location, out<std::string> error_msg) {
+bool OatFile::Setup(const char* abs_dex_location, std::string* error_msg) {
   if (!GetOatHeader().IsValid()) {
     std::string cause = GetOatHeader().GetValidationErrorMessage();
     *error_msg = StringPrintf("Invalid oat header for '%s': %s", GetLocation().c_str(),
@@ -638,9 +617,9 @@
   return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
 }
 
-std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(out<std::string> error_msg) const {
+std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
   return DexFile::Open(dex_file_pointer_, FileSize(), dex_file_location_,
-                       dex_file_location_checksum_, this, outof_forward(error_msg));
+                       dex_file_location_checksum_, this, error_msg);
 }
 
 uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
@@ -798,7 +777,7 @@
   return out.str();
 }
 
-bool OatFile::CheckStaticDexFileDependencies(const char* dex_dependencies, out<std::string> msg) {
+bool OatFile::CheckStaticDexFileDependencies(const char* dex_dependencies, std::string* msg) {
   if (dex_dependencies == nullptr || dex_dependencies[0] == 0) {
     // No dependencies.
     return true;
@@ -807,7 +786,7 @@
   // Assumption: this is not performance-critical. So it's OK to do this with a std::string and
   //             Split() instead of manual parsing of the combined char*.
   std::vector<std::string> split;
-  Split(dex_dependencies, kDexClassPathEncodingSeparator, outof(split));
+  Split(dex_dependencies, kDexClassPathEncodingSeparator, &split);
   if (split.size() % 2 != 0) {
     // Expected pairs of location and checksum.
     *msg = StringPrintf("Odd number of elements in dependency list %s", dex_dependencies);
@@ -827,8 +806,8 @@
     uint32_t dex_checksum;
     std::string error_msg;
     if (DexFile::GetChecksum(DexFile::GetDexCanonicalLocation(location.c_str()).c_str(),
-                             outof(dex_checksum),
-                             outof(error_msg))) {
+                             &dex_checksum,
+                             &error_msg)) {
       if (converted != dex_checksum) {
         *msg = StringPrintf("Checksums don't match for %s: %" PRId64 " vs %u",
                             location.c_str(), converted, dex_checksum);
@@ -847,7 +826,8 @@
 }
 
 bool OatFile::GetDexLocationsFromDependencies(const char* dex_dependencies,
-                                              out<std::vector<std::string>> locations) {
+                                              std::vector<std::string>* locations) {
+  DCHECK(locations != nullptr);
   if (dex_dependencies == nullptr || dex_dependencies[0] == 0) {
     return true;
   }
@@ -855,7 +835,7 @@
   // Assumption: this is not performance-critical. So it's OK to do this with a std::string and
   //             Split() instead of manual parsing of the combined char*.
   std::vector<std::string> split;
-  Split(dex_dependencies, kDexClassPathEncodingSeparator, outof(split));
+  Split(dex_dependencies, kDexClassPathEncodingSeparator, &split);
   if (split.size() % 2 != 0) {
     // Expected pairs of location and checksum.
     return false;
diff --git a/runtime/oat_file.h b/runtime/oat_file.h
index 6c40c68..27f8677 100644
--- a/runtime/oat_file.h
+++ b/runtime/oat_file.h
@@ -22,7 +22,6 @@
 #include <vector>
 
 #include "base/mutex.h"
-#include "base/out_fwd.h"
 #include "base/stringpiece.h"
 #include "dex_file.h"
 #include "invoke_type.h"
@@ -46,10 +45,9 @@
 
   // Opens an oat file contained within the given elf file. This is always opened as
   // non-executable at the moment.
-  static OatFile* OpenWithElfFile(ElfFile* elf_file,
-                                  const std::string& location,
+  static OatFile* OpenWithElfFile(ElfFile* elf_file, const std::string& location,
                                   const char* abs_dex_location,
-                                  out<std::string> error_msg);
+                                  std::string* error_msg);
   // Open an oat file. Returns null on failure.  Requested base can
   // optionally be used to request where the file should be loaded.
   // See the ResolveRelativeEncodedDexLocation for a description of how the
@@ -60,22 +58,20 @@
                        uint8_t* oat_file_begin,
                        bool executable,
                        const char* abs_dex_location,
-                       out<std::string> error_msg);
+                       std::string* error_msg);
 
   // Open an oat file from an already opened File.
   // Does not use dlopen underneath so cannot be used for runtime use
   // where relocations may be required. Currently used from
   // ImageWriter which wants to open a writable version from an existing
   // file descriptor for patching.
-  static OatFile* OpenWritable(File* file,
-                               const std::string& location,
+  static OatFile* OpenWritable(File* file, const std::string& location,
                                const char* abs_dex_location,
-                               out<std::string> error_msg);
+                               std::string* error_msg);
   // Opens an oat file from an already opened File. Maps it PROT_READ, MAP_PRIVATE.
-  static OatFile* OpenReadable(File* file,
-                               const std::string& location,
+  static OatFile* OpenReadable(File* file, const std::string& location,
                                const char* abs_dex_location,
-                               out<std::string> error_msg);
+                               std::string* error_msg);
 
   ~OatFile();
 
@@ -256,13 +252,12 @@
 
   // Check the given dependency list against their dex files - thus the name "Static," this does
   // not check the class-loader environment, only whether there have been file updates.
-  static bool CheckStaticDexFileDependencies(const char* dex_dependencies,
-                                             out<std::string> error_msg);
+  static bool CheckStaticDexFileDependencies(const char* dex_dependencies, std::string* msg);
 
   // Get the dex locations of a dependency list. Note: this is *not* cleaned for synthetic
   // locations of multidex files.
   static bool GetDexLocationsFromDependencies(const char* dex_dependencies,
-                                              out<std::vector<std::string>> locations);
+                                              std::vector<std::string>* locations);
 
  private:
   static void CheckLocation(const std::string& location);
@@ -271,7 +266,7 @@
                              const std::string& location,
                              uint8_t* requested_base,
                              const char* abs_dex_location,
-                             out<std::string> error_msg);
+                             std::string* error_msg);
 
   static OatFile* OpenElfFile(File* file,
                               const std::string& location,
@@ -280,22 +275,18 @@
                               bool writable,
                               bool executable,
                               const char* abs_dex_location,
-                              out<std::string> error_msg);
+                              std::string* error_msg);
 
   explicit OatFile(const std::string& filename, bool executable);
-  bool Dlopen(const std::string& elf_filename,
-              uint8_t* requested_base,
-              const char* abs_dex_location,
-              out<std::string> error_msg);
-  bool ElfFileOpen(File* file,
-                   uint8_t* requested_base,
+  bool Dlopen(const std::string& elf_filename, uint8_t* requested_base,
+              const char* abs_dex_location, std::string* error_msg);
+  bool ElfFileOpen(File* file, uint8_t* requested_base,
                    uint8_t* oat_file_begin,  // Override where the file is loaded to if not null
-                   bool writable,
-                   bool executable,
+                   bool writable, bool executable,
                    const char* abs_dex_location,
-                   out<std::string> error_msg);
+                   std::string* error_msg);
 
-  bool Setup(const char* abs_dex_location, out<std::string> error_msg);
+  bool Setup(const char* abs_dex_location, std::string* error_msg);
 
   // The oat file name.
   //
@@ -374,7 +365,7 @@
 class OatDexFile FINAL {
  public:
   // Opens the DexFile referred to by this OatDexFile from within the containing OatFile.
-  std::unique_ptr<const DexFile> OpenDexFile(out<std::string> error_msg) const;
+  std::unique_ptr<const DexFile> OpenDexFile(std::string* error_msg) const;
 
   const OatFile* GetOatFile() const {
     return oat_file_;
diff --git a/runtime/oat_file_assistant.cc b/runtime/oat_file_assistant.cc
index e919b36..29b879e 100644
--- a/runtime/oat_file_assistant.cc
+++ b/runtime/oat_file_assistant.cc
@@ -29,7 +29,6 @@
 #include <set>
 
 #include "base/logging.h"
-#include "base/out.h"
 #include "base/stringprintf.h"
 #include "class_linker.h"
 #include "gc/heap.h"
@@ -231,7 +230,7 @@
     return std::vector<std::unique_ptr<const DexFile>>();
   }
 
-  std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(outof(error_msg));
+  std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
   if (dex_file.get() == nullptr) {
     LOG(WARNING) << "Failed to open dex file from oat dex file: " << error_msg;
     return std::vector<std::unique_ptr<const DexFile>>();
@@ -247,7 +246,7 @@
       break;
     }
 
-    dex_file = oat_dex_file->OpenDexFile(outof(error_msg));
+    dex_file = oat_dex_file->OpenDexFile(&error_msg);
     if (dex_file.get() == nullptr) {
       LOG(WARNING) << "Failed to open dex file from oat dex file: " << error_msg;
       return std::vector<std::unique_ptr<const DexFile>>();
@@ -272,7 +271,7 @@
 
     std::string error_msg;
     cached_odex_file_name_found_ = DexFilenameToOdexFilename(
-        dex_location_, isa_, &cached_odex_file_name_, outof(error_msg));
+        dex_location_, isa_, &cached_odex_file_name_, &error_msg);
     if (!cached_odex_file_name_found_) {
       // If we can't figure out the odex file, we treat it as if the odex
       // file was inaccessible.
@@ -340,7 +339,7 @@
         DalvikCacheDirectory().c_str(), GetInstructionSetString(isa_));
     std::string error_msg;
     cached_oat_file_name_found_ = GetDalvikCacheFilename(dex_location_,
-        cache_dir.c_str(), &cached_oat_file_name_, outof(error_msg));
+        cache_dir.c_str(), &cached_oat_file_name_, &error_msg);
     if (!cached_oat_file_name_found_) {
       // If we can't determine the oat file name, we treat the oat file as
       // inaccessible.
@@ -433,7 +432,7 @@
     std::string error_msg;
     uint32_t expected_secondary_checksum = 0;
     if (DexFile::GetChecksum(secondary_dex_location.c_str(),
-          &expected_secondary_checksum, outof(error_msg))) {
+          &expected_secondary_checksum, &error_msg)) {
       uint32_t actual_secondary_checksum
         = secondary_oat_dex_file->GetDexFileLocationChecksum();
       if (expected_secondary_checksum != actual_secondary_checksum) {
@@ -723,7 +722,7 @@
   if (runtime->IsDebuggable()) {
     argv.push_back("--debuggable");
   }
-  runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(outof(argv));
+  runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
 
   if (!runtime->IsVerificationEnabled()) {
     argv.push_back("--compiler-filter=verify-none");
@@ -874,7 +873,7 @@
       std::string error_msg;
       cached_odex_file_.reset(OatFile::Open(odex_file_name.c_str(),
             odex_file_name.c_str(), nullptr, nullptr, load_executable_,
-            dex_location_, outof(error_msg)));
+            dex_location_, &error_msg));
       if (cached_odex_file_.get() == nullptr) {
         VLOG(oat) << "OatFileAssistant test for existing pre-compiled oat file "
           << odex_file_name << ": " << error_msg;
@@ -905,7 +904,7 @@
       std::string error_msg;
       cached_oat_file_.reset(OatFile::Open(oat_file_name.c_str(),
             oat_file_name.c_str(), nullptr, nullptr, load_executable_,
-            dex_location_, outof(error_msg)));
+            dex_location_, &error_msg));
       if (cached_oat_file_.get() == nullptr) {
         VLOG(oat) << "OatFileAssistant test for existing oat file "
           << oat_file_name << ": " << error_msg;
diff --git a/runtime/oat_file_assistant_test.cc b/runtime/oat_file_assistant_test.cc
index 4a0de59..03ad2d5 100644
--- a/runtime/oat_file_assistant_test.cc
+++ b/runtime/oat_file_assistant_test.cc
@@ -26,7 +26,6 @@
 #include <gtest/gtest.h>
 
 #include "art_field-inl.h"
-#include "base/out.h"
 #include "class_linker-inl.h"
 #include "common_runtime_test.h"
 #include "compiler_callbacks.h"
@@ -88,7 +87,7 @@
       << "Expected dex file to be at: " << GetDexSrc1();
     ASSERT_TRUE(OS::FileExists(GetStrippedDexSrc1().c_str()))
       << "Expected stripped dex file to be at: " << GetStrippedDexSrc1();
-    ASSERT_FALSE(DexFile::GetChecksum(GetStrippedDexSrc1().c_str(), &checksum, outof(error_msg)))
+    ASSERT_FALSE(DexFile::GetChecksum(GetStrippedDexSrc1().c_str(), &checksum, &error_msg))
       << "Expected stripped dex file to be stripped: " << GetStrippedDexSrc1();
     ASSERT_TRUE(OS::FileExists(GetDexSrc2().c_str()))
       << "Expected dex file to be at: " << GetDexSrc2();
@@ -97,12 +96,12 @@
     // GetMultiDexSrc1, but a different secondary dex checksum.
     std::vector<std::unique_ptr<const DexFile>> multi1;
     ASSERT_TRUE(DexFile::Open(GetMultiDexSrc1().c_str(),
-          GetMultiDexSrc1().c_str(), outof(error_msg), &multi1)) << error_msg;
+          GetMultiDexSrc1().c_str(), &error_msg, &multi1)) << error_msg;
     ASSERT_GT(multi1.size(), 1u);
 
     std::vector<std::unique_ptr<const DexFile>> multi2;
     ASSERT_TRUE(DexFile::Open(GetMultiDexSrc2().c_str(),
-          GetMultiDexSrc2().c_str(), outof(error_msg), &multi2)) << error_msg;
+          GetMultiDexSrc2().c_str(), &error_msg, &multi2)) << error_msg;
     ASSERT_GT(multi2.size(), 1u);
 
     ASSERT_EQ(multi1[0]->GetLocationChecksum(), multi2[0]->GetLocationChecksum());
@@ -232,13 +231,13 @@
     args.push_back("--runtime-arg");
     args.push_back("-Xnorelocate");
     std::string error_msg;
-    ASSERT_TRUE(OatFileAssistant::Dex2Oat(args, outof(error_msg))) << error_msg;
+    ASSERT_TRUE(OatFileAssistant::Dex2Oat(args, &error_msg)) << error_msg;
     setenv("ANDROID_DATA", android_data_.c_str(), 1);
 
     // Verify the odex file was generated as expected.
     std::unique_ptr<OatFile> odex_file(OatFile::Open(
         odex_location.c_str(), odex_location.c_str(), nullptr, nullptr,
-        false, dex_location.c_str(), outof(error_msg)));
+        false, dex_location.c_str(), &error_msg));
     ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
 
     if (!pic) {
@@ -284,7 +283,7 @@
       image_reservation_.push_back(std::unique_ptr<MemMap>(
           MemMap::MapAnonymous("image reservation",
               reinterpret_cast<uint8_t*>(start), end - start,
-              PROT_NONE, false, false, outof(error_msg))));
+              PROT_NONE, false, false, &error_msg)));
       ASSERT_TRUE(image_reservation_.back().get() != nullptr) << error_msg;
       LOG(INFO) << "Reserved space for image " <<
         reinterpret_cast<void*>(image_reservation_.back()->Begin()) << "-" <<
@@ -319,7 +318,7 @@
   OatFileAssistant oat_file_assistant(dex_location, kRuntimeISA, false);
 
   std::string error_msg;
-  ASSERT_TRUE(oat_file_assistant.GenerateOatFile(outof(error_msg))) << error_msg;
+  ASSERT_TRUE(oat_file_assistant.GenerateOatFile(&error_msg)) << error_msg;
 }
 
 // Case: We have a DEX file, but no OAT file for it.
@@ -358,7 +357,7 @@
 
   // Trying to make the oat file up to date should not fail or crash.
   std::string error_msg;
-  EXPECT_TRUE(oat_file_assistant.MakeUpToDate(outof(error_msg)));
+  EXPECT_TRUE(oat_file_assistant.MakeUpToDate(&error_msg));
 
   // Trying to get the best oat file should fail, but not crash.
   std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
@@ -442,7 +441,7 @@
   args.push_back("--oat-file=" + oat_location);
 
   std::string error_msg;
-  ASSERT_TRUE(OatFileAssistant::Dex2Oat(args, outof(error_msg))) << error_msg;
+  ASSERT_TRUE(OatFileAssistant::Dex2Oat(args, &error_msg)) << error_msg;
 
   // Verify we can load both dex files.
   OatFileAssistant oat_file_assistant(dex_location.c_str(),
@@ -541,7 +540,7 @@
 
   // Make the oat file up to date.
   std::string error_msg;
-  ASSERT_TRUE(oat_file_assistant.MakeUpToDate(outof(error_msg))) << error_msg;
+  ASSERT_TRUE(oat_file_assistant.MakeUpToDate(&error_msg)) << error_msg;
 
   EXPECT_EQ(OatFileAssistant::kNoDexOptNeeded, oat_file_assistant.GetDexOptNeeded());
 
@@ -597,7 +596,7 @@
 
   // Make the oat file up to date.
   std::string error_msg;
-  ASSERT_TRUE(oat_file_assistant.MakeUpToDate(outof(error_msg))) << error_msg;
+  ASSERT_TRUE(oat_file_assistant.MakeUpToDate(&error_msg)) << error_msg;
 
   EXPECT_EQ(OatFileAssistant::kNoDexOptNeeded, oat_file_assistant.GetDexOptNeeded());
 
@@ -645,7 +644,7 @@
 
   // Make the oat file up to date. This should have no effect.
   std::string error_msg;
-  EXPECT_TRUE(oat_file_assistant.MakeUpToDate(outof(error_msg))) << error_msg;
+  EXPECT_TRUE(oat_file_assistant.MakeUpToDate(&error_msg)) << error_msg;
 
   EXPECT_EQ(OatFileAssistant::kNoDexOptNeeded, oat_file_assistant.GetDexOptNeeded());
 
@@ -689,7 +688,7 @@
 
   // Make the oat file up to date.
   std::string error_msg;
-  ASSERT_TRUE(oat_file_assistant.MakeUpToDate(outof(error_msg))) << error_msg;
+  ASSERT_TRUE(oat_file_assistant.MakeUpToDate(&error_msg)) << error_msg;
 
   EXPECT_EQ(OatFileAssistant::kNoDexOptNeeded, oat_file_assistant.GetDexOptNeeded());
 
@@ -830,7 +829,7 @@
   OatFileAssistant oat_file_assistant(
       dex_location.c_str(), oat_location.c_str(), kRuntimeISA, true);
   std::string error_msg;
-  ASSERT_TRUE(oat_file_assistant.MakeUpToDate(outof(error_msg))) << error_msg;
+  ASSERT_TRUE(oat_file_assistant.MakeUpToDate(&error_msg)) << error_msg;
 
   std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
   ASSERT_TRUE(oat_file.get() != nullptr);
@@ -920,7 +919,7 @@
 
   // Trying to make it up to date should have no effect.
   std::string error_msg;
-  EXPECT_TRUE(oat_file_assistant.MakeUpToDate(outof(error_msg)));
+  EXPECT_TRUE(oat_file_assistant.MakeUpToDate(&error_msg));
   EXPECT_TRUE(error_msg.empty());
 }
 
@@ -959,9 +958,7 @@
     ClassLinker* linker = Runtime::Current()->GetClassLinker();
     std::vector<std::unique_ptr<const DexFile>> dex_files;
     std::vector<std::string> error_msgs;
-    dex_files = linker->OpenDexFilesFromOat(dex_location_.c_str(),
-                                            oat_location_.c_str(),
-                                            outof(error_msgs));
+    dex_files = linker->OpenDexFilesFromOat(dex_location_.c_str(), oat_location_.c_str(), &error_msgs);
     CHECK(!dex_files.empty()) << Join(error_msgs, '\n');
     CHECK(dex_files[0]->GetOatDexFile() != nullptr) << dex_files[0]->GetLocation();
     loaded_oat_file_ = dex_files[0]->GetOatDexFile()->GetOatFile();
@@ -1058,17 +1055,17 @@
   std::string odex_file;
 
   EXPECT_TRUE(OatFileAssistant::DexFilenameToOdexFilename(
-        "/foo/bar/baz.jar", kArm, &odex_file, outof(error_msg))) << error_msg;
+        "/foo/bar/baz.jar", kArm, &odex_file, &error_msg)) << error_msg;
   EXPECT_EQ("/foo/bar/oat/arm/baz.odex", odex_file);
 
   EXPECT_TRUE(OatFileAssistant::DexFilenameToOdexFilename(
-        "/foo/bar/baz.funnyext", kArm, &odex_file, outof(error_msg))) << error_msg;
+        "/foo/bar/baz.funnyext", kArm, &odex_file, &error_msg)) << error_msg;
   EXPECT_EQ("/foo/bar/oat/arm/baz.odex", odex_file);
 
   EXPECT_FALSE(OatFileAssistant::DexFilenameToOdexFilename(
-        "nopath.jar", kArm, &odex_file, outof(error_msg)));
+        "nopath.jar", kArm, &odex_file, &error_msg));
   EXPECT_FALSE(OatFileAssistant::DexFilenameToOdexFilename(
-        "/foo/bar/baz_noext", kArm, &odex_file, outof(error_msg)));
+        "/foo/bar/baz_noext", kArm, &odex_file, &error_msg));
 }
 
 // Verify the dexopt status values from dalvik.system.DexFile
diff --git a/runtime/oat_file_test.cc b/runtime/oat_file_test.cc
index 3bd6df2..a88553c 100644
--- a/runtime/oat_file_test.cc
+++ b/runtime/oat_file_test.cc
@@ -20,7 +20,6 @@
 
 #include <gtest/gtest.h>
 
-#include "base/out.h"
 #include "common_runtime_test.h"
 #include "scoped_thread_state_change.h"
 
@@ -76,16 +75,16 @@
   std::string error_msg;
 
   // No dependencies.
-  EXPECT_TRUE(OatFile::CheckStaticDexFileDependencies(nullptr, outof(error_msg))) << error_msg;
-  EXPECT_TRUE(OatFile::CheckStaticDexFileDependencies("", outof(error_msg))) << error_msg;
+  EXPECT_TRUE(OatFile::CheckStaticDexFileDependencies(nullptr, &error_msg)) << error_msg;
+  EXPECT_TRUE(OatFile::CheckStaticDexFileDependencies("", &error_msg)) << error_msg;
 
   // Ill-formed dependencies.
-  EXPECT_FALSE(OatFile::CheckStaticDexFileDependencies("abc", outof(error_msg)));
-  EXPECT_FALSE(OatFile::CheckStaticDexFileDependencies("abc*123*def", outof(error_msg)));
-  EXPECT_FALSE(OatFile::CheckStaticDexFileDependencies("abc*def*", outof(error_msg)));
+  EXPECT_FALSE(OatFile::CheckStaticDexFileDependencies("abc", &error_msg));
+  EXPECT_FALSE(OatFile::CheckStaticDexFileDependencies("abc*123*def", &error_msg));
+  EXPECT_FALSE(OatFile::CheckStaticDexFileDependencies("abc*def*", &error_msg));
 
   // Unsatisfiable dependency.
-  EXPECT_FALSE(OatFile::CheckStaticDexFileDependencies("abc*123*", outof(error_msg)));
+  EXPECT_FALSE(OatFile::CheckStaticDexFileDependencies("abc*123*", &error_msg));
 
   // Load some dex files to be able to do a real test.
   ScopedObjectAccess soa(Thread::Current());
@@ -93,10 +92,10 @@
   std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Main");
   std::vector<const DexFile*> dex_files_const1 = ToConstDexFiles(dex_files1);
   std::string encoding1 = OatFile::EncodeDexFileDependencies(dex_files_const1);
-  EXPECT_TRUE(OatFile::CheckStaticDexFileDependencies(encoding1.c_str(), outof(error_msg)))
+  EXPECT_TRUE(OatFile::CheckStaticDexFileDependencies(encoding1.c_str(), &error_msg))
       << error_msg << " " << encoding1;
   std::vector<std::string> split1;
-  EXPECT_TRUE(OatFile::GetDexLocationsFromDependencies(encoding1.c_str(), outof(split1)));
+  EXPECT_TRUE(OatFile::GetDexLocationsFromDependencies(encoding1.c_str(), &split1));
   ASSERT_EQ(split1.size(), 1U);
   EXPECT_EQ(split1[0], dex_files_const1[0]->GetLocation());
 
@@ -104,10 +103,10 @@
   EXPECT_GT(dex_files2.size(), 1U);
   std::vector<const DexFile*> dex_files_const2 = ToConstDexFiles(dex_files2);
   std::string encoding2 = OatFile::EncodeDexFileDependencies(dex_files_const2);
-  EXPECT_TRUE(OatFile::CheckStaticDexFileDependencies(encoding2.c_str(), outof(error_msg)))
+  EXPECT_TRUE(OatFile::CheckStaticDexFileDependencies(encoding2.c_str(), &error_msg))
       << error_msg << " " << encoding2;
   std::vector<std::string> split2;
-  EXPECT_TRUE(OatFile::GetDexLocationsFromDependencies(encoding2.c_str(), outof(split2)));
+  EXPECT_TRUE(OatFile::GetDexLocationsFromDependencies(encoding2.c_str(), &split2));
   ASSERT_EQ(split2.size(), 2U);
   EXPECT_EQ(split2[0], dex_files_const2[0]->GetLocation());
   EXPECT_EQ(split2[1], dex_files_const2[1]->GetLocation());
diff --git a/runtime/parsed_options.cc b/runtime/parsed_options.cc
index 7f82497..25b5e49 100644
--- a/runtime/parsed_options.cc
+++ b/runtime/parsed_options.cc
@@ -18,7 +18,6 @@
 
 #include <sstream>
 
-#include "base/out.h"
 #include "base/stringpiece.h"
 #include "debugger.h"
 #include "gc/heap.h"
@@ -42,11 +41,12 @@
                                                     // Runtime::Abort
 }
 
-ParsedOptions* ParsedOptions::Create(const RuntimeOptions& options,
-                                     bool ignore_unrecognized,
-                                     out<RuntimeArgumentMap> runtime_options) {
+ParsedOptions* ParsedOptions::Create(const RuntimeOptions& options, bool ignore_unrecognized,
+                                     RuntimeArgumentMap* runtime_options) {
+  CHECK(runtime_options != nullptr);
+
   std::unique_ptr<ParsedOptions> parsed(new ParsedOptions());
-  if (parsed->Parse(options, ignore_unrecognized, outof_forward(runtime_options))) {
+  if (parsed->Parse(options, ignore_unrecognized, runtime_options)) {
     return parsed.release();
   }
   return nullptr;
@@ -293,7 +293,6 @@
 // As a side-effect, populate the hooks from options.
 bool ParsedOptions::ProcessSpecialOptions(const RuntimeOptions& options,
                                           RuntimeArgumentMap* runtime_options,
-                                          // TODO: should be an optional_out here.
                                           std::vector<std::string>* out_options) {
   using M = RuntimeArgumentMap;
 
@@ -400,7 +399,7 @@
 }
 
 bool ParsedOptions::Parse(const RuntimeOptions& options, bool ignore_unrecognized,
-                          out<RuntimeArgumentMap> runtime_options) {
+                          RuntimeArgumentMap* runtime_options) {
   for (size_t i = 0; i < options.size(); ++i) {
     if (true && options[0].first == "-Xzygote") {
       LOG(INFO) << "option[" << i << "]=" << options[i].first;
@@ -411,9 +410,7 @@
 
   // Convert to a simple string list (without the magic pointer options)
   std::vector<std::string> argv_list;
-  if (!ProcessSpecialOptions(options,
-                             nullptr,  // No runtime argument map
-                             outof(argv_list))) {
+  if (!ProcessSpecialOptions(options, nullptr, &argv_list)) {
     return false;
   }
 
diff --git a/runtime/parsed_options.h b/runtime/parsed_options.h
index bcd6228..529dd5c 100644
--- a/runtime/parsed_options.h
+++ b/runtime/parsed_options.h
@@ -22,7 +22,6 @@
 
 #include <jni.h>
 
-#include "base/out_fwd.h"
 #include "globals.h"
 #include "gc/collector_type.h"
 #include "gc/space/large_object_space.h"
@@ -51,9 +50,8 @@
   static std::unique_ptr<RuntimeParser> MakeParser(bool ignore_unrecognized);
 
   // returns true if parsing succeeds, and stores the resulting options into runtime_options
-  static ParsedOptions* Create(const RuntimeOptions& options,
-                               bool ignore_unrecognized,
-                               out<RuntimeArgumentMap> runtime_options);
+  static ParsedOptions* Create(const RuntimeOptions& options, bool ignore_unrecognized,
+                               RuntimeArgumentMap* runtime_options);
 
   bool (*hook_is_sensitive_thread_)();
   jint (*hook_vfprintf_)(FILE* stream, const char* format, va_list ap);
@@ -65,7 +63,6 @@
 
   bool ProcessSpecialOptions(const RuntimeOptions& options,
                              RuntimeArgumentMap* runtime_options,
-                             // Optional out:
                              std::vector<std::string>* out_options);
 
   void Usage(const char* fmt, ...);
@@ -75,9 +72,8 @@
   void Exit(int status);
   void Abort();
 
-  bool Parse(const RuntimeOptions& options,
-             bool ignore_unrecognized,
-             out<RuntimeArgumentMap> runtime_options);
+  bool Parse(const RuntimeOptions& options,  bool ignore_unrecognized,
+             RuntimeArgumentMap* runtime_options);
 };
 
 }  // namespace art
diff --git a/runtime/parsed_options_test.cc b/runtime/parsed_options_test.cc
index 81a48a6..a8575de 100644
--- a/runtime/parsed_options_test.cc
+++ b/runtime/parsed_options_test.cc
@@ -18,7 +18,6 @@
 
 #include <memory>
 
-#include "base/out.h"
 #include "common_runtime_test.h"
 
 namespace art {
@@ -61,7 +60,7 @@
   options.push_back(std::make_pair("exit", test_exit));
 
   RuntimeArgumentMap map;
-  std::unique_ptr<ParsedOptions> parsed(ParsedOptions::Create(options, false, outof(map)));
+  std::unique_ptr<ParsedOptions> parsed(ParsedOptions::Create(options, false, &map));
   ASSERT_TRUE(parsed.get() != nullptr);
   ASSERT_NE(0u, map.Size());
 
@@ -103,7 +102,7 @@
   options.push_back(std::make_pair("-Xgc:MC", nullptr));
 
   RuntimeArgumentMap map;
-  std::unique_ptr<ParsedOptions> parsed(ParsedOptions::Create(options, false, outof(map)));
+  std::unique_ptr<ParsedOptions> parsed(ParsedOptions::Create(options, false, &map));
   ASSERT_TRUE(parsed.get() != nullptr);
   ASSERT_NE(0u, map.Size());
 
diff --git a/runtime/proxy_test.cc b/runtime/proxy_test.cc
index c33b126..bc9ba37 100644
--- a/runtime/proxy_test.cc
+++ b/runtime/proxy_test.cc
@@ -160,10 +160,9 @@
   ASSERT_TRUE(proxyClass->IsProxyClass());
   ASSERT_TRUE(proxyClass->IsInitialized());
 
-  ArtField* instance_fields = proxyClass->GetIFields();
-  EXPECT_TRUE(instance_fields == nullptr);
+  EXPECT_TRUE(proxyClass->GetIFieldsPtr() == nullptr);
 
-  ArtField* static_fields = proxyClass->GetSFields();
+  LengthPrefixedArray<ArtField>* static_fields = proxyClass->GetSFieldsPtr();
   ASSERT_TRUE(static_fields != nullptr);
   ASSERT_EQ(2u, proxyClass->NumStaticFields());
 
@@ -175,7 +174,7 @@
   ASSERT_TRUE(throwsFieldClass.Get() != nullptr);
 
   // Test "Class[] interfaces" field.
-  ArtField* field = &static_fields[0];
+  ArtField* field = &static_fields->At(0);
   EXPECT_STREQ("interfaces", field->GetName());
   EXPECT_STREQ("[Ljava/lang/Class;", field->GetTypeDescriptor());
   EXPECT_EQ(interfacesFieldClass.Get(), field->GetType<true>());
@@ -184,7 +183,7 @@
   EXPECT_FALSE(field->IsPrimitiveType());
 
   // Test "Class[][] throws" field.
-  field = &static_fields[1];
+  field = &static_fields->At(1);
   EXPECT_STREQ("throws", field->GetName());
   EXPECT_STREQ("[[Ljava/lang/Class;", field->GetTypeDescriptor());
   EXPECT_EQ(throwsFieldClass.Get(), field->GetType<true>());
@@ -215,30 +214,30 @@
   ASSERT_TRUE(proxyClass1->IsProxyClass());
   ASSERT_TRUE(proxyClass1->IsInitialized());
 
-  ArtField* static_fields0 = proxyClass0->GetSFields();
+  LengthPrefixedArray<ArtField>* static_fields0 = proxyClass0->GetSFieldsPtr();
   ASSERT_TRUE(static_fields0 != nullptr);
-  ASSERT_EQ(2u, proxyClass0->NumStaticFields());
-  ArtField* static_fields1 = proxyClass1->GetSFields();
+  ASSERT_EQ(2u, static_fields0->Length());
+  LengthPrefixedArray<ArtField>* static_fields1 = proxyClass1->GetSFieldsPtr();
   ASSERT_TRUE(static_fields1 != nullptr);
-  ASSERT_EQ(2u, proxyClass1->NumStaticFields());
+  ASSERT_EQ(2u, static_fields1->Length());
 
-  EXPECT_EQ(static_fields0[0].GetDeclaringClass(), proxyClass0.Get());
-  EXPECT_EQ(static_fields0[1].GetDeclaringClass(), proxyClass0.Get());
-  EXPECT_EQ(static_fields1[0].GetDeclaringClass(), proxyClass1.Get());
-  EXPECT_EQ(static_fields1[1].GetDeclaringClass(), proxyClass1.Get());
+  EXPECT_EQ(static_fields0->At(0).GetDeclaringClass(), proxyClass0.Get());
+  EXPECT_EQ(static_fields0->At(1).GetDeclaringClass(), proxyClass0.Get());
+  EXPECT_EQ(static_fields1->At(0).GetDeclaringClass(), proxyClass1.Get());
+  EXPECT_EQ(static_fields1->At(1).GetDeclaringClass(), proxyClass1.Get());
 
   Handle<mirror::Field> field00 =
-      hs.NewHandle(mirror::Field::CreateFromArtField(soa.Self(), &static_fields0[0], true));
+      hs.NewHandle(mirror::Field::CreateFromArtField(soa.Self(), &static_fields0->At(0), true));
   Handle<mirror::Field> field01 =
-      hs.NewHandle(mirror::Field::CreateFromArtField(soa.Self(), &static_fields0[1], true));
+      hs.NewHandle(mirror::Field::CreateFromArtField(soa.Self(), &static_fields0->At(1), true));
   Handle<mirror::Field> field10 =
-      hs.NewHandle(mirror::Field::CreateFromArtField(soa.Self(), &static_fields1[0], true));
+      hs.NewHandle(mirror::Field::CreateFromArtField(soa.Self(), &static_fields1->At(0), true));
   Handle<mirror::Field> field11 =
-      hs.NewHandle(mirror::Field::CreateFromArtField(soa.Self(), &static_fields1[1], true));
-  EXPECT_EQ(field00->GetArtField(), &static_fields0[0]);
-  EXPECT_EQ(field01->GetArtField(), &static_fields0[1]);
-  EXPECT_EQ(field10->GetArtField(), &static_fields1[0]);
-  EXPECT_EQ(field11->GetArtField(), &static_fields1[1]);
+      hs.NewHandle(mirror::Field::CreateFromArtField(soa.Self(), &static_fields1->At(1), true));
+  EXPECT_EQ(field00->GetArtField(), &static_fields0->At(0));
+  EXPECT_EQ(field01->GetArtField(), &static_fields0->At(1));
+  EXPECT_EQ(field10->GetArtField(), &static_fields1->At(0));
+  EXPECT_EQ(field11->GetArtField(), &static_fields1->At(1));
 }
 
 }  // namespace art
diff --git a/runtime/reflection.cc b/runtime/reflection.cc
index ee2e2c5..100d199 100644
--- a/runtime/reflection.cc
+++ b/runtime/reflection.cc
@@ -780,7 +780,7 @@
   mirror::Class* klass = o->GetClass();
   mirror::Class* src_class = nullptr;
   ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
-  ArtField* primitive_field = &klass->GetIFields()[0];
+  ArtField* primitive_field = &klass->GetIFieldsPtr()->At(0);
   if (klass->DescriptorEquals("Ljava/lang/Boolean;")) {
     src_class = class_linker->FindPrimitiveClass('Z');
     boxed_value.SetZ(primitive_field->GetBoolean(o));
diff --git a/runtime/runtime.cc b/runtime/runtime.cc
index a27acb2..1912314 100644
--- a/runtime/runtime.cc
+++ b/runtime/runtime.cc
@@ -56,7 +56,6 @@
 #include "atomic.h"
 #include "base/arena_allocator.h"
 #include "base/dumpable.h"
-#include "base/out.h"
 #include "base/unix_file/fd_file.h"
 #include "class_linker-inl.h"
 #include "compiler_callbacks.h"
@@ -308,8 +307,8 @@
     Thread* self = Thread::Current();
     if (self == nullptr) {
       os << "(Aborting thread was not attached to runtime!)\n";
-      DumpKernelStack(os, GetTid(), "  kernel: ", false /* don't include count */);
-      DumpNativeStack(os, GetTid(), "  native: ", nullptr /* no ucontext ptr */);
+      DumpKernelStack(os, GetTid(), "  kernel: ", false);
+      DumpNativeStack(os, GetTid(), "  native: ", nullptr);
     } else {
       os << "Aborting thread:\n";
       if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) {
@@ -418,7 +417,7 @@
   if (Runtime::instance_ != nullptr) {
     return false;
   }
-  InitLogging(nullptr /* no argv */);  // Calls Locks::Init() as a side effect.
+  InitLogging(nullptr);  // Calls Locks::Init() as a side effect.
   instance_ = new Runtime;
   if (!instance_->Init(options, ignore_unrecognized)) {
     // TODO: Currently deleting the instance will abort the runtime on destruction. Now This will
@@ -660,7 +659,7 @@
   // before fork aren't attributed to an app.
   heap_->ResetGcPerformanceInfo();
 
-  if (jit_ == nullptr && jit_options_->UseJIT()) {
+  if (jit_.get() == nullptr && jit_options_->UseJIT()) {
     // Create the JIT if the flag is set and we haven't already create it (happens for run-tests).
     CreateJit();
   }
@@ -708,8 +707,9 @@
 }
 
 static bool OpenDexFilesFromImage(const std::string& image_location,
-                                  out<std::vector<std::unique_ptr<const DexFile>>> dex_files,
-                                  out<size_t> failures) {
+                                  std::vector<std::unique_ptr<const DexFile>>* dex_files,
+                                  size_t* failures) {
+  DCHECK(dex_files != nullptr) << "OpenDexFilesFromImage: out-param is nullptr";
   std::string system_filename;
   bool has_system = false;
   std::string cache_filename_unused;
@@ -718,12 +718,12 @@
   bool is_global_cache_unused;
   bool found_image = gc::space::ImageSpace::FindImageFilename(image_location.c_str(),
                                                               kRuntimeISA,
-                                                              outof(system_filename),
-                                                              outof(has_system),
-                                                              outof(cache_filename_unused),
-                                                              outof(dalvik_cache_exists_unused),
-                                                              outof(has_cache_unused),
-                                                              outof(is_global_cache_unused));
+                                                              &system_filename,
+                                                              &has_system,
+                                                              &cache_filename_unused,
+                                                              &dalvik_cache_exists_unused,
+                                                              &has_cache_unused,
+                                                              &is_global_cache_unused);
   *failures = 0;
   if (!found_image || !has_system) {
     return false;
@@ -737,12 +737,12 @@
   if (file.get() == nullptr) {
     return false;
   }
-  std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file.release(), false, false, outof(error_msg)));
+  std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file.release(), false, false, &error_msg));
   if (elf_file.get() == nullptr) {
     return false;
   }
   std::unique_ptr<OatFile> oat_file(OatFile::OpenWithElfFile(elf_file.release(), oat_location,
-                                                             nullptr, outof(error_msg)));
+                                                             nullptr, &error_msg));
   if (oat_file.get() == nullptr) {
     LOG(INFO) << "Unable to use '" << oat_filename << "' because " << error_msg;
     return false;
@@ -753,7 +753,7 @@
       *failures += 1;
       continue;
     }
-    std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(outof(error_msg));
+    std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
     if (dex_file.get() == nullptr) {
       *failures += 1;
     } else {
@@ -768,11 +768,10 @@
 static size_t OpenDexFiles(const std::vector<std::string>& dex_filenames,
                            const std::vector<std::string>& dex_locations,
                            const std::string& image_location,
-                           out<std::vector<std::unique_ptr<const DexFile>>> dex_files) {
+                           std::vector<std::unique_ptr<const DexFile>>* dex_files) {
+  DCHECK(dex_files != nullptr) << "OpenDexFiles: out-param is nullptr";
   size_t failure_count = 0;
-  if (!image_location.empty() && OpenDexFilesFromImage(image_location,
-                                                       outof_forward(dex_files),
-                                                       outof(failure_count))) {
+  if (!image_location.empty() && OpenDexFilesFromImage(image_location, dex_files, &failure_count)) {
     return failure_count;
   }
   failure_count = 0;
@@ -784,7 +783,7 @@
       LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
       continue;
     }
-    if (!DexFile::Open(dex_filename, dex_location, outof(error_msg), outof_forward(dex_files))) {
+    if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
       LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
       ++failure_count;
     }
@@ -801,7 +800,7 @@
   using Opt = RuntimeArgumentMap;
   RuntimeArgumentMap runtime_options;
   std::unique_ptr<ParsedOptions> parsed_options(
-      ParsedOptions::Create(raw_options, ignore_unrecognized, outof(runtime_options)));
+      ParsedOptions::Create(raw_options, ignore_unrecognized, &runtime_options));
   if (parsed_options.get() == nullptr) {
     LOG(ERROR) << "Failed to parse options";
     ATRACE_END();
@@ -1039,7 +1038,7 @@
     OpenDexFiles(dex_filenames,
                  dex_locations,
                  runtime_options.GetOrDefault(Opt::Image),
-                 outof(boot_class_path));
+                 &boot_class_path);
     instruction_set_ = runtime_options.GetOrDefault(Opt::ImageInstructionSet);
     class_linker_->InitWithoutImage(std::move(boot_class_path));
 
@@ -1168,7 +1167,7 @@
   // the library that implements System.loadLibrary!
   {
     std::string reason;
-    if (!java_vm_->LoadNativeLibrary(env, "libjavacore.so", nullptr, outof(reason))) {
+    if (!java_vm_->LoadNativeLibrary(env, "libjavacore.so", nullptr, &reason)) {
       LOG(FATAL) << "LoadNativeLibrary failed for \"libjavacore.so\": " << reason;
     }
   }
@@ -1331,9 +1330,7 @@
   signals.Block();
 }
 
-bool Runtime::AttachCurrentThread(const char* thread_name,
-                                  bool as_daemon,
-                                  jobject thread_group,
+bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
                                   bool create_peer) {
   return Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != nullptr;
 }
@@ -1439,8 +1436,7 @@
   thread_list_->VisitRoots(visitor);
 }
 
-size_t Runtime::FlipThreadRoots(Closure* thread_flip_visitor,
-                                Closure* flip_callback,
+size_t Runtime::FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
                                 gc::collector::GarbageCollector* collector) {
   return thread_list_->FlipThreadRoots(thread_flip_visitor, flip_callback, collector);
 }
@@ -1516,7 +1512,7 @@
 
 void Runtime::AllowNewSystemWeaks() {
   monitor_list_->AllowNewMonitors();
-  intern_table_->ChangeWeakRootState(gc::kWeakRootStateNormal);  // TODO: Do this in the sweeping?
+  intern_table_->ChangeWeakRootState(gc::kWeakRootStateNormal);  // TODO: Do this in the sweeping.
   java_vm_->AllowNewWeakGlobals();
   heap_->AllowNewAllocationRecords();
   lambda_box_table_->AllowNewWeakBoxedLambdas();
@@ -1627,64 +1623,50 @@
   preinitialization_transaction_->ThrowAbortError(self, nullptr);
 }
 
-void Runtime::RecordWriteFieldBoolean(mirror::Object* obj,
-                                      MemberOffset field_offset,
-                                      uint8_t value,
-                                      bool is_volatile) const {
+void Runtime::RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset,
+                                      uint8_t value, bool is_volatile) const {
   DCHECK(IsAotCompiler());
   DCHECK(IsActiveTransaction());
   preinitialization_transaction_->RecordWriteFieldBoolean(obj, field_offset, value, is_volatile);
 }
 
-void Runtime::RecordWriteFieldByte(mirror::Object* obj,
-                                   MemberOffset field_offset,
-                                   int8_t value,
-                                   bool is_volatile) const {
+void Runtime::RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset,
+                                   int8_t value, bool is_volatile) const {
   DCHECK(IsAotCompiler());
   DCHECK(IsActiveTransaction());
   preinitialization_transaction_->RecordWriteFieldByte(obj, field_offset, value, is_volatile);
 }
 
-void Runtime::RecordWriteFieldChar(mirror::Object* obj,
-                                   MemberOffset field_offset,
-                                   uint16_t value,
-                                   bool is_volatile) const {
+void Runtime::RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset,
+                                   uint16_t value, bool is_volatile) const {
   DCHECK(IsAotCompiler());
   DCHECK(IsActiveTransaction());
   preinitialization_transaction_->RecordWriteFieldChar(obj, field_offset, value, is_volatile);
 }
 
-void Runtime::RecordWriteFieldShort(mirror::Object* obj,
-                                    MemberOffset field_offset,
-                                    int16_t value,
-                                    bool is_volatile) const {
+void Runtime::RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset,
+                                    int16_t value, bool is_volatile) const {
   DCHECK(IsAotCompiler());
   DCHECK(IsActiveTransaction());
   preinitialization_transaction_->RecordWriteFieldShort(obj, field_offset, value, is_volatile);
 }
 
-void Runtime::RecordWriteField32(mirror::Object* obj,
-                                 MemberOffset field_offset,
-                                 uint32_t value,
-                                 bool is_volatile) const {
+void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset,
+                                 uint32_t value, bool is_volatile) const {
   DCHECK(IsAotCompiler());
   DCHECK(IsActiveTransaction());
   preinitialization_transaction_->RecordWriteField32(obj, field_offset, value, is_volatile);
 }
 
-void Runtime::RecordWriteField64(mirror::Object* obj,
-                                 MemberOffset field_offset,
-                                 uint64_t value,
-                                 bool is_volatile) const {
+void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset,
+                                 uint64_t value, bool is_volatile) const {
   DCHECK(IsAotCompiler());
   DCHECK(IsActiveTransaction());
   preinitialization_transaction_->RecordWriteField64(obj, field_offset, value, is_volatile);
 }
 
-void Runtime::RecordWriteFieldReference(mirror::Object* obj,
-                                        MemberOffset field_offset,
-                                        mirror::Object* value,
-                                        bool is_volatile) const {
+void Runtime::RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset,
+                                        mirror::Object* value, bool is_volatile) const {
   DCHECK(IsAotCompiler());
   DCHECK(IsActiveTransaction());
   preinitialization_transaction_->RecordWriteFieldReference(obj, field_offset, value, is_volatile);
@@ -1725,7 +1707,7 @@
   fault_message_ = message;
 }
 
-void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(out<std::vector<std::string>> argv)
+void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv)
     const {
   if (GetInstrumentation()->InterpretOnly() || UseJit()) {
     argv->push_back("--compiler-filter=interpret-only");
diff --git a/runtime/runtime.h b/runtime/runtime.h
index 206623e..4577b75 100644
--- a/runtime/runtime.h
+++ b/runtime/runtime.h
@@ -28,7 +28,6 @@
 
 #include "arch/instruction_set.h"
 #include "base/macros.h"
-#include "base/out.h"
 #include "gc_root.h"
 #include "instrumentation.h"
 #include "jobject_comparator.h"
@@ -225,9 +224,7 @@
   jobject GetSystemClassLoader() const;
 
   // Attaches the calling native thread to the runtime.
-  bool AttachCurrentThread(const char* thread_name,
-                           bool as_daemon,
-                           jobject thread_group,
+  bool AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
                            bool create_peer);
 
   void CallExitHook(jint status);
@@ -289,7 +286,8 @@
 
   mirror::Throwable* GetPreAllocatedOutOfMemoryError() SHARED_REQUIRES(Locks::mutator_lock_);
 
-  mirror::Throwable* GetPreAllocatedNoClassDefFoundError() SHARED_REQUIRES(Locks::mutator_lock_);
+  mirror::Throwable* GetPreAllocatedNoClassDefFoundError()
+      SHARED_REQUIRES(Locks::mutator_lock_);
 
   const std::vector<std::string>& GetProperties() const {
     return properties_;
@@ -318,7 +316,8 @@
   void VisitImageRoots(RootVisitor* visitor) SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Visit all of the roots we can do safely do concurrently.
-  void VisitConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags = kVisitRootFlagAllRoots)
+  void VisitConcurrentRoots(RootVisitor* visitor,
+                            VisitRootFlags flags = kVisitRootFlagAllRoots)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Visit all of the non thread roots, we can do this with mutators unpaused.
@@ -332,8 +331,7 @@
   void VisitThreadRoots(RootVisitor* visitor) SHARED_REQUIRES(Locks::mutator_lock_);
 
   // Flip thread roots from from-space refs to to-space refs.
-  size_t FlipThreadRoots(Closure* thread_flip_visitor,
-                         Closure* flip_callback,
+  size_t FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
                          gc::collector::GarbageCollector* collector)
       REQUIRES(!Locks::mutator_lock_);
 
@@ -469,34 +467,20 @@
   void ThrowTransactionAbortError(Thread* self)
       SHARED_REQUIRES(Locks::mutator_lock_);
 
-  void RecordWriteFieldBoolean(mirror::Object* obj,
-                               MemberOffset field_offset,
-                               uint8_t value,
+  void RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset, uint8_t value,
                                bool is_volatile) const;
-  void RecordWriteFieldByte(mirror::Object* obj,
-                            MemberOffset field_offset,
-                            int8_t value,
+  void RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset, int8_t value,
                             bool is_volatile) const;
-  void RecordWriteFieldChar(mirror::Object* obj,
-                            MemberOffset field_offset,
-                            uint16_t value,
+  void RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset, uint16_t value,
                             bool is_volatile) const;
-  void RecordWriteFieldShort(mirror::Object* obj,
-                             MemberOffset field_offset,
-                             int16_t value,
+  void RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset, int16_t value,
                           bool is_volatile) const;
-  void RecordWriteField32(mirror::Object* obj,
-                          MemberOffset field_offset,
-                          uint32_t value,
+  void RecordWriteField32(mirror::Object* obj, MemberOffset field_offset, uint32_t value,
                           bool is_volatile) const;
-  void RecordWriteField64(mirror::Object* obj,
-                          MemberOffset field_offset,
-                          uint64_t value,
+  void RecordWriteField64(mirror::Object* obj, MemberOffset field_offset, uint64_t value,
                           bool is_volatile) const;
-  void RecordWriteFieldReference(mirror::Object* obj,
-                                 MemberOffset field_offset,
-                                 mirror::Object* value,
-                                 bool is_volatile) const;
+  void RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset,
+                                 mirror::Object* value, bool is_volatile) const;
   void RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const
       SHARED_REQUIRES(Locks::mutator_lock_);
   void RecordStrongStringInsertion(mirror::String* s) const
@@ -515,7 +499,7 @@
     return fault_message_;
   }
 
-  void AddCurrentRuntimeFeaturesAsDex2OatArguments(out<std::vector<std::string>> arg_vector) const;
+  void AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* arg_vector) const;
 
   bool ExplicitStackOverflowChecks() const {
     return !implicit_so_checks_;
diff --git a/runtime/stack.cc b/runtime/stack.cc
index 2916eaa..b07b244 100644
--- a/runtime/stack.cc
+++ b/runtime/stack.cc
@@ -19,7 +19,6 @@
 #include "arch/context.h"
 #include "art_method-inl.h"
 #include "base/hex_dump.h"
-#include "base/out.h"
 #include "entrypoints/entrypoint_utils-inl.h"
 #include "entrypoints/runtime_asm_entrypoints.h"
 #include "gc_map.h"
@@ -181,7 +180,7 @@
     } else {
       uint16_t reg = code_item->registers_size_ - code_item->ins_size_;
       uint32_t value = 0;
-      bool success = GetVReg(m, reg, kReferenceVReg, outof(value));
+      bool success = GetVReg(m, reg, kReferenceVReg, &value);
       // We currently always guarantee the `this` object is live throughout the method.
       CHECK(success) << "Failed to read the this object in " << PrettyMethod(m);
       return reinterpret_cast<mirror::Object*>(value);
@@ -376,8 +375,8 @@
   QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
   uint32_t vmap_offset_lo, vmap_offset_hi;
   // TODO: IsInContext stops before spotting floating point registers.
-  if (vmap_table.IsInContext(vreg, kind_lo, outof(vmap_offset_lo)) &&
-      vmap_table.IsInContext(vreg + 1, kind_hi, outof(vmap_offset_hi))) {
+  if (vmap_table.IsInContext(vreg, kind_lo, &vmap_offset_lo) &&
+      vmap_table.IsInContext(vreg + 1, kind_hi, &vmap_offset_hi)) {
     bool is_float = (kind_lo == kDoubleLoVReg);
     uint32_t spill_mask = is_float ? frame_info.FpSpillMask() : frame_info.CoreSpillMask();
     uint32_t reg_lo = vmap_table.ComputeRegister(spill_mask, vmap_offset_lo, kind_lo);
@@ -400,8 +399,8 @@
                                                 uint64_t* val) const {
   uint32_t low_32bits;
   uint32_t high_32bits;
-  bool success = GetVRegFromOptimizedCode(m, vreg, kind_lo, outof(low_32bits));
-  success &= GetVRegFromOptimizedCode(m, vreg + 1, kind_hi, outof(high_32bits));
+  bool success = GetVRegFromOptimizedCode(m, vreg, kind_lo, &low_32bits);
+  success &= GetVRegFromOptimizedCode(m, vreg + 1, kind_hi, &high_32bits);
   if (success) {
     *val = (static_cast<uint64_t>(high_32bits) << 32) | static_cast<uint64_t>(low_32bits);
   }
@@ -453,7 +452,7 @@
   QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
   uint32_t vmap_offset;
   // TODO: IsInContext stops before spotting floating point registers.
-  if (vmap_table.IsInContext(vreg, kind, outof(vmap_offset))) {
+  if (vmap_table.IsInContext(vreg, kind, &vmap_offset)) {
     bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
     uint32_t spill_mask = is_float ? frame_info.FpSpillMask() : frame_info.CoreSpillMask();
     uint32_t reg = vmap_table.ComputeRegister(spill_mask, vmap_offset, kind);
@@ -533,8 +532,8 @@
   QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
   uint32_t vmap_offset_lo, vmap_offset_hi;
   // TODO: IsInContext stops before spotting floating point registers.
-  if (vmap_table.IsInContext(vreg, kind_lo, outof(vmap_offset_lo)) &&
-      vmap_table.IsInContext(vreg + 1, kind_hi, outof(vmap_offset_hi))) {
+  if (vmap_table.IsInContext(vreg, kind_lo, &vmap_offset_lo) &&
+      vmap_table.IsInContext(vreg + 1, kind_hi, &vmap_offset_hi)) {
     bool is_float = (kind_lo == kDoubleLoVReg);
     uint32_t spill_mask = is_float ? frame_info.FpSpillMask() : frame_info.CoreSpillMask();
     uint32_t reg_lo = vmap_table.ComputeRegister(spill_mask, vmap_offset_lo, kind_lo);
diff --git a/runtime/stride_iterator.h b/runtime/stride_iterator.h
index d8d21aa..c69f30e 100644
--- a/runtime/stride_iterator.h
+++ b/runtime/stride_iterator.h
@@ -29,11 +29,12 @@
   StrideIterator& operator=(const StrideIterator&) = default;
   StrideIterator& operator=(StrideIterator&&) = default;
 
-  StrideIterator(uintptr_t ptr, size_t stride)
-      : ptr_(ptr), stride_(stride) {
-  }
+  StrideIterator(T* ptr, size_t stride)
+      : ptr_(reinterpret_cast<uintptr_t>(ptr)),
+        stride_(reinterpret_cast<uintptr_t>(stride)) {}
 
   bool operator==(const StrideIterator& other) const {
+    DCHECK_EQ(stride_, other.stride_);
     return ptr_ == other.ptr_;
   }
 
@@ -52,6 +53,12 @@
     return temp;
   }
 
+  StrideIterator operator+(ssize_t delta) const {
+    auto temp = *this;
+    temp.ptr_ += static_cast<ssize_t>(stride_) * delta;
+    return temp;
+  }
+
   T& operator*() const {
     return *reinterpret_cast<T*>(ptr_);
   }
diff --git a/runtime/thread.cc b/runtime/thread.cc
index ba1121fb..74e3f11 100644
--- a/runtime/thread.cc
+++ b/runtime/thread.cc
@@ -2744,7 +2744,7 @@
 size_t Thread::NumberOfHeldMutexes() const {
   size_t count = 0;
   for (BaseMutex* mu : tlsPtr_.held_mutexes) {
-    count += static_cast<size_t>(mu != nullptr);
+    count += mu != nullptr ? 1 : 0;
   }
   return count;
 }
diff --git a/runtime/thread_state.h b/runtime/thread_state.h
index c000e61..a11d213 100644
--- a/runtime/thread_state.h
+++ b/runtime/thread_state.h
@@ -43,7 +43,7 @@
   kWaitingForMethodTracingStart,    // WAITING        TS_WAIT      waiting for method tracing to start
   kWaitingForVisitObjects,          // WAITING        TS_WAIT      waiting for visiting objects
   kWaitingForGetObjectsAllocated,   // WAITING        TS_WAIT      waiting for getting the number of allocated objects
-  kWaitingWeakRootRead,             // WAITING        TS_WAIT      waiting to read a weak root
+  kWaitingWeakGcRootRead,           // WAITING        TS_WAIT      waiting on the GC to read a weak root
   kStarting,                        // NEW            TS_WAIT      native thread started, not yet ready to run managed code
   kNative,                          // RUNNABLE       TS_RUNNING   running in a JNI native method
   kSuspended,                       // RUNNABLE       TS_RUNNING   suspended by GC or debugger
diff --git a/test/Android.run-test.mk b/test/Android.run-test.mk
index 3698bc8..4e6df6c 100644
--- a/test/Android.run-test.mk
+++ b/test/Android.run-test.mk
@@ -853,6 +853,19 @@
       $$(error found $(13) expected $(ALL_ADDRESS_SIZES))
     endif
   endif
+  # Override of host instruction-set-features. Required to test advanced x86 intrinsics. The
+  # conditionals aren't really correct, they will fail to do the right thing on a 32-bit only
+  # host. However, this isn't common enough to worry here and make the conditions complicated.
+  ifneq ($(DEX2OAT_HOST_INSTRUCTION_SET_FEATURES),)
+    ifeq ($(13),64)
+      run_test_options += --instruction-set-features $(DEX2OAT_HOST_INSTRUCTION_SET_FEATURES)
+    endif
+  endif
+  ifneq ($($(HOST_2ND_ARCH_VAR_PREFIX)DEX2OAT_HOST_INSTRUCTION_SET_FEATURES),)
+    ifeq ($(13),32)
+      run_test_options += --instruction-set-features $($(HOST_2ND_ARCH_VAR_PREFIX)DEX2OAT_HOST_INSTRUCTION_SET_FEATURES)
+    endif
+  endif
   run_test_rule_name := test-art-$(1)-run-test-$(2)-$(3)-$(4)-$(5)-$(6)-$(7)-$(8)-$(9)-$(10)-$(11)-$(12)$(13)
   run_test_options := --output-path $(ART_HOST_TEST_DIR)/run-test-output/$$(run_test_rule_name) \
       $$(run_test_options)
diff --git a/test/etc/run-test-jar b/test/etc/run-test-jar
index db64b77..750a29f 100755
--- a/test/etc/run-test-jar
+++ b/test/etc/run-test-jar
@@ -46,6 +46,7 @@
 ZYGOTE=""
 DEX_VERIFY=""
 USE_DEX2OAT_AND_PATCHOAT="y"
+INSTRUCTION_SET_FEATURES=""
 
 while true; do
     if [ "x$1" = "x--quiet" ]; then
@@ -159,6 +160,10 @@
         shift
         ANDROID_ROOT="$1"
         shift
+    elif [ "x$1" = "x--instruction-set-features" ]; then
+        shift
+        INSTRUCTION_SET_FEATURES="$1"
+        shift
     elif [ "x$1" = "x--" ]; then
         shift
         break
@@ -330,6 +335,14 @@
                       --dex-file=$DEX_LOCATION/$TEST_NAME.jar \
                       --oat-file=$DEX_LOCATION/dalvik-cache/$ISA/$(echo $DEX_LOCATION/$TEST_NAME.jar/classes.dex | cut -d/ -f 2- | sed "s:/:@:g") \
                       --instruction-set=$ISA"
+  if [ "x$INSTRUCTION_SET_FEATURES" != "x" ] ; then
+    dex2oat_cmdline="${dex2oat_cmdline} --instruction-set-features=${INSTRUCTION_SET_FEATURES}"
+  fi
+fi
+
+DALVIKVM_ISA_FEATURES_ARGS=""
+if [ "x$INSTRUCTION_SET_FEATURES" != "x" ] ; then
+  DALVIKVM_ISA_FEATURES_ARGS="-Xcompiler-option --instruction-set-features=${INSTRUCTION_SET_FEATURES}"
 fi
 
 dalvikvm_cmdline="$INVOKE_WITH $GDB $ANDROID_ROOT/bin/$DALVIKVM \
@@ -339,6 +352,7 @@
                   -XXlib:$LIB \
                   $PATCHOAT \
                   $DEX2OAT \
+                  $DALVIKVM_ISA_FEATURES_ARGS \
                   $ZYGOTE \
                   $JNI_OPTS \
                   $INT_OPTS \
diff --git a/test/run-test b/test/run-test
index 934329f..3d6f073 100755
--- a/test/run-test
+++ b/test/run-test
@@ -339,6 +339,10 @@
     elif [ "x$1" = "x--dex2oat-swap" ]; then
         run_args="${run_args} --dex2oat-swap"
         shift
+    elif [ "x$1" = "x--instruction-set-features" ]; then
+        shift
+        run_args="${run_args} --instruction-set-features $1"
+        shift
     elif expr "x$1" : "x--" >/dev/null 2>&1; then
         echo "unknown $0 option: $1" 1>&2
         usage="yes"
@@ -556,6 +560,8 @@
         echo "    --never-clean         Keep the test files even if the test succeeds."
         echo "    --android-root [path] The path on target for the android root. (/system by default)."
         echo "    --dex2oat-swap        Use a dex2oat swap file."
+        echo "    --instruction-set-features [string]"
+        echo "                          Set instruction-set-features for compilation."
     ) 1>&2
     exit 1
 fi