SemaCast.cpp 107 KB

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