SemaCast.cpp 113 KB

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