Remove class root duplicates from well known classes.

And get well known exception classes as declaring classes
of their constructors.

Also change function `ThreadForEnv()` to `Thread::ForEnv()`
and use it where appropriate, mostly in code added recently
while cleaning up well-known methods.

Test: m test-art-host-gtest
Test: testrunner.py --host --optimizing
Change-Id: I2ededa429863a6cddbcbb879a223277fd6245557
diff --git a/runtime/class_linker.cc b/runtime/class_linker.cc
index a51e28f..7a68863 100644
--- a/runtime/class_linker.cc
+++ b/runtime/class_linker.cc
@@ -536,10 +536,9 @@
 static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
     REQUIRES_SHARED(Locks::mutator_lock_) {
   Thread* self = Thread::Current();
-  JNIEnv* env = self->GetJniEnv();
 
-  ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
-  CHECK(cause.get() != nullptr);
+  ObjPtr<mirror::Throwable> cause = self->GetException();
+  CHECK(cause != nullptr);
 
   // Boot classpath classes should not fail initialization. This is a consistency debug check.
   // This cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
@@ -554,12 +553,8 @@
                                             << self->GetException()->Dump();
   }
 
-  env->ExceptionClear();
-  bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
-  env->Throw(cause.get());
-
   // We only wrap non-Error exceptions; an Error can just be used as-is.
-  if (!is_error) {
+  if (!cause->IsError()) {
     self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
   }
   VlogClassInitializationFailure(klass);
@@ -1132,14 +1127,6 @@
   // classes are always in the boot image, so this code is primarily intended
   // for running without boot image but may be needed for boot image if the
   // AOT-initialization fails due to introduction of new code to `<clinit>`.
-  jclass classes_to_initialize[] = {
-      // Initialize `StackOverflowError`.
-      WellKnownClasses::java_lang_StackOverflowError,
-  };
-  auto* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
-  for (jclass c : classes_to_initialize) {
-    EnsureRootInitialized(this, self, ObjPtr<mirror::Class>::DownCast(vm->DecodeGlobal(c)));
-  }
   ArtMethod* static_methods_of_classes_to_initialize[] = {
       // Initialize primitive boxing classes (avoid check at runtime).
       WellKnownClasses::java_lang_Boolean_valueOf,
@@ -1150,6 +1137,8 @@
       WellKnownClasses::java_lang_Integer_valueOf,
       WellKnownClasses::java_lang_Long_valueOf,
       WellKnownClasses::java_lang_Short_valueOf,
+      // Initialize `StackOverflowError`.
+      WellKnownClasses::java_lang_StackOverflowError_init,
       // Ensure class loader classes are initialized (avoid check at runtime).
       // Superclass `ClassLoader` is a class root and already initialized above.
       // Superclass `BaseDexClassLoader` is initialized implicitly.