Backport Improve optimization of IsInstanceOf.

(cherry picked from commit f514be61685ff5c23f1d27a0f0aae0308605ae4c)