SemaStmt.cpp 165 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446
  1. //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for statements.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Sema/Ownership.h"
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTDiagnostic.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/ExprObjC.h"
  23. #include "clang/AST/RecursiveASTVisitor.h"
  24. #include "clang/AST/StmtCXX.h"
  25. #include "clang/AST/StmtObjC.h"
  26. #include "clang/AST/TypeLoc.h"
  27. #include "clang/AST/TypeOrdering.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/Preprocessor.h"
  30. #include "clang/Sema/Initialization.h"
  31. #include "clang/Sema/Lookup.h"
  32. #include "clang/Sema/Scope.h"
  33. #include "clang/Sema/ScopeInfo.h"
  34. #include "llvm/ADT/ArrayRef.h"
  35. #include "llvm/ADT/DenseMap.h"
  36. #include "llvm/ADT/STLExtras.h"
  37. #include "llvm/ADT/SmallPtrSet.h"
  38. #include "llvm/ADT/SmallString.h"
  39. #include "llvm/ADT/SmallVector.h"
  40. using namespace clang;
  41. using namespace sema;
  42. StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
  43. if (FE.isInvalid())
  44. return StmtError();
  45. FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
  46. if (FE.isInvalid())
  47. return StmtError();
  48. // C99 6.8.3p2: The expression in an expression statement is evaluated as a
  49. // void expression for its side effects. Conversion to void allows any
  50. // operand, even incomplete types.
  51. // Same thing in for stmt first clause (when expr) and third clause.
  52. return StmtResult(FE.getAs<Stmt>());
  53. }
  54. StmtResult Sema::ActOnExprStmtError() {
  55. DiscardCleanupsInEvaluationContext();
  56. return StmtError();
  57. }
  58. StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
  59. bool HasLeadingEmptyMacro) {
  60. return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
  61. }
  62. StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
  63. SourceLocation EndLoc) {
  64. DeclGroupRef DG = dg.get();
  65. // If we have an invalid decl, just return an error.
  66. if (DG.isNull()) return StmtError();
  67. return new (Context) DeclStmt(DG, StartLoc, EndLoc);
  68. }
  69. void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
  70. DeclGroupRef DG = dg.get();
  71. // If we don't have a declaration, or we have an invalid declaration,
  72. // just return.
  73. if (DG.isNull() || !DG.isSingleDecl())
  74. return;
  75. Decl *decl = DG.getSingleDecl();
  76. if (!decl || decl->isInvalidDecl())
  77. return;
  78. // Only variable declarations are permitted.
  79. VarDecl *var = dyn_cast<VarDecl>(decl);
  80. if (!var) {
  81. Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
  82. decl->setInvalidDecl();
  83. return;
  84. }
  85. // foreach variables are never actually initialized in the way that
  86. // the parser came up with.
  87. var->setInit(nullptr);
  88. // In ARC, we don't need to retain the iteration variable of a fast
  89. // enumeration loop. Rather than actually trying to catch that
  90. // during declaration processing, we remove the consequences here.
  91. if (getLangOpts().ObjCAutoRefCount) {
  92. QualType type = var->getType();
  93. // Only do this if we inferred the lifetime. Inferred lifetime
  94. // will show up as a local qualifier because explicit lifetime
  95. // should have shown up as an AttributedType instead.
  96. if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
  97. // Add 'const' and mark the variable as pseudo-strong.
  98. var->setType(type.withConst());
  99. var->setARCPseudoStrong(true);
  100. }
  101. }
  102. }
  103. /// Diagnose unused comparisons, both builtin and overloaded operators.
  104. /// For '==' and '!=', suggest fixits for '=' or '|='.
  105. ///
  106. /// Adding a cast to void (or other expression wrappers) will prevent the
  107. /// warning from firing.
  108. static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
  109. SourceLocation Loc;
  110. bool CanAssign;
  111. enum { Equality, Inequality, Relational, ThreeWay } Kind;
  112. if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  113. if (!Op->isComparisonOp())
  114. return false;
  115. if (Op->getOpcode() == BO_EQ)
  116. Kind = Equality;
  117. else if (Op->getOpcode() == BO_NE)
  118. Kind = Inequality;
  119. else if (Op->getOpcode() == BO_Cmp)
  120. Kind = ThreeWay;
  121. else {
  122. assert(Op->isRelationalOp());
  123. Kind = Relational;
  124. }
  125. Loc = Op->getOperatorLoc();
  126. CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
  127. } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  128. switch (Op->getOperator()) {
  129. case OO_EqualEqual:
  130. Kind = Equality;
  131. break;
  132. case OO_ExclaimEqual:
  133. Kind = Inequality;
  134. break;
  135. case OO_Less:
  136. case OO_Greater:
  137. case OO_GreaterEqual:
  138. case OO_LessEqual:
  139. Kind = Relational;
  140. break;
  141. case OO_Spaceship:
  142. Kind = ThreeWay;
  143. break;
  144. default:
  145. return false;
  146. }
  147. Loc = Op->getOperatorLoc();
  148. CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
  149. } else {
  150. // Not a typo-prone comparison.
  151. return false;
  152. }
  153. // Suppress warnings when the operator, suspicious as it may be, comes from
  154. // a macro expansion.
  155. if (S.SourceMgr.isMacroBodyExpansion(Loc))
  156. return false;
  157. S.Diag(Loc, diag::warn_unused_comparison)
  158. << (unsigned)Kind << E->getSourceRange();
  159. // If the LHS is a plausible entity to assign to, provide a fixit hint to
  160. // correct common typos.
  161. if (CanAssign) {
  162. if (Kind == Inequality)
  163. S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
  164. << FixItHint::CreateReplacement(Loc, "|=");
  165. else if (Kind == Equality)
  166. S.Diag(Loc, diag::note_equality_comparison_to_assign)
  167. << FixItHint::CreateReplacement(Loc, "=");
  168. }
  169. return true;
  170. }
  171. static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A,
  172. SourceLocation Loc, SourceRange R1,
  173. SourceRange R2, bool IsCtor) {
  174. if (!A)
  175. return false;
  176. StringRef Msg = A->getMessage();
  177. if (Msg.empty()) {
  178. if (IsCtor)
  179. return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
  180. return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
  181. }
  182. if (IsCtor)
  183. return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1
  184. << R2;
  185. return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
  186. }
  187. void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
  188. if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
  189. return DiagnoseUnusedExprResult(Label->getSubStmt());
  190. const Expr *E = dyn_cast_or_null<Expr>(S);
  191. if (!E)
  192. return;
  193. // If we are in an unevaluated expression context, then there can be no unused
  194. // results because the results aren't expected to be used in the first place.
  195. if (isUnevaluatedContext())
  196. return;
  197. SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
  198. // In most cases, we don't want to warn if the expression is written in a
  199. // macro body, or if the macro comes from a system header. If the offending
  200. // expression is a call to a function with the warn_unused_result attribute,
  201. // we warn no matter the location. Because of the order in which the various
  202. // checks need to happen, we factor out the macro-related test here.
  203. bool ShouldSuppress =
  204. SourceMgr.isMacroBodyExpansion(ExprLoc) ||
  205. SourceMgr.isInSystemMacro(ExprLoc);
  206. const Expr *WarnExpr;
  207. SourceLocation Loc;
  208. SourceRange R1, R2;
  209. if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
  210. return;
  211. // If this is a GNU statement expression expanded from a macro, it is probably
  212. // unused because it is a function-like macro that can be used as either an
  213. // expression or statement. Don't warn, because it is almost certainly a
  214. // false positive.
  215. if (isa<StmtExpr>(E) && Loc.isMacroID())
  216. return;
  217. // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
  218. // That macro is frequently used to suppress "unused parameter" warnings,
  219. // but its implementation makes clang's -Wunused-value fire. Prevent this.
  220. if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
  221. SourceLocation SpellLoc = Loc;
  222. if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
  223. return;
  224. }
  225. // Okay, we have an unused result. Depending on what the base expression is,
  226. // we might want to make a more specific diagnostic. Check for one of these
  227. // cases now.
  228. unsigned DiagID = diag::warn_unused_expr;
  229. if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
  230. E = Temps->getSubExpr();
  231. if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
  232. E = TempExpr->getSubExpr();
  233. if (DiagnoseUnusedComparison(*this, E))
  234. return;
  235. E = WarnExpr;
  236. if (const auto *Cast = dyn_cast<CastExpr>(E))
  237. if (Cast->getCastKind() == CK_NoOp ||
  238. Cast->getCastKind() == CK_ConstructorConversion)
  239. E = Cast->getSubExpr()->IgnoreImpCasts();
  240. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  241. if (E->getType()->isVoidType())
  242. return;
  243. if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>(
  244. CE->getUnusedResultAttr(Context)),
  245. Loc, R1, R2, /*isCtor=*/false))
  246. return;
  247. // If the callee has attribute pure, const, or warn_unused_result, warn with
  248. // a more specific message to make it clear what is happening. If the call
  249. // is written in a macro body, only warn if it has the warn_unused_result
  250. // attribute.
  251. if (const Decl *FD = CE->getCalleeDecl()) {
  252. if (ShouldSuppress)
  253. return;
  254. if (FD->hasAttr<PureAttr>()) {
  255. Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
  256. return;
  257. }
  258. if (FD->hasAttr<ConstAttr>()) {
  259. Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
  260. return;
  261. }
  262. }
  263. } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
  264. if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
  265. const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
  266. A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>();
  267. if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true))
  268. return;
  269. }
  270. } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
  271. if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
  272. if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
  273. R2, /*isCtor=*/false))
  274. return;
  275. }
  276. } else if (ShouldSuppress)
  277. return;
  278. E = WarnExpr;
  279. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
  280. if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
  281. Diag(Loc, diag::err_arc_unused_init_message) << R1;
  282. return;
  283. }
  284. const ObjCMethodDecl *MD = ME->getMethodDecl();
  285. if (MD) {
  286. if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
  287. R2, /*isCtor=*/false))
  288. return;
  289. }
  290. } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  291. const Expr *Source = POE->getSyntacticForm();
  292. if (isa<ObjCSubscriptRefExpr>(Source))
  293. DiagID = diag::warn_unused_container_subscript_expr;
  294. else
  295. DiagID = diag::warn_unused_property_expr;
  296. } else if (const CXXFunctionalCastExpr *FC
  297. = dyn_cast<CXXFunctionalCastExpr>(E)) {
  298. const Expr *E = FC->getSubExpr();
  299. if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
  300. E = TE->getSubExpr();
  301. if (isa<CXXTemporaryObjectExpr>(E))
  302. return;
  303. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
  304. if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
  305. if (!RD->getAttr<WarnUnusedAttr>())
  306. return;
  307. }
  308. // Diagnose "(void*) blah" as a typo for "(void) blah".
  309. else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
  310. TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
  311. QualType T = TI->getType();
  312. // We really do want to use the non-canonical type here.
  313. if (T == Context.VoidPtrTy) {
  314. PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
  315. Diag(Loc, diag::warn_unused_voidptr)
  316. << FixItHint::CreateRemoval(TL.getStarLoc());
  317. return;
  318. }
  319. }
  320. if (E->isGLValue() && E->getType().isVolatileQualified()) {
  321. Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
  322. return;
  323. }
  324. DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
  325. }
  326. void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
  327. PushCompoundScope(IsStmtExpr);
  328. }
  329. void Sema::ActOnFinishOfCompoundStmt() {
  330. PopCompoundScope();
  331. }
  332. sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
  333. return getCurFunction()->CompoundScopes.back();
  334. }
  335. StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
  336. ArrayRef<Stmt *> Elts, bool isStmtExpr) {
  337. const unsigned NumElts = Elts.size();
  338. // If we're in C89 mode, check that we don't have any decls after stmts. If
  339. // so, emit an extension diagnostic.
  340. if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
  341. // Note that __extension__ can be around a decl.
  342. unsigned i = 0;
  343. // Skip over all declarations.
  344. for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
  345. /*empty*/;
  346. // We found the end of the list or a statement. Scan for another declstmt.
  347. for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
  348. /*empty*/;
  349. if (i != NumElts) {
  350. Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
  351. Diag(D->getLocation(), diag::ext_mixed_decls_code);
  352. }
  353. }
  354. // Check for suspicious empty body (null statement) in `for' and `while'
  355. // statements. Don't do anything for template instantiations, this just adds
  356. // noise.
  357. if (NumElts != 0 && !CurrentInstantiationScope &&
  358. getCurCompoundScope().HasEmptyLoopBodies) {
  359. for (unsigned i = 0; i != NumElts - 1; ++i)
  360. DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
  361. }
  362. return CompoundStmt::Create(Context, Elts, L, R);
  363. }
  364. ExprResult
  365. Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
  366. if (!Val.get())
  367. return Val;
  368. if (DiagnoseUnexpandedParameterPack(Val.get()))
  369. return ExprError();
  370. // If we're not inside a switch, let the 'case' statement handling diagnose
  371. // this. Just clean up after the expression as best we can.
  372. if (getCurFunction()->SwitchStack.empty())
  373. return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
  374. getLangOpts().CPlusPlus11);
  375. Expr *CondExpr =
  376. getCurFunction()->SwitchStack.back().getPointer()->getCond();
  377. if (!CondExpr)
  378. return ExprError();
  379. QualType CondType = CondExpr->getType();
  380. auto CheckAndFinish = [&](Expr *E) {
  381. if (CondType->isDependentType() || E->isTypeDependent())
  382. return ExprResult(E);
  383. if (getLangOpts().CPlusPlus11) {
  384. // C++11 [stmt.switch]p2: the constant-expression shall be a converted
  385. // constant expression of the promoted type of the switch condition.
  386. llvm::APSInt TempVal;
  387. return CheckConvertedConstantExpression(E, CondType, TempVal,
  388. CCEK_CaseValue);
  389. }
  390. ExprResult ER = E;
  391. if (!E->isValueDependent())
  392. ER = VerifyIntegerConstantExpression(E);
  393. if (!ER.isInvalid())
  394. ER = DefaultLvalueConversion(ER.get());
  395. if (!ER.isInvalid())
  396. ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
  397. if (!ER.isInvalid())
  398. ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false);
  399. return ER;
  400. };
  401. ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
  402. if (Converted.get() == Val.get())
  403. Converted = CheckAndFinish(Val.get());
  404. return Converted;
  405. }
  406. StmtResult
  407. Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
  408. SourceLocation DotDotDotLoc, ExprResult RHSVal,
  409. SourceLocation ColonLoc) {
  410. assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
  411. assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
  412. : RHSVal.isInvalid() || RHSVal.get()) &&
  413. "missing RHS value");
  414. if (getCurFunction()->SwitchStack.empty()) {
  415. Diag(CaseLoc, diag::err_case_not_in_switch);
  416. return StmtError();
  417. }
  418. if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
  419. getCurFunction()->SwitchStack.back().setInt(true);
  420. return StmtError();
  421. }
  422. auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
  423. CaseLoc, DotDotDotLoc, ColonLoc);
  424. getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
  425. return CS;
  426. }
  427. /// ActOnCaseStmtBody - This installs a statement as the body of a case.
  428. void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
  429. cast<CaseStmt>(S)->setSubStmt(SubStmt);
  430. }
  431. StmtResult
  432. Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
  433. Stmt *SubStmt, Scope *CurScope) {
  434. if (getCurFunction()->SwitchStack.empty()) {
  435. Diag(DefaultLoc, diag::err_default_not_in_switch);
  436. return SubStmt;
  437. }
  438. DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
  439. getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
  440. return DS;
  441. }
  442. StmtResult
  443. Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
  444. SourceLocation ColonLoc, Stmt *SubStmt) {
  445. // If the label was multiply defined, reject it now.
  446. if (TheDecl->getStmt()) {
  447. Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
  448. Diag(TheDecl->getLocation(), diag::note_previous_definition);
  449. return SubStmt;
  450. }
  451. // Otherwise, things are good. Fill in the declaration and return it.
  452. LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
  453. TheDecl->setStmt(LS);
  454. if (!TheDecl->isGnuLocal()) {
  455. TheDecl->setLocStart(IdentLoc);
  456. if (!TheDecl->isMSAsmLabel()) {
  457. // Don't update the location of MS ASM labels. These will result in
  458. // a diagnostic, and changing the location here will mess that up.
  459. TheDecl->setLocation(IdentLoc);
  460. }
  461. }
  462. return LS;
  463. }
  464. StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
  465. ArrayRef<const Attr*> Attrs,
  466. Stmt *SubStmt) {
  467. // Fill in the declaration and return it.
  468. AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
  469. return LS;
  470. }
  471. namespace {
  472. class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
  473. typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
  474. Sema &SemaRef;
  475. public:
  476. CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
  477. void VisitBinaryOperator(BinaryOperator *E) {
  478. if (E->getOpcode() == BO_Comma)
  479. SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
  480. EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
  481. }
  482. };
  483. }
  484. StmtResult
  485. Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
  486. ConditionResult Cond,
  487. Stmt *thenStmt, SourceLocation ElseLoc,
  488. Stmt *elseStmt) {
  489. if (Cond.isInvalid())
  490. Cond = ConditionResult(
  491. *this, nullptr,
  492. MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
  493. Context.BoolTy, VK_RValue),
  494. IfLoc),
  495. false);
  496. Expr *CondExpr = Cond.get().second;
  497. // Only call the CommaVisitor when not C89 due to differences in scope flags.
  498. if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
  499. !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
  500. CommaVisitor(*this).Visit(CondExpr);
  501. if (!elseStmt)
  502. DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
  503. diag::warn_empty_if_body);
  504. return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
  505. elseStmt);
  506. }
  507. StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
  508. Stmt *InitStmt, ConditionResult Cond,
  509. Stmt *thenStmt, SourceLocation ElseLoc,
  510. Stmt *elseStmt) {
  511. if (Cond.isInvalid())
  512. return StmtError();
  513. if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
  514. setFunctionHasBranchProtectedScope();
  515. return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
  516. Cond.get().second, thenStmt, ElseLoc, elseStmt);
  517. }
  518. namespace {
  519. struct CaseCompareFunctor {
  520. bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
  521. const llvm::APSInt &RHS) {
  522. return LHS.first < RHS;
  523. }
  524. bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
  525. const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
  526. return LHS.first < RHS.first;
  527. }
  528. bool operator()(const llvm::APSInt &LHS,
  529. const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
  530. return LHS < RHS.first;
  531. }
  532. };
  533. }
  534. /// CmpCaseVals - Comparison predicate for sorting case values.
  535. ///
  536. static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
  537. const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
  538. if (lhs.first < rhs.first)
  539. return true;
  540. if (lhs.first == rhs.first &&
  541. lhs.second->getCaseLoc().getRawEncoding()
  542. < rhs.second->getCaseLoc().getRawEncoding())
  543. return true;
  544. return false;
  545. }
  546. /// CmpEnumVals - Comparison predicate for sorting enumeration values.
  547. ///
  548. static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
  549. const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
  550. {
  551. return lhs.first < rhs.first;
  552. }
  553. /// EqEnumVals - Comparison preficate for uniqing enumeration values.
  554. ///
  555. static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
  556. const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
  557. {
  558. return lhs.first == rhs.first;
  559. }
  560. /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
  561. /// potentially integral-promoted expression @p expr.
  562. static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
  563. if (const auto *FE = dyn_cast<FullExpr>(E))
  564. E = FE->getSubExpr();
  565. while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
  566. if (ImpCast->getCastKind() != CK_IntegralCast) break;
  567. E = ImpCast->getSubExpr();
  568. }
  569. return E->getType();
  570. }
  571. ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
  572. class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
  573. Expr *Cond;
  574. public:
  575. SwitchConvertDiagnoser(Expr *Cond)
  576. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
  577. Cond(Cond) {}
  578. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  579. QualType T) override {
  580. return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
  581. }
  582. SemaDiagnosticBuilder diagnoseIncomplete(
  583. Sema &S, SourceLocation Loc, QualType T) override {
  584. return S.Diag(Loc, diag::err_switch_incomplete_class_type)
  585. << T << Cond->getSourceRange();
  586. }
  587. SemaDiagnosticBuilder diagnoseExplicitConv(
  588. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  589. return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
  590. }
  591. SemaDiagnosticBuilder noteExplicitConv(
  592. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  593. return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
  594. << ConvTy->isEnumeralType() << ConvTy;
  595. }
  596. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  597. QualType T) override {
  598. return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
  599. }
  600. SemaDiagnosticBuilder noteAmbiguous(
  601. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  602. return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
  603. << ConvTy->isEnumeralType() << ConvTy;
  604. }
  605. SemaDiagnosticBuilder diagnoseConversion(
  606. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  607. llvm_unreachable("conversion functions are permitted");
  608. }
  609. } SwitchDiagnoser(Cond);
  610. ExprResult CondResult =
  611. PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
  612. if (CondResult.isInvalid())
  613. return ExprError();
  614. // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
  615. // failed and produced a diagnostic.
  616. Cond = CondResult.get();
  617. if (!Cond->isTypeDependent() &&
  618. !Cond->getType()->isIntegralOrEnumerationType())
  619. return ExprError();
  620. // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
  621. return UsualUnaryConversions(Cond);
  622. }
  623. StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
  624. Stmt *InitStmt, ConditionResult Cond) {
  625. Expr *CondExpr = Cond.get().second;
  626. assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
  627. if (CondExpr && !CondExpr->isTypeDependent()) {
  628. // We have already converted the expression to an integral or enumeration
  629. // type, when we parsed the switch condition. If we don't have an
  630. // appropriate type now, enter the switch scope but remember that it's
  631. // invalid.
  632. assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
  633. "invalid condition type");
  634. if (CondExpr->isKnownToHaveBooleanValue()) {
  635. // switch(bool_expr) {...} is often a programmer error, e.g.
  636. // switch(n && mask) { ... } // Doh - should be "n & mask".
  637. // One can always use an if statement instead of switch(bool_expr).
  638. Diag(SwitchLoc, diag::warn_bool_switch_condition)
  639. << CondExpr->getSourceRange();
  640. }
  641. }
  642. setFunctionHasBranchIntoScope();
  643. auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
  644. getCurFunction()->SwitchStack.push_back(
  645. FunctionScopeInfo::SwitchInfo(SS, false));
  646. return SS;
  647. }
  648. static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
  649. Val = Val.extOrTrunc(BitWidth);
  650. Val.setIsSigned(IsSigned);
  651. }
  652. /// Check the specified case value is in range for the given unpromoted switch
  653. /// type.
  654. static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
  655. unsigned UnpromotedWidth, bool UnpromotedSign) {
  656. // In C++11 onwards, this is checked by the language rules.
  657. if (S.getLangOpts().CPlusPlus11)
  658. return;
  659. // If the case value was signed and negative and the switch expression is
  660. // unsigned, don't bother to warn: this is implementation-defined behavior.
  661. // FIXME: Introduce a second, default-ignored warning for this case?
  662. if (UnpromotedWidth < Val.getBitWidth()) {
  663. llvm::APSInt ConvVal(Val);
  664. AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
  665. AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
  666. // FIXME: Use different diagnostics for overflow in conversion to promoted
  667. // type versus "switch expression cannot have this value". Use proper
  668. // IntRange checking rather than just looking at the unpromoted type here.
  669. if (ConvVal != Val)
  670. S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
  671. << ConvVal.toString(10);
  672. }
  673. }
  674. typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
  675. /// Returns true if we should emit a diagnostic about this case expression not
  676. /// being a part of the enum used in the switch controlling expression.
  677. static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
  678. const EnumDecl *ED,
  679. const Expr *CaseExpr,
  680. EnumValsTy::iterator &EI,
  681. EnumValsTy::iterator &EIEnd,
  682. const llvm::APSInt &Val) {
  683. if (!ED->isClosed())
  684. return false;
  685. if (const DeclRefExpr *DRE =
  686. dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
  687. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  688. QualType VarType = VD->getType();
  689. QualType EnumType = S.Context.getTypeDeclType(ED);
  690. if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
  691. S.Context.hasSameUnqualifiedType(EnumType, VarType))
  692. return false;
  693. }
  694. }
  695. if (ED->hasAttr<FlagEnumAttr>())
  696. return !S.IsValueInFlagEnum(ED, Val, false);
  697. while (EI != EIEnd && EI->first < Val)
  698. EI++;
  699. if (EI != EIEnd && EI->first == Val)
  700. return false;
  701. return true;
  702. }
  703. static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
  704. const Expr *Case) {
  705. QualType CondType = Cond->getType();
  706. QualType CaseType = Case->getType();
  707. const EnumType *CondEnumType = CondType->getAs<EnumType>();
  708. const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
  709. if (!CondEnumType || !CaseEnumType)
  710. return;
  711. // Ignore anonymous enums.
  712. if (!CondEnumType->getDecl()->getIdentifier() &&
  713. !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
  714. return;
  715. if (!CaseEnumType->getDecl()->getIdentifier() &&
  716. !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
  717. return;
  718. if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
  719. return;
  720. S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
  721. << CondType << CaseType << Cond->getSourceRange()
  722. << Case->getSourceRange();
  723. }
  724. StmtResult
  725. Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
  726. Stmt *BodyStmt) {
  727. SwitchStmt *SS = cast<SwitchStmt>(Switch);
  728. bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
  729. assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
  730. "switch stack missing push/pop!");
  731. getCurFunction()->SwitchStack.pop_back();
  732. if (!BodyStmt) return StmtError();
  733. SS->setBody(BodyStmt, SwitchLoc);
  734. Expr *CondExpr = SS->getCond();
  735. if (!CondExpr) return StmtError();
  736. QualType CondType = CondExpr->getType();
  737. // C++ 6.4.2.p2:
  738. // Integral promotions are performed (on the switch condition).
  739. //
  740. // A case value unrepresentable by the original switch condition
  741. // type (before the promotion) doesn't make sense, even when it can
  742. // be represented by the promoted type. Therefore we need to find
  743. // the pre-promotion type of the switch condition.
  744. const Expr *CondExprBeforePromotion = CondExpr;
  745. QualType CondTypeBeforePromotion =
  746. GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
  747. // Get the bitwidth of the switched-on value after promotions. We must
  748. // convert the integer case values to this width before comparison.
  749. bool HasDependentValue
  750. = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
  751. unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
  752. bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
  753. // Get the width and signedness that the condition might actually have, for
  754. // warning purposes.
  755. // FIXME: Grab an IntRange for the condition rather than using the unpromoted
  756. // type.
  757. unsigned CondWidthBeforePromotion
  758. = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
  759. bool CondIsSignedBeforePromotion
  760. = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
  761. // Accumulate all of the case values in a vector so that we can sort them
  762. // and detect duplicates. This vector contains the APInt for the case after
  763. // it has been converted to the condition type.
  764. typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
  765. CaseValsTy CaseVals;
  766. // Keep track of any GNU case ranges we see. The APSInt is the low value.
  767. typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
  768. CaseRangesTy CaseRanges;
  769. DefaultStmt *TheDefaultStmt = nullptr;
  770. bool CaseListIsErroneous = false;
  771. for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
  772. SC = SC->getNextSwitchCase()) {
  773. if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
  774. if (TheDefaultStmt) {
  775. Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
  776. Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
  777. // FIXME: Remove the default statement from the switch block so that
  778. // we'll return a valid AST. This requires recursing down the AST and
  779. // finding it, not something we are set up to do right now. For now,
  780. // just lop the entire switch stmt out of the AST.
  781. CaseListIsErroneous = true;
  782. }
  783. TheDefaultStmt = DS;
  784. } else {
  785. CaseStmt *CS = cast<CaseStmt>(SC);
  786. Expr *Lo = CS->getLHS();
  787. if (Lo->isValueDependent()) {
  788. HasDependentValue = true;
  789. break;
  790. }
  791. // We already verified that the expression has a constant value;
  792. // get that value (prior to conversions).
  793. const Expr *LoBeforePromotion = Lo;
  794. GetTypeBeforeIntegralPromotion(LoBeforePromotion);
  795. llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
  796. // Check the unconverted value is within the range of possible values of
  797. // the switch expression.
  798. checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
  799. CondIsSignedBeforePromotion);
  800. // FIXME: This duplicates the check performed for warn_not_in_enum below.
  801. checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
  802. LoBeforePromotion);
  803. // Convert the value to the same width/sign as the condition.
  804. AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
  805. // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
  806. if (CS->getRHS()) {
  807. if (CS->getRHS()->isValueDependent()) {
  808. HasDependentValue = true;
  809. break;
  810. }
  811. CaseRanges.push_back(std::make_pair(LoVal, CS));
  812. } else
  813. CaseVals.push_back(std::make_pair(LoVal, CS));
  814. }
  815. }
  816. if (!HasDependentValue) {
  817. // If we don't have a default statement, check whether the
  818. // condition is constant.
  819. llvm::APSInt ConstantCondValue;
  820. bool HasConstantCond = false;
  821. if (!TheDefaultStmt) {
  822. Expr::EvalResult Result;
  823. HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
  824. Expr::SE_AllowSideEffects);
  825. if (Result.Val.isInt())
  826. ConstantCondValue = Result.Val.getInt();
  827. assert(!HasConstantCond ||
  828. (ConstantCondValue.getBitWidth() == CondWidth &&
  829. ConstantCondValue.isSigned() == CondIsSigned));
  830. }
  831. bool ShouldCheckConstantCond = HasConstantCond;
  832. // Sort all the scalar case values so we can easily detect duplicates.
  833. llvm::stable_sort(CaseVals, CmpCaseVals);
  834. if (!CaseVals.empty()) {
  835. for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
  836. if (ShouldCheckConstantCond &&
  837. CaseVals[i].first == ConstantCondValue)
  838. ShouldCheckConstantCond = false;
  839. if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
  840. // If we have a duplicate, report it.
  841. // First, determine if either case value has a name
  842. StringRef PrevString, CurrString;
  843. Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
  844. Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
  845. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
  846. PrevString = DeclRef->getDecl()->getName();
  847. }
  848. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
  849. CurrString = DeclRef->getDecl()->getName();
  850. }
  851. SmallString<16> CaseValStr;
  852. CaseVals[i-1].first.toString(CaseValStr);
  853. if (PrevString == CurrString)
  854. Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
  855. diag::err_duplicate_case)
  856. << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
  857. else
  858. Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
  859. diag::err_duplicate_case_differing_expr)
  860. << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
  861. << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
  862. << CaseValStr;
  863. Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
  864. diag::note_duplicate_case_prev);
  865. // FIXME: We really want to remove the bogus case stmt from the
  866. // substmt, but we have no way to do this right now.
  867. CaseListIsErroneous = true;
  868. }
  869. }
  870. }
  871. // Detect duplicate case ranges, which usually don't exist at all in
  872. // the first place.
  873. if (!CaseRanges.empty()) {
  874. // Sort all the case ranges by their low value so we can easily detect
  875. // overlaps between ranges.
  876. llvm::stable_sort(CaseRanges);
  877. // Scan the ranges, computing the high values and removing empty ranges.
  878. std::vector<llvm::APSInt> HiVals;
  879. for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
  880. llvm::APSInt &LoVal = CaseRanges[i].first;
  881. CaseStmt *CR = CaseRanges[i].second;
  882. Expr *Hi = CR->getRHS();
  883. const Expr *HiBeforePromotion = Hi;
  884. GetTypeBeforeIntegralPromotion(HiBeforePromotion);
  885. llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
  886. // Check the unconverted value is within the range of possible values of
  887. // the switch expression.
  888. checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
  889. CondWidthBeforePromotion, CondIsSignedBeforePromotion);
  890. // Convert the value to the same width/sign as the condition.
  891. AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
  892. // If the low value is bigger than the high value, the case is empty.
  893. if (LoVal > HiVal) {
  894. Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
  895. << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
  896. CaseRanges.erase(CaseRanges.begin()+i);
  897. --i;
  898. --e;
  899. continue;
  900. }
  901. if (ShouldCheckConstantCond &&
  902. LoVal <= ConstantCondValue &&
  903. ConstantCondValue <= HiVal)
  904. ShouldCheckConstantCond = false;
  905. HiVals.push_back(HiVal);
  906. }
  907. // Rescan the ranges, looking for overlap with singleton values and other
  908. // ranges. Since the range list is sorted, we only need to compare case
  909. // ranges with their neighbors.
  910. for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
  911. llvm::APSInt &CRLo = CaseRanges[i].first;
  912. llvm::APSInt &CRHi = HiVals[i];
  913. CaseStmt *CR = CaseRanges[i].second;
  914. // Check to see whether the case range overlaps with any
  915. // singleton cases.
  916. CaseStmt *OverlapStmt = nullptr;
  917. llvm::APSInt OverlapVal(32);
  918. // Find the smallest value >= the lower bound. If I is in the
  919. // case range, then we have overlap.
  920. CaseValsTy::iterator I =
  921. llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
  922. if (I != CaseVals.end() && I->first < CRHi) {
  923. OverlapVal = I->first; // Found overlap with scalar.
  924. OverlapStmt = I->second;
  925. }
  926. // Find the smallest value bigger than the upper bound.
  927. I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
  928. if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
  929. OverlapVal = (I-1)->first; // Found overlap with scalar.
  930. OverlapStmt = (I-1)->second;
  931. }
  932. // Check to see if this case stmt overlaps with the subsequent
  933. // case range.
  934. if (i && CRLo <= HiVals[i-1]) {
  935. OverlapVal = HiVals[i-1]; // Found overlap with range.
  936. OverlapStmt = CaseRanges[i-1].second;
  937. }
  938. if (OverlapStmt) {
  939. // If we have a duplicate, report it.
  940. Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
  941. << OverlapVal.toString(10);
  942. Diag(OverlapStmt->getLHS()->getBeginLoc(),
  943. diag::note_duplicate_case_prev);
  944. // FIXME: We really want to remove the bogus case stmt from the
  945. // substmt, but we have no way to do this right now.
  946. CaseListIsErroneous = true;
  947. }
  948. }
  949. }
  950. // Complain if we have a constant condition and we didn't find a match.
  951. if (!CaseListIsErroneous && !CaseListIsIncomplete &&
  952. ShouldCheckConstantCond) {
  953. // TODO: it would be nice if we printed enums as enums, chars as
  954. // chars, etc.
  955. Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
  956. << ConstantCondValue.toString(10)
  957. << CondExpr->getSourceRange();
  958. }
  959. // Check to see if switch is over an Enum and handles all of its
  960. // values. We only issue a warning if there is not 'default:', but
  961. // we still do the analysis to preserve this information in the AST
  962. // (which can be used by flow-based analyes).
  963. //
  964. const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
  965. // If switch has default case, then ignore it.
  966. if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
  967. ET && ET->getDecl()->isCompleteDefinition()) {
  968. const EnumDecl *ED = ET->getDecl();
  969. EnumValsTy EnumVals;
  970. // Gather all enum values, set their type and sort them,
  971. // allowing easier comparison with CaseVals.
  972. for (auto *EDI : ED->enumerators()) {
  973. llvm::APSInt Val = EDI->getInitVal();
  974. AdjustAPSInt(Val, CondWidth, CondIsSigned);
  975. EnumVals.push_back(std::make_pair(Val, EDI));
  976. }
  977. llvm::stable_sort(EnumVals, CmpEnumVals);
  978. auto EI = EnumVals.begin(), EIEnd =
  979. std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
  980. // See which case values aren't in enum.
  981. for (CaseValsTy::const_iterator CI = CaseVals.begin();
  982. CI != CaseVals.end(); CI++) {
  983. Expr *CaseExpr = CI->second->getLHS();
  984. if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
  985. CI->first))
  986. Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
  987. << CondTypeBeforePromotion;
  988. }
  989. // See which of case ranges aren't in enum
  990. EI = EnumVals.begin();
  991. for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
  992. RI != CaseRanges.end(); RI++) {
  993. Expr *CaseExpr = RI->second->getLHS();
  994. if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
  995. RI->first))
  996. Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
  997. << CondTypeBeforePromotion;
  998. llvm::APSInt Hi =
  999. RI->second->getRHS()->EvaluateKnownConstInt(Context);
  1000. AdjustAPSInt(Hi, CondWidth, CondIsSigned);
  1001. CaseExpr = RI->second->getRHS();
  1002. if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
  1003. Hi))
  1004. Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
  1005. << CondTypeBeforePromotion;
  1006. }
  1007. // Check which enum vals aren't in switch
  1008. auto CI = CaseVals.begin();
  1009. auto RI = CaseRanges.begin();
  1010. bool hasCasesNotInSwitch = false;
  1011. SmallVector<DeclarationName,8> UnhandledNames;
  1012. for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
  1013. // Don't warn about omitted unavailable EnumConstantDecls.
  1014. switch (EI->second->getAvailability()) {
  1015. case AR_Deprecated:
  1016. // Omitting a deprecated constant is ok; it should never materialize.
  1017. case AR_Unavailable:
  1018. continue;
  1019. case AR_NotYetIntroduced:
  1020. // Partially available enum constants should be present. Note that we
  1021. // suppress -Wunguarded-availability diagnostics for such uses.
  1022. case AR_Available:
  1023. break;
  1024. }
  1025. if (EI->second->hasAttr<UnusedAttr>())
  1026. continue;
  1027. // Drop unneeded case values
  1028. while (CI != CaseVals.end() && CI->first < EI->first)
  1029. CI++;
  1030. if (CI != CaseVals.end() && CI->first == EI->first)
  1031. continue;
  1032. // Drop unneeded case ranges
  1033. for (; RI != CaseRanges.end(); RI++) {
  1034. llvm::APSInt Hi =
  1035. RI->second->getRHS()->EvaluateKnownConstInt(Context);
  1036. AdjustAPSInt(Hi, CondWidth, CondIsSigned);
  1037. if (EI->first <= Hi)
  1038. break;
  1039. }
  1040. if (RI == CaseRanges.end() || EI->first < RI->first) {
  1041. hasCasesNotInSwitch = true;
  1042. UnhandledNames.push_back(EI->second->getDeclName());
  1043. }
  1044. }
  1045. if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
  1046. Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
  1047. // Produce a nice diagnostic if multiple values aren't handled.
  1048. if (!UnhandledNames.empty()) {
  1049. DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
  1050. TheDefaultStmt ? diag::warn_def_missing_case
  1051. : diag::warn_missing_case)
  1052. << (int)UnhandledNames.size();
  1053. for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
  1054. I != E; ++I)
  1055. DB << UnhandledNames[I];
  1056. }
  1057. if (!hasCasesNotInSwitch)
  1058. SS->setAllEnumCasesCovered();
  1059. }
  1060. }
  1061. if (BodyStmt)
  1062. DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
  1063. diag::warn_empty_switch_body);
  1064. // FIXME: If the case list was broken is some way, we don't have a good system
  1065. // to patch it up. Instead, just return the whole substmt as broken.
  1066. if (CaseListIsErroneous)
  1067. return StmtError();
  1068. return SS;
  1069. }
  1070. void
  1071. Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
  1072. Expr *SrcExpr) {
  1073. if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
  1074. return;
  1075. if (const EnumType *ET = DstType->getAs<EnumType>())
  1076. if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
  1077. SrcType->isIntegerType()) {
  1078. if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
  1079. SrcExpr->isIntegerConstantExpr(Context)) {
  1080. // Get the bitwidth of the enum value before promotions.
  1081. unsigned DstWidth = Context.getIntWidth(DstType);
  1082. bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
  1083. llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
  1084. AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
  1085. const EnumDecl *ED = ET->getDecl();
  1086. if (!ED->isClosed())
  1087. return;
  1088. if (ED->hasAttr<FlagEnumAttr>()) {
  1089. if (!IsValueInFlagEnum(ED, RhsVal, true))
  1090. Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
  1091. << DstType.getUnqualifiedType();
  1092. } else {
  1093. typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
  1094. EnumValsTy;
  1095. EnumValsTy EnumVals;
  1096. // Gather all enum values, set their type and sort them,
  1097. // allowing easier comparison with rhs constant.
  1098. for (auto *EDI : ED->enumerators()) {
  1099. llvm::APSInt Val = EDI->getInitVal();
  1100. AdjustAPSInt(Val, DstWidth, DstIsSigned);
  1101. EnumVals.push_back(std::make_pair(Val, EDI));
  1102. }
  1103. if (EnumVals.empty())
  1104. return;
  1105. llvm::stable_sort(EnumVals, CmpEnumVals);
  1106. EnumValsTy::iterator EIend =
  1107. std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
  1108. // See which values aren't in the enum.
  1109. EnumValsTy::const_iterator EI = EnumVals.begin();
  1110. while (EI != EIend && EI->first < RhsVal)
  1111. EI++;
  1112. if (EI == EIend || EI->first != RhsVal) {
  1113. Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
  1114. << DstType.getUnqualifiedType();
  1115. }
  1116. }
  1117. }
  1118. }
  1119. }
  1120. StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
  1121. Stmt *Body) {
  1122. if (Cond.isInvalid())
  1123. return StmtError();
  1124. auto CondVal = Cond.get();
  1125. CheckBreakContinueBinding(CondVal.second);
  1126. if (CondVal.second &&
  1127. !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
  1128. CommaVisitor(*this).Visit(CondVal.second);
  1129. if (isa<NullStmt>(Body))
  1130. getCurCompoundScope().setHasEmptyLoopBodies();
  1131. return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
  1132. WhileLoc);
  1133. }
  1134. StmtResult
  1135. Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
  1136. SourceLocation WhileLoc, SourceLocation CondLParen,
  1137. Expr *Cond, SourceLocation CondRParen) {
  1138. assert(Cond && "ActOnDoStmt(): missing expression");
  1139. CheckBreakContinueBinding(Cond);
  1140. ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
  1141. if (CondResult.isInvalid())
  1142. return StmtError();
  1143. Cond = CondResult.get();
  1144. CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
  1145. if (CondResult.isInvalid())
  1146. return StmtError();
  1147. Cond = CondResult.get();
  1148. // Only call the CommaVisitor for C89 due to differences in scope flags.
  1149. if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
  1150. !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
  1151. CommaVisitor(*this).Visit(Cond);
  1152. return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
  1153. }
  1154. namespace {
  1155. // Use SetVector since the diagnostic cares about the ordering of the Decl's.
  1156. using DeclSetVector =
  1157. llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
  1158. llvm::SmallPtrSet<VarDecl *, 8>>;
  1159. // This visitor will traverse a conditional statement and store all
  1160. // the evaluated decls into a vector. Simple is set to true if none
  1161. // of the excluded constructs are used.
  1162. class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
  1163. DeclSetVector &Decls;
  1164. SmallVectorImpl<SourceRange> &Ranges;
  1165. bool Simple;
  1166. public:
  1167. typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
  1168. DeclExtractor(Sema &S, DeclSetVector &Decls,
  1169. SmallVectorImpl<SourceRange> &Ranges) :
  1170. Inherited(S.Context),
  1171. Decls(Decls),
  1172. Ranges(Ranges),
  1173. Simple(true) {}
  1174. bool isSimple() { return Simple; }
  1175. // Replaces the method in EvaluatedExprVisitor.
  1176. void VisitMemberExpr(MemberExpr* E) {
  1177. Simple = false;
  1178. }
  1179. // Any Stmt not whitelisted will cause the condition to be marked complex.
  1180. void VisitStmt(Stmt *S) {
  1181. Simple = false;
  1182. }
  1183. void VisitBinaryOperator(BinaryOperator *E) {
  1184. Visit(E->getLHS());
  1185. Visit(E->getRHS());
  1186. }
  1187. void VisitCastExpr(CastExpr *E) {
  1188. Visit(E->getSubExpr());
  1189. }
  1190. void VisitUnaryOperator(UnaryOperator *E) {
  1191. // Skip checking conditionals with derefernces.
  1192. if (E->getOpcode() == UO_Deref)
  1193. Simple = false;
  1194. else
  1195. Visit(E->getSubExpr());
  1196. }
  1197. void VisitConditionalOperator(ConditionalOperator *E) {
  1198. Visit(E->getCond());
  1199. Visit(E->getTrueExpr());
  1200. Visit(E->getFalseExpr());
  1201. }
  1202. void VisitParenExpr(ParenExpr *E) {
  1203. Visit(E->getSubExpr());
  1204. }
  1205. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  1206. Visit(E->getOpaqueValue()->getSourceExpr());
  1207. Visit(E->getFalseExpr());
  1208. }
  1209. void VisitIntegerLiteral(IntegerLiteral *E) { }
  1210. void VisitFloatingLiteral(FloatingLiteral *E) { }
  1211. void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
  1212. void VisitCharacterLiteral(CharacterLiteral *E) { }
  1213. void VisitGNUNullExpr(GNUNullExpr *E) { }
  1214. void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
  1215. void VisitDeclRefExpr(DeclRefExpr *E) {
  1216. VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
  1217. if (!VD) {
  1218. // Don't allow unhandled Decl types.
  1219. Simple = false;
  1220. return;
  1221. }
  1222. Ranges.push_back(E->getSourceRange());
  1223. Decls.insert(VD);
  1224. }
  1225. }; // end class DeclExtractor
  1226. // DeclMatcher checks to see if the decls are used in a non-evaluated
  1227. // context.
  1228. class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
  1229. DeclSetVector &Decls;
  1230. bool FoundDecl;
  1231. public:
  1232. typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
  1233. DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
  1234. Inherited(S.Context), Decls(Decls), FoundDecl(false) {
  1235. if (!Statement) return;
  1236. Visit(Statement);
  1237. }
  1238. void VisitReturnStmt(ReturnStmt *S) {
  1239. FoundDecl = true;
  1240. }
  1241. void VisitBreakStmt(BreakStmt *S) {
  1242. FoundDecl = true;
  1243. }
  1244. void VisitGotoStmt(GotoStmt *S) {
  1245. FoundDecl = true;
  1246. }
  1247. void VisitCastExpr(CastExpr *E) {
  1248. if (E->getCastKind() == CK_LValueToRValue)
  1249. CheckLValueToRValueCast(E->getSubExpr());
  1250. else
  1251. Visit(E->getSubExpr());
  1252. }
  1253. void CheckLValueToRValueCast(Expr *E) {
  1254. E = E->IgnoreParenImpCasts();
  1255. if (isa<DeclRefExpr>(E)) {
  1256. return;
  1257. }
  1258. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  1259. Visit(CO->getCond());
  1260. CheckLValueToRValueCast(CO->getTrueExpr());
  1261. CheckLValueToRValueCast(CO->getFalseExpr());
  1262. return;
  1263. }
  1264. if (BinaryConditionalOperator *BCO =
  1265. dyn_cast<BinaryConditionalOperator>(E)) {
  1266. CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
  1267. CheckLValueToRValueCast(BCO->getFalseExpr());
  1268. return;
  1269. }
  1270. Visit(E);
  1271. }
  1272. void VisitDeclRefExpr(DeclRefExpr *E) {
  1273. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  1274. if (Decls.count(VD))
  1275. FoundDecl = true;
  1276. }
  1277. void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
  1278. // Only need to visit the semantics for POE.
  1279. // SyntaticForm doesn't really use the Decal.
  1280. for (auto *S : POE->semantics()) {
  1281. if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
  1282. // Look past the OVE into the expression it binds.
  1283. Visit(OVE->getSourceExpr());
  1284. else
  1285. Visit(S);
  1286. }
  1287. }
  1288. bool FoundDeclInUse() { return FoundDecl; }
  1289. }; // end class DeclMatcher
  1290. void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
  1291. Expr *Third, Stmt *Body) {
  1292. // Condition is empty
  1293. if (!Second) return;
  1294. if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
  1295. Second->getBeginLoc()))
  1296. return;
  1297. PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
  1298. DeclSetVector Decls;
  1299. SmallVector<SourceRange, 10> Ranges;
  1300. DeclExtractor DE(S, Decls, Ranges);
  1301. DE.Visit(Second);
  1302. // Don't analyze complex conditionals.
  1303. if (!DE.isSimple()) return;
  1304. // No decls found.
  1305. if (Decls.size() == 0) return;
  1306. // Don't warn on volatile, static, or global variables.
  1307. for (auto *VD : Decls)
  1308. if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
  1309. return;
  1310. if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
  1311. DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
  1312. DeclMatcher(S, Decls, Body).FoundDeclInUse())
  1313. return;
  1314. // Load decl names into diagnostic.
  1315. if (Decls.size() > 4) {
  1316. PDiag << 0;
  1317. } else {
  1318. PDiag << (unsigned)Decls.size();
  1319. for (auto *VD : Decls)
  1320. PDiag << VD->getDeclName();
  1321. }
  1322. for (auto Range : Ranges)
  1323. PDiag << Range;
  1324. S.Diag(Ranges.begin()->getBegin(), PDiag);
  1325. }
  1326. // If Statement is an incemement or decrement, return true and sets the
  1327. // variables Increment and DRE.
  1328. bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
  1329. DeclRefExpr *&DRE) {
  1330. if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
  1331. if (!Cleanups->cleanupsHaveSideEffects())
  1332. Statement = Cleanups->getSubExpr();
  1333. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
  1334. switch (UO->getOpcode()) {
  1335. default: return false;
  1336. case UO_PostInc:
  1337. case UO_PreInc:
  1338. Increment = true;
  1339. break;
  1340. case UO_PostDec:
  1341. case UO_PreDec:
  1342. Increment = false;
  1343. break;
  1344. }
  1345. DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
  1346. return DRE;
  1347. }
  1348. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
  1349. FunctionDecl *FD = Call->getDirectCallee();
  1350. if (!FD || !FD->isOverloadedOperator()) return false;
  1351. switch (FD->getOverloadedOperator()) {
  1352. default: return false;
  1353. case OO_PlusPlus:
  1354. Increment = true;
  1355. break;
  1356. case OO_MinusMinus:
  1357. Increment = false;
  1358. break;
  1359. }
  1360. DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
  1361. return DRE;
  1362. }
  1363. return false;
  1364. }
  1365. // A visitor to determine if a continue or break statement is a
  1366. // subexpression.
  1367. class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
  1368. SourceLocation BreakLoc;
  1369. SourceLocation ContinueLoc;
  1370. bool InSwitch = false;
  1371. public:
  1372. BreakContinueFinder(Sema &S, const Stmt* Body) :
  1373. Inherited(S.Context) {
  1374. Visit(Body);
  1375. }
  1376. typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
  1377. void VisitContinueStmt(const ContinueStmt* E) {
  1378. ContinueLoc = E->getContinueLoc();
  1379. }
  1380. void VisitBreakStmt(const BreakStmt* E) {
  1381. if (!InSwitch)
  1382. BreakLoc = E->getBreakLoc();
  1383. }
  1384. void VisitSwitchStmt(const SwitchStmt* S) {
  1385. if (const Stmt *Init = S->getInit())
  1386. Visit(Init);
  1387. if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
  1388. Visit(CondVar);
  1389. if (const Stmt *Cond = S->getCond())
  1390. Visit(Cond);
  1391. // Don't return break statements from the body of a switch.
  1392. InSwitch = true;
  1393. if (const Stmt *Body = S->getBody())
  1394. Visit(Body);
  1395. InSwitch = false;
  1396. }
  1397. void VisitForStmt(const ForStmt *S) {
  1398. // Only visit the init statement of a for loop; the body
  1399. // has a different break/continue scope.
  1400. if (const Stmt *Init = S->getInit())
  1401. Visit(Init);
  1402. }
  1403. void VisitWhileStmt(const WhileStmt *) {
  1404. // Do nothing; the children of a while loop have a different
  1405. // break/continue scope.
  1406. }
  1407. void VisitDoStmt(const DoStmt *) {
  1408. // Do nothing; the children of a while loop have a different
  1409. // break/continue scope.
  1410. }
  1411. void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
  1412. // Only visit the initialization of a for loop; the body
  1413. // has a different break/continue scope.
  1414. if (const Stmt *Init = S->getInit())
  1415. Visit(Init);
  1416. if (const Stmt *Range = S->getRangeStmt())
  1417. Visit(Range);
  1418. if (const Stmt *Begin = S->getBeginStmt())
  1419. Visit(Begin);
  1420. if (const Stmt *End = S->getEndStmt())
  1421. Visit(End);
  1422. }
  1423. void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
  1424. // Only visit the initialization of a for loop; the body
  1425. // has a different break/continue scope.
  1426. if (const Stmt *Element = S->getElement())
  1427. Visit(Element);
  1428. if (const Stmt *Collection = S->getCollection())
  1429. Visit(Collection);
  1430. }
  1431. bool ContinueFound() { return ContinueLoc.isValid(); }
  1432. bool BreakFound() { return BreakLoc.isValid(); }
  1433. SourceLocation GetContinueLoc() { return ContinueLoc; }
  1434. SourceLocation GetBreakLoc() { return BreakLoc; }
  1435. }; // end class BreakContinueFinder
  1436. // Emit a warning when a loop increment/decrement appears twice per loop
  1437. // iteration. The conditions which trigger this warning are:
  1438. // 1) The last statement in the loop body and the third expression in the
  1439. // for loop are both increment or both decrement of the same variable
  1440. // 2) No continue statements in the loop body.
  1441. void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
  1442. // Return when there is nothing to check.
  1443. if (!Body || !Third) return;
  1444. if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
  1445. Third->getBeginLoc()))
  1446. return;
  1447. // Get the last statement from the loop body.
  1448. CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
  1449. if (!CS || CS->body_empty()) return;
  1450. Stmt *LastStmt = CS->body_back();
  1451. if (!LastStmt) return;
  1452. bool LoopIncrement, LastIncrement;
  1453. DeclRefExpr *LoopDRE, *LastDRE;
  1454. if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
  1455. if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
  1456. // Check that the two statements are both increments or both decrements
  1457. // on the same variable.
  1458. if (LoopIncrement != LastIncrement ||
  1459. LoopDRE->getDecl() != LastDRE->getDecl()) return;
  1460. if (BreakContinueFinder(S, Body).ContinueFound()) return;
  1461. S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
  1462. << LastDRE->getDecl() << LastIncrement;
  1463. S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
  1464. << LoopIncrement;
  1465. }
  1466. } // end namespace
  1467. void Sema::CheckBreakContinueBinding(Expr *E) {
  1468. if (!E || getLangOpts().CPlusPlus)
  1469. return;
  1470. BreakContinueFinder BCFinder(*this, E);
  1471. Scope *BreakParent = CurScope->getBreakParent();
  1472. if (BCFinder.BreakFound() && BreakParent) {
  1473. if (BreakParent->getFlags() & Scope::SwitchScope) {
  1474. Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
  1475. } else {
  1476. Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
  1477. << "break";
  1478. }
  1479. } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
  1480. Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
  1481. << "continue";
  1482. }
  1483. }
  1484. StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
  1485. Stmt *First, ConditionResult Second,
  1486. FullExprArg third, SourceLocation RParenLoc,
  1487. Stmt *Body) {
  1488. if (Second.isInvalid())
  1489. return StmtError();
  1490. if (!getLangOpts().CPlusPlus) {
  1491. if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
  1492. // C99 6.8.5p3: The declaration part of a 'for' statement shall only
  1493. // declare identifiers for objects having storage class 'auto' or
  1494. // 'register'.
  1495. for (auto *DI : DS->decls()) {
  1496. VarDecl *VD = dyn_cast<VarDecl>(DI);
  1497. if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
  1498. VD = nullptr;
  1499. if (!VD) {
  1500. Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
  1501. DI->setInvalidDecl();
  1502. }
  1503. }
  1504. }
  1505. }
  1506. CheckBreakContinueBinding(Second.get().second);
  1507. CheckBreakContinueBinding(third.get());
  1508. if (!Second.get().first)
  1509. CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
  1510. Body);
  1511. CheckForRedundantIteration(*this, third.get(), Body);
  1512. if (Second.get().second &&
  1513. !Diags.isIgnored(diag::warn_comma_operator,
  1514. Second.get().second->getExprLoc()))
  1515. CommaVisitor(*this).Visit(Second.get().second);
  1516. Expr *Third = third.release().getAs<Expr>();
  1517. if (isa<NullStmt>(Body))
  1518. getCurCompoundScope().setHasEmptyLoopBodies();
  1519. return new (Context)
  1520. ForStmt(Context, First, Second.get().second, Second.get().first, Third,
  1521. Body, ForLoc, LParenLoc, RParenLoc);
  1522. }
  1523. /// In an Objective C collection iteration statement:
  1524. /// for (x in y)
  1525. /// x can be an arbitrary l-value expression. Bind it up as a
  1526. /// full-expression.
  1527. StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
  1528. // Reduce placeholder expressions here. Note that this rejects the
  1529. // use of pseudo-object l-values in this position.
  1530. ExprResult result = CheckPlaceholderExpr(E);
  1531. if (result.isInvalid()) return StmtError();
  1532. E = result.get();
  1533. ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
  1534. if (FullExpr.isInvalid())
  1535. return StmtError();
  1536. return StmtResult(static_cast<Stmt*>(FullExpr.get()));
  1537. }
  1538. ExprResult
  1539. Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
  1540. if (!collection)
  1541. return ExprError();
  1542. ExprResult result = CorrectDelayedTyposInExpr(collection);
  1543. if (!result.isUsable())
  1544. return ExprError();
  1545. collection = result.get();
  1546. // Bail out early if we've got a type-dependent expression.
  1547. if (collection->isTypeDependent()) return collection;
  1548. // Perform normal l-value conversion.
  1549. result = DefaultFunctionArrayLvalueConversion(collection);
  1550. if (result.isInvalid())
  1551. return ExprError();
  1552. collection = result.get();
  1553. // The operand needs to have object-pointer type.
  1554. // TODO: should we do a contextual conversion?
  1555. const ObjCObjectPointerType *pointerType =
  1556. collection->getType()->getAs<ObjCObjectPointerType>();
  1557. if (!pointerType)
  1558. return Diag(forLoc, diag::err_collection_expr_type)
  1559. << collection->getType() << collection->getSourceRange();
  1560. // Check that the operand provides
  1561. // - countByEnumeratingWithState:objects:count:
  1562. const ObjCObjectType *objectType = pointerType->getObjectType();
  1563. ObjCInterfaceDecl *iface = objectType->getInterface();
  1564. // If we have a forward-declared type, we can't do this check.
  1565. // Under ARC, it is an error not to have a forward-declared class.
  1566. if (iface &&
  1567. (getLangOpts().ObjCAutoRefCount
  1568. ? RequireCompleteType(forLoc, QualType(objectType, 0),
  1569. diag::err_arc_collection_forward, collection)
  1570. : !isCompleteType(forLoc, QualType(objectType, 0)))) {
  1571. // Otherwise, if we have any useful type information, check that
  1572. // the type declares the appropriate method.
  1573. } else if (iface || !objectType->qual_empty()) {
  1574. IdentifierInfo *selectorIdents[] = {
  1575. &Context.Idents.get("countByEnumeratingWithState"),
  1576. &Context.Idents.get("objects"),
  1577. &Context.Idents.get("count")
  1578. };
  1579. Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
  1580. ObjCMethodDecl *method = nullptr;
  1581. // If there's an interface, look in both the public and private APIs.
  1582. if (iface) {
  1583. method = iface->lookupInstanceMethod(selector);
  1584. if (!method) method = iface->lookupPrivateMethod(selector);
  1585. }
  1586. // Also check protocol qualifiers.
  1587. if (!method)
  1588. method = LookupMethodInQualifiedType(selector, pointerType,
  1589. /*instance*/ true);
  1590. // If we didn't find it anywhere, give up.
  1591. if (!method) {
  1592. Diag(forLoc, diag::warn_collection_expr_type)
  1593. << collection->getType() << selector << collection->getSourceRange();
  1594. }
  1595. // TODO: check for an incompatible signature?
  1596. }
  1597. // Wrap up any cleanups in the expression.
  1598. return collection;
  1599. }
  1600. StmtResult
  1601. Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
  1602. Stmt *First, Expr *collection,
  1603. SourceLocation RParenLoc) {
  1604. setFunctionHasBranchProtectedScope();
  1605. ExprResult CollectionExprResult =
  1606. CheckObjCForCollectionOperand(ForLoc, collection);
  1607. if (First) {
  1608. QualType FirstType;
  1609. if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
  1610. if (!DS->isSingleDecl())
  1611. return StmtError(Diag((*DS->decl_begin())->getLocation(),
  1612. diag::err_toomany_element_decls));
  1613. VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
  1614. if (!D || D->isInvalidDecl())
  1615. return StmtError();
  1616. FirstType = D->getType();
  1617. // C99 6.8.5p3: The declaration part of a 'for' statement shall only
  1618. // declare identifiers for objects having storage class 'auto' or
  1619. // 'register'.
  1620. if (!D->hasLocalStorage())
  1621. return StmtError(Diag(D->getLocation(),
  1622. diag::err_non_local_variable_decl_in_for));
  1623. // If the type contained 'auto', deduce the 'auto' to 'id'.
  1624. if (FirstType->getContainedAutoType()) {
  1625. OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
  1626. VK_RValue);
  1627. Expr *DeducedInit = &OpaqueId;
  1628. if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
  1629. DAR_Failed)
  1630. DiagnoseAutoDeductionFailure(D, DeducedInit);
  1631. if (FirstType.isNull()) {
  1632. D->setInvalidDecl();
  1633. return StmtError();
  1634. }
  1635. D->setType(FirstType);
  1636. if (!inTemplateInstantiation()) {
  1637. SourceLocation Loc =
  1638. D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
  1639. Diag(Loc, diag::warn_auto_var_is_id)
  1640. << D->getDeclName();
  1641. }
  1642. }
  1643. } else {
  1644. Expr *FirstE = cast<Expr>(First);
  1645. if (!FirstE->isTypeDependent() && !FirstE->isLValue())
  1646. return StmtError(
  1647. Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
  1648. << First->getSourceRange());
  1649. FirstType = static_cast<Expr*>(First)->getType();
  1650. if (FirstType.isConstQualified())
  1651. Diag(ForLoc, diag::err_selector_element_const_type)
  1652. << FirstType << First->getSourceRange();
  1653. }
  1654. if (!FirstType->isDependentType() &&
  1655. !FirstType->isObjCObjectPointerType() &&
  1656. !FirstType->isBlockPointerType())
  1657. return StmtError(Diag(ForLoc, diag::err_selector_element_type)
  1658. << FirstType << First->getSourceRange());
  1659. }
  1660. if (CollectionExprResult.isInvalid())
  1661. return StmtError();
  1662. CollectionExprResult =
  1663. ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
  1664. if (CollectionExprResult.isInvalid())
  1665. return StmtError();
  1666. return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
  1667. nullptr, ForLoc, RParenLoc);
  1668. }
  1669. /// Finish building a variable declaration for a for-range statement.
  1670. /// \return true if an error occurs.
  1671. static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
  1672. SourceLocation Loc, int DiagID) {
  1673. if (Decl->getType()->isUndeducedType()) {
  1674. ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
  1675. if (!Res.isUsable()) {
  1676. Decl->setInvalidDecl();
  1677. return true;
  1678. }
  1679. Init = Res.get();
  1680. }
  1681. // Deduce the type for the iterator variable now rather than leaving it to
  1682. // AddInitializerToDecl, so we can produce a more suitable diagnostic.
  1683. QualType InitType;
  1684. if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
  1685. SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
  1686. Sema::DAR_Failed)
  1687. SemaRef.Diag(Loc, DiagID) << Init->getType();
  1688. if (InitType.isNull()) {
  1689. Decl->setInvalidDecl();
  1690. return true;
  1691. }
  1692. Decl->setType(InitType);
  1693. // In ARC, infer lifetime.
  1694. // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
  1695. // we're doing the equivalent of fast iteration.
  1696. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  1697. SemaRef.inferObjCARCLifetime(Decl))
  1698. Decl->setInvalidDecl();
  1699. SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
  1700. SemaRef.FinalizeDeclaration(Decl);
  1701. SemaRef.CurContext->addHiddenDecl(Decl);
  1702. return false;
  1703. }
  1704. namespace {
  1705. // An enum to represent whether something is dealing with a call to begin()
  1706. // or a call to end() in a range-based for loop.
  1707. enum BeginEndFunction {
  1708. BEF_begin,
  1709. BEF_end
  1710. };
  1711. /// Produce a note indicating which begin/end function was implicitly called
  1712. /// by a C++11 for-range statement. This is often not obvious from the code,
  1713. /// nor from the diagnostics produced when analysing the implicit expressions
  1714. /// required in a for-range statement.
  1715. void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
  1716. BeginEndFunction BEF) {
  1717. CallExpr *CE = dyn_cast<CallExpr>(E);
  1718. if (!CE)
  1719. return;
  1720. FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
  1721. if (!D)
  1722. return;
  1723. SourceLocation Loc = D->getLocation();
  1724. std::string Description;
  1725. bool IsTemplate = false;
  1726. if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
  1727. Description = SemaRef.getTemplateArgumentBindingsText(
  1728. FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
  1729. IsTemplate = true;
  1730. }
  1731. SemaRef.Diag(Loc, diag::note_for_range_begin_end)
  1732. << BEF << IsTemplate << Description << E->getType();
  1733. }
  1734. /// Build a variable declaration for a for-range statement.
  1735. VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
  1736. QualType Type, StringRef Name) {
  1737. DeclContext *DC = SemaRef.CurContext;
  1738. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  1739. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  1740. VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
  1741. TInfo, SC_None);
  1742. Decl->setImplicit();
  1743. return Decl;
  1744. }
  1745. }
  1746. static bool ObjCEnumerationCollection(Expr *Collection) {
  1747. return !Collection->isTypeDependent()
  1748. && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
  1749. }
  1750. /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
  1751. ///
  1752. /// C++11 [stmt.ranged]:
  1753. /// A range-based for statement is equivalent to
  1754. ///
  1755. /// {
  1756. /// auto && __range = range-init;
  1757. /// for ( auto __begin = begin-expr,
  1758. /// __end = end-expr;
  1759. /// __begin != __end;
  1760. /// ++__begin ) {
  1761. /// for-range-declaration = *__begin;
  1762. /// statement
  1763. /// }
  1764. /// }
  1765. ///
  1766. /// The body of the loop is not available yet, since it cannot be analysed until
  1767. /// we have determined the type of the for-range-declaration.
  1768. StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
  1769. SourceLocation CoawaitLoc, Stmt *InitStmt,
  1770. Stmt *First, SourceLocation ColonLoc,
  1771. Expr *Range, SourceLocation RParenLoc,
  1772. BuildForRangeKind Kind) {
  1773. if (!First)
  1774. return StmtError();
  1775. if (Range && ObjCEnumerationCollection(Range)) {
  1776. // FIXME: Support init-statements in Objective-C++20 ranged for statement.
  1777. if (InitStmt)
  1778. return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
  1779. << InitStmt->getSourceRange();
  1780. return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
  1781. }
  1782. DeclStmt *DS = dyn_cast<DeclStmt>(First);
  1783. assert(DS && "first part of for range not a decl stmt");
  1784. if (!DS->isSingleDecl()) {
  1785. Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
  1786. return StmtError();
  1787. }
  1788. Decl *LoopVar = DS->getSingleDecl();
  1789. if (LoopVar->isInvalidDecl() || !Range ||
  1790. DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
  1791. LoopVar->setInvalidDecl();
  1792. return StmtError();
  1793. }
  1794. // Build the coroutine state immediately and not later during template
  1795. // instantiation
  1796. if (!CoawaitLoc.isInvalid()) {
  1797. if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
  1798. return StmtError();
  1799. }
  1800. // Build auto && __range = range-init
  1801. // Divide by 2, since the variables are in the inner scope (loop body).
  1802. const auto DepthStr = std::to_string(S->getDepth() / 2);
  1803. SourceLocation RangeLoc = Range->getBeginLoc();
  1804. VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
  1805. Context.getAutoRRefDeductType(),
  1806. std::string("__range") + DepthStr);
  1807. if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
  1808. diag::err_for_range_deduction_failure)) {
  1809. LoopVar->setInvalidDecl();
  1810. return StmtError();
  1811. }
  1812. // Claim the type doesn't contain auto: we've already done the checking.
  1813. DeclGroupPtrTy RangeGroup =
  1814. BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
  1815. StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
  1816. if (RangeDecl.isInvalid()) {
  1817. LoopVar->setInvalidDecl();
  1818. return StmtError();
  1819. }
  1820. return BuildCXXForRangeStmt(
  1821. ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
  1822. /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
  1823. /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
  1824. }
  1825. /// Create the initialization, compare, and increment steps for
  1826. /// the range-based for loop expression.
  1827. /// This function does not handle array-based for loops,
  1828. /// which are created in Sema::BuildCXXForRangeStmt.
  1829. ///
  1830. /// \returns a ForRangeStatus indicating success or what kind of error occurred.
  1831. /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
  1832. /// CandidateSet and BEF are set and some non-success value is returned on
  1833. /// failure.
  1834. static Sema::ForRangeStatus
  1835. BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
  1836. QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
  1837. SourceLocation ColonLoc, SourceLocation CoawaitLoc,
  1838. OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
  1839. ExprResult *EndExpr, BeginEndFunction *BEF) {
  1840. DeclarationNameInfo BeginNameInfo(
  1841. &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
  1842. DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
  1843. ColonLoc);
  1844. LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
  1845. Sema::LookupMemberName);
  1846. LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
  1847. auto BuildBegin = [&] {
  1848. *BEF = BEF_begin;
  1849. Sema::ForRangeStatus RangeStatus =
  1850. SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
  1851. BeginMemberLookup, CandidateSet,
  1852. BeginRange, BeginExpr);
  1853. if (RangeStatus != Sema::FRS_Success) {
  1854. if (RangeStatus == Sema::FRS_DiagnosticIssued)
  1855. SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
  1856. << ColonLoc << BEF_begin << BeginRange->getType();
  1857. return RangeStatus;
  1858. }
  1859. if (!CoawaitLoc.isInvalid()) {
  1860. // FIXME: getCurScope() should not be used during template instantiation.
  1861. // We should pick up the set of unqualified lookup results for operator
  1862. // co_await during the initial parse.
  1863. *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
  1864. BeginExpr->get());
  1865. if (BeginExpr->isInvalid())
  1866. return Sema::FRS_DiagnosticIssued;
  1867. }
  1868. if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
  1869. diag::err_for_range_iter_deduction_failure)) {
  1870. NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
  1871. return Sema::FRS_DiagnosticIssued;
  1872. }
  1873. return Sema::FRS_Success;
  1874. };
  1875. auto BuildEnd = [&] {
  1876. *BEF = BEF_end;
  1877. Sema::ForRangeStatus RangeStatus =
  1878. SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
  1879. EndMemberLookup, CandidateSet,
  1880. EndRange, EndExpr);
  1881. if (RangeStatus != Sema::FRS_Success) {
  1882. if (RangeStatus == Sema::FRS_DiagnosticIssued)
  1883. SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
  1884. << ColonLoc << BEF_end << EndRange->getType();
  1885. return RangeStatus;
  1886. }
  1887. if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
  1888. diag::err_for_range_iter_deduction_failure)) {
  1889. NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
  1890. return Sema::FRS_DiagnosticIssued;
  1891. }
  1892. return Sema::FRS_Success;
  1893. };
  1894. if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
  1895. // - if _RangeT is a class type, the unqualified-ids begin and end are
  1896. // looked up in the scope of class _RangeT as if by class member access
  1897. // lookup (3.4.5), and if either (or both) finds at least one
  1898. // declaration, begin-expr and end-expr are __range.begin() and
  1899. // __range.end(), respectively;
  1900. SemaRef.LookupQualifiedName(BeginMemberLookup, D);
  1901. if (BeginMemberLookup.isAmbiguous())
  1902. return Sema::FRS_DiagnosticIssued;
  1903. SemaRef.LookupQualifiedName(EndMemberLookup, D);
  1904. if (EndMemberLookup.isAmbiguous())
  1905. return Sema::FRS_DiagnosticIssued;
  1906. if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
  1907. // Look up the non-member form of the member we didn't find, first.
  1908. // This way we prefer a "no viable 'end'" diagnostic over a "i found
  1909. // a 'begin' but ignored it because there was no member 'end'"
  1910. // diagnostic.
  1911. auto BuildNonmember = [&](
  1912. BeginEndFunction BEFFound, LookupResult &Found,
  1913. llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
  1914. llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
  1915. LookupResult OldFound = std::move(Found);
  1916. Found.clear();
  1917. if (Sema::ForRangeStatus Result = BuildNotFound())
  1918. return Result;
  1919. switch (BuildFound()) {
  1920. case Sema::FRS_Success:
  1921. return Sema::FRS_Success;
  1922. case Sema::FRS_NoViableFunction:
  1923. CandidateSet->NoteCandidates(
  1924. PartialDiagnosticAt(BeginRange->getBeginLoc(),
  1925. SemaRef.PDiag(diag::err_for_range_invalid)
  1926. << BeginRange->getType() << BEFFound),
  1927. SemaRef, OCD_AllCandidates, BeginRange);
  1928. LLVM_FALLTHROUGH;
  1929. case Sema::FRS_DiagnosticIssued:
  1930. for (NamedDecl *D : OldFound) {
  1931. SemaRef.Diag(D->getLocation(),
  1932. diag::note_for_range_member_begin_end_ignored)
  1933. << BeginRange->getType() << BEFFound;
  1934. }
  1935. return Sema::FRS_DiagnosticIssued;
  1936. }
  1937. llvm_unreachable("unexpected ForRangeStatus");
  1938. };
  1939. if (BeginMemberLookup.empty())
  1940. return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
  1941. return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
  1942. }
  1943. } else {
  1944. // - otherwise, begin-expr and end-expr are begin(__range) and
  1945. // end(__range), respectively, where begin and end are looked up with
  1946. // argument-dependent lookup (3.4.2). For the purposes of this name
  1947. // lookup, namespace std is an associated namespace.
  1948. }
  1949. if (Sema::ForRangeStatus Result = BuildBegin())
  1950. return Result;
  1951. return BuildEnd();
  1952. }
  1953. /// Speculatively attempt to dereference an invalid range expression.
  1954. /// If the attempt fails, this function will return a valid, null StmtResult
  1955. /// and emit no diagnostics.
  1956. static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
  1957. SourceLocation ForLoc,
  1958. SourceLocation CoawaitLoc,
  1959. Stmt *InitStmt,
  1960. Stmt *LoopVarDecl,
  1961. SourceLocation ColonLoc,
  1962. Expr *Range,
  1963. SourceLocation RangeLoc,
  1964. SourceLocation RParenLoc) {
  1965. // Determine whether we can rebuild the for-range statement with a
  1966. // dereferenced range expression.
  1967. ExprResult AdjustedRange;
  1968. {
  1969. Sema::SFINAETrap Trap(SemaRef);
  1970. AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
  1971. if (AdjustedRange.isInvalid())
  1972. return StmtResult();
  1973. StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
  1974. S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
  1975. AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
  1976. if (SR.isInvalid())
  1977. return StmtResult();
  1978. }
  1979. // The attempt to dereference worked well enough that it could produce a valid
  1980. // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
  1981. // case there are any other (non-fatal) problems with it.
  1982. SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
  1983. << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
  1984. return SemaRef.ActOnCXXForRangeStmt(
  1985. S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
  1986. AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
  1987. }
  1988. namespace {
  1989. /// RAII object to automatically invalidate a declaration if an error occurs.
  1990. struct InvalidateOnErrorScope {
  1991. InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
  1992. : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
  1993. ~InvalidateOnErrorScope() {
  1994. if (Enabled && Trap.hasErrorOccurred())
  1995. D->setInvalidDecl();
  1996. }
  1997. DiagnosticErrorTrap Trap;
  1998. Decl *D;
  1999. bool Enabled;
  2000. };
  2001. }
  2002. /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
  2003. StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
  2004. SourceLocation CoawaitLoc, Stmt *InitStmt,
  2005. SourceLocation ColonLoc, Stmt *RangeDecl,
  2006. Stmt *Begin, Stmt *End, Expr *Cond,
  2007. Expr *Inc, Stmt *LoopVarDecl,
  2008. SourceLocation RParenLoc,
  2009. BuildForRangeKind Kind) {
  2010. // FIXME: This should not be used during template instantiation. We should
  2011. // pick up the set of unqualified lookup results for the != and + operators
  2012. // in the initial parse.
  2013. //
  2014. // Testcase (accepts-invalid):
  2015. // template<typename T> void f() { for (auto x : T()) {} }
  2016. // namespace N { struct X { X begin(); X end(); int operator*(); }; }
  2017. // bool operator!=(N::X, N::X); void operator++(N::X);
  2018. // void g() { f<N::X>(); }
  2019. Scope *S = getCurScope();
  2020. DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
  2021. VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
  2022. QualType RangeVarType = RangeVar->getType();
  2023. DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
  2024. VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
  2025. // If we hit any errors, mark the loop variable as invalid if its type
  2026. // contains 'auto'.
  2027. InvalidateOnErrorScope Invalidate(*this, LoopVar,
  2028. LoopVar->getType()->isUndeducedType());
  2029. StmtResult BeginDeclStmt = Begin;
  2030. StmtResult EndDeclStmt = End;
  2031. ExprResult NotEqExpr = Cond, IncrExpr = Inc;
  2032. if (RangeVarType->isDependentType()) {
  2033. // The range is implicitly used as a placeholder when it is dependent.
  2034. RangeVar->markUsed(Context);
  2035. // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
  2036. // them in properly when we instantiate the loop.
  2037. if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
  2038. if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
  2039. for (auto *Binding : DD->bindings())
  2040. Binding->setType(Context.DependentTy);
  2041. LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
  2042. }
  2043. } else if (!BeginDeclStmt.get()) {
  2044. SourceLocation RangeLoc = RangeVar->getLocation();
  2045. const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
  2046. ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
  2047. VK_LValue, ColonLoc);
  2048. if (BeginRangeRef.isInvalid())
  2049. return StmtError();
  2050. ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
  2051. VK_LValue, ColonLoc);
  2052. if (EndRangeRef.isInvalid())
  2053. return StmtError();
  2054. QualType AutoType = Context.getAutoDeductType();
  2055. Expr *Range = RangeVar->getInit();
  2056. if (!Range)
  2057. return StmtError();
  2058. QualType RangeType = Range->getType();
  2059. if (RequireCompleteType(RangeLoc, RangeType,
  2060. diag::err_for_range_incomplete_type))
  2061. return StmtError();
  2062. // Build auto __begin = begin-expr, __end = end-expr.
  2063. // Divide by 2, since the variables are in the inner scope (loop body).
  2064. const auto DepthStr = std::to_string(S->getDepth() / 2);
  2065. VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
  2066. std::string("__begin") + DepthStr);
  2067. VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
  2068. std::string("__end") + DepthStr);
  2069. // Build begin-expr and end-expr and attach to __begin and __end variables.
  2070. ExprResult BeginExpr, EndExpr;
  2071. if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
  2072. // - if _RangeT is an array type, begin-expr and end-expr are __range and
  2073. // __range + __bound, respectively, where __bound is the array bound. If
  2074. // _RangeT is an array of unknown size or an array of incomplete type,
  2075. // the program is ill-formed;
  2076. // begin-expr is __range.
  2077. BeginExpr = BeginRangeRef;
  2078. if (!CoawaitLoc.isInvalid()) {
  2079. BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
  2080. if (BeginExpr.isInvalid())
  2081. return StmtError();
  2082. }
  2083. if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
  2084. diag::err_for_range_iter_deduction_failure)) {
  2085. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2086. return StmtError();
  2087. }
  2088. // Find the array bound.
  2089. ExprResult BoundExpr;
  2090. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
  2091. BoundExpr = IntegerLiteral::Create(
  2092. Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
  2093. else if (const VariableArrayType *VAT =
  2094. dyn_cast<VariableArrayType>(UnqAT)) {
  2095. // For a variably modified type we can't just use the expression within
  2096. // the array bounds, since we don't want that to be re-evaluated here.
  2097. // Rather, we need to determine what it was when the array was first
  2098. // created - so we resort to using sizeof(vla)/sizeof(element).
  2099. // For e.g.
  2100. // void f(int b) {
  2101. // int vla[b];
  2102. // b = -1; <-- This should not affect the num of iterations below
  2103. // for (int &c : vla) { .. }
  2104. // }
  2105. // FIXME: This results in codegen generating IR that recalculates the
  2106. // run-time number of elements (as opposed to just using the IR Value
  2107. // that corresponds to the run-time value of each bound that was
  2108. // generated when the array was created.) If this proves too embarrassing
  2109. // even for unoptimized IR, consider passing a magic-value/cookie to
  2110. // codegen that then knows to simply use that initial llvm::Value (that
  2111. // corresponds to the bound at time of array creation) within
  2112. // getelementptr. But be prepared to pay the price of increasing a
  2113. // customized form of coupling between the two components - which could
  2114. // be hard to maintain as the codebase evolves.
  2115. ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
  2116. EndVar->getLocation(), UETT_SizeOf,
  2117. /*IsType=*/true,
  2118. CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
  2119. VAT->desugar(), RangeLoc))
  2120. .getAsOpaquePtr(),
  2121. EndVar->getSourceRange());
  2122. if (SizeOfVLAExprR.isInvalid())
  2123. return StmtError();
  2124. ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
  2125. EndVar->getLocation(), UETT_SizeOf,
  2126. /*IsType=*/true,
  2127. CreateParsedType(VAT->desugar(),
  2128. Context.getTrivialTypeSourceInfo(
  2129. VAT->getElementType(), RangeLoc))
  2130. .getAsOpaquePtr(),
  2131. EndVar->getSourceRange());
  2132. if (SizeOfEachElementExprR.isInvalid())
  2133. return StmtError();
  2134. BoundExpr =
  2135. ActOnBinOp(S, EndVar->getLocation(), tok::slash,
  2136. SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
  2137. if (BoundExpr.isInvalid())
  2138. return StmtError();
  2139. } else {
  2140. // Can't be a DependentSizedArrayType or an IncompleteArrayType since
  2141. // UnqAT is not incomplete and Range is not type-dependent.
  2142. llvm_unreachable("Unexpected array type in for-range");
  2143. }
  2144. // end-expr is __range + __bound.
  2145. EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
  2146. BoundExpr.get());
  2147. if (EndExpr.isInvalid())
  2148. return StmtError();
  2149. if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
  2150. diag::err_for_range_iter_deduction_failure)) {
  2151. NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
  2152. return StmtError();
  2153. }
  2154. } else {
  2155. OverloadCandidateSet CandidateSet(RangeLoc,
  2156. OverloadCandidateSet::CSK_Normal);
  2157. BeginEndFunction BEFFailure;
  2158. ForRangeStatus RangeStatus = BuildNonArrayForRange(
  2159. *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
  2160. EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
  2161. &BEFFailure);
  2162. if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
  2163. BEFFailure == BEF_begin) {
  2164. // If the range is being built from an array parameter, emit a
  2165. // a diagnostic that it is being treated as a pointer.
  2166. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
  2167. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  2168. QualType ArrayTy = PVD->getOriginalType();
  2169. QualType PointerTy = PVD->getType();
  2170. if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
  2171. Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
  2172. << RangeLoc << PVD << ArrayTy << PointerTy;
  2173. Diag(PVD->getLocation(), diag::note_declared_at);
  2174. return StmtError();
  2175. }
  2176. }
  2177. }
  2178. // If building the range failed, try dereferencing the range expression
  2179. // unless a diagnostic was issued or the end function is problematic.
  2180. StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
  2181. CoawaitLoc, InitStmt,
  2182. LoopVarDecl, ColonLoc,
  2183. Range, RangeLoc,
  2184. RParenLoc);
  2185. if (SR.isInvalid() || SR.isUsable())
  2186. return SR;
  2187. }
  2188. // Otherwise, emit diagnostics if we haven't already.
  2189. if (RangeStatus == FRS_NoViableFunction) {
  2190. Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
  2191. CandidateSet.NoteCandidates(
  2192. PartialDiagnosticAt(Range->getBeginLoc(),
  2193. PDiag(diag::err_for_range_invalid)
  2194. << RangeLoc << Range->getType()
  2195. << BEFFailure),
  2196. *this, OCD_AllCandidates, Range);
  2197. }
  2198. // Return an error if no fix was discovered.
  2199. if (RangeStatus != FRS_Success)
  2200. return StmtError();
  2201. }
  2202. assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
  2203. "invalid range expression in for loop");
  2204. // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
  2205. // C++1z removes this restriction.
  2206. QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
  2207. if (!Context.hasSameType(BeginType, EndType)) {
  2208. Diag(RangeLoc, getLangOpts().CPlusPlus17
  2209. ? diag::warn_for_range_begin_end_types_differ
  2210. : diag::ext_for_range_begin_end_types_differ)
  2211. << BeginType << EndType;
  2212. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2213. NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
  2214. }
  2215. BeginDeclStmt =
  2216. ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
  2217. EndDeclStmt =
  2218. ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
  2219. const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
  2220. ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
  2221. VK_LValue, ColonLoc);
  2222. if (BeginRef.isInvalid())
  2223. return StmtError();
  2224. ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
  2225. VK_LValue, ColonLoc);
  2226. if (EndRef.isInvalid())
  2227. return StmtError();
  2228. // Build and check __begin != __end expression.
  2229. NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
  2230. BeginRef.get(), EndRef.get());
  2231. if (!NotEqExpr.isInvalid())
  2232. NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
  2233. if (!NotEqExpr.isInvalid())
  2234. NotEqExpr =
  2235. ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
  2236. if (NotEqExpr.isInvalid()) {
  2237. Diag(RangeLoc, diag::note_for_range_invalid_iterator)
  2238. << RangeLoc << 0 << BeginRangeRef.get()->getType();
  2239. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2240. if (!Context.hasSameType(BeginType, EndType))
  2241. NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
  2242. return StmtError();
  2243. }
  2244. // Build and check ++__begin expression.
  2245. BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
  2246. VK_LValue, ColonLoc);
  2247. if (BeginRef.isInvalid())
  2248. return StmtError();
  2249. IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
  2250. if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
  2251. // FIXME: getCurScope() should not be used during template instantiation.
  2252. // We should pick up the set of unqualified lookup results for operator
  2253. // co_await during the initial parse.
  2254. IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
  2255. if (!IncrExpr.isInvalid())
  2256. IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
  2257. if (IncrExpr.isInvalid()) {
  2258. Diag(RangeLoc, diag::note_for_range_invalid_iterator)
  2259. << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
  2260. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2261. return StmtError();
  2262. }
  2263. // Build and check *__begin expression.
  2264. BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
  2265. VK_LValue, ColonLoc);
  2266. if (BeginRef.isInvalid())
  2267. return StmtError();
  2268. ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
  2269. if (DerefExpr.isInvalid()) {
  2270. Diag(RangeLoc, diag::note_for_range_invalid_iterator)
  2271. << RangeLoc << 1 << BeginRangeRef.get()->getType();
  2272. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2273. return StmtError();
  2274. }
  2275. // Attach *__begin as initializer for VD. Don't touch it if we're just
  2276. // trying to determine whether this would be a valid range.
  2277. if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
  2278. AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
  2279. if (LoopVar->isInvalidDecl())
  2280. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2281. }
  2282. }
  2283. // Don't bother to actually allocate the result if we're just trying to
  2284. // determine whether it would be valid.
  2285. if (Kind == BFRK_Check)
  2286. return StmtResult();
  2287. // In OpenMP loop region loop control variable must be private. Perform
  2288. // analysis of first part (if any).
  2289. if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
  2290. ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get());
  2291. return new (Context) CXXForRangeStmt(
  2292. InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
  2293. cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
  2294. IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
  2295. ColonLoc, RParenLoc);
  2296. }
  2297. /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
  2298. /// statement.
  2299. StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
  2300. if (!S || !B)
  2301. return StmtError();
  2302. ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
  2303. ForStmt->setBody(B);
  2304. return S;
  2305. }
  2306. // Warn when the loop variable is a const reference that creates a copy.
  2307. // Suggest using the non-reference type for copies. If a copy can be prevented
  2308. // suggest the const reference type that would do so.
  2309. // For instance, given "for (const &Foo : Range)", suggest
  2310. // "for (const Foo : Range)" to denote a copy is made for the loop. If
  2311. // possible, also suggest "for (const &Bar : Range)" if this type prevents
  2312. // the copy altogether.
  2313. static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
  2314. const VarDecl *VD,
  2315. QualType RangeInitType) {
  2316. const Expr *InitExpr = VD->getInit();
  2317. if (!InitExpr)
  2318. return;
  2319. QualType VariableType = VD->getType();
  2320. if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
  2321. if (!Cleanups->cleanupsHaveSideEffects())
  2322. InitExpr = Cleanups->getSubExpr();
  2323. const MaterializeTemporaryExpr *MTE =
  2324. dyn_cast<MaterializeTemporaryExpr>(InitExpr);
  2325. // No copy made.
  2326. if (!MTE)
  2327. return;
  2328. const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
  2329. // Searching for either UnaryOperator for dereference of a pointer or
  2330. // CXXOperatorCallExpr for handling iterators.
  2331. while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
  2332. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
  2333. E = CCE->getArg(0);
  2334. } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
  2335. const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
  2336. E = ME->getBase();
  2337. } else {
  2338. const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
  2339. E = MTE->GetTemporaryExpr();
  2340. }
  2341. E = E->IgnoreImpCasts();
  2342. }
  2343. bool ReturnsReference = false;
  2344. if (isa<UnaryOperator>(E)) {
  2345. ReturnsReference = true;
  2346. } else {
  2347. const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
  2348. const FunctionDecl *FD = Call->getDirectCallee();
  2349. QualType ReturnType = FD->getReturnType();
  2350. ReturnsReference = ReturnType->isReferenceType();
  2351. }
  2352. if (ReturnsReference) {
  2353. // Loop variable creates a temporary. Suggest either to go with
  2354. // non-reference loop variable to indicate a copy is made, or
  2355. // the correct time to bind a const reference.
  2356. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
  2357. << VD << VariableType << E->getType();
  2358. QualType NonReferenceType = VariableType.getNonReferenceType();
  2359. NonReferenceType.removeLocalConst();
  2360. QualType NewReferenceType =
  2361. SemaRef.Context.getLValueReferenceType(E->getType().withConst());
  2362. SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
  2363. << NonReferenceType << NewReferenceType << VD->getSourceRange();
  2364. } else {
  2365. // The range always returns a copy, so a temporary is always created.
  2366. // Suggest removing the reference from the loop variable.
  2367. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
  2368. << VD << RangeInitType;
  2369. QualType NonReferenceType = VariableType.getNonReferenceType();
  2370. NonReferenceType.removeLocalConst();
  2371. SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
  2372. << NonReferenceType << VD->getSourceRange();
  2373. }
  2374. }
  2375. // Warns when the loop variable can be changed to a reference type to
  2376. // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
  2377. // "for (const Foo &x : Range)" if this form does not make a copy.
  2378. static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
  2379. const VarDecl *VD) {
  2380. const Expr *InitExpr = VD->getInit();
  2381. if (!InitExpr)
  2382. return;
  2383. QualType VariableType = VD->getType();
  2384. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
  2385. if (!CE->getConstructor()->isCopyConstructor())
  2386. return;
  2387. } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
  2388. if (CE->getCastKind() != CK_LValueToRValue)
  2389. return;
  2390. } else {
  2391. return;
  2392. }
  2393. // TODO: Determine a maximum size that a POD type can be before a diagnostic
  2394. // should be emitted. Also, only ignore POD types with trivial copy
  2395. // constructors.
  2396. if (VariableType.isPODType(SemaRef.Context))
  2397. return;
  2398. // Suggest changing from a const variable to a const reference variable
  2399. // if doing so will prevent a copy.
  2400. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
  2401. << VD << VariableType << InitExpr->getType();
  2402. SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
  2403. << SemaRef.Context.getLValueReferenceType(VariableType)
  2404. << VD->getSourceRange();
  2405. }
  2406. /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
  2407. /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
  2408. /// using "const foo x" to show that a copy is made
  2409. /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
  2410. /// Suggest either "const bar x" to keep the copying or "const foo& x" to
  2411. /// prevent the copy.
  2412. /// 3) for (const foo x : foos) where x is constructed from a reference foo.
  2413. /// Suggest "const foo &x" to prevent the copy.
  2414. static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
  2415. const CXXForRangeStmt *ForStmt) {
  2416. if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
  2417. ForStmt->getBeginLoc()) &&
  2418. SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
  2419. ForStmt->getBeginLoc()) &&
  2420. SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
  2421. ForStmt->getBeginLoc())) {
  2422. return;
  2423. }
  2424. const VarDecl *VD = ForStmt->getLoopVariable();
  2425. if (!VD)
  2426. return;
  2427. QualType VariableType = VD->getType();
  2428. if (VariableType->isIncompleteType())
  2429. return;
  2430. const Expr *InitExpr = VD->getInit();
  2431. if (!InitExpr)
  2432. return;
  2433. if (VariableType->isReferenceType()) {
  2434. DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
  2435. ForStmt->getRangeInit()->getType());
  2436. } else if (VariableType.isConstQualified()) {
  2437. DiagnoseForRangeConstVariableCopies(SemaRef, VD);
  2438. }
  2439. }
  2440. /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
  2441. /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
  2442. /// body cannot be performed until after the type of the range variable is
  2443. /// determined.
  2444. StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
  2445. if (!S || !B)
  2446. return StmtError();
  2447. if (isa<ObjCForCollectionStmt>(S))
  2448. return FinishObjCForCollectionStmt(S, B);
  2449. CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
  2450. ForStmt->setBody(B);
  2451. DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
  2452. diag::warn_empty_range_based_for_body);
  2453. DiagnoseForRangeVariableCopies(*this, ForStmt);
  2454. return S;
  2455. }
  2456. StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
  2457. SourceLocation LabelLoc,
  2458. LabelDecl *TheDecl) {
  2459. setFunctionHasBranchIntoScope();
  2460. TheDecl->markUsed(Context);
  2461. return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
  2462. }
  2463. StmtResult
  2464. Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
  2465. Expr *E) {
  2466. // Convert operand to void*
  2467. if (!E->isTypeDependent()) {
  2468. QualType ETy = E->getType();
  2469. QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
  2470. ExprResult ExprRes = E;
  2471. AssignConvertType ConvTy =
  2472. CheckSingleAssignmentConstraints(DestTy, ExprRes);
  2473. if (ExprRes.isInvalid())
  2474. return StmtError();
  2475. E = ExprRes.get();
  2476. if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
  2477. return StmtError();
  2478. }
  2479. ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
  2480. if (ExprRes.isInvalid())
  2481. return StmtError();
  2482. E = ExprRes.get();
  2483. setFunctionHasIndirectGoto();
  2484. return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
  2485. }
  2486. static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
  2487. const Scope &DestScope) {
  2488. if (!S.CurrentSEHFinally.empty() &&
  2489. DestScope.Contains(*S.CurrentSEHFinally.back())) {
  2490. S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
  2491. }
  2492. }
  2493. StmtResult
  2494. Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
  2495. Scope *S = CurScope->getContinueParent();
  2496. if (!S) {
  2497. // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
  2498. return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
  2499. }
  2500. CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
  2501. return new (Context) ContinueStmt(ContinueLoc);
  2502. }
  2503. StmtResult
  2504. Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
  2505. Scope *S = CurScope->getBreakParent();
  2506. if (!S) {
  2507. // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
  2508. return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
  2509. }
  2510. if (S->isOpenMPLoopScope())
  2511. return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
  2512. << "break");
  2513. CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
  2514. return new (Context) BreakStmt(BreakLoc);
  2515. }
  2516. /// Determine whether the given expression is a candidate for
  2517. /// copy elision in either a return statement or a throw expression.
  2518. ///
  2519. /// \param ReturnType If we're determining the copy elision candidate for
  2520. /// a return statement, this is the return type of the function. If we're
  2521. /// determining the copy elision candidate for a throw expression, this will
  2522. /// be a NULL type.
  2523. ///
  2524. /// \param E The expression being returned from the function or block, or
  2525. /// being thrown.
  2526. ///
  2527. /// \param CESK Whether we allow function parameters or
  2528. /// id-expressions that could be moved out of the function to be considered NRVO
  2529. /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
  2530. /// determine whether we should try to move as part of a return or throw (which
  2531. /// does allow function parameters).
  2532. ///
  2533. /// \returns The NRVO candidate variable, if the return statement may use the
  2534. /// NRVO, or NULL if there is no such candidate.
  2535. VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
  2536. CopyElisionSemanticsKind CESK) {
  2537. // - in a return statement in a function [where] ...
  2538. // ... the expression is the name of a non-volatile automatic object ...
  2539. DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
  2540. if (!DR || DR->refersToEnclosingVariableOrCapture())
  2541. return nullptr;
  2542. VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  2543. if (!VD)
  2544. return nullptr;
  2545. if (isCopyElisionCandidate(ReturnType, VD, CESK))
  2546. return VD;
  2547. return nullptr;
  2548. }
  2549. bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
  2550. CopyElisionSemanticsKind CESK) {
  2551. QualType VDType = VD->getType();
  2552. // - in a return statement in a function with ...
  2553. // ... a class return type ...
  2554. if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
  2555. if (!ReturnType->isRecordType())
  2556. return false;
  2557. // ... the same cv-unqualified type as the function return type ...
  2558. // When considering moving this expression out, allow dissimilar types.
  2559. if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
  2560. !Context.hasSameUnqualifiedType(ReturnType, VDType))
  2561. return false;
  2562. }
  2563. // ...object (other than a function or catch-clause parameter)...
  2564. if (VD->getKind() != Decl::Var &&
  2565. !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
  2566. return false;
  2567. if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
  2568. return false;
  2569. // ...automatic...
  2570. if (!VD->hasLocalStorage()) return false;
  2571. // Return false if VD is a __block variable. We don't want to implicitly move
  2572. // out of a __block variable during a return because we cannot assume the
  2573. // variable will no longer be used.
  2574. if (VD->hasAttr<BlocksAttr>()) return false;
  2575. if (CESK & CES_AllowDifferentTypes)
  2576. return true;
  2577. // ...non-volatile...
  2578. if (VD->getType().isVolatileQualified()) return false;
  2579. // Variables with higher required alignment than their type's ABI
  2580. // alignment cannot use NRVO.
  2581. if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
  2582. Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
  2583. return false;
  2584. return true;
  2585. }
  2586. /// Try to perform the initialization of a potentially-movable value,
  2587. /// which is the operand to a return or throw statement.
  2588. ///
  2589. /// This routine implements C++14 [class.copy]p32, which attempts to treat
  2590. /// returned lvalues as rvalues in certain cases (to prefer move construction),
  2591. /// then falls back to treating them as lvalues if that failed.
  2592. ///
  2593. /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
  2594. /// resolutions that find non-constructors, such as derived-to-base conversions
  2595. /// or `operator T()&&` member functions. If false, do consider such
  2596. /// conversion sequences.
  2597. ///
  2598. /// \param Res We will fill this in if move-initialization was possible.
  2599. /// If move-initialization is not possible, such that we must fall back to
  2600. /// treating the operand as an lvalue, we will leave Res in its original
  2601. /// invalid state.
  2602. static void TryMoveInitialization(Sema& S,
  2603. const InitializedEntity &Entity,
  2604. const VarDecl *NRVOCandidate,
  2605. QualType ResultType,
  2606. Expr *&Value,
  2607. bool ConvertingConstructorsOnly,
  2608. ExprResult &Res) {
  2609. ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
  2610. CK_NoOp, Value, VK_XValue);
  2611. Expr *InitExpr = &AsRvalue;
  2612. InitializationKind Kind = InitializationKind::CreateCopy(
  2613. Value->getBeginLoc(), Value->getBeginLoc());
  2614. InitializationSequence Seq(S, Entity, Kind, InitExpr);
  2615. if (!Seq)
  2616. return;
  2617. for (const InitializationSequence::Step &Step : Seq.steps()) {
  2618. if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
  2619. Step.Kind != InitializationSequence::SK_UserConversion)
  2620. continue;
  2621. FunctionDecl *FD = Step.Function.Function;
  2622. if (ConvertingConstructorsOnly) {
  2623. if (isa<CXXConstructorDecl>(FD)) {
  2624. // C++14 [class.copy]p32:
  2625. // [...] If the first overload resolution fails or was not performed,
  2626. // or if the type of the first parameter of the selected constructor
  2627. // is not an rvalue reference to the object's type (possibly
  2628. // cv-qualified), overload resolution is performed again, considering
  2629. // the object as an lvalue.
  2630. const RValueReferenceType *RRefType =
  2631. FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
  2632. if (!RRefType)
  2633. break;
  2634. if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
  2635. NRVOCandidate->getType()))
  2636. break;
  2637. } else {
  2638. continue;
  2639. }
  2640. } else {
  2641. if (isa<CXXConstructorDecl>(FD)) {
  2642. // Check that overload resolution selected a constructor taking an
  2643. // rvalue reference. If it selected an lvalue reference, then we
  2644. // didn't need to cast this thing to an rvalue in the first place.
  2645. if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
  2646. break;
  2647. } else if (isa<CXXMethodDecl>(FD)) {
  2648. // Check that overload resolution selected a conversion operator
  2649. // taking an rvalue reference.
  2650. if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
  2651. break;
  2652. } else {
  2653. continue;
  2654. }
  2655. }
  2656. // Promote "AsRvalue" to the heap, since we now need this
  2657. // expression node to persist.
  2658. Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
  2659. Value, nullptr, VK_XValue);
  2660. // Complete type-checking the initialization of the return type
  2661. // using the constructor we found.
  2662. Res = Seq.Perform(S, Entity, Kind, Value);
  2663. }
  2664. }
  2665. /// Perform the initialization of a potentially-movable value, which
  2666. /// is the result of return value.
  2667. ///
  2668. /// This routine implements C++14 [class.copy]p32, which attempts to treat
  2669. /// returned lvalues as rvalues in certain cases (to prefer move construction),
  2670. /// then falls back to treating them as lvalues if that failed.
  2671. ExprResult
  2672. Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
  2673. const VarDecl *NRVOCandidate,
  2674. QualType ResultType,
  2675. Expr *Value,
  2676. bool AllowNRVO) {
  2677. // C++14 [class.copy]p32:
  2678. // When the criteria for elision of a copy/move operation are met, but not for
  2679. // an exception-declaration, and the object to be copied is designated by an
  2680. // lvalue, or when the expression in a return statement is a (possibly
  2681. // parenthesized) id-expression that names an object with automatic storage
  2682. // duration declared in the body or parameter-declaration-clause of the
  2683. // innermost enclosing function or lambda-expression, overload resolution to
  2684. // select the constructor for the copy is first performed as if the object
  2685. // were designated by an rvalue.
  2686. ExprResult Res = ExprError();
  2687. if (AllowNRVO) {
  2688. bool AffectedByCWG1579 = false;
  2689. if (!NRVOCandidate) {
  2690. NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
  2691. if (NRVOCandidate &&
  2692. !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
  2693. Value->getExprLoc())) {
  2694. const VarDecl *NRVOCandidateInCXX11 =
  2695. getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
  2696. AffectedByCWG1579 = (!NRVOCandidateInCXX11);
  2697. }
  2698. }
  2699. if (NRVOCandidate) {
  2700. TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
  2701. true, Res);
  2702. }
  2703. if (!Res.isInvalid() && AffectedByCWG1579) {
  2704. QualType QT = NRVOCandidate->getType();
  2705. if (QT.getNonReferenceType()
  2706. .getUnqualifiedType()
  2707. .isTriviallyCopyableType(Context)) {
  2708. // Adding 'std::move' around a trivially copyable variable is probably
  2709. // pointless. Don't suggest it.
  2710. } else {
  2711. // Common cases for this are returning unique_ptr<Derived> from a
  2712. // function of return type unique_ptr<Base>, or returning T from a
  2713. // function of return type Expected<T>. This is totally fine in a
  2714. // post-CWG1579 world, but was not fine before.
  2715. assert(!ResultType.isNull());
  2716. SmallString<32> Str;
  2717. Str += "std::move(";
  2718. Str += NRVOCandidate->getDeclName().getAsString();
  2719. Str += ")";
  2720. Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
  2721. << Value->getSourceRange()
  2722. << NRVOCandidate->getDeclName() << ResultType << QT;
  2723. Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
  2724. << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
  2725. }
  2726. } else if (Res.isInvalid() &&
  2727. !getDiagnostics().isIgnored(diag::warn_return_std_move,
  2728. Value->getExprLoc())) {
  2729. const VarDecl *FakeNRVOCandidate =
  2730. getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
  2731. if (FakeNRVOCandidate) {
  2732. QualType QT = FakeNRVOCandidate->getType();
  2733. if (QT->isLValueReferenceType()) {
  2734. // Adding 'std::move' around an lvalue reference variable's name is
  2735. // dangerous. Don't suggest it.
  2736. } else if (QT.getNonReferenceType()
  2737. .getUnqualifiedType()
  2738. .isTriviallyCopyableType(Context)) {
  2739. // Adding 'std::move' around a trivially copyable variable is probably
  2740. // pointless. Don't suggest it.
  2741. } else {
  2742. ExprResult FakeRes = ExprError();
  2743. Expr *FakeValue = Value;
  2744. TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
  2745. FakeValue, false, FakeRes);
  2746. if (!FakeRes.isInvalid()) {
  2747. bool IsThrow =
  2748. (Entity.getKind() == InitializedEntity::EK_Exception);
  2749. SmallString<32> Str;
  2750. Str += "std::move(";
  2751. Str += FakeNRVOCandidate->getDeclName().getAsString();
  2752. Str += ")";
  2753. Diag(Value->getExprLoc(), diag::warn_return_std_move)
  2754. << Value->getSourceRange()
  2755. << FakeNRVOCandidate->getDeclName() << IsThrow;
  2756. Diag(Value->getExprLoc(), diag::note_add_std_move)
  2757. << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
  2758. }
  2759. }
  2760. }
  2761. }
  2762. }
  2763. // Either we didn't meet the criteria for treating an lvalue as an rvalue,
  2764. // above, or overload resolution failed. Either way, we need to try
  2765. // (again) now with the return value expression as written.
  2766. if (Res.isInvalid())
  2767. Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
  2768. return Res;
  2769. }
  2770. /// Determine whether the declared return type of the specified function
  2771. /// contains 'auto'.
  2772. static bool hasDeducedReturnType(FunctionDecl *FD) {
  2773. const FunctionProtoType *FPT =
  2774. FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
  2775. return FPT->getReturnType()->isUndeducedType();
  2776. }
  2777. /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
  2778. /// for capturing scopes.
  2779. ///
  2780. StmtResult
  2781. Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
  2782. // If this is the first return we've seen, infer the return type.
  2783. // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
  2784. CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
  2785. QualType FnRetType = CurCap->ReturnType;
  2786. LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
  2787. bool HasDeducedReturnType =
  2788. CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
  2789. if (ExprEvalContexts.back().Context ==
  2790. ExpressionEvaluationContext::DiscardedStatement &&
  2791. (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
  2792. if (RetValExp) {
  2793. ExprResult ER =
  2794. ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
  2795. if (ER.isInvalid())
  2796. return StmtError();
  2797. RetValExp = ER.get();
  2798. }
  2799. return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
  2800. /* NRVOCandidate=*/nullptr);
  2801. }
  2802. if (HasDeducedReturnType) {
  2803. // In C++1y, the return type may involve 'auto'.
  2804. // FIXME: Blocks might have a return type of 'auto' explicitly specified.
  2805. FunctionDecl *FD = CurLambda->CallOperator;
  2806. if (CurCap->ReturnType.isNull())
  2807. CurCap->ReturnType = FD->getReturnType();
  2808. AutoType *AT = CurCap->ReturnType->getContainedAutoType();
  2809. assert(AT && "lost auto type from lambda return type");
  2810. if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
  2811. FD->setInvalidDecl();
  2812. return StmtError();
  2813. }
  2814. CurCap->ReturnType = FnRetType = FD->getReturnType();
  2815. } else if (CurCap->HasImplicitReturnType) {
  2816. // For blocks/lambdas with implicit return types, we check each return
  2817. // statement individually, and deduce the common return type when the block
  2818. // or lambda is completed.
  2819. // FIXME: Fold this into the 'auto' codepath above.
  2820. if (RetValExp && !isa<InitListExpr>(RetValExp)) {
  2821. ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
  2822. if (Result.isInvalid())
  2823. return StmtError();
  2824. RetValExp = Result.get();
  2825. // DR1048: even prior to C++14, we should use the 'auto' deduction rules
  2826. // when deducing a return type for a lambda-expression (or by extension
  2827. // for a block). These rules differ from the stated C++11 rules only in
  2828. // that they remove top-level cv-qualifiers.
  2829. if (!CurContext->isDependentContext())
  2830. FnRetType = RetValExp->getType().getUnqualifiedType();
  2831. else
  2832. FnRetType = CurCap->ReturnType = Context.DependentTy;
  2833. } else {
  2834. if (RetValExp) {
  2835. // C++11 [expr.lambda.prim]p4 bans inferring the result from an
  2836. // initializer list, because it is not an expression (even
  2837. // though we represent it as one). We still deduce 'void'.
  2838. Diag(ReturnLoc, diag::err_lambda_return_init_list)
  2839. << RetValExp->getSourceRange();
  2840. }
  2841. FnRetType = Context.VoidTy;
  2842. }
  2843. // Although we'll properly infer the type of the block once it's completed,
  2844. // make sure we provide a return type now for better error recovery.
  2845. if (CurCap->ReturnType.isNull())
  2846. CurCap->ReturnType = FnRetType;
  2847. }
  2848. assert(!FnRetType.isNull());
  2849. if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
  2850. if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
  2851. Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
  2852. return StmtError();
  2853. }
  2854. } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
  2855. Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
  2856. return StmtError();
  2857. } else {
  2858. assert(CurLambda && "unknown kind of captured scope");
  2859. if (CurLambda->CallOperator->getType()
  2860. ->castAs<FunctionType>()
  2861. ->getNoReturnAttr()) {
  2862. Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
  2863. return StmtError();
  2864. }
  2865. }
  2866. // Otherwise, verify that this result type matches the previous one. We are
  2867. // pickier with blocks than for normal functions because we don't have GCC
  2868. // compatibility to worry about here.
  2869. const VarDecl *NRVOCandidate = nullptr;
  2870. if (FnRetType->isDependentType()) {
  2871. // Delay processing for now. TODO: there are lots of dependent
  2872. // types we can conclusively prove aren't void.
  2873. } else if (FnRetType->isVoidType()) {
  2874. if (RetValExp && !isa<InitListExpr>(RetValExp) &&
  2875. !(getLangOpts().CPlusPlus &&
  2876. (RetValExp->isTypeDependent() ||
  2877. RetValExp->getType()->isVoidType()))) {
  2878. if (!getLangOpts().CPlusPlus &&
  2879. RetValExp->getType()->isVoidType())
  2880. Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
  2881. else {
  2882. Diag(ReturnLoc, diag::err_return_block_has_expr);
  2883. RetValExp = nullptr;
  2884. }
  2885. }
  2886. } else if (!RetValExp) {
  2887. return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
  2888. } else if (!RetValExp->isTypeDependent()) {
  2889. // we have a non-void block with an expression, continue checking
  2890. // C99 6.8.6.4p3(136): The return statement is not an assignment. The
  2891. // overlap restriction of subclause 6.5.16.1 does not apply to the case of
  2892. // function return.
  2893. // In C++ the return statement is handled via a copy initialization.
  2894. // the C version of which boils down to CheckSingleAssignmentConstraints.
  2895. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
  2896. InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
  2897. FnRetType,
  2898. NRVOCandidate != nullptr);
  2899. ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
  2900. FnRetType, RetValExp);
  2901. if (Res.isInvalid()) {
  2902. // FIXME: Cleanup temporaries here, anyway?
  2903. return StmtError();
  2904. }
  2905. RetValExp = Res.get();
  2906. CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
  2907. } else {
  2908. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
  2909. }
  2910. if (RetValExp) {
  2911. ExprResult ER =
  2912. ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
  2913. if (ER.isInvalid())
  2914. return StmtError();
  2915. RetValExp = ER.get();
  2916. }
  2917. auto *Result =
  2918. ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
  2919. // If we need to check for the named return value optimization,
  2920. // or if we need to infer the return type,
  2921. // save the return statement in our scope for later processing.
  2922. if (CurCap->HasImplicitReturnType || NRVOCandidate)
  2923. FunctionScopes.back()->Returns.push_back(Result);
  2924. if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
  2925. FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
  2926. return Result;
  2927. }
  2928. namespace {
  2929. /// Marks all typedefs in all local classes in a type referenced.
  2930. ///
  2931. /// In a function like
  2932. /// auto f() {
  2933. /// struct S { typedef int a; };
  2934. /// return S();
  2935. /// }
  2936. ///
  2937. /// the local type escapes and could be referenced in some TUs but not in
  2938. /// others. Pretend that all local typedefs are always referenced, to not warn
  2939. /// on this. This isn't necessary if f has internal linkage, or the typedef
  2940. /// is private.
  2941. class LocalTypedefNameReferencer
  2942. : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
  2943. public:
  2944. LocalTypedefNameReferencer(Sema &S) : S(S) {}
  2945. bool VisitRecordType(const RecordType *RT);
  2946. private:
  2947. Sema &S;
  2948. };
  2949. bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
  2950. auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
  2951. if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
  2952. R->isDependentType())
  2953. return true;
  2954. for (auto *TmpD : R->decls())
  2955. if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  2956. if (T->getAccess() != AS_private || R->hasFriends())
  2957. S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
  2958. return true;
  2959. }
  2960. }
  2961. TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
  2962. return FD->getTypeSourceInfo()
  2963. ->getTypeLoc()
  2964. .getAsAdjusted<FunctionProtoTypeLoc>()
  2965. .getReturnLoc();
  2966. }
  2967. /// Deduce the return type for a function from a returned expression, per
  2968. /// C++1y [dcl.spec.auto]p6.
  2969. bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
  2970. SourceLocation ReturnLoc,
  2971. Expr *&RetExpr,
  2972. AutoType *AT) {
  2973. // If this is the conversion function for a lambda, we choose to deduce it
  2974. // type from the corresponding call operator, not from the synthesized return
  2975. // statement within it. See Sema::DeduceReturnType.
  2976. if (isLambdaConversionOperator(FD))
  2977. return false;
  2978. TypeLoc OrigResultType = getReturnTypeLoc(FD);
  2979. QualType Deduced;
  2980. if (RetExpr && isa<InitListExpr>(RetExpr)) {
  2981. // If the deduction is for a return statement and the initializer is
  2982. // a braced-init-list, the program is ill-formed.
  2983. Diag(RetExpr->getExprLoc(),
  2984. getCurLambda() ? diag::err_lambda_return_init_list
  2985. : diag::err_auto_fn_return_init_list)
  2986. << RetExpr->getSourceRange();
  2987. return true;
  2988. }
  2989. if (FD->isDependentContext()) {
  2990. // C++1y [dcl.spec.auto]p12:
  2991. // Return type deduction [...] occurs when the definition is
  2992. // instantiated even if the function body contains a return
  2993. // statement with a non-type-dependent operand.
  2994. assert(AT->isDeduced() && "should have deduced to dependent type");
  2995. return false;
  2996. }
  2997. if (RetExpr) {
  2998. // Otherwise, [...] deduce a value for U using the rules of template
  2999. // argument deduction.
  3000. DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
  3001. if (DAR == DAR_Failed && !FD->isInvalidDecl())
  3002. Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
  3003. << OrigResultType.getType() << RetExpr->getType();
  3004. if (DAR != DAR_Succeeded)
  3005. return true;
  3006. // If a local type is part of the returned type, mark its fields as
  3007. // referenced.
  3008. LocalTypedefNameReferencer Referencer(*this);
  3009. Referencer.TraverseType(RetExpr->getType());
  3010. } else {
  3011. // In the case of a return with no operand, the initializer is considered
  3012. // to be void().
  3013. //
  3014. // Deduction here can only succeed if the return type is exactly 'cv auto'
  3015. // or 'decltype(auto)', so just check for that case directly.
  3016. if (!OrigResultType.getType()->getAs<AutoType>()) {
  3017. Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
  3018. << OrigResultType.getType();
  3019. return true;
  3020. }
  3021. // We always deduce U = void in this case.
  3022. Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
  3023. if (Deduced.isNull())
  3024. return true;
  3025. }
  3026. // CUDA: Kernel function must have 'void' return type.
  3027. if (getLangOpts().CUDA)
  3028. if (FD->hasAttr<CUDAGlobalAttr>() && !Deduced->isVoidType()) {
  3029. Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
  3030. << FD->getType() << FD->getSourceRange();
  3031. return true;
  3032. }
  3033. // If a function with a declared return type that contains a placeholder type
  3034. // has multiple return statements, the return type is deduced for each return
  3035. // statement. [...] if the type deduced is not the same in each deduction,
  3036. // the program is ill-formed.
  3037. QualType DeducedT = AT->getDeducedType();
  3038. if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
  3039. AutoType *NewAT = Deduced->getContainedAutoType();
  3040. // It is possible that NewAT->getDeducedType() is null. When that happens,
  3041. // we should not crash, instead we ignore this deduction.
  3042. if (NewAT->getDeducedType().isNull())
  3043. return false;
  3044. CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
  3045. DeducedT);
  3046. CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
  3047. NewAT->getDeducedType());
  3048. if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
  3049. const LambdaScopeInfo *LambdaSI = getCurLambda();
  3050. if (LambdaSI && LambdaSI->HasImplicitReturnType) {
  3051. Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
  3052. << NewAT->getDeducedType() << DeducedT
  3053. << true /*IsLambda*/;
  3054. } else {
  3055. Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
  3056. << (AT->isDecltypeAuto() ? 1 : 0)
  3057. << NewAT->getDeducedType() << DeducedT;
  3058. }
  3059. return true;
  3060. }
  3061. } else if (!FD->isInvalidDecl()) {
  3062. // Update all declarations of the function to have the deduced return type.
  3063. Context.adjustDeducedFunctionResultType(FD, Deduced);
  3064. }
  3065. return false;
  3066. }
  3067. StmtResult
  3068. Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
  3069. Scope *CurScope) {
  3070. // Correct typos, in case the containing function returns 'auto' and
  3071. // RetValExp should determine the deduced type.
  3072. ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp);
  3073. if (RetVal.isInvalid())
  3074. return StmtError();
  3075. StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get());
  3076. if (R.isInvalid() || ExprEvalContexts.back().Context ==
  3077. ExpressionEvaluationContext::DiscardedStatement)
  3078. return R;
  3079. if (VarDecl *VD =
  3080. const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
  3081. CurScope->addNRVOCandidate(VD);
  3082. } else {
  3083. CurScope->setNoNRVO();
  3084. }
  3085. CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
  3086. return R;
  3087. }
  3088. StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
  3089. // Check for unexpanded parameter packs.
  3090. if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
  3091. return StmtError();
  3092. if (isa<CapturingScopeInfo>(getCurFunction()))
  3093. return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
  3094. QualType FnRetType;
  3095. QualType RelatedRetType;
  3096. const AttrVec *Attrs = nullptr;
  3097. bool isObjCMethod = false;
  3098. if (const FunctionDecl *FD = getCurFunctionDecl()) {
  3099. FnRetType = FD->getReturnType();
  3100. if (FD->hasAttrs())
  3101. Attrs = &FD->getAttrs();
  3102. if (FD->isNoReturn())
  3103. Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
  3104. << FD->getDeclName();
  3105. if (FD->isMain() && RetValExp)
  3106. if (isa<CXXBoolLiteralExpr>(RetValExp))
  3107. Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
  3108. << RetValExp->getSourceRange();
  3109. } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
  3110. FnRetType = MD->getReturnType();
  3111. isObjCMethod = true;
  3112. if (MD->hasAttrs())
  3113. Attrs = &MD->getAttrs();
  3114. if (MD->hasRelatedResultType() && MD->getClassInterface()) {
  3115. // In the implementation of a method with a related return type, the
  3116. // type used to type-check the validity of return statements within the
  3117. // method body is a pointer to the type of the class being implemented.
  3118. RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
  3119. RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
  3120. }
  3121. } else // If we don't have a function/method context, bail.
  3122. return StmtError();
  3123. // C++1z: discarded return statements are not considered when deducing a
  3124. // return type.
  3125. if (ExprEvalContexts.back().Context ==
  3126. ExpressionEvaluationContext::DiscardedStatement &&
  3127. FnRetType->getContainedAutoType()) {
  3128. if (RetValExp) {
  3129. ExprResult ER =
  3130. ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
  3131. if (ER.isInvalid())
  3132. return StmtError();
  3133. RetValExp = ER.get();
  3134. }
  3135. return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
  3136. /* NRVOCandidate=*/nullptr);
  3137. }
  3138. // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
  3139. // deduction.
  3140. if (getLangOpts().CPlusPlus14) {
  3141. if (AutoType *AT = FnRetType->getContainedAutoType()) {
  3142. FunctionDecl *FD = cast<FunctionDecl>(CurContext);
  3143. if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
  3144. FD->setInvalidDecl();
  3145. return StmtError();
  3146. } else {
  3147. FnRetType = FD->getReturnType();
  3148. }
  3149. }
  3150. }
  3151. bool HasDependentReturnType = FnRetType->isDependentType();
  3152. ReturnStmt *Result = nullptr;
  3153. if (FnRetType->isVoidType()) {
  3154. if (RetValExp) {
  3155. if (isa<InitListExpr>(RetValExp)) {
  3156. // We simply never allow init lists as the return value of void
  3157. // functions. This is compatible because this was never allowed before,
  3158. // so there's no legacy code to deal with.
  3159. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  3160. int FunctionKind = 0;
  3161. if (isa<ObjCMethodDecl>(CurDecl))
  3162. FunctionKind = 1;
  3163. else if (isa<CXXConstructorDecl>(CurDecl))
  3164. FunctionKind = 2;
  3165. else if (isa<CXXDestructorDecl>(CurDecl))
  3166. FunctionKind = 3;
  3167. Diag(ReturnLoc, diag::err_return_init_list)
  3168. << CurDecl->getDeclName() << FunctionKind
  3169. << RetValExp->getSourceRange();
  3170. // Drop the expression.
  3171. RetValExp = nullptr;
  3172. } else if (!RetValExp->isTypeDependent()) {
  3173. // C99 6.8.6.4p1 (ext_ since GCC warns)
  3174. unsigned D = diag::ext_return_has_expr;
  3175. if (RetValExp->getType()->isVoidType()) {
  3176. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  3177. if (isa<CXXConstructorDecl>(CurDecl) ||
  3178. isa<CXXDestructorDecl>(CurDecl))
  3179. D = diag::err_ctor_dtor_returns_void;
  3180. else
  3181. D = diag::ext_return_has_void_expr;
  3182. }
  3183. else {
  3184. ExprResult Result = RetValExp;
  3185. Result = IgnoredValueConversions(Result.get());
  3186. if (Result.isInvalid())
  3187. return StmtError();
  3188. RetValExp = Result.get();
  3189. RetValExp = ImpCastExprToType(RetValExp,
  3190. Context.VoidTy, CK_ToVoid).get();
  3191. }
  3192. // return of void in constructor/destructor is illegal in C++.
  3193. if (D == diag::err_ctor_dtor_returns_void) {
  3194. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  3195. Diag(ReturnLoc, D)
  3196. << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
  3197. << RetValExp->getSourceRange();
  3198. }
  3199. // return (some void expression); is legal in C++.
  3200. else if (D != diag::ext_return_has_void_expr ||
  3201. !getLangOpts().CPlusPlus) {
  3202. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  3203. int FunctionKind = 0;
  3204. if (isa<ObjCMethodDecl>(CurDecl))
  3205. FunctionKind = 1;
  3206. else if (isa<CXXConstructorDecl>(CurDecl))
  3207. FunctionKind = 2;
  3208. else if (isa<CXXDestructorDecl>(CurDecl))
  3209. FunctionKind = 3;
  3210. Diag(ReturnLoc, D)
  3211. << CurDecl->getDeclName() << FunctionKind
  3212. << RetValExp->getSourceRange();
  3213. }
  3214. }
  3215. if (RetValExp) {
  3216. ExprResult ER =
  3217. ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
  3218. if (ER.isInvalid())
  3219. return StmtError();
  3220. RetValExp = ER.get();
  3221. }
  3222. }
  3223. Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
  3224. /* NRVOCandidate=*/nullptr);
  3225. } else if (!RetValExp && !HasDependentReturnType) {
  3226. FunctionDecl *FD = getCurFunctionDecl();
  3227. unsigned DiagID;
  3228. if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
  3229. // C++11 [stmt.return]p2
  3230. DiagID = diag::err_constexpr_return_missing_expr;
  3231. FD->setInvalidDecl();
  3232. } else if (getLangOpts().C99) {
  3233. // C99 6.8.6.4p1 (ext_ since GCC warns)
  3234. DiagID = diag::ext_return_missing_expr;
  3235. } else {
  3236. // C90 6.6.6.4p4
  3237. DiagID = diag::warn_return_missing_expr;
  3238. }
  3239. if (FD)
  3240. Diag(ReturnLoc, DiagID)
  3241. << FD->getIdentifier() << 0 /*fn*/ << FD->isConsteval();
  3242. else
  3243. Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
  3244. Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
  3245. /* NRVOCandidate=*/nullptr);
  3246. } else {
  3247. assert(RetValExp || HasDependentReturnType);
  3248. const VarDecl *NRVOCandidate = nullptr;
  3249. QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
  3250. // C99 6.8.6.4p3(136): The return statement is not an assignment. The
  3251. // overlap restriction of subclause 6.5.16.1 does not apply to the case of
  3252. // function return.
  3253. // In C++ the return statement is handled via a copy initialization,
  3254. // the C version of which boils down to CheckSingleAssignmentConstraints.
  3255. if (RetValExp)
  3256. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
  3257. if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
  3258. // we have a non-void function with an expression, continue checking
  3259. InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
  3260. RetType,
  3261. NRVOCandidate != nullptr);
  3262. ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
  3263. RetType, RetValExp);
  3264. if (Res.isInvalid()) {
  3265. // FIXME: Clean up temporaries here anyway?
  3266. return StmtError();
  3267. }
  3268. RetValExp = Res.getAs<Expr>();
  3269. // If we have a related result type, we need to implicitly
  3270. // convert back to the formal result type. We can't pretend to
  3271. // initialize the result again --- we might end double-retaining
  3272. // --- so instead we initialize a notional temporary.
  3273. if (!RelatedRetType.isNull()) {
  3274. Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
  3275. FnRetType);
  3276. Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
  3277. if (Res.isInvalid()) {
  3278. // FIXME: Clean up temporaries here anyway?
  3279. return StmtError();
  3280. }
  3281. RetValExp = Res.getAs<Expr>();
  3282. }
  3283. CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
  3284. getCurFunctionDecl());
  3285. }
  3286. if (RetValExp) {
  3287. ExprResult ER =
  3288. ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
  3289. if (ER.isInvalid())
  3290. return StmtError();
  3291. RetValExp = ER.get();
  3292. }
  3293. Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
  3294. }
  3295. // If we need to check for the named return value optimization, save the
  3296. // return statement in our scope for later processing.
  3297. if (Result->getNRVOCandidate())
  3298. FunctionScopes.back()->Returns.push_back(Result);
  3299. if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
  3300. FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
  3301. return Result;
  3302. }
  3303. StmtResult
  3304. Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
  3305. SourceLocation RParen, Decl *Parm,
  3306. Stmt *Body) {
  3307. VarDecl *Var = cast_or_null<VarDecl>(Parm);
  3308. if (Var && Var->isInvalidDecl())
  3309. return StmtError();
  3310. return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
  3311. }
  3312. StmtResult
  3313. Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
  3314. return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
  3315. }
  3316. StmtResult
  3317. Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
  3318. MultiStmtArg CatchStmts, Stmt *Finally) {
  3319. if (!getLangOpts().ObjCExceptions)
  3320. Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
  3321. setFunctionHasBranchProtectedScope();
  3322. unsigned NumCatchStmts = CatchStmts.size();
  3323. return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
  3324. NumCatchStmts, Finally);
  3325. }
  3326. StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
  3327. if (Throw) {
  3328. ExprResult Result = DefaultLvalueConversion(Throw);
  3329. if (Result.isInvalid())
  3330. return StmtError();
  3331. Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
  3332. if (Result.isInvalid())
  3333. return StmtError();
  3334. Throw = Result.get();
  3335. QualType ThrowType = Throw->getType();
  3336. // Make sure the expression type is an ObjC pointer or "void *".
  3337. if (!ThrowType->isDependentType() &&
  3338. !ThrowType->isObjCObjectPointerType()) {
  3339. const PointerType *PT = ThrowType->getAs<PointerType>();
  3340. if (!PT || !PT->getPointeeType()->isVoidType())
  3341. return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
  3342. << Throw->getType() << Throw->getSourceRange());
  3343. }
  3344. }
  3345. return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
  3346. }
  3347. StmtResult
  3348. Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
  3349. Scope *CurScope) {
  3350. if (!getLangOpts().ObjCExceptions)
  3351. Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
  3352. if (!Throw) {
  3353. // @throw without an expression designates a rethrow (which must occur
  3354. // in the context of an @catch clause).
  3355. Scope *AtCatchParent = CurScope;
  3356. while (AtCatchParent && !AtCatchParent->isAtCatchScope())
  3357. AtCatchParent = AtCatchParent->getParent();
  3358. if (!AtCatchParent)
  3359. return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
  3360. }
  3361. return BuildObjCAtThrowStmt(AtLoc, Throw);
  3362. }
  3363. ExprResult
  3364. Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
  3365. ExprResult result = DefaultLvalueConversion(operand);
  3366. if (result.isInvalid())
  3367. return ExprError();
  3368. operand = result.get();
  3369. // Make sure the expression type is an ObjC pointer or "void *".
  3370. QualType type = operand->getType();
  3371. if (!type->isDependentType() &&
  3372. !type->isObjCObjectPointerType()) {
  3373. const PointerType *pointerType = type->getAs<PointerType>();
  3374. if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
  3375. if (getLangOpts().CPlusPlus) {
  3376. if (RequireCompleteType(atLoc, type,
  3377. diag::err_incomplete_receiver_type))
  3378. return Diag(atLoc, diag::err_objc_synchronized_expects_object)
  3379. << type << operand->getSourceRange();
  3380. ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
  3381. if (result.isInvalid())
  3382. return ExprError();
  3383. if (!result.isUsable())
  3384. return Diag(atLoc, diag::err_objc_synchronized_expects_object)
  3385. << type << operand->getSourceRange();
  3386. operand = result.get();
  3387. } else {
  3388. return Diag(atLoc, diag::err_objc_synchronized_expects_object)
  3389. << type << operand->getSourceRange();
  3390. }
  3391. }
  3392. }
  3393. // The operand to @synchronized is a full-expression.
  3394. return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
  3395. }
  3396. StmtResult
  3397. Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
  3398. Stmt *SyncBody) {
  3399. // We can't jump into or indirect-jump out of a @synchronized block.
  3400. setFunctionHasBranchProtectedScope();
  3401. return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
  3402. }
  3403. /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
  3404. /// and creates a proper catch handler from them.
  3405. StmtResult
  3406. Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
  3407. Stmt *HandlerBlock) {
  3408. // There's nothing to test that ActOnExceptionDecl didn't already test.
  3409. return new (Context)
  3410. CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
  3411. }
  3412. StmtResult
  3413. Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
  3414. setFunctionHasBranchProtectedScope();
  3415. return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
  3416. }
  3417. namespace {
  3418. class CatchHandlerType {
  3419. QualType QT;
  3420. unsigned IsPointer : 1;
  3421. // This is a special constructor to be used only with DenseMapInfo's
  3422. // getEmptyKey() and getTombstoneKey() functions.
  3423. friend struct llvm::DenseMapInfo<CatchHandlerType>;
  3424. enum Unique { ForDenseMap };
  3425. CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
  3426. public:
  3427. /// Used when creating a CatchHandlerType from a handler type; will determine
  3428. /// whether the type is a pointer or reference and will strip off the top
  3429. /// level pointer and cv-qualifiers.
  3430. CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
  3431. if (QT->isPointerType())
  3432. IsPointer = true;
  3433. if (IsPointer || QT->isReferenceType())
  3434. QT = QT->getPointeeType();
  3435. QT = QT.getUnqualifiedType();
  3436. }
  3437. /// Used when creating a CatchHandlerType from a base class type; pretends the
  3438. /// type passed in had the pointer qualifier, does not need to get an
  3439. /// unqualified type.
  3440. CatchHandlerType(QualType QT, bool IsPointer)
  3441. : QT(QT), IsPointer(IsPointer) {}
  3442. QualType underlying() const { return QT; }
  3443. bool isPointer() const { return IsPointer; }
  3444. friend bool operator==(const CatchHandlerType &LHS,
  3445. const CatchHandlerType &RHS) {
  3446. // If the pointer qualification does not match, we can return early.
  3447. if (LHS.IsPointer != RHS.IsPointer)
  3448. return false;
  3449. // Otherwise, check the underlying type without cv-qualifiers.
  3450. return LHS.QT == RHS.QT;
  3451. }
  3452. };
  3453. } // namespace
  3454. namespace llvm {
  3455. template <> struct DenseMapInfo<CatchHandlerType> {
  3456. static CatchHandlerType getEmptyKey() {
  3457. return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
  3458. CatchHandlerType::ForDenseMap);
  3459. }
  3460. static CatchHandlerType getTombstoneKey() {
  3461. return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
  3462. CatchHandlerType::ForDenseMap);
  3463. }
  3464. static unsigned getHashValue(const CatchHandlerType &Base) {
  3465. return DenseMapInfo<QualType>::getHashValue(Base.underlying());
  3466. }
  3467. static bool isEqual(const CatchHandlerType &LHS,
  3468. const CatchHandlerType &RHS) {
  3469. return LHS == RHS;
  3470. }
  3471. };
  3472. }
  3473. namespace {
  3474. class CatchTypePublicBases {
  3475. ASTContext &Ctx;
  3476. const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
  3477. const bool CheckAgainstPointer;
  3478. CXXCatchStmt *FoundHandler;
  3479. CanQualType FoundHandlerType;
  3480. public:
  3481. CatchTypePublicBases(
  3482. ASTContext &Ctx,
  3483. const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
  3484. : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
  3485. FoundHandler(nullptr) {}
  3486. CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
  3487. CanQualType getFoundHandlerType() const { return FoundHandlerType; }
  3488. bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
  3489. if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
  3490. CatchHandlerType Check(S->getType(), CheckAgainstPointer);
  3491. const auto &M = TypesToCheck;
  3492. auto I = M.find(Check);
  3493. if (I != M.end()) {
  3494. FoundHandler = I->second;
  3495. FoundHandlerType = Ctx.getCanonicalType(S->getType());
  3496. return true;
  3497. }
  3498. }
  3499. return false;
  3500. }
  3501. };
  3502. }
  3503. /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
  3504. /// handlers and creates a try statement from them.
  3505. StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
  3506. ArrayRef<Stmt *> Handlers) {
  3507. // Don't report an error if 'try' is used in system headers.
  3508. if (!getLangOpts().CXXExceptions &&
  3509. !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
  3510. // Delay error emission for the OpenMP device code.
  3511. targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
  3512. }
  3513. // Exceptions aren't allowed in CUDA device code.
  3514. if (getLangOpts().CUDA)
  3515. CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
  3516. << "try" << CurrentCUDATarget();
  3517. if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
  3518. Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
  3519. sema::FunctionScopeInfo *FSI = getCurFunction();
  3520. // C++ try is incompatible with SEH __try.
  3521. if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
  3522. Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
  3523. Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
  3524. }
  3525. const unsigned NumHandlers = Handlers.size();
  3526. assert(!Handlers.empty() &&
  3527. "The parser shouldn't call this if there are no handlers.");
  3528. llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
  3529. for (unsigned i = 0; i < NumHandlers; ++i) {
  3530. CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
  3531. // Diagnose when the handler is a catch-all handler, but it isn't the last
  3532. // handler for the try block. [except.handle]p5. Also, skip exception
  3533. // declarations that are invalid, since we can't usefully report on them.
  3534. if (!H->getExceptionDecl()) {
  3535. if (i < NumHandlers - 1)
  3536. return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
  3537. continue;
  3538. } else if (H->getExceptionDecl()->isInvalidDecl())
  3539. continue;
  3540. // Walk the type hierarchy to diagnose when this type has already been
  3541. // handled (duplication), or cannot be handled (derivation inversion). We
  3542. // ignore top-level cv-qualifiers, per [except.handle]p3
  3543. CatchHandlerType HandlerCHT =
  3544. (QualType)Context.getCanonicalType(H->getCaughtType());
  3545. // We can ignore whether the type is a reference or a pointer; we need the
  3546. // underlying declaration type in order to get at the underlying record
  3547. // decl, if there is one.
  3548. QualType Underlying = HandlerCHT.underlying();
  3549. if (auto *RD = Underlying->getAsCXXRecordDecl()) {
  3550. if (!RD->hasDefinition())
  3551. continue;
  3552. // Check that none of the public, unambiguous base classes are in the
  3553. // map ([except.handle]p1). Give the base classes the same pointer
  3554. // qualification as the original type we are basing off of. This allows
  3555. // comparison against the handler type using the same top-level pointer
  3556. // as the original type.
  3557. CXXBasePaths Paths;
  3558. Paths.setOrigin(RD);
  3559. CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
  3560. if (RD->lookupInBases(CTPB, Paths)) {
  3561. const CXXCatchStmt *Problem = CTPB.getFoundHandler();
  3562. if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
  3563. Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
  3564. diag::warn_exception_caught_by_earlier_handler)
  3565. << H->getCaughtType();
  3566. Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
  3567. diag::note_previous_exception_handler)
  3568. << Problem->getCaughtType();
  3569. }
  3570. }
  3571. }
  3572. // Add the type the list of ones we have handled; diagnose if we've already
  3573. // handled it.
  3574. auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
  3575. if (!R.second) {
  3576. const CXXCatchStmt *Problem = R.first->second;
  3577. Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
  3578. diag::warn_exception_caught_by_earlier_handler)
  3579. << H->getCaughtType();
  3580. Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
  3581. diag::note_previous_exception_handler)
  3582. << Problem->getCaughtType();
  3583. }
  3584. }
  3585. FSI->setHasCXXTry(TryLoc);
  3586. return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
  3587. }
  3588. StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
  3589. Stmt *TryBlock, Stmt *Handler) {
  3590. assert(TryBlock && Handler);
  3591. sema::FunctionScopeInfo *FSI = getCurFunction();
  3592. // SEH __try is incompatible with C++ try. Borland appears to support this,
  3593. // however.
  3594. if (!getLangOpts().Borland) {
  3595. if (FSI->FirstCXXTryLoc.isValid()) {
  3596. Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
  3597. Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
  3598. }
  3599. }
  3600. FSI->setHasSEHTry(TryLoc);
  3601. // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
  3602. // track if they use SEH.
  3603. DeclContext *DC = CurContext;
  3604. while (DC && !DC->isFunctionOrMethod())
  3605. DC = DC->getParent();
  3606. FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
  3607. if (FD)
  3608. FD->setUsesSEHTry(true);
  3609. else
  3610. Diag(TryLoc, diag::err_seh_try_outside_functions);
  3611. // Reject __try on unsupported targets.
  3612. if (!Context.getTargetInfo().isSEHTrySupported())
  3613. Diag(TryLoc, diag::err_seh_try_unsupported);
  3614. return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
  3615. }
  3616. StmtResult
  3617. Sema::ActOnSEHExceptBlock(SourceLocation Loc,
  3618. Expr *FilterExpr,
  3619. Stmt *Block) {
  3620. assert(FilterExpr && Block);
  3621. if(!FilterExpr->getType()->isIntegerType()) {
  3622. return StmtError(Diag(FilterExpr->getExprLoc(),
  3623. diag::err_filter_expression_integral)
  3624. << FilterExpr->getType());
  3625. }
  3626. return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
  3627. }
  3628. void Sema::ActOnStartSEHFinallyBlock() {
  3629. CurrentSEHFinally.push_back(CurScope);
  3630. }
  3631. void Sema::ActOnAbortSEHFinallyBlock() {
  3632. CurrentSEHFinally.pop_back();
  3633. }
  3634. StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
  3635. assert(Block);
  3636. CurrentSEHFinally.pop_back();
  3637. return SEHFinallyStmt::Create(Context, Loc, Block);
  3638. }
  3639. StmtResult
  3640. Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
  3641. Scope *SEHTryParent = CurScope;
  3642. while (SEHTryParent && !SEHTryParent->isSEHTryScope())
  3643. SEHTryParent = SEHTryParent->getParent();
  3644. if (!SEHTryParent)
  3645. return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
  3646. CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
  3647. return new (Context) SEHLeaveStmt(Loc);
  3648. }
  3649. StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
  3650. bool IsIfExists,
  3651. NestedNameSpecifierLoc QualifierLoc,
  3652. DeclarationNameInfo NameInfo,
  3653. Stmt *Nested)
  3654. {
  3655. return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
  3656. QualifierLoc, NameInfo,
  3657. cast<CompoundStmt>(Nested));
  3658. }
  3659. StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
  3660. bool IsIfExists,
  3661. CXXScopeSpec &SS,
  3662. UnqualifiedId &Name,
  3663. Stmt *Nested) {
  3664. return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
  3665. SS.getWithLocInContext(Context),
  3666. GetNameFromUnqualifiedId(Name),
  3667. Nested);
  3668. }
  3669. RecordDecl*
  3670. Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
  3671. unsigned NumParams) {
  3672. DeclContext *DC = CurContext;
  3673. while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
  3674. DC = DC->getParent();
  3675. RecordDecl *RD = nullptr;
  3676. if (getLangOpts().CPlusPlus)
  3677. RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
  3678. /*Id=*/nullptr);
  3679. else
  3680. RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
  3681. RD->setCapturedRecord();
  3682. DC->addDecl(RD);
  3683. RD->setImplicit();
  3684. RD->startDefinition();
  3685. assert(NumParams > 0 && "CapturedStmt requires context parameter");
  3686. CD = CapturedDecl::Create(Context, CurContext, NumParams);
  3687. DC->addDecl(CD);
  3688. return RD;
  3689. }
  3690. static bool
  3691. buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
  3692. SmallVectorImpl<CapturedStmt::Capture> &Captures,
  3693. SmallVectorImpl<Expr *> &CaptureInits) {
  3694. for (const sema::Capture &Cap : RSI->Captures) {
  3695. if (Cap.isInvalid())
  3696. continue;
  3697. // Form the initializer for the capture.
  3698. ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
  3699. RSI->CapRegionKind == CR_OpenMP);
  3700. // FIXME: Bail out now if the capture is not used and the initializer has
  3701. // no side-effects.
  3702. // Create a field for this capture.
  3703. FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
  3704. // Add the capture to our list of captures.
  3705. if (Cap.isThisCapture()) {
  3706. Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
  3707. CapturedStmt::VCK_This));
  3708. } else if (Cap.isVLATypeCapture()) {
  3709. Captures.push_back(
  3710. CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
  3711. } else {
  3712. assert(Cap.isVariableCapture() && "unknown kind of capture");
  3713. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
  3714. S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel);
  3715. Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
  3716. Cap.isReferenceCapture()
  3717. ? CapturedStmt::VCK_ByRef
  3718. : CapturedStmt::VCK_ByCopy,
  3719. Cap.getVariable()));
  3720. }
  3721. CaptureInits.push_back(Init.get());
  3722. }
  3723. return false;
  3724. }
  3725. void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
  3726. CapturedRegionKind Kind,
  3727. unsigned NumParams) {
  3728. CapturedDecl *CD = nullptr;
  3729. RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
  3730. // Build the context parameter
  3731. DeclContext *DC = CapturedDecl::castToDeclContext(CD);
  3732. IdentifierInfo *ParamName = &Context.Idents.get("__context");
  3733. QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
  3734. auto *Param =
  3735. ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
  3736. ImplicitParamDecl::CapturedContext);
  3737. DC->addDecl(Param);
  3738. CD->setContextParam(0, Param);
  3739. // Enter the capturing scope for this captured region.
  3740. PushCapturedRegionScope(CurScope, CD, RD, Kind);
  3741. if (CurScope)
  3742. PushDeclContext(CurScope, CD);
  3743. else
  3744. CurContext = CD;
  3745. PushExpressionEvaluationContext(
  3746. ExpressionEvaluationContext::PotentiallyEvaluated);
  3747. }
  3748. void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
  3749. CapturedRegionKind Kind,
  3750. ArrayRef<CapturedParamNameType> Params,
  3751. unsigned OpenMPCaptureLevel) {
  3752. CapturedDecl *CD = nullptr;
  3753. RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
  3754. // Build the context parameter
  3755. DeclContext *DC = CapturedDecl::castToDeclContext(CD);
  3756. bool ContextIsFound = false;
  3757. unsigned ParamNum = 0;
  3758. for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
  3759. E = Params.end();
  3760. I != E; ++I, ++ParamNum) {
  3761. if (I->second.isNull()) {
  3762. assert(!ContextIsFound &&
  3763. "null type has been found already for '__context' parameter");
  3764. IdentifierInfo *ParamName = &Context.Idents.get("__context");
  3765. QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
  3766. .withConst()
  3767. .withRestrict();
  3768. auto *Param =
  3769. ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
  3770. ImplicitParamDecl::CapturedContext);
  3771. DC->addDecl(Param);
  3772. CD->setContextParam(ParamNum, Param);
  3773. ContextIsFound = true;
  3774. } else {
  3775. IdentifierInfo *ParamName = &Context.Idents.get(I->first);
  3776. auto *Param =
  3777. ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
  3778. ImplicitParamDecl::CapturedContext);
  3779. DC->addDecl(Param);
  3780. CD->setParam(ParamNum, Param);
  3781. }
  3782. }
  3783. assert(ContextIsFound && "no null type for '__context' parameter");
  3784. if (!ContextIsFound) {
  3785. // Add __context implicitly if it is not specified.
  3786. IdentifierInfo *ParamName = &Context.Idents.get("__context");
  3787. QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
  3788. auto *Param =
  3789. ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
  3790. ImplicitParamDecl::CapturedContext);
  3791. DC->addDecl(Param);
  3792. CD->setContextParam(ParamNum, Param);
  3793. }
  3794. // Enter the capturing scope for this captured region.
  3795. PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel);
  3796. if (CurScope)
  3797. PushDeclContext(CurScope, CD);
  3798. else
  3799. CurContext = CD;
  3800. PushExpressionEvaluationContext(
  3801. ExpressionEvaluationContext::PotentiallyEvaluated);
  3802. }
  3803. void Sema::ActOnCapturedRegionError() {
  3804. DiscardCleanupsInEvaluationContext();
  3805. PopExpressionEvaluationContext();
  3806. PopDeclContext();
  3807. PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
  3808. CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
  3809. RecordDecl *Record = RSI->TheRecordDecl;
  3810. Record->setInvalidDecl();
  3811. SmallVector<Decl*, 4> Fields(Record->fields());
  3812. ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
  3813. SourceLocation(), SourceLocation(), ParsedAttributesView());
  3814. }
  3815. StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
  3816. // Leave the captured scope before we start creating captures in the
  3817. // enclosing scope.
  3818. DiscardCleanupsInEvaluationContext();
  3819. PopExpressionEvaluationContext();
  3820. PopDeclContext();
  3821. PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
  3822. CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
  3823. SmallVector<CapturedStmt::Capture, 4> Captures;
  3824. SmallVector<Expr *, 4> CaptureInits;
  3825. if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
  3826. return StmtError();
  3827. CapturedDecl *CD = RSI->TheCapturedDecl;
  3828. RecordDecl *RD = RSI->TheRecordDecl;
  3829. CapturedStmt *Res = CapturedStmt::Create(
  3830. getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
  3831. Captures, CaptureInits, CD, RD);
  3832. CD->setBody(Res->getCapturedStmt());
  3833. RD->completeDefinition();
  3834. return Res;
  3835. }