SemaCast.cpp 128 KB

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