SemaCast.cpp 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707
  1. //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for cast expressions, including
  11. // 1) C-style casts like '(int) x'
  12. // 2) C++ functional casts like 'int(x)'
  13. // 3) C++ named casts like 'static_cast<int>(x)'
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "clang/Sema/SemaInternal.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExprObjC.h"
  21. #include "clang/AST/RecordLayout.h"
  22. #include "clang/Basic/PartialDiagnostic.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "clang/Lex/Preprocessor.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include <set>
  28. using namespace clang;
  29. enum TryCastResult {
  30. TC_NotApplicable, ///< The cast method is not applicable.
  31. TC_Success, ///< The cast method is appropriate and successful.
  32. TC_Failed ///< The cast method is appropriate, but failed. A
  33. ///< diagnostic has been emitted.
  34. };
  35. enum CastType {
  36. CT_Const, ///< const_cast
  37. CT_Static, ///< static_cast
  38. CT_Reinterpret, ///< reinterpret_cast
  39. CT_Dynamic, ///< dynamic_cast
  40. CT_CStyle, ///< (Type)expr
  41. CT_Functional ///< Type(expr)
  42. };
  43. namespace {
  44. struct CastOperation {
  45. CastOperation(Sema &S, QualType destType, ExprResult src)
  46. : Self(S), SrcExpr(src), DestType(destType),
  47. ResultType(destType.getNonLValueExprType(S.Context)),
  48. ValueKind(Expr::getValueKindForType(destType)),
  49. Kind(CK_Dependent), IsARCUnbridgedCast(false) {
  50. if (const BuiltinType *placeholder =
  51. src.get()->getType()->getAsPlaceholderType()) {
  52. PlaceholderKind = placeholder->getKind();
  53. } else {
  54. PlaceholderKind = (BuiltinType::Kind) 0;
  55. }
  56. }
  57. Sema &Self;
  58. ExprResult SrcExpr;
  59. QualType DestType;
  60. QualType ResultType;
  61. ExprValueKind ValueKind;
  62. CastKind Kind;
  63. BuiltinType::Kind PlaceholderKind;
  64. CXXCastPath BasePath;
  65. bool IsARCUnbridgedCast;
  66. SourceRange OpRange;
  67. SourceRange DestRange;
  68. // Top-level semantics-checking routines.
  69. void CheckConstCast();
  70. void CheckReinterpretCast();
  71. void CheckStaticCast();
  72. void CheckDynamicCast();
  73. void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
  74. void CheckCStyleCast();
  75. /// Complete an apparently-successful cast operation that yields
  76. /// the given expression.
  77. ExprResult complete(CastExpr *castExpr) {
  78. // If this is an unbridged cast, wrap the result in an implicit
  79. // cast that yields the unbridged-cast placeholder type.
  80. if (IsARCUnbridgedCast) {
  81. castExpr = ImplicitCastExpr::Create(Self.Context,
  82. Self.Context.ARCUnbridgedCastTy,
  83. CK_Dependent, castExpr, nullptr,
  84. castExpr->getValueKind());
  85. }
  86. return castExpr;
  87. }
  88. // Internal convenience methods.
  89. /// Try to handle the given placeholder expression kind. Return
  90. /// true if the source expression has the appropriate placeholder
  91. /// kind. A placeholder can only be claimed once.
  92. bool claimPlaceholder(BuiltinType::Kind K) {
  93. if (PlaceholderKind != K) return false;
  94. PlaceholderKind = (BuiltinType::Kind) 0;
  95. return true;
  96. }
  97. bool isPlaceholder() const {
  98. return PlaceholderKind != 0;
  99. }
  100. bool isPlaceholder(BuiltinType::Kind K) const {
  101. return PlaceholderKind == K;
  102. }
  103. void checkCastAlign() {
  104. Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
  105. }
  106. void checkObjCConversion(Sema::CheckedConversionKind CCK) {
  107. assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
  108. Expr *src = SrcExpr.get();
  109. if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
  110. Sema::ACR_unbridged)
  111. IsARCUnbridgedCast = true;
  112. SrcExpr = src;
  113. }
  114. /// Check for and handle non-overload placeholder expressions.
  115. void checkNonOverloadPlaceholders() {
  116. if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
  117. return;
  118. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  119. if (SrcExpr.isInvalid())
  120. return;
  121. PlaceholderKind = (BuiltinType::Kind) 0;
  122. }
  123. };
  124. }
  125. static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
  126. QualType DestType);
  127. // The Try functions attempt a specific way of casting. If they succeed, they
  128. // return TC_Success. If their way of casting is not appropriate for the given
  129. // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
  130. // to emit if no other way succeeds. If their way of casting is appropriate but
  131. // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
  132. // they emit a specialized diagnostic.
  133. // All diagnostics returned by these functions must expect the same three
  134. // arguments:
  135. // %0: Cast Type (a value from the CastType enumeration)
  136. // %1: Source Type
  137. // %2: Destination Type
  138. static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
  139. QualType DestType, bool CStyle,
  140. CastKind &Kind,
  141. CXXCastPath &BasePath,
  142. unsigned &msg);
  143. static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
  144. QualType DestType, bool CStyle,
  145. SourceRange OpRange,
  146. unsigned &msg,
  147. CastKind &Kind,
  148. CXXCastPath &BasePath);
  149. static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
  150. QualType DestType, bool CStyle,
  151. SourceRange OpRange,
  152. unsigned &msg,
  153. CastKind &Kind,
  154. CXXCastPath &BasePath);
  155. static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
  156. CanQualType DestType, bool CStyle,
  157. SourceRange OpRange,
  158. QualType OrigSrcType,
  159. QualType OrigDestType, unsigned &msg,
  160. CastKind &Kind,
  161. CXXCastPath &BasePath);
  162. static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
  163. QualType SrcType,
  164. QualType DestType,bool CStyle,
  165. SourceRange OpRange,
  166. unsigned &msg,
  167. CastKind &Kind,
  168. CXXCastPath &BasePath);
  169. static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
  170. QualType DestType,
  171. Sema::CheckedConversionKind CCK,
  172. SourceRange OpRange,
  173. unsigned &msg, CastKind &Kind,
  174. bool ListInitialization);
  175. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
  176. QualType DestType,
  177. Sema::CheckedConversionKind CCK,
  178. SourceRange OpRange,
  179. unsigned &msg, CastKind &Kind,
  180. CXXCastPath &BasePath,
  181. bool ListInitialization);
  182. static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
  183. QualType DestType, bool CStyle,
  184. unsigned &msg);
  185. static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
  186. QualType DestType, bool CStyle,
  187. SourceRange OpRange,
  188. unsigned &msg,
  189. CastKind &Kind);
  190. /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
  191. ExprResult
  192. Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
  193. SourceLocation LAngleBracketLoc, Declarator &D,
  194. SourceLocation RAngleBracketLoc,
  195. SourceLocation LParenLoc, Expr *E,
  196. SourceLocation RParenLoc) {
  197. assert(!D.isInvalidType());
  198. TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
  199. if (D.isInvalidType())
  200. return ExprError();
  201. if (getLangOpts().CPlusPlus) {
  202. // Check that there are no default arguments (C++ only).
  203. CheckExtraCXXDefaultArguments(D);
  204. }
  205. return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
  206. SourceRange(LAngleBracketLoc, RAngleBracketLoc),
  207. SourceRange(LParenLoc, RParenLoc));
  208. }
  209. ExprResult
  210. Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
  211. TypeSourceInfo *DestTInfo, Expr *E,
  212. SourceRange AngleBrackets, SourceRange Parens) {
  213. ExprResult Ex = E;
  214. QualType DestType = DestTInfo->getType();
  215. // If the type is dependent, we won't do the semantic analysis now.
  216. bool TypeDependent =
  217. DestType->isDependentType() || Ex.get()->isTypeDependent();
  218. CastOperation Op(*this, DestType, E);
  219. Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
  220. Op.DestRange = AngleBrackets;
  221. switch (Kind) {
  222. default: llvm_unreachable("Unknown C++ cast!");
  223. case tok::kw_const_cast:
  224. if (!TypeDependent) {
  225. Op.CheckConstCast();
  226. if (Op.SrcExpr.isInvalid())
  227. return ExprError();
  228. DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
  229. }
  230. return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
  231. Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
  232. OpLoc, Parens.getEnd(),
  233. AngleBrackets));
  234. case tok::kw_dynamic_cast: {
  235. // OpenCL C++ 1.0 s2.9: dynamic_cast is not supported.
  236. if (getLangOpts().OpenCLCPlusPlus) {
  237. return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
  238. << "dynamic_cast");
  239. }
  240. if (!TypeDependent) {
  241. Op.CheckDynamicCast();
  242. if (Op.SrcExpr.isInvalid())
  243. return ExprError();
  244. }
  245. return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
  246. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  247. &Op.BasePath, DestTInfo,
  248. OpLoc, Parens.getEnd(),
  249. AngleBrackets));
  250. }
  251. case tok::kw_reinterpret_cast: {
  252. if (!TypeDependent) {
  253. Op.CheckReinterpretCast();
  254. if (Op.SrcExpr.isInvalid())
  255. return ExprError();
  256. DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
  257. }
  258. return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
  259. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  260. nullptr, DestTInfo, OpLoc,
  261. Parens.getEnd(),
  262. AngleBrackets));
  263. }
  264. case tok::kw_static_cast: {
  265. if (!TypeDependent) {
  266. Op.CheckStaticCast();
  267. if (Op.SrcExpr.isInvalid())
  268. return ExprError();
  269. DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
  270. }
  271. return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
  272. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  273. &Op.BasePath, DestTInfo,
  274. OpLoc, Parens.getEnd(),
  275. AngleBrackets));
  276. }
  277. }
  278. }
  279. /// Try to diagnose a failed overloaded cast. Returns true if
  280. /// diagnostics were emitted.
  281. static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
  282. SourceRange range, Expr *src,
  283. QualType destType,
  284. bool listInitialization) {
  285. switch (CT) {
  286. // These cast kinds don't consider user-defined conversions.
  287. case CT_Const:
  288. case CT_Reinterpret:
  289. case CT_Dynamic:
  290. return false;
  291. // These do.
  292. case CT_Static:
  293. case CT_CStyle:
  294. case CT_Functional:
  295. break;
  296. }
  297. QualType srcType = src->getType();
  298. if (!destType->isRecordType() && !srcType->isRecordType())
  299. return false;
  300. InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
  301. InitializationKind initKind
  302. = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
  303. range, listInitialization)
  304. : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
  305. listInitialization)
  306. : InitializationKind::CreateCast(/*type range?*/ range);
  307. InitializationSequence sequence(S, entity, initKind, src);
  308. assert(sequence.Failed() && "initialization succeeded on second try?");
  309. switch (sequence.getFailureKind()) {
  310. default: return false;
  311. case InitializationSequence::FK_ConstructorOverloadFailed:
  312. case InitializationSequence::FK_UserConversionOverloadFailed:
  313. break;
  314. }
  315. OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
  316. unsigned msg = 0;
  317. OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
  318. switch (sequence.getFailedOverloadResult()) {
  319. case OR_Success: llvm_unreachable("successful failed overload");
  320. case OR_No_Viable_Function:
  321. if (candidates.empty())
  322. msg = diag::err_ovl_no_conversion_in_cast;
  323. else
  324. msg = diag::err_ovl_no_viable_conversion_in_cast;
  325. howManyCandidates = OCD_AllCandidates;
  326. break;
  327. case OR_Ambiguous:
  328. msg = diag::err_ovl_ambiguous_conversion_in_cast;
  329. howManyCandidates = OCD_ViableCandidates;
  330. break;
  331. case OR_Deleted:
  332. msg = diag::err_ovl_deleted_conversion_in_cast;
  333. howManyCandidates = OCD_ViableCandidates;
  334. break;
  335. }
  336. S.Diag(range.getBegin(), msg)
  337. << CT << srcType << destType
  338. << range << src->getSourceRange();
  339. candidates.NoteCandidates(S, howManyCandidates, src);
  340. return true;
  341. }
  342. /// Diagnose a failed cast.
  343. static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
  344. SourceRange opRange, Expr *src, QualType destType,
  345. bool listInitialization) {
  346. if (msg == diag::err_bad_cxx_cast_generic &&
  347. tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
  348. listInitialization))
  349. return;
  350. S.Diag(opRange.getBegin(), msg) << castType
  351. << src->getType() << destType << opRange << src->getSourceRange();
  352. // Detect if both types are (ptr to) class, and note any incompleteness.
  353. int DifferentPtrness = 0;
  354. QualType From = destType;
  355. if (auto Ptr = From->getAs<PointerType>()) {
  356. From = Ptr->getPointeeType();
  357. DifferentPtrness++;
  358. }
  359. QualType To = src->getType();
  360. if (auto Ptr = To->getAs<PointerType>()) {
  361. To = Ptr->getPointeeType();
  362. DifferentPtrness--;
  363. }
  364. if (!DifferentPtrness) {
  365. auto RecFrom = From->getAs<RecordType>();
  366. auto RecTo = To->getAs<RecordType>();
  367. if (RecFrom && RecTo) {
  368. auto DeclFrom = RecFrom->getAsCXXRecordDecl();
  369. if (!DeclFrom->isCompleteDefinition())
  370. S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
  371. << DeclFrom->getDeclName();
  372. auto DeclTo = RecTo->getAsCXXRecordDecl();
  373. if (!DeclTo->isCompleteDefinition())
  374. S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
  375. << DeclTo->getDeclName();
  376. }
  377. }
  378. }
  379. /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
  380. /// this removes one level of indirection from both types, provided that they're
  381. /// the same kind of pointer (plain or to-member). Unlike the Sema function,
  382. /// this one doesn't care if the two pointers-to-member don't point into the
  383. /// same class. This is because CastsAwayConstness doesn't care.
  384. /// And additionally, it handles C++ references. If both the types are
  385. /// references, then their pointee types are returned,
  386. /// else if only one of them is reference, it's pointee type is returned,
  387. /// and the other type is returned as-is.
  388. static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
  389. const PointerType *T1PtrType = T1->getAs<PointerType>(),
  390. *T2PtrType = T2->getAs<PointerType>();
  391. if (T1PtrType && T2PtrType) {
  392. T1 = T1PtrType->getPointeeType();
  393. T2 = T2PtrType->getPointeeType();
  394. return true;
  395. }
  396. const ObjCObjectPointerType *T1ObjCPtrType =
  397. T1->getAs<ObjCObjectPointerType>(),
  398. *T2ObjCPtrType =
  399. T2->getAs<ObjCObjectPointerType>();
  400. if (T1ObjCPtrType) {
  401. if (T2ObjCPtrType) {
  402. T1 = T1ObjCPtrType->getPointeeType();
  403. T2 = T2ObjCPtrType->getPointeeType();
  404. return true;
  405. }
  406. else if (T2PtrType) {
  407. T1 = T1ObjCPtrType->getPointeeType();
  408. T2 = T2PtrType->getPointeeType();
  409. return true;
  410. }
  411. }
  412. else if (T2ObjCPtrType) {
  413. if (T1PtrType) {
  414. T2 = T2ObjCPtrType->getPointeeType();
  415. T1 = T1PtrType->getPointeeType();
  416. return true;
  417. }
  418. }
  419. const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
  420. *T2MPType = T2->getAs<MemberPointerType>();
  421. if (T1MPType && T2MPType) {
  422. T1 = T1MPType->getPointeeType();
  423. T2 = T2MPType->getPointeeType();
  424. return true;
  425. }
  426. const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
  427. *T2BPType = T2->getAs<BlockPointerType>();
  428. if (T1BPType && T2BPType) {
  429. T1 = T1BPType->getPointeeType();
  430. T2 = T2BPType->getPointeeType();
  431. return true;
  432. }
  433. const LValueReferenceType *T1RefType = T1->getAs<LValueReferenceType>(),
  434. *T2RefType = T2->getAs<LValueReferenceType>();
  435. if (T1RefType && T2RefType) {
  436. T1 = T1RefType->getPointeeType();
  437. T2 = T2RefType->getPointeeType();
  438. return true;
  439. }
  440. if (T1RefType) {
  441. T1 = T1RefType->getPointeeType();
  442. // T2 = T2;
  443. return true;
  444. }
  445. if (T2RefType) {
  446. // T1 = T1;
  447. T2 = T2RefType->getPointeeType();
  448. return true;
  449. }
  450. return false;
  451. }
  452. /// CastsAwayConstness - Check if the pointer conversion from SrcType to
  453. /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
  454. /// the cast checkers. Both arguments must denote pointer (possibly to member)
  455. /// types.
  456. ///
  457. /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
  458. ///
  459. /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
  460. static bool
  461. CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
  462. bool CheckCVR, bool CheckObjCLifetime,
  463. QualType *TheOffendingSrcType = nullptr,
  464. QualType *TheOffendingDestType = nullptr,
  465. Qualifiers *CastAwayQualifiers = nullptr) {
  466. // If the only checking we care about is for Objective-C lifetime qualifiers,
  467. // and we're not in ObjC mode, there's nothing to check.
  468. if (!CheckCVR && CheckObjCLifetime &&
  469. !Self.Context.getLangOpts().ObjC1)
  470. return false;
  471. // Casting away constness is defined in C++ 5.2.11p8 with reference to
  472. // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
  473. // the rules are non-trivial. So first we construct Tcv *...cv* as described
  474. // in C++ 5.2.11p8.
  475. assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
  476. SrcType->isBlockPointerType() ||
  477. DestType->isLValueReferenceType()) &&
  478. "Source type is not pointer or pointer to member.");
  479. assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
  480. DestType->isBlockPointerType() ||
  481. DestType->isLValueReferenceType()) &&
  482. "Destination type is not pointer or pointer to member, or reference.");
  483. QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
  484. UnwrappedDestType = Self.Context.getCanonicalType(DestType);
  485. SmallVector<Qualifiers, 8> cv1, cv2;
  486. // Find the qualifiers. We only care about cvr-qualifiers for the
  487. // purpose of this check, because other qualifiers (address spaces,
  488. // Objective-C GC, etc.) are part of the type's identity.
  489. QualType PrevUnwrappedSrcType = UnwrappedSrcType;
  490. QualType PrevUnwrappedDestType = UnwrappedDestType;
  491. while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
  492. // Determine the relevant qualifiers at this level.
  493. Qualifiers SrcQuals, DestQuals;
  494. Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
  495. Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
  496. // We do not meaningfully track object const-ness of Objective-C object
  497. // types. Remove const from the source type if either the source or
  498. // the destination is an Objective-C object type.
  499. if (UnwrappedSrcType->isObjCObjectType() ||
  500. UnwrappedDestType->isObjCObjectType())
  501. SrcQuals.removeConst();
  502. Qualifiers RetainedSrcQuals, RetainedDestQuals;
  503. if (CheckCVR) {
  504. RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
  505. RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
  506. if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
  507. TheOffendingDestType && CastAwayQualifiers) {
  508. *TheOffendingSrcType = PrevUnwrappedSrcType;
  509. *TheOffendingDestType = PrevUnwrappedDestType;
  510. *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
  511. }
  512. }
  513. if (CheckObjCLifetime &&
  514. !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
  515. return true;
  516. cv1.push_back(RetainedSrcQuals);
  517. cv2.push_back(RetainedDestQuals);
  518. PrevUnwrappedSrcType = UnwrappedSrcType;
  519. PrevUnwrappedDestType = UnwrappedDestType;
  520. }
  521. if (cv1.empty())
  522. return false;
  523. // Construct void pointers with those qualifiers (in reverse order of
  524. // unwrapping, of course).
  525. QualType SrcConstruct = Self.Context.VoidTy;
  526. QualType DestConstruct = Self.Context.VoidTy;
  527. ASTContext &Context = Self.Context;
  528. for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
  529. i2 = cv2.rbegin();
  530. i1 != cv1.rend(); ++i1, ++i2) {
  531. SrcConstruct
  532. = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
  533. DestConstruct
  534. = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
  535. }
  536. // Test if they're compatible.
  537. bool ObjCLifetimeConversion;
  538. return SrcConstruct != DestConstruct &&
  539. !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
  540. ObjCLifetimeConversion);
  541. }
  542. /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
  543. /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
  544. /// checked downcasts in class hierarchies.
  545. void CastOperation::CheckDynamicCast() {
  546. if (ValueKind == VK_RValue)
  547. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  548. else if (isPlaceholder())
  549. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  550. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  551. return;
  552. QualType OrigSrcType = SrcExpr.get()->getType();
  553. QualType DestType = Self.Context.getCanonicalType(this->DestType);
  554. // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
  555. // or "pointer to cv void".
  556. QualType DestPointee;
  557. const PointerType *DestPointer = DestType->getAs<PointerType>();
  558. const ReferenceType *DestReference = nullptr;
  559. if (DestPointer) {
  560. DestPointee = DestPointer->getPointeeType();
  561. } else if ((DestReference = DestType->getAs<ReferenceType>())) {
  562. DestPointee = DestReference->getPointeeType();
  563. } else {
  564. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
  565. << this->DestType << DestRange;
  566. SrcExpr = ExprError();
  567. return;
  568. }
  569. const RecordType *DestRecord = DestPointee->getAs<RecordType>();
  570. if (DestPointee->isVoidType()) {
  571. assert(DestPointer && "Reference to void is not possible");
  572. } else if (DestRecord) {
  573. if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
  574. diag::err_bad_dynamic_cast_incomplete,
  575. DestRange)) {
  576. SrcExpr = ExprError();
  577. return;
  578. }
  579. } else {
  580. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
  581. << DestPointee.getUnqualifiedType() << DestRange;
  582. SrcExpr = ExprError();
  583. return;
  584. }
  585. // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
  586. // complete class type, [...]. If T is an lvalue reference type, v shall be
  587. // an lvalue of a complete class type, [...]. If T is an rvalue reference
  588. // type, v shall be an expression having a complete class type, [...]
  589. QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
  590. QualType SrcPointee;
  591. if (DestPointer) {
  592. if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
  593. SrcPointee = SrcPointer->getPointeeType();
  594. } else {
  595. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
  596. << OrigSrcType << SrcExpr.get()->getSourceRange();
  597. SrcExpr = ExprError();
  598. return;
  599. }
  600. } else if (DestReference->isLValueReferenceType()) {
  601. if (!SrcExpr.get()->isLValue()) {
  602. Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
  603. << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
  604. }
  605. SrcPointee = SrcType;
  606. } else {
  607. // If we're dynamic_casting from a prvalue to an rvalue reference, we need
  608. // to materialize the prvalue before we bind the reference to it.
  609. if (SrcExpr.get()->isRValue())
  610. SrcExpr = Self.CreateMaterializeTemporaryExpr(
  611. SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
  612. SrcPointee = SrcType;
  613. }
  614. const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
  615. if (SrcRecord) {
  616. if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
  617. diag::err_bad_dynamic_cast_incomplete,
  618. SrcExpr.get())) {
  619. SrcExpr = ExprError();
  620. return;
  621. }
  622. } else {
  623. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
  624. << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
  625. SrcExpr = ExprError();
  626. return;
  627. }
  628. assert((DestPointer || DestReference) &&
  629. "Bad destination non-ptr/ref slipped through.");
  630. assert((DestRecord || DestPointee->isVoidType()) &&
  631. "Bad destination pointee slipped through.");
  632. assert(SrcRecord && "Bad source pointee slipped through.");
  633. // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
  634. if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
  635. Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
  636. << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
  637. SrcExpr = ExprError();
  638. return;
  639. }
  640. // C++ 5.2.7p3: If the type of v is the same as the required result type,
  641. // [except for cv].
  642. if (DestRecord == SrcRecord) {
  643. Kind = CK_NoOp;
  644. return;
  645. }
  646. // C++ 5.2.7p5
  647. // Upcasts are resolved statically.
  648. if (DestRecord &&
  649. Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
  650. if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
  651. OpRange.getBegin(), OpRange,
  652. &BasePath)) {
  653. SrcExpr = ExprError();
  654. return;
  655. }
  656. Kind = CK_DerivedToBase;
  657. return;
  658. }
  659. // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
  660. const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
  661. assert(SrcDecl && "Definition missing");
  662. if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
  663. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
  664. << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
  665. SrcExpr = ExprError();
  666. }
  667. // dynamic_cast is not available with -fno-rtti.
  668. // As an exception, dynamic_cast to void* is available because it doesn't
  669. // use RTTI.
  670. if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
  671. Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
  672. SrcExpr = ExprError();
  673. return;
  674. }
  675. // Done. Everything else is run-time checks.
  676. Kind = CK_Dynamic;
  677. }
  678. /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
  679. /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
  680. /// like this:
  681. /// const char *str = "literal";
  682. /// legacy_function(const_cast\<char*\>(str));
  683. void CastOperation::CheckConstCast() {
  684. if (ValueKind == VK_RValue)
  685. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  686. else if (isPlaceholder())
  687. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  688. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  689. return;
  690. unsigned msg = diag::err_bad_cxx_cast_generic;
  691. if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
  692. && msg != 0) {
  693. Self.Diag(OpRange.getBegin(), msg) << CT_Const
  694. << SrcExpr.get()->getType() << DestType << OpRange;
  695. SrcExpr = ExprError();
  696. }
  697. }
  698. /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
  699. /// or downcast between respective pointers or references.
  700. static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
  701. QualType DestType,
  702. SourceRange OpRange) {
  703. QualType SrcType = SrcExpr->getType();
  704. // When casting from pointer or reference, get pointee type; use original
  705. // type otherwise.
  706. const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
  707. const CXXRecordDecl *SrcRD =
  708. SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
  709. // Examining subobjects for records is only possible if the complete and
  710. // valid definition is available. Also, template instantiation is not
  711. // allowed here.
  712. if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
  713. return;
  714. const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
  715. if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
  716. return;
  717. enum {
  718. ReinterpretUpcast,
  719. ReinterpretDowncast
  720. } ReinterpretKind;
  721. CXXBasePaths BasePaths;
  722. if (SrcRD->isDerivedFrom(DestRD, BasePaths))
  723. ReinterpretKind = ReinterpretUpcast;
  724. else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
  725. ReinterpretKind = ReinterpretDowncast;
  726. else
  727. return;
  728. bool VirtualBase = true;
  729. bool NonZeroOffset = false;
  730. for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
  731. E = BasePaths.end();
  732. I != E; ++I) {
  733. const CXXBasePath &Path = *I;
  734. CharUnits Offset = CharUnits::Zero();
  735. bool IsVirtual = false;
  736. for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
  737. IElem != EElem; ++IElem) {
  738. IsVirtual = IElem->Base->isVirtual();
  739. if (IsVirtual)
  740. break;
  741. const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
  742. assert(BaseRD && "Base type should be a valid unqualified class type");
  743. // Don't check if any base has invalid declaration or has no definition
  744. // since it has no layout info.
  745. const CXXRecordDecl *Class = IElem->Class,
  746. *ClassDefinition = Class->getDefinition();
  747. if (Class->isInvalidDecl() || !ClassDefinition ||
  748. !ClassDefinition->isCompleteDefinition())
  749. return;
  750. const ASTRecordLayout &DerivedLayout =
  751. Self.Context.getASTRecordLayout(Class);
  752. Offset += DerivedLayout.getBaseClassOffset(BaseRD);
  753. }
  754. if (!IsVirtual) {
  755. // Don't warn if any path is a non-virtually derived base at offset zero.
  756. if (Offset.isZero())
  757. return;
  758. // Offset makes sense only for non-virtual bases.
  759. else
  760. NonZeroOffset = true;
  761. }
  762. VirtualBase = VirtualBase && IsVirtual;
  763. }
  764. (void) NonZeroOffset; // Silence set but not used warning.
  765. assert((VirtualBase || NonZeroOffset) &&
  766. "Should have returned if has non-virtual base with zero offset");
  767. QualType BaseType =
  768. ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
  769. QualType DerivedType =
  770. ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
  771. SourceLocation BeginLoc = OpRange.getBegin();
  772. Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
  773. << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
  774. << OpRange;
  775. Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
  776. << int(ReinterpretKind)
  777. << FixItHint::CreateReplacement(BeginLoc, "static_cast");
  778. }
  779. /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
  780. /// valid.
  781. /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
  782. /// like this:
  783. /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
  784. void CastOperation::CheckReinterpretCast() {
  785. if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
  786. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  787. else
  788. checkNonOverloadPlaceholders();
  789. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  790. return;
  791. unsigned msg = diag::err_bad_cxx_cast_generic;
  792. TryCastResult tcr =
  793. TryReinterpretCast(Self, SrcExpr, DestType,
  794. /*CStyle*/false, OpRange, msg, Kind);
  795. if (tcr != TC_Success && msg != 0)
  796. {
  797. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  798. return;
  799. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  800. //FIXME: &f<int>; is overloaded and resolvable
  801. Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
  802. << OverloadExpr::find(SrcExpr.get()).Expression->getName()
  803. << DestType << OpRange;
  804. Self.NoteAllOverloadCandidates(SrcExpr.get());
  805. } else {
  806. diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
  807. DestType, /*listInitialization=*/false);
  808. }
  809. SrcExpr = ExprError();
  810. } else if (tcr == TC_Success) {
  811. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
  812. checkObjCConversion(Sema::CCK_OtherCast);
  813. DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
  814. }
  815. }
  816. /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
  817. /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
  818. /// implicit conversions explicit and getting rid of data loss warnings.
  819. void CastOperation::CheckStaticCast() {
  820. if (isPlaceholder()) {
  821. checkNonOverloadPlaceholders();
  822. if (SrcExpr.isInvalid())
  823. return;
  824. }
  825. // This test is outside everything else because it's the only case where
  826. // a non-lvalue-reference target type does not lead to decay.
  827. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  828. if (DestType->isVoidType()) {
  829. Kind = CK_ToVoid;
  830. if (claimPlaceholder(BuiltinType::Overload)) {
  831. Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
  832. false, // Decay Function to ptr
  833. true, // Complain
  834. OpRange, DestType, diag::err_bad_static_cast_overload);
  835. if (SrcExpr.isInvalid())
  836. return;
  837. }
  838. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  839. return;
  840. }
  841. if (ValueKind == VK_RValue && !DestType->isRecordType() &&
  842. !isPlaceholder(BuiltinType::Overload)) {
  843. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  844. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  845. return;
  846. }
  847. unsigned msg = diag::err_bad_cxx_cast_generic;
  848. TryCastResult tcr
  849. = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
  850. Kind, BasePath, /*ListInitialization=*/false);
  851. if (tcr != TC_Success && msg != 0) {
  852. if (SrcExpr.isInvalid())
  853. return;
  854. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  855. OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
  856. Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
  857. << oe->getName() << DestType << OpRange
  858. << oe->getQualifierLoc().getSourceRange();
  859. Self.NoteAllOverloadCandidates(SrcExpr.get());
  860. } else {
  861. diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
  862. /*listInitialization=*/false);
  863. }
  864. SrcExpr = ExprError();
  865. } else if (tcr == TC_Success) {
  866. if (Kind == CK_BitCast)
  867. checkCastAlign();
  868. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
  869. checkObjCConversion(Sema::CCK_OtherCast);
  870. } else if (Kind == CK_BitCast) {
  871. checkCastAlign();
  872. }
  873. }
  874. /// TryStaticCast - Check if a static cast can be performed, and do so if
  875. /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
  876. /// and casting away constness.
  877. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
  878. QualType DestType,
  879. Sema::CheckedConversionKind CCK,
  880. SourceRange OpRange, unsigned &msg,
  881. CastKind &Kind, CXXCastPath &BasePath,
  882. bool ListInitialization) {
  883. // Determine whether we have the semantics of a C-style cast.
  884. bool CStyle
  885. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  886. // The order the tests is not entirely arbitrary. There is one conversion
  887. // that can be handled in two different ways. Given:
  888. // struct A {};
  889. // struct B : public A {
  890. // B(); B(const A&);
  891. // };
  892. // const A &a = B();
  893. // the cast static_cast<const B&>(a) could be seen as either a static
  894. // reference downcast, or an explicit invocation of the user-defined
  895. // conversion using B's conversion constructor.
  896. // DR 427 specifies that the downcast is to be applied here.
  897. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  898. // Done outside this function.
  899. TryCastResult tcr;
  900. // C++ 5.2.9p5, reference downcast.
  901. // See the function for details.
  902. // DR 427 specifies that this is to be applied before paragraph 2.
  903. tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
  904. OpRange, msg, Kind, BasePath);
  905. if (tcr != TC_NotApplicable)
  906. return tcr;
  907. // C++11 [expr.static.cast]p3:
  908. // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
  909. // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
  910. tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
  911. BasePath, msg);
  912. if (tcr != TC_NotApplicable)
  913. return tcr;
  914. // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
  915. // [...] if the declaration "T t(e);" is well-formed, [...].
  916. tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
  917. Kind, ListInitialization);
  918. if (SrcExpr.isInvalid())
  919. return TC_Failed;
  920. if (tcr != TC_NotApplicable)
  921. return tcr;
  922. // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
  923. // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
  924. // conversions, subject to further restrictions.
  925. // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
  926. // of qualification conversions impossible.
  927. // In the CStyle case, the earlier attempt to const_cast should have taken
  928. // care of reverse qualification conversions.
  929. QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
  930. // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
  931. // converted to an integral type. [...] A value of a scoped enumeration type
  932. // can also be explicitly converted to a floating-point type [...].
  933. if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
  934. if (Enum->getDecl()->isScoped()) {
  935. if (DestType->isBooleanType()) {
  936. Kind = CK_IntegralToBoolean;
  937. return TC_Success;
  938. } else if (DestType->isIntegralType(Self.Context)) {
  939. Kind = CK_IntegralCast;
  940. return TC_Success;
  941. } else if (DestType->isRealFloatingType()) {
  942. Kind = CK_IntegralToFloating;
  943. return TC_Success;
  944. }
  945. }
  946. }
  947. // Reverse integral promotion/conversion. All such conversions are themselves
  948. // again integral promotions or conversions and are thus already handled by
  949. // p2 (TryDirectInitialization above).
  950. // (Note: any data loss warnings should be suppressed.)
  951. // The exception is the reverse of enum->integer, i.e. integer->enum (and
  952. // enum->enum). See also C++ 5.2.9p7.
  953. // The same goes for reverse floating point promotion/conversion and
  954. // floating-integral conversions. Again, only floating->enum is relevant.
  955. if (DestType->isEnumeralType()) {
  956. if (SrcType->isIntegralOrEnumerationType()) {
  957. Kind = CK_IntegralCast;
  958. return TC_Success;
  959. } else if (SrcType->isRealFloatingType()) {
  960. Kind = CK_FloatingToIntegral;
  961. return TC_Success;
  962. }
  963. }
  964. // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
  965. // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
  966. tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
  967. Kind, BasePath);
  968. if (tcr != TC_NotApplicable)
  969. return tcr;
  970. // Reverse member pointer conversion. C++ 4.11 specifies member pointer
  971. // conversion. C++ 5.2.9p9 has additional information.
  972. // DR54's access restrictions apply here also.
  973. tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
  974. OpRange, msg, Kind, BasePath);
  975. if (tcr != TC_NotApplicable)
  976. return tcr;
  977. // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
  978. // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
  979. // just the usual constness stuff.
  980. if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
  981. QualType SrcPointee = SrcPointer->getPointeeType();
  982. if (SrcPointee->isVoidType()) {
  983. if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
  984. QualType DestPointee = DestPointer->getPointeeType();
  985. if (DestPointee->isIncompleteOrObjectType()) {
  986. // This is definitely the intended conversion, but it might fail due
  987. // to a qualifier violation. Note that we permit Objective-C lifetime
  988. // and GC qualifier mismatches here.
  989. if (!CStyle) {
  990. Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
  991. Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
  992. DestPointeeQuals.removeObjCGCAttr();
  993. DestPointeeQuals.removeObjCLifetime();
  994. SrcPointeeQuals.removeObjCGCAttr();
  995. SrcPointeeQuals.removeObjCLifetime();
  996. if (DestPointeeQuals != SrcPointeeQuals &&
  997. !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
  998. msg = diag::err_bad_cxx_cast_qualifiers_away;
  999. return TC_Failed;
  1000. }
  1001. }
  1002. Kind = CK_BitCast;
  1003. return TC_Success;
  1004. }
  1005. // Microsoft permits static_cast from 'pointer-to-void' to
  1006. // 'pointer-to-function'.
  1007. if (!CStyle && Self.getLangOpts().MSVCCompat &&
  1008. DestPointee->isFunctionType()) {
  1009. Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
  1010. Kind = CK_BitCast;
  1011. return TC_Success;
  1012. }
  1013. }
  1014. else if (DestType->isObjCObjectPointerType()) {
  1015. // allow both c-style cast and static_cast of objective-c pointers as
  1016. // they are pervasive.
  1017. Kind = CK_CPointerToObjCPointerCast;
  1018. return TC_Success;
  1019. }
  1020. else if (CStyle && DestType->isBlockPointerType()) {
  1021. // allow c-style cast of void * to block pointers.
  1022. Kind = CK_AnyPointerToBlockPointerCast;
  1023. return TC_Success;
  1024. }
  1025. }
  1026. }
  1027. // Allow arbitrary objective-c pointer conversion with static casts.
  1028. if (SrcType->isObjCObjectPointerType() &&
  1029. DestType->isObjCObjectPointerType()) {
  1030. Kind = CK_BitCast;
  1031. return TC_Success;
  1032. }
  1033. // Allow ns-pointer to cf-pointer conversion in either direction
  1034. // with static casts.
  1035. if (!CStyle &&
  1036. Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
  1037. return TC_Success;
  1038. // See if it looks like the user is trying to convert between
  1039. // related record types, and select a better diagnostic if so.
  1040. if (auto SrcPointer = SrcType->getAs<PointerType>())
  1041. if (auto DestPointer = DestType->getAs<PointerType>())
  1042. if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
  1043. DestPointer->getPointeeType()->getAs<RecordType>())
  1044. msg = diag::err_bad_cxx_cast_unrelated_class;
  1045. // We tried everything. Everything! Nothing works! :-(
  1046. return TC_NotApplicable;
  1047. }
  1048. /// Tests whether a conversion according to N2844 is valid.
  1049. TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
  1050. QualType DestType, bool CStyle,
  1051. CastKind &Kind, CXXCastPath &BasePath,
  1052. unsigned &msg) {
  1053. // C++11 [expr.static.cast]p3:
  1054. // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
  1055. // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
  1056. const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
  1057. if (!R)
  1058. return TC_NotApplicable;
  1059. if (!SrcExpr->isGLValue())
  1060. return TC_NotApplicable;
  1061. // Because we try the reference downcast before this function, from now on
  1062. // this is the only cast possibility, so we issue an error if we fail now.
  1063. // FIXME: Should allow casting away constness if CStyle.
  1064. bool DerivedToBase;
  1065. bool ObjCConversion;
  1066. bool ObjCLifetimeConversion;
  1067. QualType FromType = SrcExpr->getType();
  1068. QualType ToType = R->getPointeeType();
  1069. if (CStyle) {
  1070. FromType = FromType.getUnqualifiedType();
  1071. ToType = ToType.getUnqualifiedType();
  1072. }
  1073. Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
  1074. SrcExpr->getLocStart(), ToType, FromType, DerivedToBase, ObjCConversion,
  1075. ObjCLifetimeConversion);
  1076. if (RefResult != Sema::Ref_Compatible) {
  1077. if (CStyle || RefResult == Sema::Ref_Incompatible)
  1078. return TC_NotApplicable;
  1079. // Diagnose types which are reference-related but not compatible here since
  1080. // we can provide better diagnostics. In these cases forwarding to
  1081. // [expr.static.cast]p4 should never result in a well-formed cast.
  1082. msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
  1083. : diag::err_bad_rvalue_to_rvalue_cast;
  1084. return TC_Failed;
  1085. }
  1086. if (DerivedToBase) {
  1087. Kind = CK_DerivedToBase;
  1088. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1089. /*DetectVirtual=*/true);
  1090. if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(),
  1091. R->getPointeeType(), Paths))
  1092. return TC_NotApplicable;
  1093. Self.BuildBasePathArray(Paths, BasePath);
  1094. } else
  1095. Kind = CK_NoOp;
  1096. return TC_Success;
  1097. }
  1098. /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
  1099. TryCastResult
  1100. TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
  1101. bool CStyle, SourceRange OpRange,
  1102. unsigned &msg, CastKind &Kind,
  1103. CXXCastPath &BasePath) {
  1104. // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
  1105. // cast to type "reference to cv2 D", where D is a class derived from B,
  1106. // if a valid standard conversion from "pointer to D" to "pointer to B"
  1107. // exists, cv2 >= cv1, and B is not a virtual base class of D.
  1108. // In addition, DR54 clarifies that the base must be accessible in the
  1109. // current context. Although the wording of DR54 only applies to the pointer
  1110. // variant of this rule, the intent is clearly for it to apply to the this
  1111. // conversion as well.
  1112. const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
  1113. if (!DestReference) {
  1114. return TC_NotApplicable;
  1115. }
  1116. bool RValueRef = DestReference->isRValueReferenceType();
  1117. if (!RValueRef && !SrcExpr->isLValue()) {
  1118. // We know the left side is an lvalue reference, so we can suggest a reason.
  1119. msg = diag::err_bad_cxx_cast_rvalue;
  1120. return TC_NotApplicable;
  1121. }
  1122. QualType DestPointee = DestReference->getPointeeType();
  1123. // FIXME: If the source is a prvalue, we should issue a warning (because the
  1124. // cast always has undefined behavior), and for AST consistency, we should
  1125. // materialize a temporary.
  1126. return TryStaticDowncast(Self,
  1127. Self.Context.getCanonicalType(SrcExpr->getType()),
  1128. Self.Context.getCanonicalType(DestPointee), CStyle,
  1129. OpRange, SrcExpr->getType(), DestType, msg, Kind,
  1130. BasePath);
  1131. }
  1132. /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
  1133. TryCastResult
  1134. TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
  1135. bool CStyle, SourceRange OpRange,
  1136. unsigned &msg, CastKind &Kind,
  1137. CXXCastPath &BasePath) {
  1138. // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
  1139. // type, can be converted to an rvalue of type "pointer to cv2 D", where D
  1140. // is a class derived from B, if a valid standard conversion from "pointer
  1141. // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
  1142. // class of D.
  1143. // In addition, DR54 clarifies that the base must be accessible in the
  1144. // current context.
  1145. const PointerType *DestPointer = DestType->getAs<PointerType>();
  1146. if (!DestPointer) {
  1147. return TC_NotApplicable;
  1148. }
  1149. const PointerType *SrcPointer = SrcType->getAs<PointerType>();
  1150. if (!SrcPointer) {
  1151. msg = diag::err_bad_static_cast_pointer_nonpointer;
  1152. return TC_NotApplicable;
  1153. }
  1154. return TryStaticDowncast(Self,
  1155. Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
  1156. Self.Context.getCanonicalType(DestPointer->getPointeeType()),
  1157. CStyle, OpRange, SrcType, DestType, msg, Kind,
  1158. BasePath);
  1159. }
  1160. /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
  1161. /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
  1162. /// DestType is possible and allowed.
  1163. TryCastResult
  1164. TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
  1165. bool CStyle, SourceRange OpRange, QualType OrigSrcType,
  1166. QualType OrigDestType, unsigned &msg,
  1167. CastKind &Kind, CXXCastPath &BasePath) {
  1168. // We can only work with complete types. But don't complain if it doesn't work
  1169. if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
  1170. !Self.isCompleteType(OpRange.getBegin(), DestType))
  1171. return TC_NotApplicable;
  1172. // Downcast can only happen in class hierarchies, so we need classes.
  1173. if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
  1174. return TC_NotApplicable;
  1175. }
  1176. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1177. /*DetectVirtual=*/true);
  1178. if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
  1179. return TC_NotApplicable;
  1180. }
  1181. // Target type does derive from source type. Now we're serious. If an error
  1182. // appears now, it's not ignored.
  1183. // This may not be entirely in line with the standard. Take for example:
  1184. // struct A {};
  1185. // struct B : virtual A {
  1186. // B(A&);
  1187. // };
  1188. //
  1189. // void f()
  1190. // {
  1191. // (void)static_cast<const B&>(*((A*)0));
  1192. // }
  1193. // As far as the standard is concerned, p5 does not apply (A is virtual), so
  1194. // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
  1195. // However, both GCC and Comeau reject this example, and accepting it would
  1196. // mean more complex code if we're to preserve the nice error message.
  1197. // FIXME: Being 100% compliant here would be nice to have.
  1198. // Must preserve cv, as always, unless we're in C-style mode.
  1199. if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
  1200. msg = diag::err_bad_cxx_cast_qualifiers_away;
  1201. return TC_Failed;
  1202. }
  1203. if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
  1204. // This code is analoguous to that in CheckDerivedToBaseConversion, except
  1205. // that it builds the paths in reverse order.
  1206. // To sum up: record all paths to the base and build a nice string from
  1207. // them. Use it to spice up the error message.
  1208. if (!Paths.isRecordingPaths()) {
  1209. Paths.clear();
  1210. Paths.setRecordingPaths(true);
  1211. Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
  1212. }
  1213. std::string PathDisplayStr;
  1214. std::set<unsigned> DisplayedPaths;
  1215. for (clang::CXXBasePath &Path : Paths) {
  1216. if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
  1217. // We haven't displayed a path to this particular base
  1218. // class subobject yet.
  1219. PathDisplayStr += "\n ";
  1220. for (CXXBasePathElement &PE : llvm::reverse(Path))
  1221. PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
  1222. PathDisplayStr += QualType(DestType).getAsString();
  1223. }
  1224. }
  1225. Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
  1226. << QualType(SrcType).getUnqualifiedType()
  1227. << QualType(DestType).getUnqualifiedType()
  1228. << PathDisplayStr << OpRange;
  1229. msg = 0;
  1230. return TC_Failed;
  1231. }
  1232. if (Paths.getDetectedVirtual() != nullptr) {
  1233. QualType VirtualBase(Paths.getDetectedVirtual(), 0);
  1234. Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
  1235. << OrigSrcType << OrigDestType << VirtualBase << OpRange;
  1236. msg = 0;
  1237. return TC_Failed;
  1238. }
  1239. if (!CStyle) {
  1240. switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
  1241. SrcType, DestType,
  1242. Paths.front(),
  1243. diag::err_downcast_from_inaccessible_base)) {
  1244. case Sema::AR_accessible:
  1245. case Sema::AR_delayed: // be optimistic
  1246. case Sema::AR_dependent: // be optimistic
  1247. break;
  1248. case Sema::AR_inaccessible:
  1249. msg = 0;
  1250. return TC_Failed;
  1251. }
  1252. }
  1253. Self.BuildBasePathArray(Paths, BasePath);
  1254. Kind = CK_BaseToDerived;
  1255. return TC_Success;
  1256. }
  1257. /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
  1258. /// C++ 5.2.9p9 is valid:
  1259. ///
  1260. /// An rvalue of type "pointer to member of D of type cv1 T" can be
  1261. /// converted to an rvalue of type "pointer to member of B of type cv2 T",
  1262. /// where B is a base class of D [...].
  1263. ///
  1264. TryCastResult
  1265. TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
  1266. QualType DestType, bool CStyle,
  1267. SourceRange OpRange,
  1268. unsigned &msg, CastKind &Kind,
  1269. CXXCastPath &BasePath) {
  1270. const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
  1271. if (!DestMemPtr)
  1272. return TC_NotApplicable;
  1273. bool WasOverloadedFunction = false;
  1274. DeclAccessPair FoundOverload;
  1275. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  1276. if (FunctionDecl *Fn
  1277. = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
  1278. FoundOverload)) {
  1279. CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
  1280. SrcType = Self.Context.getMemberPointerType(Fn->getType(),
  1281. Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
  1282. WasOverloadedFunction = true;
  1283. }
  1284. }
  1285. const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
  1286. if (!SrcMemPtr) {
  1287. msg = diag::err_bad_static_cast_member_pointer_nonmp;
  1288. return TC_NotApplicable;
  1289. }
  1290. // Lock down the inheritance model right now in MS ABI, whether or not the
  1291. // pointee types are the same.
  1292. if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1293. (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
  1294. (void)Self.isCompleteType(OpRange.getBegin(), DestType);
  1295. }
  1296. // T == T, modulo cv
  1297. if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
  1298. DestMemPtr->getPointeeType()))
  1299. return TC_NotApplicable;
  1300. // B base of D
  1301. QualType SrcClass(SrcMemPtr->getClass(), 0);
  1302. QualType DestClass(DestMemPtr->getClass(), 0);
  1303. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1304. /*DetectVirtual=*/true);
  1305. if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
  1306. return TC_NotApplicable;
  1307. // B is a base of D. But is it an allowed base? If not, it's a hard error.
  1308. if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
  1309. Paths.clear();
  1310. Paths.setRecordingPaths(true);
  1311. bool StillOkay =
  1312. Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
  1313. assert(StillOkay);
  1314. (void)StillOkay;
  1315. std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
  1316. Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
  1317. << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
  1318. msg = 0;
  1319. return TC_Failed;
  1320. }
  1321. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  1322. Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
  1323. << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
  1324. msg = 0;
  1325. return TC_Failed;
  1326. }
  1327. if (!CStyle) {
  1328. switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
  1329. DestClass, SrcClass,
  1330. Paths.front(),
  1331. diag::err_upcast_to_inaccessible_base)) {
  1332. case Sema::AR_accessible:
  1333. case Sema::AR_delayed:
  1334. case Sema::AR_dependent:
  1335. // Optimistically assume that the delayed and dependent cases
  1336. // will work out.
  1337. break;
  1338. case Sema::AR_inaccessible:
  1339. msg = 0;
  1340. return TC_Failed;
  1341. }
  1342. }
  1343. if (WasOverloadedFunction) {
  1344. // Resolve the address of the overloaded function again, this time
  1345. // allowing complaints if something goes wrong.
  1346. FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
  1347. DestType,
  1348. true,
  1349. FoundOverload);
  1350. if (!Fn) {
  1351. msg = 0;
  1352. return TC_Failed;
  1353. }
  1354. SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
  1355. if (!SrcExpr.isUsable()) {
  1356. msg = 0;
  1357. return TC_Failed;
  1358. }
  1359. }
  1360. Self.BuildBasePathArray(Paths, BasePath);
  1361. Kind = CK_DerivedToBaseMemberPointer;
  1362. return TC_Success;
  1363. }
  1364. /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
  1365. /// is valid:
  1366. ///
  1367. /// An expression e can be explicitly converted to a type T using a
  1368. /// @c static_cast if the declaration "T t(e);" is well-formed [...].
  1369. TryCastResult
  1370. TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
  1371. Sema::CheckedConversionKind CCK,
  1372. SourceRange OpRange, unsigned &msg,
  1373. CastKind &Kind, bool ListInitialization) {
  1374. if (DestType->isRecordType()) {
  1375. if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
  1376. diag::err_bad_dynamic_cast_incomplete) ||
  1377. Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
  1378. diag::err_allocation_of_abstract_type)) {
  1379. msg = 0;
  1380. return TC_Failed;
  1381. }
  1382. }
  1383. InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
  1384. InitializationKind InitKind
  1385. = (CCK == Sema::CCK_CStyleCast)
  1386. ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
  1387. ListInitialization)
  1388. : (CCK == Sema::CCK_FunctionalCast)
  1389. ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
  1390. : InitializationKind::CreateCast(OpRange);
  1391. Expr *SrcExprRaw = SrcExpr.get();
  1392. // FIXME: Per DR242, we should check for an implicit conversion sequence
  1393. // or for a constructor that could be invoked by direct-initialization
  1394. // here, not for an initialization sequence.
  1395. InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
  1396. // At this point of CheckStaticCast, if the destination is a reference,
  1397. // or the expression is an overload expression this has to work.
  1398. // There is no other way that works.
  1399. // On the other hand, if we're checking a C-style cast, we've still got
  1400. // the reinterpret_cast way.
  1401. bool CStyle
  1402. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  1403. if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
  1404. return TC_NotApplicable;
  1405. ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
  1406. if (Result.isInvalid()) {
  1407. msg = 0;
  1408. return TC_Failed;
  1409. }
  1410. if (InitSeq.isConstructorInitialization())
  1411. Kind = CK_ConstructorConversion;
  1412. else
  1413. Kind = CK_NoOp;
  1414. SrcExpr = Result;
  1415. return TC_Success;
  1416. }
  1417. /// TryConstCast - See if a const_cast from source to destination is allowed,
  1418. /// and perform it if it is.
  1419. static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
  1420. QualType DestType, bool CStyle,
  1421. unsigned &msg) {
  1422. DestType = Self.Context.getCanonicalType(DestType);
  1423. QualType SrcType = SrcExpr.get()->getType();
  1424. bool NeedToMaterializeTemporary = false;
  1425. if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
  1426. // C++11 5.2.11p4:
  1427. // if a pointer to T1 can be explicitly converted to the type "pointer to
  1428. // T2" using a const_cast, then the following conversions can also be
  1429. // made:
  1430. // -- an lvalue of type T1 can be explicitly converted to an lvalue of
  1431. // type T2 using the cast const_cast<T2&>;
  1432. // -- a glvalue of type T1 can be explicitly converted to an xvalue of
  1433. // type T2 using the cast const_cast<T2&&>; and
  1434. // -- if T1 is a class type, a prvalue of type T1 can be explicitly
  1435. // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
  1436. if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
  1437. // Cannot const_cast non-lvalue to lvalue reference type. But if this
  1438. // is C-style, static_cast might find a way, so we simply suggest a
  1439. // message and tell the parent to keep searching.
  1440. msg = diag::err_bad_cxx_cast_rvalue;
  1441. return TC_NotApplicable;
  1442. }
  1443. if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
  1444. if (!SrcType->isRecordType()) {
  1445. // Cannot const_cast non-class prvalue to rvalue reference type. But if
  1446. // this is C-style, static_cast can do this.
  1447. msg = diag::err_bad_cxx_cast_rvalue;
  1448. return TC_NotApplicable;
  1449. }
  1450. // Materialize the class prvalue so that the const_cast can bind a
  1451. // reference to it.
  1452. NeedToMaterializeTemporary = true;
  1453. }
  1454. // It's not completely clear under the standard whether we can
  1455. // const_cast bit-field gl-values. Doing so would not be
  1456. // intrinsically complicated, but for now, we say no for
  1457. // consistency with other compilers and await the word of the
  1458. // committee.
  1459. if (SrcExpr.get()->refersToBitField()) {
  1460. msg = diag::err_bad_cxx_cast_bitfield;
  1461. return TC_NotApplicable;
  1462. }
  1463. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
  1464. SrcType = Self.Context.getPointerType(SrcType);
  1465. }
  1466. // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
  1467. // the rules for const_cast are the same as those used for pointers.
  1468. if (!DestType->isPointerType() &&
  1469. !DestType->isMemberPointerType() &&
  1470. !DestType->isObjCObjectPointerType()) {
  1471. // Cannot cast to non-pointer, non-reference type. Note that, if DestType
  1472. // was a reference type, we converted it to a pointer above.
  1473. // The status of rvalue references isn't entirely clear, but it looks like
  1474. // conversion to them is simply invalid.
  1475. // C++ 5.2.11p3: For two pointer types [...]
  1476. if (!CStyle)
  1477. msg = diag::err_bad_const_cast_dest;
  1478. return TC_NotApplicable;
  1479. }
  1480. if (DestType->isFunctionPointerType() ||
  1481. DestType->isMemberFunctionPointerType()) {
  1482. // Cannot cast direct function pointers.
  1483. // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
  1484. // T is the ultimate pointee of source and target type.
  1485. if (!CStyle)
  1486. msg = diag::err_bad_const_cast_dest;
  1487. return TC_NotApplicable;
  1488. }
  1489. SrcType = Self.Context.getCanonicalType(SrcType);
  1490. // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
  1491. // completely equal.
  1492. // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
  1493. // in multi-level pointers may change, but the level count must be the same,
  1494. // as must be the final pointee type.
  1495. while (SrcType != DestType &&
  1496. Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
  1497. Qualifiers SrcQuals, DestQuals;
  1498. SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
  1499. DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
  1500. // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
  1501. // the other qualifiers (e.g., address spaces) are identical.
  1502. SrcQuals.removeCVRQualifiers();
  1503. DestQuals.removeCVRQualifiers();
  1504. if (SrcQuals != DestQuals)
  1505. return TC_NotApplicable;
  1506. }
  1507. // Since we're dealing in canonical types, the remainder must be the same.
  1508. if (SrcType != DestType)
  1509. return TC_NotApplicable;
  1510. if (NeedToMaterializeTemporary)
  1511. // This is a const_cast from a class prvalue to an rvalue reference type.
  1512. // Materialize a temporary to store the result of the conversion.
  1513. SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
  1514. SrcExpr.get(),
  1515. /*IsLValueReference*/ false);
  1516. return TC_Success;
  1517. }
  1518. // Checks for undefined behavior in reinterpret_cast.
  1519. // The cases that is checked for is:
  1520. // *reinterpret_cast<T*>(&a)
  1521. // reinterpret_cast<T&>(a)
  1522. // where accessing 'a' as type 'T' will result in undefined behavior.
  1523. void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
  1524. bool IsDereference,
  1525. SourceRange Range) {
  1526. unsigned DiagID = IsDereference ?
  1527. diag::warn_pointer_indirection_from_incompatible_type :
  1528. diag::warn_undefined_reinterpret_cast;
  1529. if (Diags.isIgnored(DiagID, Range.getBegin()))
  1530. return;
  1531. QualType SrcTy, DestTy;
  1532. if (IsDereference) {
  1533. if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
  1534. return;
  1535. }
  1536. SrcTy = SrcType->getPointeeType();
  1537. DestTy = DestType->getPointeeType();
  1538. } else {
  1539. if (!DestType->getAs<ReferenceType>()) {
  1540. return;
  1541. }
  1542. SrcTy = SrcType;
  1543. DestTy = DestType->getPointeeType();
  1544. }
  1545. // Cast is compatible if the types are the same.
  1546. if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
  1547. return;
  1548. }
  1549. // or one of the types is a char or void type
  1550. if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
  1551. SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
  1552. return;
  1553. }
  1554. // or one of the types is a tag type.
  1555. if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
  1556. return;
  1557. }
  1558. // FIXME: Scoped enums?
  1559. if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
  1560. (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
  1561. if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
  1562. return;
  1563. }
  1564. }
  1565. Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
  1566. }
  1567. static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
  1568. QualType DestType) {
  1569. QualType SrcType = SrcExpr.get()->getType();
  1570. if (Self.Context.hasSameType(SrcType, DestType))
  1571. return;
  1572. if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
  1573. if (SrcPtrTy->isObjCSelType()) {
  1574. QualType DT = DestType;
  1575. if (isa<PointerType>(DestType))
  1576. DT = DestType->getPointeeType();
  1577. if (!DT.getUnqualifiedType()->isVoidType())
  1578. Self.Diag(SrcExpr.get()->getExprLoc(),
  1579. diag::warn_cast_pointer_from_sel)
  1580. << SrcType << DestType << SrcExpr.get()->getSourceRange();
  1581. }
  1582. }
  1583. /// Diagnose casts that change the calling convention of a pointer to a function
  1584. /// defined in the current TU.
  1585. static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
  1586. QualType DstType, SourceRange OpRange) {
  1587. // Check if this cast would change the calling convention of a function
  1588. // pointer type.
  1589. QualType SrcType = SrcExpr.get()->getType();
  1590. if (Self.Context.hasSameType(SrcType, DstType) ||
  1591. !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
  1592. return;
  1593. const auto *SrcFTy =
  1594. SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
  1595. const auto *DstFTy =
  1596. DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
  1597. CallingConv SrcCC = SrcFTy->getCallConv();
  1598. CallingConv DstCC = DstFTy->getCallConv();
  1599. if (SrcCC == DstCC)
  1600. return;
  1601. // We have a calling convention cast. Check if the source is a pointer to a
  1602. // known, specific function that has already been defined.
  1603. Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
  1604. if (auto *UO = dyn_cast<UnaryOperator>(Src))
  1605. if (UO->getOpcode() == UO_AddrOf)
  1606. Src = UO->getSubExpr()->IgnoreParenImpCasts();
  1607. auto *DRE = dyn_cast<DeclRefExpr>(Src);
  1608. if (!DRE)
  1609. return;
  1610. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  1611. if (!FD)
  1612. return;
  1613. // Only warn if we are casting from the default convention to a non-default
  1614. // convention. This can happen when the programmer forgot to apply the calling
  1615. // convention to the function declaration and then inserted this cast to
  1616. // satisfy the type system.
  1617. CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
  1618. FD->isVariadic(), FD->isCXXInstanceMember());
  1619. if (DstCC == DefaultCC || SrcCC != DefaultCC)
  1620. return;
  1621. // Diagnose this cast, as it is probably bad.
  1622. StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
  1623. StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
  1624. Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
  1625. << SrcCCName << DstCCName << OpRange;
  1626. // The checks above are cheaper than checking if the diagnostic is enabled.
  1627. // However, it's worth checking if the warning is enabled before we construct
  1628. // a fixit.
  1629. if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
  1630. return;
  1631. // Try to suggest a fixit to change the calling convention of the function
  1632. // whose address was taken. Try to use the latest macro for the convention.
  1633. // For example, users probably want to write "WINAPI" instead of "__stdcall"
  1634. // to match the Windows header declarations.
  1635. SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
  1636. Preprocessor &PP = Self.getPreprocessor();
  1637. SmallVector<TokenValue, 6> AttrTokens;
  1638. SmallString<64> CCAttrText;
  1639. llvm::raw_svector_ostream OS(CCAttrText);
  1640. if (Self.getLangOpts().MicrosoftExt) {
  1641. // __stdcall or __vectorcall
  1642. OS << "__" << DstCCName;
  1643. IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
  1644. AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
  1645. ? TokenValue(II->getTokenID())
  1646. : TokenValue(II));
  1647. } else {
  1648. // __attribute__((stdcall)) or __attribute__((vectorcall))
  1649. OS << "__attribute__((" << DstCCName << "))";
  1650. AttrTokens.push_back(tok::kw___attribute);
  1651. AttrTokens.push_back(tok::l_paren);
  1652. AttrTokens.push_back(tok::l_paren);
  1653. IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
  1654. AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
  1655. ? TokenValue(II->getTokenID())
  1656. : TokenValue(II));
  1657. AttrTokens.push_back(tok::r_paren);
  1658. AttrTokens.push_back(tok::r_paren);
  1659. }
  1660. StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
  1661. if (!AttrSpelling.empty())
  1662. CCAttrText = AttrSpelling;
  1663. OS << ' ';
  1664. Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
  1665. << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
  1666. }
  1667. static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
  1668. const Expr *SrcExpr, QualType DestType,
  1669. Sema &Self) {
  1670. QualType SrcType = SrcExpr->getType();
  1671. // Not warning on reinterpret_cast, boolean, constant expressions, etc
  1672. // are not explicit design choices, but consistent with GCC's behavior.
  1673. // Feel free to modify them if you've reason/evidence for an alternative.
  1674. if (CStyle && SrcType->isIntegralType(Self.Context)
  1675. && !SrcType->isBooleanType()
  1676. && !SrcType->isEnumeralType()
  1677. && !SrcExpr->isIntegerConstantExpr(Self.Context)
  1678. && Self.Context.getTypeSize(DestType) >
  1679. Self.Context.getTypeSize(SrcType)) {
  1680. // Separate between casts to void* and non-void* pointers.
  1681. // Some APIs use (abuse) void* for something like a user context,
  1682. // and often that value is an integer even if it isn't a pointer itself.
  1683. // Having a separate warning flag allows users to control the warning
  1684. // for their workflow.
  1685. unsigned Diag = DestType->isVoidPointerType() ?
  1686. diag::warn_int_to_void_pointer_cast
  1687. : diag::warn_int_to_pointer_cast;
  1688. Self.Diag(Loc, Diag) << SrcType << DestType;
  1689. }
  1690. }
  1691. static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
  1692. ExprResult &Result) {
  1693. // We can only fix an overloaded reinterpret_cast if
  1694. // - it is a template with explicit arguments that resolves to an lvalue
  1695. // unambiguously, or
  1696. // - it is the only function in an overload set that may have its address
  1697. // taken.
  1698. Expr *E = Result.get();
  1699. // TODO: what if this fails because of DiagnoseUseOfDecl or something
  1700. // like it?
  1701. if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
  1702. Result,
  1703. Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
  1704. ) &&
  1705. Result.isUsable())
  1706. return true;
  1707. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  1708. // preserves Result.
  1709. Result = E;
  1710. if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
  1711. Result, /*DoFunctionPointerConversion=*/true))
  1712. return false;
  1713. return Result.isUsable();
  1714. }
  1715. static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
  1716. QualType DestType, bool CStyle,
  1717. SourceRange OpRange,
  1718. unsigned &msg,
  1719. CastKind &Kind) {
  1720. bool IsLValueCast = false;
  1721. DestType = Self.Context.getCanonicalType(DestType);
  1722. QualType SrcType = SrcExpr.get()->getType();
  1723. // Is the source an overloaded name? (i.e. &foo)
  1724. // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
  1725. if (SrcType == Self.Context.OverloadTy) {
  1726. ExprResult FixedExpr = SrcExpr;
  1727. if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
  1728. return TC_NotApplicable;
  1729. assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
  1730. SrcExpr = FixedExpr;
  1731. SrcType = SrcExpr.get()->getType();
  1732. }
  1733. if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
  1734. if (!SrcExpr.get()->isGLValue()) {
  1735. // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
  1736. // similar comment in const_cast.
  1737. msg = diag::err_bad_cxx_cast_rvalue;
  1738. return TC_NotApplicable;
  1739. }
  1740. if (!CStyle) {
  1741. Self.CheckCompatibleReinterpretCast(SrcType, DestType,
  1742. /*isDereference=*/false, OpRange);
  1743. }
  1744. // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
  1745. // same effect as the conversion *reinterpret_cast<T*>(&x) with the
  1746. // built-in & and * operators.
  1747. const char *inappropriate = nullptr;
  1748. switch (SrcExpr.get()->getObjectKind()) {
  1749. case OK_Ordinary:
  1750. break;
  1751. case OK_BitField:
  1752. msg = diag::err_bad_cxx_cast_bitfield;
  1753. return TC_NotApplicable;
  1754. // FIXME: Use a specific diagnostic for the rest of these cases.
  1755. case OK_VectorComponent: inappropriate = "vector element"; break;
  1756. case OK_ObjCProperty: inappropriate = "property expression"; break;
  1757. case OK_ObjCSubscript: inappropriate = "container subscripting expression";
  1758. break;
  1759. }
  1760. if (inappropriate) {
  1761. Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
  1762. << inappropriate << DestType
  1763. << OpRange << SrcExpr.get()->getSourceRange();
  1764. msg = 0; SrcExpr = ExprError();
  1765. return TC_NotApplicable;
  1766. }
  1767. // This code does this transformation for the checked types.
  1768. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
  1769. SrcType = Self.Context.getPointerType(SrcType);
  1770. IsLValueCast = true;
  1771. }
  1772. // Canonicalize source for comparison.
  1773. SrcType = Self.Context.getCanonicalType(SrcType);
  1774. const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
  1775. *SrcMemPtr = SrcType->getAs<MemberPointerType>();
  1776. if (DestMemPtr && SrcMemPtr) {
  1777. // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
  1778. // can be explicitly converted to an rvalue of type "pointer to member
  1779. // of Y of type T2" if T1 and T2 are both function types or both object
  1780. // types.
  1781. if (DestMemPtr->isMemberFunctionPointer() !=
  1782. SrcMemPtr->isMemberFunctionPointer())
  1783. return TC_NotApplicable;
  1784. // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
  1785. // constness.
  1786. // A reinterpret_cast followed by a const_cast can, though, so in C-style,
  1787. // we accept it.
  1788. if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
  1789. /*CheckObjCLifetime=*/CStyle)) {
  1790. msg = diag::err_bad_cxx_cast_qualifiers_away;
  1791. return TC_Failed;
  1792. }
  1793. if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1794. // We need to determine the inheritance model that the class will use if
  1795. // haven't yet.
  1796. (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
  1797. (void)Self.isCompleteType(OpRange.getBegin(), DestType);
  1798. }
  1799. // Don't allow casting between member pointers of different sizes.
  1800. if (Self.Context.getTypeSize(DestMemPtr) !=
  1801. Self.Context.getTypeSize(SrcMemPtr)) {
  1802. msg = diag::err_bad_cxx_cast_member_pointer_size;
  1803. return TC_Failed;
  1804. }
  1805. // A valid member pointer cast.
  1806. assert(!IsLValueCast);
  1807. Kind = CK_ReinterpretMemberPointer;
  1808. return TC_Success;
  1809. }
  1810. // See below for the enumeral issue.
  1811. if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
  1812. // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
  1813. // type large enough to hold it. A value of std::nullptr_t can be
  1814. // converted to an integral type; the conversion has the same meaning
  1815. // and validity as a conversion of (void*)0 to the integral type.
  1816. if (Self.Context.getTypeSize(SrcType) >
  1817. Self.Context.getTypeSize(DestType)) {
  1818. msg = diag::err_bad_reinterpret_cast_small_int;
  1819. return TC_Failed;
  1820. }
  1821. Kind = CK_PointerToIntegral;
  1822. return TC_Success;
  1823. }
  1824. // Allow reinterpret_casts between vectors of the same size and
  1825. // between vectors and integers of the same size.
  1826. bool destIsVector = DestType->isVectorType();
  1827. bool srcIsVector = SrcType->isVectorType();
  1828. if (srcIsVector || destIsVector) {
  1829. // The non-vector type, if any, must have integral type. This is
  1830. // the same rule that C vector casts use; note, however, that enum
  1831. // types are not integral in C++.
  1832. if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
  1833. (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
  1834. return TC_NotApplicable;
  1835. // The size we want to consider is eltCount * eltSize.
  1836. // That's exactly what the lax-conversion rules will check.
  1837. if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
  1838. Kind = CK_BitCast;
  1839. return TC_Success;
  1840. }
  1841. // Otherwise, pick a reasonable diagnostic.
  1842. if (!destIsVector)
  1843. msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
  1844. else if (!srcIsVector)
  1845. msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
  1846. else
  1847. msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
  1848. return TC_Failed;
  1849. }
  1850. if (SrcType == DestType) {
  1851. // C++ 5.2.10p2 has a note that mentions that, subject to all other
  1852. // restrictions, a cast to the same type is allowed so long as it does not
  1853. // cast away constness. In C++98, the intent was not entirely clear here,
  1854. // since all other paragraphs explicitly forbid casts to the same type.
  1855. // C++11 clarifies this case with p2.
  1856. //
  1857. // The only allowed types are: integral, enumeration, pointer, or
  1858. // pointer-to-member types. We also won't restrict Obj-C pointers either.
  1859. Kind = CK_NoOp;
  1860. TryCastResult Result = TC_NotApplicable;
  1861. if (SrcType->isIntegralOrEnumerationType() ||
  1862. SrcType->isAnyPointerType() ||
  1863. SrcType->isMemberPointerType() ||
  1864. SrcType->isBlockPointerType()) {
  1865. Result = TC_Success;
  1866. }
  1867. return Result;
  1868. }
  1869. bool destIsPtr = DestType->isAnyPointerType() ||
  1870. DestType->isBlockPointerType();
  1871. bool srcIsPtr = SrcType->isAnyPointerType() ||
  1872. SrcType->isBlockPointerType();
  1873. if (!destIsPtr && !srcIsPtr) {
  1874. // Except for std::nullptr_t->integer and lvalue->reference, which are
  1875. // handled above, at least one of the two arguments must be a pointer.
  1876. return TC_NotApplicable;
  1877. }
  1878. if (DestType->isIntegralType(Self.Context)) {
  1879. assert(srcIsPtr && "One type must be a pointer");
  1880. // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
  1881. // type large enough to hold it; except in Microsoft mode, where the
  1882. // integral type size doesn't matter (except we don't allow bool).
  1883. bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
  1884. !DestType->isBooleanType();
  1885. if ((Self.Context.getTypeSize(SrcType) >
  1886. Self.Context.getTypeSize(DestType)) &&
  1887. !MicrosoftException) {
  1888. msg = diag::err_bad_reinterpret_cast_small_int;
  1889. return TC_Failed;
  1890. }
  1891. Kind = CK_PointerToIntegral;
  1892. return TC_Success;
  1893. }
  1894. if (SrcType->isIntegralOrEnumerationType()) {
  1895. assert(destIsPtr && "One type must be a pointer");
  1896. checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
  1897. Self);
  1898. // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
  1899. // converted to a pointer.
  1900. // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
  1901. // necessarily converted to a null pointer value.]
  1902. Kind = CK_IntegralToPointer;
  1903. return TC_Success;
  1904. }
  1905. if (!destIsPtr || !srcIsPtr) {
  1906. // With the valid non-pointer conversions out of the way, we can be even
  1907. // more stringent.
  1908. return TC_NotApplicable;
  1909. }
  1910. // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
  1911. // The C-style cast operator can.
  1912. if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
  1913. /*CheckObjCLifetime=*/CStyle)) {
  1914. msg = diag::err_bad_cxx_cast_qualifiers_away;
  1915. return TC_Failed;
  1916. }
  1917. // Cannot convert between block pointers and Objective-C object pointers.
  1918. if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
  1919. (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
  1920. return TC_NotApplicable;
  1921. if (IsLValueCast) {
  1922. Kind = CK_LValueBitCast;
  1923. } else if (DestType->isObjCObjectPointerType()) {
  1924. Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
  1925. } else if (DestType->isBlockPointerType()) {
  1926. if (!SrcType->isBlockPointerType()) {
  1927. Kind = CK_AnyPointerToBlockPointerCast;
  1928. } else {
  1929. Kind = CK_BitCast;
  1930. }
  1931. } else {
  1932. Kind = CK_BitCast;
  1933. }
  1934. // Any pointer can be cast to an Objective-C pointer type with a C-style
  1935. // cast.
  1936. if (CStyle && DestType->isObjCObjectPointerType()) {
  1937. return TC_Success;
  1938. }
  1939. if (CStyle)
  1940. DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
  1941. DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
  1942. // Not casting away constness, so the only remaining check is for compatible
  1943. // pointer categories.
  1944. if (SrcType->isFunctionPointerType()) {
  1945. if (DestType->isFunctionPointerType()) {
  1946. // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
  1947. // a pointer to a function of a different type.
  1948. return TC_Success;
  1949. }
  1950. // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
  1951. // an object type or vice versa is conditionally-supported.
  1952. // Compilers support it in C++03 too, though, because it's necessary for
  1953. // casting the return value of dlsym() and GetProcAddress().
  1954. // FIXME: Conditionally-supported behavior should be configurable in the
  1955. // TargetInfo or similar.
  1956. Self.Diag(OpRange.getBegin(),
  1957. Self.getLangOpts().CPlusPlus11 ?
  1958. diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
  1959. << OpRange;
  1960. return TC_Success;
  1961. }
  1962. if (DestType->isFunctionPointerType()) {
  1963. // See above.
  1964. Self.Diag(OpRange.getBegin(),
  1965. Self.getLangOpts().CPlusPlus11 ?
  1966. diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
  1967. << OpRange;
  1968. return TC_Success;
  1969. }
  1970. // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
  1971. // a pointer to an object of different type.
  1972. // Void pointers are not specified, but supported by every compiler out there.
  1973. // So we finish by allowing everything that remains - it's got to be two
  1974. // object pointers.
  1975. return TC_Success;
  1976. }
  1977. void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
  1978. bool ListInitialization) {
  1979. assert(Self.getLangOpts().CPlusPlus);
  1980. // Handle placeholders.
  1981. if (isPlaceholder()) {
  1982. // C-style casts can resolve __unknown_any types.
  1983. if (claimPlaceholder(BuiltinType::UnknownAny)) {
  1984. SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
  1985. SrcExpr.get(), Kind,
  1986. ValueKind, BasePath);
  1987. return;
  1988. }
  1989. checkNonOverloadPlaceholders();
  1990. if (SrcExpr.isInvalid())
  1991. return;
  1992. }
  1993. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  1994. // This test is outside everything else because it's the only case where
  1995. // a non-lvalue-reference target type does not lead to decay.
  1996. if (DestType->isVoidType()) {
  1997. Kind = CK_ToVoid;
  1998. if (claimPlaceholder(BuiltinType::Overload)) {
  1999. Self.ResolveAndFixSingleFunctionTemplateSpecialization(
  2000. SrcExpr, /* Decay Function to ptr */ false,
  2001. /* Complain */ true, DestRange, DestType,
  2002. diag::err_bad_cstyle_cast_overload);
  2003. if (SrcExpr.isInvalid())
  2004. return;
  2005. }
  2006. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  2007. return;
  2008. }
  2009. // If the type is dependent, we won't do any other semantic analysis now.
  2010. if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
  2011. SrcExpr.get()->isValueDependent()) {
  2012. assert(Kind == CK_Dependent);
  2013. return;
  2014. }
  2015. if (ValueKind == VK_RValue && !DestType->isRecordType() &&
  2016. !isPlaceholder(BuiltinType::Overload)) {
  2017. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  2018. if (SrcExpr.isInvalid())
  2019. return;
  2020. }
  2021. // AltiVec vector initialization with a single literal.
  2022. if (const VectorType *vecTy = DestType->getAs<VectorType>())
  2023. if (vecTy->getVectorKind() == VectorType::AltiVecVector
  2024. && (SrcExpr.get()->getType()->isIntegerType()
  2025. || SrcExpr.get()->getType()->isFloatingType())) {
  2026. Kind = CK_VectorSplat;
  2027. SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
  2028. return;
  2029. }
  2030. // C++ [expr.cast]p5: The conversions performed by
  2031. // - a const_cast,
  2032. // - a static_cast,
  2033. // - a static_cast followed by a const_cast,
  2034. // - a reinterpret_cast, or
  2035. // - a reinterpret_cast followed by a const_cast,
  2036. // can be performed using the cast notation of explicit type conversion.
  2037. // [...] If a conversion can be interpreted in more than one of the ways
  2038. // listed above, the interpretation that appears first in the list is used,
  2039. // even if a cast resulting from that interpretation is ill-formed.
  2040. // In plain language, this means trying a const_cast ...
  2041. unsigned msg = diag::err_bad_cxx_cast_generic;
  2042. TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
  2043. /*CStyle*/true, msg);
  2044. if (SrcExpr.isInvalid())
  2045. return;
  2046. if (tcr == TC_Success)
  2047. Kind = CK_NoOp;
  2048. Sema::CheckedConversionKind CCK
  2049. = FunctionalStyle? Sema::CCK_FunctionalCast
  2050. : Sema::CCK_CStyleCast;
  2051. if (tcr == TC_NotApplicable) {
  2052. // ... or if that is not possible, a static_cast, ignoring const, ...
  2053. tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
  2054. msg, Kind, BasePath, ListInitialization);
  2055. if (SrcExpr.isInvalid())
  2056. return;
  2057. if (tcr == TC_NotApplicable) {
  2058. // ... and finally a reinterpret_cast, ignoring const.
  2059. tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
  2060. OpRange, msg, Kind);
  2061. if (SrcExpr.isInvalid())
  2062. return;
  2063. }
  2064. }
  2065. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  2066. tcr == TC_Success)
  2067. checkObjCConversion(CCK);
  2068. if (tcr != TC_Success && msg != 0) {
  2069. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  2070. DeclAccessPair Found;
  2071. FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
  2072. DestType,
  2073. /*Complain*/ true,
  2074. Found);
  2075. if (Fn) {
  2076. // If DestType is a function type (not to be confused with the function
  2077. // pointer type), it will be possible to resolve the function address,
  2078. // but the type cast should be considered as failure.
  2079. OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
  2080. Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
  2081. << OE->getName() << DestType << OpRange
  2082. << OE->getQualifierLoc().getSourceRange();
  2083. Self.NoteAllOverloadCandidates(SrcExpr.get());
  2084. }
  2085. } else {
  2086. diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
  2087. OpRange, SrcExpr.get(), DestType, ListInitialization);
  2088. }
  2089. } else if (Kind == CK_BitCast) {
  2090. checkCastAlign();
  2091. }
  2092. // Clear out SrcExpr if there was a fatal error.
  2093. if (tcr != TC_Success)
  2094. SrcExpr = ExprError();
  2095. }
  2096. /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
  2097. /// non-matching type. Such as enum function call to int, int call to
  2098. /// pointer; etc. Cast to 'void' is an exception.
  2099. static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
  2100. QualType DestType) {
  2101. if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
  2102. SrcExpr.get()->getExprLoc()))
  2103. return;
  2104. if (!isa<CallExpr>(SrcExpr.get()))
  2105. return;
  2106. QualType SrcType = SrcExpr.get()->getType();
  2107. if (DestType.getUnqualifiedType()->isVoidType())
  2108. return;
  2109. if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
  2110. && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
  2111. return;
  2112. if (SrcType->isIntegerType() && DestType->isIntegerType() &&
  2113. (SrcType->isBooleanType() == DestType->isBooleanType()) &&
  2114. (SrcType->isEnumeralType() == DestType->isEnumeralType()))
  2115. return;
  2116. if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
  2117. return;
  2118. if (SrcType->isEnumeralType() && DestType->isEnumeralType())
  2119. return;
  2120. if (SrcType->isComplexType() && DestType->isComplexType())
  2121. return;
  2122. if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
  2123. return;
  2124. Self.Diag(SrcExpr.get()->getExprLoc(),
  2125. diag::warn_bad_function_cast)
  2126. << SrcType << DestType << SrcExpr.get()->getSourceRange();
  2127. }
  2128. /// Check the semantics of a C-style cast operation, in C.
  2129. void CastOperation::CheckCStyleCast() {
  2130. assert(!Self.getLangOpts().CPlusPlus);
  2131. // C-style casts can resolve __unknown_any types.
  2132. if (claimPlaceholder(BuiltinType::UnknownAny)) {
  2133. SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
  2134. SrcExpr.get(), Kind,
  2135. ValueKind, BasePath);
  2136. return;
  2137. }
  2138. // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
  2139. // type needs to be scalar.
  2140. if (DestType->isVoidType()) {
  2141. // We don't necessarily do lvalue-to-rvalue conversions on this.
  2142. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  2143. if (SrcExpr.isInvalid())
  2144. return;
  2145. // Cast to void allows any expr type.
  2146. Kind = CK_ToVoid;
  2147. return;
  2148. }
  2149. // Overloads are allowed with C extensions, so we need to support them.
  2150. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  2151. DeclAccessPair DAP;
  2152. if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
  2153. SrcExpr.get(), DestType, /*Complain=*/true, DAP))
  2154. SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
  2155. else
  2156. return;
  2157. assert(SrcExpr.isUsable());
  2158. }
  2159. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  2160. if (SrcExpr.isInvalid())
  2161. return;
  2162. QualType SrcType = SrcExpr.get()->getType();
  2163. assert(!SrcType->isPlaceholderType());
  2164. // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
  2165. // address space B is illegal.
  2166. if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
  2167. SrcType->isPointerType()) {
  2168. const PointerType *DestPtr = DestType->getAs<PointerType>();
  2169. if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
  2170. Self.Diag(OpRange.getBegin(),
  2171. diag::err_typecheck_incompatible_address_space)
  2172. << SrcType << DestType << Sema::AA_Casting
  2173. << SrcExpr.get()->getSourceRange();
  2174. SrcExpr = ExprError();
  2175. return;
  2176. }
  2177. }
  2178. if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
  2179. diag::err_typecheck_cast_to_incomplete)) {
  2180. SrcExpr = ExprError();
  2181. return;
  2182. }
  2183. if (!DestType->isScalarType() && !DestType->isVectorType()) {
  2184. const RecordType *DestRecordTy = DestType->getAs<RecordType>();
  2185. if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
  2186. // GCC struct/union extension: allow cast to self.
  2187. Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
  2188. << DestType << SrcExpr.get()->getSourceRange();
  2189. Kind = CK_NoOp;
  2190. return;
  2191. }
  2192. // GCC's cast to union extension.
  2193. if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
  2194. RecordDecl *RD = DestRecordTy->getDecl();
  2195. if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
  2196. Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
  2197. << SrcExpr.get()->getSourceRange();
  2198. Kind = CK_ToUnion;
  2199. return;
  2200. } else {
  2201. Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
  2202. << SrcType << SrcExpr.get()->getSourceRange();
  2203. SrcExpr = ExprError();
  2204. return;
  2205. }
  2206. }
  2207. // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
  2208. if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
  2209. llvm::APSInt CastInt;
  2210. if (SrcExpr.get()->EvaluateAsInt(CastInt, Self.Context)) {
  2211. if (0 == CastInt) {
  2212. Kind = CK_ZeroToOCLEvent;
  2213. return;
  2214. }
  2215. Self.Diag(OpRange.getBegin(),
  2216. diag::err_opencl_cast_non_zero_to_event_t)
  2217. << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
  2218. SrcExpr = ExprError();
  2219. return;
  2220. }
  2221. }
  2222. // Reject any other conversions to non-scalar types.
  2223. Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
  2224. << DestType << SrcExpr.get()->getSourceRange();
  2225. SrcExpr = ExprError();
  2226. return;
  2227. }
  2228. // The type we're casting to is known to be a scalar or vector.
  2229. // Require the operand to be a scalar or vector.
  2230. if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
  2231. Self.Diag(SrcExpr.get()->getExprLoc(),
  2232. diag::err_typecheck_expect_scalar_operand)
  2233. << SrcType << SrcExpr.get()->getSourceRange();
  2234. SrcExpr = ExprError();
  2235. return;
  2236. }
  2237. if (DestType->isExtVectorType()) {
  2238. SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
  2239. return;
  2240. }
  2241. if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
  2242. if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
  2243. (SrcType->isIntegerType() || SrcType->isFloatingType())) {
  2244. Kind = CK_VectorSplat;
  2245. SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
  2246. } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
  2247. SrcExpr = ExprError();
  2248. }
  2249. return;
  2250. }
  2251. if (SrcType->isVectorType()) {
  2252. if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
  2253. SrcExpr = ExprError();
  2254. return;
  2255. }
  2256. // The source and target types are both scalars, i.e.
  2257. // - arithmetic types (fundamental, enum, and complex)
  2258. // - all kinds of pointers
  2259. // Note that member pointers were filtered out with C++, above.
  2260. if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
  2261. Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
  2262. SrcExpr = ExprError();
  2263. return;
  2264. }
  2265. // If either type is a pointer, the other type has to be either an
  2266. // integer or a pointer.
  2267. if (!DestType->isArithmeticType()) {
  2268. if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
  2269. Self.Diag(SrcExpr.get()->getExprLoc(),
  2270. diag::err_cast_pointer_from_non_pointer_int)
  2271. << SrcType << SrcExpr.get()->getSourceRange();
  2272. SrcExpr = ExprError();
  2273. return;
  2274. }
  2275. checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
  2276. DestType, Self);
  2277. } else if (!SrcType->isArithmeticType()) {
  2278. if (!DestType->isIntegralType(Self.Context) &&
  2279. DestType->isArithmeticType()) {
  2280. Self.Diag(SrcExpr.get()->getLocStart(),
  2281. diag::err_cast_pointer_to_non_pointer_int)
  2282. << DestType << SrcExpr.get()->getSourceRange();
  2283. SrcExpr = ExprError();
  2284. return;
  2285. }
  2286. }
  2287. if (Self.getLangOpts().OpenCL &&
  2288. !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  2289. if (DestType->isHalfType()) {
  2290. Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
  2291. << DestType << SrcExpr.get()->getSourceRange();
  2292. SrcExpr = ExprError();
  2293. return;
  2294. }
  2295. }
  2296. // ARC imposes extra restrictions on casts.
  2297. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
  2298. checkObjCConversion(Sema::CCK_CStyleCast);
  2299. if (SrcExpr.isInvalid())
  2300. return;
  2301. const PointerType *CastPtr = DestType->getAs<PointerType>();
  2302. if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
  2303. if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
  2304. Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
  2305. Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
  2306. if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
  2307. ExprPtr->getPointeeType()->isObjCLifetimeType() &&
  2308. !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
  2309. Self.Diag(SrcExpr.get()->getLocStart(),
  2310. diag::err_typecheck_incompatible_ownership)
  2311. << SrcType << DestType << Sema::AA_Casting
  2312. << SrcExpr.get()->getSourceRange();
  2313. return;
  2314. }
  2315. }
  2316. }
  2317. else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
  2318. Self.Diag(SrcExpr.get()->getLocStart(),
  2319. diag::err_arc_convesion_of_weak_unavailable)
  2320. << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
  2321. SrcExpr = ExprError();
  2322. return;
  2323. }
  2324. }
  2325. DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
  2326. DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
  2327. DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
  2328. Kind = Self.PrepareScalarCast(SrcExpr, DestType);
  2329. if (SrcExpr.isInvalid())
  2330. return;
  2331. if (Kind == CK_BitCast)
  2332. checkCastAlign();
  2333. }
  2334. /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
  2335. /// const, volatile or both.
  2336. static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
  2337. QualType DestType) {
  2338. if (SrcExpr.isInvalid())
  2339. return;
  2340. QualType SrcType = SrcExpr.get()->getType();
  2341. if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
  2342. DestType->isLValueReferenceType()))
  2343. return;
  2344. QualType TheOffendingSrcType, TheOffendingDestType;
  2345. Qualifiers CastAwayQualifiers;
  2346. if (!CastsAwayConstness(Self, SrcType, DestType, true, false,
  2347. &TheOffendingSrcType, &TheOffendingDestType,
  2348. &CastAwayQualifiers))
  2349. return;
  2350. int qualifiers = -1;
  2351. if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
  2352. qualifiers = 0;
  2353. } else if (CastAwayQualifiers.hasConst()) {
  2354. qualifiers = 1;
  2355. } else if (CastAwayQualifiers.hasVolatile()) {
  2356. qualifiers = 2;
  2357. }
  2358. // This is a variant of int **x; const int **y = (const int **)x;
  2359. if (qualifiers == -1)
  2360. Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2)
  2361. << SrcType << DestType;
  2362. else
  2363. Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual)
  2364. << TheOffendingSrcType << TheOffendingDestType << qualifiers;
  2365. }
  2366. ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
  2367. TypeSourceInfo *CastTypeInfo,
  2368. SourceLocation RPLoc,
  2369. Expr *CastExpr) {
  2370. CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
  2371. Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
  2372. Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
  2373. if (getLangOpts().CPlusPlus) {
  2374. Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
  2375. isa<InitListExpr>(CastExpr));
  2376. } else {
  2377. Op.CheckCStyleCast();
  2378. }
  2379. if (Op.SrcExpr.isInvalid())
  2380. return ExprError();
  2381. // -Wcast-qual
  2382. DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
  2383. return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
  2384. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  2385. &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
  2386. }
  2387. ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
  2388. QualType Type,
  2389. SourceLocation LPLoc,
  2390. Expr *CastExpr,
  2391. SourceLocation RPLoc) {
  2392. assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
  2393. CastOperation Op(*this, Type, CastExpr);
  2394. Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
  2395. Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
  2396. Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
  2397. if (Op.SrcExpr.isInvalid())
  2398. return ExprError();
  2399. auto *SubExpr = Op.SrcExpr.get();
  2400. if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
  2401. SubExpr = BindExpr->getSubExpr();
  2402. if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
  2403. ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
  2404. return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
  2405. Op.ValueKind, CastTypeInfo, Op.Kind,
  2406. Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
  2407. }