D103532 modified this case to preserve type sugar but we can end up with cases where the cast is not valid. I modified the code to use GetLValueReferenceType(type)/GetRValueReferenceType(type) respectively.
In the case being tested in the test case we end with the following type:
TypedefType 0x7f8a710202f0 'std::__compressed_pair_elem<struct std::basic_string<char, struct std::char_traits<char>, class std::allocator<char> >::__rep, 0, false>::const_reference' sugar |-Typedef 0x7f8a71020280 'const_reference' `-LValueReferenceType 0x7f8a71020250 'const struct std::basic_string<char, struct std::char_traits<char>, class std::allocator<char> >::__rep &' ...
which can't be cast to ReferenceType.
I really like the idea of reusing the TypeSystemClang functions here (we should do this everywhere I think). FWIW, I think this can all just be CompilerType pointee_clang_type = GetNonReferenceType(type); From the code below GetPointeeType would also work. We already call the variable here pointee type so I don't think calling references pointers here will hurt too much, so I think both is fine.