SemaChecking.cpp 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649
  1. //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements extra semantic analysis beyond what is enforced
  11. // by the C type system.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Sema/Initialization.h"
  15. #include "clang/Sema/Sema.h"
  16. #include "clang/Sema/SemaInternal.h"
  17. #include "clang/Sema/Initialization.h"
  18. #include "clang/Sema/ScopeInfo.h"
  19. #include "clang/Analysis/Analyses/FormatString.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/CharUnits.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/DeclObjC.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExprObjC.h"
  26. #include "clang/AST/EvaluatedExprVisitor.h"
  27. #include "clang/AST/DeclObjC.h"
  28. #include "clang/AST/StmtCXX.h"
  29. #include "clang/AST/StmtObjC.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "llvm/ADT/BitVector.h"
  32. #include "llvm/ADT/STLExtras.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include "clang/Basic/TargetBuiltins.h"
  35. #include "clang/Basic/TargetInfo.h"
  36. #include "clang/Basic/ConvertUTF.h"
  37. #include <limits>
  38. using namespace clang;
  39. using namespace sema;
  40. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  41. unsigned ByteNo) const {
  42. return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
  43. PP.getLangOptions(), PP.getTargetInfo());
  44. }
  45. /// CheckablePrintfAttr - does a function call have a "printf" attribute
  46. /// and arguments that merit checking?
  47. bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
  48. if (Format->getType() == "printf") return true;
  49. if (Format->getType() == "printf0") {
  50. // printf0 allows null "format" string; if so don't check format/args
  51. unsigned format_idx = Format->getFormatIdx() - 1;
  52. // Does the index refer to the implicit object argument?
  53. if (isa<CXXMemberCallExpr>(TheCall)) {
  54. if (format_idx == 0)
  55. return false;
  56. --format_idx;
  57. }
  58. if (format_idx < TheCall->getNumArgs()) {
  59. Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
  60. if (!Format->isNullPointerConstant(Context,
  61. Expr::NPC_ValueDependentIsNull))
  62. return true;
  63. }
  64. }
  65. return false;
  66. }
  67. /// Checks that a call expression's argument count is the desired number.
  68. /// This is useful when doing custom type-checking. Returns true on error.
  69. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  70. unsigned argCount = call->getNumArgs();
  71. if (argCount == desiredArgCount) return false;
  72. if (argCount < desiredArgCount)
  73. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  74. << 0 /*function call*/ << desiredArgCount << argCount
  75. << call->getSourceRange();
  76. // Highlight all the excess arguments.
  77. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  78. call->getArg(argCount - 1)->getLocEnd());
  79. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  80. << 0 /*function call*/ << desiredArgCount << argCount
  81. << call->getArg(1)->getSourceRange();
  82. }
  83. /// CheckBuiltinAnnotationString - Checks that string argument to the builtin
  84. /// annotation is a non wide string literal.
  85. static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
  86. Arg = Arg->IgnoreParenCasts();
  87. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  88. if (!Literal || !Literal->isAscii()) {
  89. S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
  90. << Arg->getSourceRange();
  91. return true;
  92. }
  93. return false;
  94. }
  95. ExprResult
  96. Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  97. ExprResult TheCallResult(Owned(TheCall));
  98. // Find out if any arguments are required to be integer constant expressions.
  99. unsigned ICEArguments = 0;
  100. ASTContext::GetBuiltinTypeError Error;
  101. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  102. if (Error != ASTContext::GE_None)
  103. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  104. // If any arguments are required to be ICE's, check and diagnose.
  105. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  106. // Skip arguments not required to be ICE's.
  107. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  108. llvm::APSInt Result;
  109. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  110. return true;
  111. ICEArguments &= ~(1 << ArgNo);
  112. }
  113. switch (BuiltinID) {
  114. case Builtin::BI__builtin___CFStringMakeConstantString:
  115. assert(TheCall->getNumArgs() == 1 &&
  116. "Wrong # arguments to builtin CFStringMakeConstantString");
  117. if (CheckObjCString(TheCall->getArg(0)))
  118. return ExprError();
  119. break;
  120. case Builtin::BI__builtin_stdarg_start:
  121. case Builtin::BI__builtin_va_start:
  122. if (SemaBuiltinVAStart(TheCall))
  123. return ExprError();
  124. break;
  125. case Builtin::BI__builtin_isgreater:
  126. case Builtin::BI__builtin_isgreaterequal:
  127. case Builtin::BI__builtin_isless:
  128. case Builtin::BI__builtin_islessequal:
  129. case Builtin::BI__builtin_islessgreater:
  130. case Builtin::BI__builtin_isunordered:
  131. if (SemaBuiltinUnorderedCompare(TheCall))
  132. return ExprError();
  133. break;
  134. case Builtin::BI__builtin_fpclassify:
  135. if (SemaBuiltinFPClassification(TheCall, 6))
  136. return ExprError();
  137. break;
  138. case Builtin::BI__builtin_isfinite:
  139. case Builtin::BI__builtin_isinf:
  140. case Builtin::BI__builtin_isinf_sign:
  141. case Builtin::BI__builtin_isnan:
  142. case Builtin::BI__builtin_isnormal:
  143. if (SemaBuiltinFPClassification(TheCall, 1))
  144. return ExprError();
  145. break;
  146. case Builtin::BI__builtin_shufflevector:
  147. return SemaBuiltinShuffleVector(TheCall);
  148. // TheCall will be freed by the smart pointer here, but that's fine, since
  149. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  150. case Builtin::BI__builtin_prefetch:
  151. if (SemaBuiltinPrefetch(TheCall))
  152. return ExprError();
  153. break;
  154. case Builtin::BI__builtin_object_size:
  155. if (SemaBuiltinObjectSize(TheCall))
  156. return ExprError();
  157. break;
  158. case Builtin::BI__builtin_longjmp:
  159. if (SemaBuiltinLongjmp(TheCall))
  160. return ExprError();
  161. break;
  162. case Builtin::BI__builtin_classify_type:
  163. if (checkArgCount(*this, TheCall, 1)) return true;
  164. TheCall->setType(Context.IntTy);
  165. break;
  166. case Builtin::BI__builtin_constant_p:
  167. if (checkArgCount(*this, TheCall, 1)) return true;
  168. TheCall->setType(Context.IntTy);
  169. break;
  170. case Builtin::BI__sync_fetch_and_add:
  171. case Builtin::BI__sync_fetch_and_add_1:
  172. case Builtin::BI__sync_fetch_and_add_2:
  173. case Builtin::BI__sync_fetch_and_add_4:
  174. case Builtin::BI__sync_fetch_and_add_8:
  175. case Builtin::BI__sync_fetch_and_add_16:
  176. case Builtin::BI__sync_fetch_and_sub:
  177. case Builtin::BI__sync_fetch_and_sub_1:
  178. case Builtin::BI__sync_fetch_and_sub_2:
  179. case Builtin::BI__sync_fetch_and_sub_4:
  180. case Builtin::BI__sync_fetch_and_sub_8:
  181. case Builtin::BI__sync_fetch_and_sub_16:
  182. case Builtin::BI__sync_fetch_and_or:
  183. case Builtin::BI__sync_fetch_and_or_1:
  184. case Builtin::BI__sync_fetch_and_or_2:
  185. case Builtin::BI__sync_fetch_and_or_4:
  186. case Builtin::BI__sync_fetch_and_or_8:
  187. case Builtin::BI__sync_fetch_and_or_16:
  188. case Builtin::BI__sync_fetch_and_and:
  189. case Builtin::BI__sync_fetch_and_and_1:
  190. case Builtin::BI__sync_fetch_and_and_2:
  191. case Builtin::BI__sync_fetch_and_and_4:
  192. case Builtin::BI__sync_fetch_and_and_8:
  193. case Builtin::BI__sync_fetch_and_and_16:
  194. case Builtin::BI__sync_fetch_and_xor:
  195. case Builtin::BI__sync_fetch_and_xor_1:
  196. case Builtin::BI__sync_fetch_and_xor_2:
  197. case Builtin::BI__sync_fetch_and_xor_4:
  198. case Builtin::BI__sync_fetch_and_xor_8:
  199. case Builtin::BI__sync_fetch_and_xor_16:
  200. case Builtin::BI__sync_add_and_fetch:
  201. case Builtin::BI__sync_add_and_fetch_1:
  202. case Builtin::BI__sync_add_and_fetch_2:
  203. case Builtin::BI__sync_add_and_fetch_4:
  204. case Builtin::BI__sync_add_and_fetch_8:
  205. case Builtin::BI__sync_add_and_fetch_16:
  206. case Builtin::BI__sync_sub_and_fetch:
  207. case Builtin::BI__sync_sub_and_fetch_1:
  208. case Builtin::BI__sync_sub_and_fetch_2:
  209. case Builtin::BI__sync_sub_and_fetch_4:
  210. case Builtin::BI__sync_sub_and_fetch_8:
  211. case Builtin::BI__sync_sub_and_fetch_16:
  212. case Builtin::BI__sync_and_and_fetch:
  213. case Builtin::BI__sync_and_and_fetch_1:
  214. case Builtin::BI__sync_and_and_fetch_2:
  215. case Builtin::BI__sync_and_and_fetch_4:
  216. case Builtin::BI__sync_and_and_fetch_8:
  217. case Builtin::BI__sync_and_and_fetch_16:
  218. case Builtin::BI__sync_or_and_fetch:
  219. case Builtin::BI__sync_or_and_fetch_1:
  220. case Builtin::BI__sync_or_and_fetch_2:
  221. case Builtin::BI__sync_or_and_fetch_4:
  222. case Builtin::BI__sync_or_and_fetch_8:
  223. case Builtin::BI__sync_or_and_fetch_16:
  224. case Builtin::BI__sync_xor_and_fetch:
  225. case Builtin::BI__sync_xor_and_fetch_1:
  226. case Builtin::BI__sync_xor_and_fetch_2:
  227. case Builtin::BI__sync_xor_and_fetch_4:
  228. case Builtin::BI__sync_xor_and_fetch_8:
  229. case Builtin::BI__sync_xor_and_fetch_16:
  230. case Builtin::BI__sync_val_compare_and_swap:
  231. case Builtin::BI__sync_val_compare_and_swap_1:
  232. case Builtin::BI__sync_val_compare_and_swap_2:
  233. case Builtin::BI__sync_val_compare_and_swap_4:
  234. case Builtin::BI__sync_val_compare_and_swap_8:
  235. case Builtin::BI__sync_val_compare_and_swap_16:
  236. case Builtin::BI__sync_bool_compare_and_swap:
  237. case Builtin::BI__sync_bool_compare_and_swap_1:
  238. case Builtin::BI__sync_bool_compare_and_swap_2:
  239. case Builtin::BI__sync_bool_compare_and_swap_4:
  240. case Builtin::BI__sync_bool_compare_and_swap_8:
  241. case Builtin::BI__sync_bool_compare_and_swap_16:
  242. case Builtin::BI__sync_lock_test_and_set:
  243. case Builtin::BI__sync_lock_test_and_set_1:
  244. case Builtin::BI__sync_lock_test_and_set_2:
  245. case Builtin::BI__sync_lock_test_and_set_4:
  246. case Builtin::BI__sync_lock_test_and_set_8:
  247. case Builtin::BI__sync_lock_test_and_set_16:
  248. case Builtin::BI__sync_lock_release:
  249. case Builtin::BI__sync_lock_release_1:
  250. case Builtin::BI__sync_lock_release_2:
  251. case Builtin::BI__sync_lock_release_4:
  252. case Builtin::BI__sync_lock_release_8:
  253. case Builtin::BI__sync_lock_release_16:
  254. case Builtin::BI__sync_swap:
  255. case Builtin::BI__sync_swap_1:
  256. case Builtin::BI__sync_swap_2:
  257. case Builtin::BI__sync_swap_4:
  258. case Builtin::BI__sync_swap_8:
  259. case Builtin::BI__sync_swap_16:
  260. return SemaBuiltinAtomicOverloaded(move(TheCallResult));
  261. case Builtin::BI__atomic_load:
  262. return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
  263. case Builtin::BI__atomic_store:
  264. return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
  265. case Builtin::BI__atomic_exchange:
  266. return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
  267. case Builtin::BI__atomic_compare_exchange_strong:
  268. return SemaAtomicOpsOverloaded(move(TheCallResult),
  269. AtomicExpr::CmpXchgStrong);
  270. case Builtin::BI__atomic_compare_exchange_weak:
  271. return SemaAtomicOpsOverloaded(move(TheCallResult),
  272. AtomicExpr::CmpXchgWeak);
  273. case Builtin::BI__atomic_fetch_add:
  274. return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
  275. case Builtin::BI__atomic_fetch_sub:
  276. return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
  277. case Builtin::BI__atomic_fetch_and:
  278. return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
  279. case Builtin::BI__atomic_fetch_or:
  280. return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
  281. case Builtin::BI__atomic_fetch_xor:
  282. return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
  283. case Builtin::BI__builtin_annotation:
  284. if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
  285. return ExprError();
  286. break;
  287. }
  288. // Since the target specific builtins for each arch overlap, only check those
  289. // of the arch we are compiling for.
  290. if (BuiltinID >= Builtin::FirstTSBuiltin) {
  291. switch (Context.getTargetInfo().getTriple().getArch()) {
  292. case llvm::Triple::arm:
  293. case llvm::Triple::thumb:
  294. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  295. return ExprError();
  296. break;
  297. default:
  298. break;
  299. }
  300. }
  301. return move(TheCallResult);
  302. }
  303. // Get the valid immediate range for the specified NEON type code.
  304. static unsigned RFT(unsigned t, bool shift = false) {
  305. NeonTypeFlags Type(t);
  306. int IsQuad = Type.isQuad();
  307. switch (Type.getEltType()) {
  308. case NeonTypeFlags::Int8:
  309. case NeonTypeFlags::Poly8:
  310. return shift ? 7 : (8 << IsQuad) - 1;
  311. case NeonTypeFlags::Int16:
  312. case NeonTypeFlags::Poly16:
  313. return shift ? 15 : (4 << IsQuad) - 1;
  314. case NeonTypeFlags::Int32:
  315. return shift ? 31 : (2 << IsQuad) - 1;
  316. case NeonTypeFlags::Int64:
  317. return shift ? 63 : (1 << IsQuad) - 1;
  318. case NeonTypeFlags::Float16:
  319. assert(!shift && "cannot shift float types!");
  320. return (4 << IsQuad) - 1;
  321. case NeonTypeFlags::Float32:
  322. assert(!shift && "cannot shift float types!");
  323. return (2 << IsQuad) - 1;
  324. }
  325. return 0;
  326. }
  327. /// getNeonEltType - Return the QualType corresponding to the elements of
  328. /// the vector type specified by the NeonTypeFlags. This is used to check
  329. /// the pointer arguments for Neon load/store intrinsics.
  330. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
  331. switch (Flags.getEltType()) {
  332. case NeonTypeFlags::Int8:
  333. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  334. case NeonTypeFlags::Int16:
  335. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  336. case NeonTypeFlags::Int32:
  337. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  338. case NeonTypeFlags::Int64:
  339. return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
  340. case NeonTypeFlags::Poly8:
  341. return Context.SignedCharTy;
  342. case NeonTypeFlags::Poly16:
  343. return Context.ShortTy;
  344. case NeonTypeFlags::Float16:
  345. return Context.UnsignedShortTy;
  346. case NeonTypeFlags::Float32:
  347. return Context.FloatTy;
  348. }
  349. return QualType();
  350. }
  351. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  352. llvm::APSInt Result;
  353. unsigned mask = 0;
  354. unsigned TV = 0;
  355. int PtrArgNum = -1;
  356. bool HasConstPtr = false;
  357. switch (BuiltinID) {
  358. #define GET_NEON_OVERLOAD_CHECK
  359. #include "clang/Basic/arm_neon.inc"
  360. #undef GET_NEON_OVERLOAD_CHECK
  361. }
  362. // For NEON intrinsics which are overloaded on vector element type, validate
  363. // the immediate which specifies which variant to emit.
  364. unsigned ImmArg = TheCall->getNumArgs()-1;
  365. if (mask) {
  366. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  367. return true;
  368. TV = Result.getLimitedValue(64);
  369. if ((TV > 63) || (mask & (1 << TV)) == 0)
  370. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  371. << TheCall->getArg(ImmArg)->getSourceRange();
  372. }
  373. if (PtrArgNum >= 0) {
  374. // Check that pointer arguments have the specified type.
  375. Expr *Arg = TheCall->getArg(PtrArgNum);
  376. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  377. Arg = ICE->getSubExpr();
  378. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  379. QualType RHSTy = RHS.get()->getType();
  380. QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
  381. if (HasConstPtr)
  382. EltTy = EltTy.withConst();
  383. QualType LHSTy = Context.getPointerType(EltTy);
  384. AssignConvertType ConvTy;
  385. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  386. if (RHS.isInvalid())
  387. return true;
  388. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  389. RHS.get(), AA_Assigning))
  390. return true;
  391. }
  392. // For NEON intrinsics which take an immediate value as part of the
  393. // instruction, range check them here.
  394. unsigned i = 0, l = 0, u = 0;
  395. switch (BuiltinID) {
  396. default: return false;
  397. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  398. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  399. case ARM::BI__builtin_arm_vcvtr_f:
  400. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  401. #define GET_NEON_IMMEDIATE_CHECK
  402. #include "clang/Basic/arm_neon.inc"
  403. #undef GET_NEON_IMMEDIATE_CHECK
  404. };
  405. // Check that the immediate argument is actually a constant.
  406. if (SemaBuiltinConstantArg(TheCall, i, Result))
  407. return true;
  408. // Range check against the upper/lower values for this isntruction.
  409. unsigned Val = Result.getZExtValue();
  410. if (Val < l || Val > (u + l))
  411. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  412. << l << u+l << TheCall->getArg(i)->getSourceRange();
  413. // FIXME: VFP Intrinsics should error if VFP not present.
  414. return false;
  415. }
  416. /// CheckFunctionCall - Check a direct function call for various correctness
  417. /// and safety properties not strictly enforced by the C type system.
  418. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
  419. // Get the IdentifierInfo* for the called function.
  420. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  421. // None of the checks below are needed for functions that don't have
  422. // simple names (e.g., C++ conversion functions).
  423. if (!FnInfo)
  424. return false;
  425. // FIXME: This mechanism should be abstracted to be less fragile and
  426. // more efficient. For example, just map function ids to custom
  427. // handlers.
  428. // Printf and scanf checking.
  429. for (specific_attr_iterator<FormatAttr>
  430. i = FDecl->specific_attr_begin<FormatAttr>(),
  431. e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
  432. const FormatAttr *Format = *i;
  433. const bool b = Format->getType() == "scanf";
  434. if (b || CheckablePrintfAttr(Format, TheCall)) {
  435. bool HasVAListArg = Format->getFirstArg() == 0;
  436. CheckPrintfScanfArguments(TheCall, HasVAListArg,
  437. Format->getFormatIdx() - 1,
  438. HasVAListArg ? 0 : Format->getFirstArg() - 1,
  439. !b);
  440. }
  441. }
  442. for (specific_attr_iterator<NonNullAttr>
  443. i = FDecl->specific_attr_begin<NonNullAttr>(),
  444. e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
  445. CheckNonNullArguments(*i, TheCall->getArgs(),
  446. TheCall->getCallee()->getLocStart());
  447. }
  448. // Builtin handling
  449. int CMF = -1;
  450. switch (FDecl->getBuiltinID()) {
  451. case Builtin::BI__builtin_memset:
  452. case Builtin::BI__builtin___memset_chk:
  453. case Builtin::BImemset:
  454. CMF = CMF_Memset;
  455. break;
  456. case Builtin::BI__builtin_memcpy:
  457. case Builtin::BI__builtin___memcpy_chk:
  458. case Builtin::BImemcpy:
  459. CMF = CMF_Memcpy;
  460. break;
  461. case Builtin::BI__builtin_memmove:
  462. case Builtin::BI__builtin___memmove_chk:
  463. case Builtin::BImemmove:
  464. CMF = CMF_Memmove;
  465. break;
  466. case Builtin::BIstrlcpy:
  467. case Builtin::BIstrlcat:
  468. CheckStrlcpycatArguments(TheCall, FnInfo);
  469. break;
  470. case Builtin::BI__builtin_memcmp:
  471. CMF = CMF_Memcmp;
  472. break;
  473. case Builtin::BI__builtin_strncpy:
  474. case Builtin::BI__builtin___strncpy_chk:
  475. case Builtin::BIstrncpy:
  476. CMF = CMF_Strncpy;
  477. break;
  478. case Builtin::BI__builtin_strncmp:
  479. CMF = CMF_Strncmp;
  480. break;
  481. case Builtin::BI__builtin_strncasecmp:
  482. CMF = CMF_Strncasecmp;
  483. break;
  484. case Builtin::BI__builtin_strncat:
  485. case Builtin::BIstrncat:
  486. CMF = CMF_Strncat;
  487. break;
  488. case Builtin::BI__builtin_strndup:
  489. case Builtin::BIstrndup:
  490. CMF = CMF_Strndup;
  491. break;
  492. default:
  493. if (FDecl->getLinkage() == ExternalLinkage &&
  494. (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
  495. if (FnInfo->isStr("memset"))
  496. CMF = CMF_Memset;
  497. else if (FnInfo->isStr("memcpy"))
  498. CMF = CMF_Memcpy;
  499. else if (FnInfo->isStr("memmove"))
  500. CMF = CMF_Memmove;
  501. else if (FnInfo->isStr("memcmp"))
  502. CMF = CMF_Memcmp;
  503. else if (FnInfo->isStr("strncpy"))
  504. CMF = CMF_Strncpy;
  505. else if (FnInfo->isStr("strncmp"))
  506. CMF = CMF_Strncmp;
  507. else if (FnInfo->isStr("strncasecmp"))
  508. CMF = CMF_Strncasecmp;
  509. else if (FnInfo->isStr("strncat"))
  510. CMF = CMF_Strncat;
  511. else if (FnInfo->isStr("strndup"))
  512. CMF = CMF_Strndup;
  513. }
  514. break;
  515. }
  516. // Memset/memcpy/memmove handling
  517. if (CMF != -1)
  518. CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
  519. return false;
  520. }
  521. bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
  522. // Printf checking.
  523. const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
  524. if (!Format)
  525. return false;
  526. const VarDecl *V = dyn_cast<VarDecl>(NDecl);
  527. if (!V)
  528. return false;
  529. QualType Ty = V->getType();
  530. if (!Ty->isBlockPointerType())
  531. return false;
  532. const bool b = Format->getType() == "scanf";
  533. if (!b && !CheckablePrintfAttr(Format, TheCall))
  534. return false;
  535. bool HasVAListArg = Format->getFirstArg() == 0;
  536. CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
  537. HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
  538. return false;
  539. }
  540. ExprResult
  541. Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
  542. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  543. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  544. // All these operations take one of the following four forms:
  545. // T __atomic_load(_Atomic(T)*, int) (loads)
  546. // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
  547. // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
  548. // (cmpxchg)
  549. // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
  550. // where T is an appropriate type, and the int paremeterss are for orderings.
  551. unsigned NumVals = 1;
  552. unsigned NumOrders = 1;
  553. if (Op == AtomicExpr::Load) {
  554. NumVals = 0;
  555. } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
  556. NumVals = 2;
  557. NumOrders = 2;
  558. }
  559. if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
  560. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  561. << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
  562. << TheCall->getCallee()->getSourceRange();
  563. return ExprError();
  564. } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
  565. Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
  566. diag::err_typecheck_call_too_many_args)
  567. << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
  568. << TheCall->getCallee()->getSourceRange();
  569. return ExprError();
  570. }
  571. // Inspect the first argument of the atomic operation. This should always be
  572. // a pointer to an _Atomic type.
  573. Expr *Ptr = TheCall->getArg(0);
  574. Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
  575. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  576. if (!pointerType) {
  577. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  578. << Ptr->getType() << Ptr->getSourceRange();
  579. return ExprError();
  580. }
  581. QualType AtomTy = pointerType->getPointeeType();
  582. if (!AtomTy->isAtomicType()) {
  583. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  584. << Ptr->getType() << Ptr->getSourceRange();
  585. return ExprError();
  586. }
  587. QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
  588. if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
  589. !ValType->isIntegerType() && !ValType->isPointerType()) {
  590. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  591. << Ptr->getType() << Ptr->getSourceRange();
  592. return ExprError();
  593. }
  594. if (!ValType->isIntegerType() &&
  595. (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
  596. Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
  597. << Ptr->getType() << Ptr->getSourceRange();
  598. return ExprError();
  599. }
  600. switch (ValType.getObjCLifetime()) {
  601. case Qualifiers::OCL_None:
  602. case Qualifiers::OCL_ExplicitNone:
  603. // okay
  604. break;
  605. case Qualifiers::OCL_Weak:
  606. case Qualifiers::OCL_Strong:
  607. case Qualifiers::OCL_Autoreleasing:
  608. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  609. << ValType << Ptr->getSourceRange();
  610. return ExprError();
  611. }
  612. QualType ResultType = ValType;
  613. if (Op == AtomicExpr::Store)
  614. ResultType = Context.VoidTy;
  615. else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
  616. ResultType = Context.BoolTy;
  617. // The first argument --- the pointer --- has a fixed type; we
  618. // deduce the types of the rest of the arguments accordingly. Walk
  619. // the remaining arguments, converting them to the deduced value type.
  620. for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
  621. ExprResult Arg = TheCall->getArg(i);
  622. QualType Ty;
  623. if (i < NumVals+1) {
  624. // The second argument to a cmpxchg is a pointer to the data which will
  625. // be exchanged. The second argument to a pointer add/subtract is the
  626. // amount to add/subtract, which must be a ptrdiff_t. The third
  627. // argument to a cmpxchg and the second argument in all other cases
  628. // is the type of the value.
  629. if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
  630. Op == AtomicExpr::CmpXchgStrong))
  631. Ty = Context.getPointerType(ValType.getUnqualifiedType());
  632. else if (!ValType->isIntegerType() &&
  633. (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
  634. Ty = Context.getPointerDiffType();
  635. else
  636. Ty = ValType;
  637. } else {
  638. // The order(s) are always converted to int.
  639. Ty = Context.IntTy;
  640. }
  641. InitializedEntity Entity =
  642. InitializedEntity::InitializeParameter(Context, Ty, false);
  643. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  644. if (Arg.isInvalid())
  645. return true;
  646. TheCall->setArg(i, Arg.get());
  647. }
  648. SmallVector<Expr*, 5> SubExprs;
  649. SubExprs.push_back(Ptr);
  650. if (Op == AtomicExpr::Load) {
  651. SubExprs.push_back(TheCall->getArg(1)); // Order
  652. } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
  653. SubExprs.push_back(TheCall->getArg(2)); // Order
  654. SubExprs.push_back(TheCall->getArg(1)); // Val1
  655. } else {
  656. SubExprs.push_back(TheCall->getArg(3)); // Order
  657. SubExprs.push_back(TheCall->getArg(1)); // Val1
  658. SubExprs.push_back(TheCall->getArg(2)); // Val2
  659. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  660. }
  661. return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  662. SubExprs.data(), SubExprs.size(),
  663. ResultType, Op,
  664. TheCall->getRParenLoc()));
  665. }
  666. /// checkBuiltinArgument - Given a call to a builtin function, perform
  667. /// normal type-checking on the given argument, updating the call in
  668. /// place. This is useful when a builtin function requires custom
  669. /// type-checking for some of its arguments but not necessarily all of
  670. /// them.
  671. ///
  672. /// Returns true on error.
  673. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  674. FunctionDecl *Fn = E->getDirectCallee();
  675. assert(Fn && "builtin call without direct callee!");
  676. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  677. InitializedEntity Entity =
  678. InitializedEntity::InitializeParameter(S.Context, Param);
  679. ExprResult Arg = E->getArg(0);
  680. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  681. if (Arg.isInvalid())
  682. return true;
  683. E->setArg(ArgIndex, Arg.take());
  684. return false;
  685. }
  686. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  687. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  688. /// type of its first argument. The main ActOnCallExpr routines have already
  689. /// promoted the types of arguments because all of these calls are prototyped as
  690. /// void(...).
  691. ///
  692. /// This function goes through and does final semantic checking for these
  693. /// builtins,
  694. ExprResult
  695. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  696. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  697. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  698. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  699. // Ensure that we have at least one argument to do type inference from.
  700. if (TheCall->getNumArgs() < 1) {
  701. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  702. << 0 << 1 << TheCall->getNumArgs()
  703. << TheCall->getCallee()->getSourceRange();
  704. return ExprError();
  705. }
  706. // Inspect the first argument of the atomic builtin. This should always be
  707. // a pointer type, whose element is an integral scalar or pointer type.
  708. // Because it is a pointer type, we don't have to worry about any implicit
  709. // casts here.
  710. // FIXME: We don't allow floating point scalars as input.
  711. Expr *FirstArg = TheCall->getArg(0);
  712. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  713. if (!pointerType) {
  714. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  715. << FirstArg->getType() << FirstArg->getSourceRange();
  716. return ExprError();
  717. }
  718. QualType ValType = pointerType->getPointeeType();
  719. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  720. !ValType->isBlockPointerType()) {
  721. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  722. << FirstArg->getType() << FirstArg->getSourceRange();
  723. return ExprError();
  724. }
  725. switch (ValType.getObjCLifetime()) {
  726. case Qualifiers::OCL_None:
  727. case Qualifiers::OCL_ExplicitNone:
  728. // okay
  729. break;
  730. case Qualifiers::OCL_Weak:
  731. case Qualifiers::OCL_Strong:
  732. case Qualifiers::OCL_Autoreleasing:
  733. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  734. << ValType << FirstArg->getSourceRange();
  735. return ExprError();
  736. }
  737. // Strip any qualifiers off ValType.
  738. ValType = ValType.getUnqualifiedType();
  739. // The majority of builtins return a value, but a few have special return
  740. // types, so allow them to override appropriately below.
  741. QualType ResultType = ValType;
  742. // We need to figure out which concrete builtin this maps onto. For example,
  743. // __sync_fetch_and_add with a 2 byte object turns into
  744. // __sync_fetch_and_add_2.
  745. #define BUILTIN_ROW(x) \
  746. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  747. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  748. static const unsigned BuiltinIndices[][5] = {
  749. BUILTIN_ROW(__sync_fetch_and_add),
  750. BUILTIN_ROW(__sync_fetch_and_sub),
  751. BUILTIN_ROW(__sync_fetch_and_or),
  752. BUILTIN_ROW(__sync_fetch_and_and),
  753. BUILTIN_ROW(__sync_fetch_and_xor),
  754. BUILTIN_ROW(__sync_add_and_fetch),
  755. BUILTIN_ROW(__sync_sub_and_fetch),
  756. BUILTIN_ROW(__sync_and_and_fetch),
  757. BUILTIN_ROW(__sync_or_and_fetch),
  758. BUILTIN_ROW(__sync_xor_and_fetch),
  759. BUILTIN_ROW(__sync_val_compare_and_swap),
  760. BUILTIN_ROW(__sync_bool_compare_and_swap),
  761. BUILTIN_ROW(__sync_lock_test_and_set),
  762. BUILTIN_ROW(__sync_lock_release),
  763. BUILTIN_ROW(__sync_swap)
  764. };
  765. #undef BUILTIN_ROW
  766. // Determine the index of the size.
  767. unsigned SizeIndex;
  768. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  769. case 1: SizeIndex = 0; break;
  770. case 2: SizeIndex = 1; break;
  771. case 4: SizeIndex = 2; break;
  772. case 8: SizeIndex = 3; break;
  773. case 16: SizeIndex = 4; break;
  774. default:
  775. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  776. << FirstArg->getType() << FirstArg->getSourceRange();
  777. return ExprError();
  778. }
  779. // Each of these builtins has one pointer argument, followed by some number of
  780. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  781. // that we ignore. Find out which row of BuiltinIndices to read from as well
  782. // as the number of fixed args.
  783. unsigned BuiltinID = FDecl->getBuiltinID();
  784. unsigned BuiltinIndex, NumFixed = 1;
  785. switch (BuiltinID) {
  786. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  787. case Builtin::BI__sync_fetch_and_add:
  788. case Builtin::BI__sync_fetch_and_add_1:
  789. case Builtin::BI__sync_fetch_and_add_2:
  790. case Builtin::BI__sync_fetch_and_add_4:
  791. case Builtin::BI__sync_fetch_and_add_8:
  792. case Builtin::BI__sync_fetch_and_add_16:
  793. BuiltinIndex = 0;
  794. break;
  795. case Builtin::BI__sync_fetch_and_sub:
  796. case Builtin::BI__sync_fetch_and_sub_1:
  797. case Builtin::BI__sync_fetch_and_sub_2:
  798. case Builtin::BI__sync_fetch_and_sub_4:
  799. case Builtin::BI__sync_fetch_and_sub_8:
  800. case Builtin::BI__sync_fetch_and_sub_16:
  801. BuiltinIndex = 1;
  802. break;
  803. case Builtin::BI__sync_fetch_and_or:
  804. case Builtin::BI__sync_fetch_and_or_1:
  805. case Builtin::BI__sync_fetch_and_or_2:
  806. case Builtin::BI__sync_fetch_and_or_4:
  807. case Builtin::BI__sync_fetch_and_or_8:
  808. case Builtin::BI__sync_fetch_and_or_16:
  809. BuiltinIndex = 2;
  810. break;
  811. case Builtin::BI__sync_fetch_and_and:
  812. case Builtin::BI__sync_fetch_and_and_1:
  813. case Builtin::BI__sync_fetch_and_and_2:
  814. case Builtin::BI__sync_fetch_and_and_4:
  815. case Builtin::BI__sync_fetch_and_and_8:
  816. case Builtin::BI__sync_fetch_and_and_16:
  817. BuiltinIndex = 3;
  818. break;
  819. case Builtin::BI__sync_fetch_and_xor:
  820. case Builtin::BI__sync_fetch_and_xor_1:
  821. case Builtin::BI__sync_fetch_and_xor_2:
  822. case Builtin::BI__sync_fetch_and_xor_4:
  823. case Builtin::BI__sync_fetch_and_xor_8:
  824. case Builtin::BI__sync_fetch_and_xor_16:
  825. BuiltinIndex = 4;
  826. break;
  827. case Builtin::BI__sync_add_and_fetch:
  828. case Builtin::BI__sync_add_and_fetch_1:
  829. case Builtin::BI__sync_add_and_fetch_2:
  830. case Builtin::BI__sync_add_and_fetch_4:
  831. case Builtin::BI__sync_add_and_fetch_8:
  832. case Builtin::BI__sync_add_and_fetch_16:
  833. BuiltinIndex = 5;
  834. break;
  835. case Builtin::BI__sync_sub_and_fetch:
  836. case Builtin::BI__sync_sub_and_fetch_1:
  837. case Builtin::BI__sync_sub_and_fetch_2:
  838. case Builtin::BI__sync_sub_and_fetch_4:
  839. case Builtin::BI__sync_sub_and_fetch_8:
  840. case Builtin::BI__sync_sub_and_fetch_16:
  841. BuiltinIndex = 6;
  842. break;
  843. case Builtin::BI__sync_and_and_fetch:
  844. case Builtin::BI__sync_and_and_fetch_1:
  845. case Builtin::BI__sync_and_and_fetch_2:
  846. case Builtin::BI__sync_and_and_fetch_4:
  847. case Builtin::BI__sync_and_and_fetch_8:
  848. case Builtin::BI__sync_and_and_fetch_16:
  849. BuiltinIndex = 7;
  850. break;
  851. case Builtin::BI__sync_or_and_fetch:
  852. case Builtin::BI__sync_or_and_fetch_1:
  853. case Builtin::BI__sync_or_and_fetch_2:
  854. case Builtin::BI__sync_or_and_fetch_4:
  855. case Builtin::BI__sync_or_and_fetch_8:
  856. case Builtin::BI__sync_or_and_fetch_16:
  857. BuiltinIndex = 8;
  858. break;
  859. case Builtin::BI__sync_xor_and_fetch:
  860. case Builtin::BI__sync_xor_and_fetch_1:
  861. case Builtin::BI__sync_xor_and_fetch_2:
  862. case Builtin::BI__sync_xor_and_fetch_4:
  863. case Builtin::BI__sync_xor_and_fetch_8:
  864. case Builtin::BI__sync_xor_and_fetch_16:
  865. BuiltinIndex = 9;
  866. break;
  867. case Builtin::BI__sync_val_compare_and_swap:
  868. case Builtin::BI__sync_val_compare_and_swap_1:
  869. case Builtin::BI__sync_val_compare_and_swap_2:
  870. case Builtin::BI__sync_val_compare_and_swap_4:
  871. case Builtin::BI__sync_val_compare_and_swap_8:
  872. case Builtin::BI__sync_val_compare_and_swap_16:
  873. BuiltinIndex = 10;
  874. NumFixed = 2;
  875. break;
  876. case Builtin::BI__sync_bool_compare_and_swap:
  877. case Builtin::BI__sync_bool_compare_and_swap_1:
  878. case Builtin::BI__sync_bool_compare_and_swap_2:
  879. case Builtin::BI__sync_bool_compare_and_swap_4:
  880. case Builtin::BI__sync_bool_compare_and_swap_8:
  881. case Builtin::BI__sync_bool_compare_and_swap_16:
  882. BuiltinIndex = 11;
  883. NumFixed = 2;
  884. ResultType = Context.BoolTy;
  885. break;
  886. case Builtin::BI__sync_lock_test_and_set:
  887. case Builtin::BI__sync_lock_test_and_set_1:
  888. case Builtin::BI__sync_lock_test_and_set_2:
  889. case Builtin::BI__sync_lock_test_and_set_4:
  890. case Builtin::BI__sync_lock_test_and_set_8:
  891. case Builtin::BI__sync_lock_test_and_set_16:
  892. BuiltinIndex = 12;
  893. break;
  894. case Builtin::BI__sync_lock_release:
  895. case Builtin::BI__sync_lock_release_1:
  896. case Builtin::BI__sync_lock_release_2:
  897. case Builtin::BI__sync_lock_release_4:
  898. case Builtin::BI__sync_lock_release_8:
  899. case Builtin::BI__sync_lock_release_16:
  900. BuiltinIndex = 13;
  901. NumFixed = 0;
  902. ResultType = Context.VoidTy;
  903. break;
  904. case Builtin::BI__sync_swap:
  905. case Builtin::BI__sync_swap_1:
  906. case Builtin::BI__sync_swap_2:
  907. case Builtin::BI__sync_swap_4:
  908. case Builtin::BI__sync_swap_8:
  909. case Builtin::BI__sync_swap_16:
  910. BuiltinIndex = 14;
  911. break;
  912. }
  913. // Now that we know how many fixed arguments we expect, first check that we
  914. // have at least that many.
  915. if (TheCall->getNumArgs() < 1+NumFixed) {
  916. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  917. << 0 << 1+NumFixed << TheCall->getNumArgs()
  918. << TheCall->getCallee()->getSourceRange();
  919. return ExprError();
  920. }
  921. // Get the decl for the concrete builtin from this, we can tell what the
  922. // concrete integer type we should convert to is.
  923. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  924. const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
  925. IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
  926. FunctionDecl *NewBuiltinDecl =
  927. cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
  928. TUScope, false, DRE->getLocStart()));
  929. // The first argument --- the pointer --- has a fixed type; we
  930. // deduce the types of the rest of the arguments accordingly. Walk
  931. // the remaining arguments, converting them to the deduced value type.
  932. for (unsigned i = 0; i != NumFixed; ++i) {
  933. ExprResult Arg = TheCall->getArg(i+1);
  934. // GCC does an implicit conversion to the pointer or integer ValType. This
  935. // can fail in some cases (1i -> int**), check for this error case now.
  936. // Initialize the argument.
  937. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  938. ValType, /*consume*/ false);
  939. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  940. if (Arg.isInvalid())
  941. return ExprError();
  942. // Okay, we have something that *can* be converted to the right type. Check
  943. // to see if there is a potentially weird extension going on here. This can
  944. // happen when you do an atomic operation on something like an char* and
  945. // pass in 42. The 42 gets converted to char. This is even more strange
  946. // for things like 45.123 -> char, etc.
  947. // FIXME: Do this check.
  948. TheCall->setArg(i+1, Arg.take());
  949. }
  950. ASTContext& Context = this->getASTContext();
  951. // Create a new DeclRefExpr to refer to the new decl.
  952. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  953. Context,
  954. DRE->getQualifierLoc(),
  955. NewBuiltinDecl,
  956. DRE->getLocation(),
  957. NewBuiltinDecl->getType(),
  958. DRE->getValueKind());
  959. // Set the callee in the CallExpr.
  960. // FIXME: This leaks the original parens and implicit casts.
  961. ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
  962. if (PromotedCall.isInvalid())
  963. return ExprError();
  964. TheCall->setCallee(PromotedCall.take());
  965. // Change the result type of the call to match the original value type. This
  966. // is arbitrary, but the codegen for these builtins ins design to handle it
  967. // gracefully.
  968. TheCall->setType(ResultType);
  969. return move(TheCallResult);
  970. }
  971. /// CheckObjCString - Checks that the argument to the builtin
  972. /// CFString constructor is correct
  973. /// Note: It might also make sense to do the UTF-16 conversion here (would
  974. /// simplify the backend).
  975. bool Sema::CheckObjCString(Expr *Arg) {
  976. Arg = Arg->IgnoreParenCasts();
  977. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  978. if (!Literal || !Literal->isAscii()) {
  979. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  980. << Arg->getSourceRange();
  981. return true;
  982. }
  983. if (Literal->containsNonAsciiOrNull()) {
  984. StringRef String = Literal->getString();
  985. unsigned NumBytes = String.size();
  986. SmallVector<UTF16, 128> ToBuf(NumBytes);
  987. const UTF8 *FromPtr = (UTF8 *)String.data();
  988. UTF16 *ToPtr = &ToBuf[0];
  989. ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  990. &ToPtr, ToPtr + NumBytes,
  991. strictConversion);
  992. // Check for conversion failure.
  993. if (Result != conversionOK)
  994. Diag(Arg->getLocStart(),
  995. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  996. }
  997. return false;
  998. }
  999. /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
  1000. /// Emit an error and return true on failure, return false on success.
  1001. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
  1002. Expr *Fn = TheCall->getCallee();
  1003. if (TheCall->getNumArgs() > 2) {
  1004. Diag(TheCall->getArg(2)->getLocStart(),
  1005. diag::err_typecheck_call_too_many_args)
  1006. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1007. << Fn->getSourceRange()
  1008. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1009. (*(TheCall->arg_end()-1))->getLocEnd());
  1010. return true;
  1011. }
  1012. if (TheCall->getNumArgs() < 2) {
  1013. return Diag(TheCall->getLocEnd(),
  1014. diag::err_typecheck_call_too_few_args_at_least)
  1015. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  1016. }
  1017. // Type-check the first argument normally.
  1018. if (checkBuiltinArgument(*this, TheCall, 0))
  1019. return true;
  1020. // Determine whether the current function is variadic or not.
  1021. BlockScopeInfo *CurBlock = getCurBlock();
  1022. bool isVariadic;
  1023. if (CurBlock)
  1024. isVariadic = CurBlock->TheDecl->isVariadic();
  1025. else if (FunctionDecl *FD = getCurFunctionDecl())
  1026. isVariadic = FD->isVariadic();
  1027. else
  1028. isVariadic = getCurMethodDecl()->isVariadic();
  1029. if (!isVariadic) {
  1030. Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  1031. return true;
  1032. }
  1033. // Verify that the second argument to the builtin is the last argument of the
  1034. // current function or method.
  1035. bool SecondArgIsLastNamedArgument = false;
  1036. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  1037. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  1038. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  1039. // FIXME: This isn't correct for methods (results in bogus warning).
  1040. // Get the last formal in the current function.
  1041. const ParmVarDecl *LastArg;
  1042. if (CurBlock)
  1043. LastArg = *(CurBlock->TheDecl->param_end()-1);
  1044. else if (FunctionDecl *FD = getCurFunctionDecl())
  1045. LastArg = *(FD->param_end()-1);
  1046. else
  1047. LastArg = *(getCurMethodDecl()->param_end()-1);
  1048. SecondArgIsLastNamedArgument = PV == LastArg;
  1049. }
  1050. }
  1051. if (!SecondArgIsLastNamedArgument)
  1052. Diag(TheCall->getArg(1)->getLocStart(),
  1053. diag::warn_second_parameter_of_va_start_not_last_named_argument);
  1054. return false;
  1055. }
  1056. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  1057. /// friends. This is declared to take (...), so we have to check everything.
  1058. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  1059. if (TheCall->getNumArgs() < 2)
  1060. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1061. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  1062. if (TheCall->getNumArgs() > 2)
  1063. return Diag(TheCall->getArg(2)->getLocStart(),
  1064. diag::err_typecheck_call_too_many_args)
  1065. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1066. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1067. (*(TheCall->arg_end()-1))->getLocEnd());
  1068. ExprResult OrigArg0 = TheCall->getArg(0);
  1069. ExprResult OrigArg1 = TheCall->getArg(1);
  1070. // Do standard promotions between the two arguments, returning their common
  1071. // type.
  1072. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  1073. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  1074. return true;
  1075. // Make sure any conversions are pushed back into the call; this is
  1076. // type safe since unordered compare builtins are declared as "_Bool
  1077. // foo(...)".
  1078. TheCall->setArg(0, OrigArg0.get());
  1079. TheCall->setArg(1, OrigArg1.get());
  1080. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  1081. return false;
  1082. // If the common type isn't a real floating type, then the arguments were
  1083. // invalid for this operation.
  1084. if (!Res->isRealFloatingType())
  1085. return Diag(OrigArg0.get()->getLocStart(),
  1086. diag::err_typecheck_call_invalid_ordered_compare)
  1087. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  1088. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  1089. return false;
  1090. }
  1091. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  1092. /// __builtin_isnan and friends. This is declared to take (...), so we have
  1093. /// to check everything. We expect the last argument to be a floating point
  1094. /// value.
  1095. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  1096. if (TheCall->getNumArgs() < NumArgs)
  1097. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1098. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  1099. if (TheCall->getNumArgs() > NumArgs)
  1100. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  1101. diag::err_typecheck_call_too_many_args)
  1102. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  1103. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  1104. (*(TheCall->arg_end()-1))->getLocEnd());
  1105. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  1106. if (OrigArg->isTypeDependent())
  1107. return false;
  1108. // This operation requires a non-_Complex floating-point number.
  1109. if (!OrigArg->getType()->isRealFloatingType())
  1110. return Diag(OrigArg->getLocStart(),
  1111. diag::err_typecheck_call_invalid_unary_fp)
  1112. << OrigArg->getType() << OrigArg->getSourceRange();
  1113. // If this is an implicit conversion from float -> double, remove it.
  1114. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  1115. Expr *CastArg = Cast->getSubExpr();
  1116. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  1117. assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
  1118. "promotion from float to double is the only expected cast here");
  1119. Cast->setSubExpr(0);
  1120. TheCall->setArg(NumArgs-1, CastArg);
  1121. OrigArg = CastArg;
  1122. }
  1123. }
  1124. return false;
  1125. }
  1126. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  1127. // This is declared to take (...), so we have to check everything.
  1128. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  1129. if (TheCall->getNumArgs() < 2)
  1130. return ExprError(Diag(TheCall->getLocEnd(),
  1131. diag::err_typecheck_call_too_few_args_at_least)
  1132. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1133. << TheCall->getSourceRange());
  1134. // Determine which of the following types of shufflevector we're checking:
  1135. // 1) unary, vector mask: (lhs, mask)
  1136. // 2) binary, vector mask: (lhs, rhs, mask)
  1137. // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
  1138. QualType resType = TheCall->getArg(0)->getType();
  1139. unsigned numElements = 0;
  1140. if (!TheCall->getArg(0)->isTypeDependent() &&
  1141. !TheCall->getArg(1)->isTypeDependent()) {
  1142. QualType LHSType = TheCall->getArg(0)->getType();
  1143. QualType RHSType = TheCall->getArg(1)->getType();
  1144. if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
  1145. Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
  1146. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1147. TheCall->getArg(1)->getLocEnd());
  1148. return ExprError();
  1149. }
  1150. numElements = LHSType->getAs<VectorType>()->getNumElements();
  1151. unsigned numResElements = TheCall->getNumArgs() - 2;
  1152. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  1153. // with mask. If so, verify that RHS is an integer vector type with the
  1154. // same number of elts as lhs.
  1155. if (TheCall->getNumArgs() == 2) {
  1156. if (!RHSType->hasIntegerRepresentation() ||
  1157. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  1158. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  1159. << SourceRange(TheCall->getArg(1)->getLocStart(),
  1160. TheCall->getArg(1)->getLocEnd());
  1161. numResElements = numElements;
  1162. }
  1163. else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  1164. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  1165. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1166. TheCall->getArg(1)->getLocEnd());
  1167. return ExprError();
  1168. } else if (numElements != numResElements) {
  1169. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  1170. resType = Context.getVectorType(eltType, numResElements,
  1171. VectorType::GenericVector);
  1172. }
  1173. }
  1174. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  1175. if (TheCall->getArg(i)->isTypeDependent() ||
  1176. TheCall->getArg(i)->isValueDependent())
  1177. continue;
  1178. llvm::APSInt Result(32);
  1179. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  1180. return ExprError(Diag(TheCall->getLocStart(),
  1181. diag::err_shufflevector_nonconstant_argument)
  1182. << TheCall->getArg(i)->getSourceRange());
  1183. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  1184. return ExprError(Diag(TheCall->getLocStart(),
  1185. diag::err_shufflevector_argument_too_large)
  1186. << TheCall->getArg(i)->getSourceRange());
  1187. }
  1188. SmallVector<Expr*, 32> exprs;
  1189. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  1190. exprs.push_back(TheCall->getArg(i));
  1191. TheCall->setArg(i, 0);
  1192. }
  1193. return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
  1194. exprs.size(), resType,
  1195. TheCall->getCallee()->getLocStart(),
  1196. TheCall->getRParenLoc()));
  1197. }
  1198. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  1199. // This is declared to take (const void*, ...) and can take two
  1200. // optional constant int args.
  1201. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  1202. unsigned NumArgs = TheCall->getNumArgs();
  1203. if (NumArgs > 3)
  1204. return Diag(TheCall->getLocEnd(),
  1205. diag::err_typecheck_call_too_many_args_at_most)
  1206. << 0 /*function call*/ << 3 << NumArgs
  1207. << TheCall->getSourceRange();
  1208. // Argument 0 is checked for us and the remaining arguments must be
  1209. // constant integers.
  1210. for (unsigned i = 1; i != NumArgs; ++i) {
  1211. Expr *Arg = TheCall->getArg(i);
  1212. llvm::APSInt Result;
  1213. if (SemaBuiltinConstantArg(TheCall, i, Result))
  1214. return true;
  1215. // FIXME: gcc issues a warning and rewrites these to 0. These
  1216. // seems especially odd for the third argument since the default
  1217. // is 3.
  1218. if (i == 1) {
  1219. if (Result.getLimitedValue() > 1)
  1220. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1221. << "0" << "1" << Arg->getSourceRange();
  1222. } else {
  1223. if (Result.getLimitedValue() > 3)
  1224. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1225. << "0" << "3" << Arg->getSourceRange();
  1226. }
  1227. }
  1228. return false;
  1229. }
  1230. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  1231. /// TheCall is a constant expression.
  1232. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  1233. llvm::APSInt &Result) {
  1234. Expr *Arg = TheCall->getArg(ArgNum);
  1235. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1236. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  1237. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  1238. if (!Arg->isIntegerConstantExpr(Result, Context))
  1239. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  1240. << FDecl->getDeclName() << Arg->getSourceRange();
  1241. return false;
  1242. }
  1243. /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
  1244. /// int type). This simply type checks that type is one of the defined
  1245. /// constants (0-3).
  1246. // For compatibility check 0-3, llvm only handles 0 and 2.
  1247. bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
  1248. llvm::APSInt Result;
  1249. // Check constant-ness first.
  1250. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1251. return true;
  1252. Expr *Arg = TheCall->getArg(1);
  1253. if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
  1254. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1255. << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1256. }
  1257. return false;
  1258. }
  1259. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  1260. /// This checks that val is a constant 1.
  1261. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  1262. Expr *Arg = TheCall->getArg(1);
  1263. llvm::APSInt Result;
  1264. // TODO: This is less than ideal. Overload this to take a value.
  1265. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1266. return true;
  1267. if (Result != 1)
  1268. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  1269. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1270. return false;
  1271. }
  1272. // Handle i > 1 ? "x" : "y", recursively.
  1273. bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
  1274. bool HasVAListArg,
  1275. unsigned format_idx, unsigned firstDataArg,
  1276. bool isPrintf, bool inFunctionCall) {
  1277. tryAgain:
  1278. if (E->isTypeDependent() || E->isValueDependent())
  1279. return false;
  1280. E = E->IgnoreParens();
  1281. switch (E->getStmtClass()) {
  1282. case Stmt::BinaryConditionalOperatorClass:
  1283. case Stmt::ConditionalOperatorClass: {
  1284. const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
  1285. return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
  1286. format_idx, firstDataArg, isPrintf,
  1287. inFunctionCall)
  1288. && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
  1289. format_idx, firstDataArg, isPrintf,
  1290. inFunctionCall);
  1291. }
  1292. case Stmt::IntegerLiteralClass:
  1293. // Technically -Wformat-nonliteral does not warn about this case.
  1294. // The behavior of printf and friends in this case is implementation
  1295. // dependent. Ideally if the format string cannot be null then
  1296. // it should have a 'nonnull' attribute in the function prototype.
  1297. return true;
  1298. case Stmt::ImplicitCastExprClass: {
  1299. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  1300. goto tryAgain;
  1301. }
  1302. case Stmt::OpaqueValueExprClass:
  1303. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  1304. E = src;
  1305. goto tryAgain;
  1306. }
  1307. return false;
  1308. case Stmt::PredefinedExprClass:
  1309. // While __func__, etc., are technically not string literals, they
  1310. // cannot contain format specifiers and thus are not a security
  1311. // liability.
  1312. return true;
  1313. case Stmt::DeclRefExprClass: {
  1314. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  1315. // As an exception, do not flag errors for variables binding to
  1316. // const string literals.
  1317. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1318. bool isConstant = false;
  1319. QualType T = DR->getType();
  1320. if (const ArrayType *AT = Context.getAsArrayType(T)) {
  1321. isConstant = AT->getElementType().isConstant(Context);
  1322. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  1323. isConstant = T.isConstant(Context) &&
  1324. PT->getPointeeType().isConstant(Context);
  1325. }
  1326. if (isConstant) {
  1327. if (const Expr *Init = VD->getAnyInitializer())
  1328. return SemaCheckStringLiteral(Init, TheCall,
  1329. HasVAListArg, format_idx, firstDataArg,
  1330. isPrintf, /*inFunctionCall*/false);
  1331. }
  1332. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  1333. // special check to see if the format string is a function parameter
  1334. // of the function calling the printf function. If the function
  1335. // has an attribute indicating it is a printf-like function, then we
  1336. // should suppress warnings concerning non-literals being used in a call
  1337. // to a vprintf function. For example:
  1338. //
  1339. // void
  1340. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  1341. // va_list ap;
  1342. // va_start(ap, fmt);
  1343. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  1344. // ...
  1345. //
  1346. //
  1347. // FIXME: We don't have full attribute support yet, so just check to see
  1348. // if the argument is a DeclRefExpr that references a parameter. We'll
  1349. // add proper support for checking the attribute later.
  1350. if (HasVAListArg)
  1351. if (isa<ParmVarDecl>(VD))
  1352. return true;
  1353. }
  1354. return false;
  1355. }
  1356. case Stmt::CallExprClass: {
  1357. const CallExpr *CE = cast<CallExpr>(E);
  1358. if (const ImplicitCastExpr *ICE
  1359. = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
  1360. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
  1361. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
  1362. if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
  1363. unsigned ArgIndex = FA->getFormatIdx();
  1364. const Expr *Arg = CE->getArg(ArgIndex - 1);
  1365. return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
  1366. format_idx, firstDataArg, isPrintf,
  1367. inFunctionCall);
  1368. }
  1369. }
  1370. }
  1371. }
  1372. return false;
  1373. }
  1374. case Stmt::ObjCStringLiteralClass:
  1375. case Stmt::StringLiteralClass: {
  1376. const StringLiteral *StrE = NULL;
  1377. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  1378. StrE = ObjCFExpr->getString();
  1379. else
  1380. StrE = cast<StringLiteral>(E);
  1381. if (StrE) {
  1382. CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
  1383. firstDataArg, isPrintf, inFunctionCall);
  1384. return true;
  1385. }
  1386. return false;
  1387. }
  1388. default:
  1389. return false;
  1390. }
  1391. }
  1392. void
  1393. Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
  1394. const Expr * const *ExprArgs,
  1395. SourceLocation CallSiteLoc) {
  1396. for (NonNullAttr::args_iterator i = NonNull->args_begin(),
  1397. e = NonNull->args_end();
  1398. i != e; ++i) {
  1399. const Expr *ArgExpr = ExprArgs[*i];
  1400. if (ArgExpr->isNullPointerConstant(Context,
  1401. Expr::NPC_ValueDependentIsNotNull))
  1402. Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  1403. }
  1404. }
  1405. /// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
  1406. /// functions) for correct use of format strings.
  1407. void
  1408. Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
  1409. unsigned format_idx, unsigned firstDataArg,
  1410. bool isPrintf) {
  1411. const Expr *Fn = TheCall->getCallee();
  1412. // The way the format attribute works in GCC, the implicit this argument
  1413. // of member functions is counted. However, it doesn't appear in our own
  1414. // lists, so decrement format_idx in that case.
  1415. if (isa<CXXMemberCallExpr>(TheCall)) {
  1416. const CXXMethodDecl *method_decl =
  1417. dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
  1418. if (method_decl && method_decl->isInstance()) {
  1419. // Catch a format attribute mistakenly referring to the object argument.
  1420. if (format_idx == 0)
  1421. return;
  1422. --format_idx;
  1423. if(firstDataArg != 0)
  1424. --firstDataArg;
  1425. }
  1426. }
  1427. // CHECK: printf/scanf-like function is called with no format string.
  1428. if (format_idx >= TheCall->getNumArgs()) {
  1429. Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
  1430. << Fn->getSourceRange();
  1431. return;
  1432. }
  1433. const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
  1434. // CHECK: format string is not a string literal.
  1435. //
  1436. // Dynamically generated format strings are difficult to
  1437. // automatically vet at compile time. Requiring that format strings
  1438. // are string literals: (1) permits the checking of format strings by
  1439. // the compiler and thereby (2) can practically remove the source of
  1440. // many format string exploits.
  1441. // Format string can be either ObjC string (e.g. @"%d") or
  1442. // C string (e.g. "%d")
  1443. // ObjC string uses the same format specifiers as C string, so we can use
  1444. // the same format string checking logic for both ObjC and C strings.
  1445. if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
  1446. firstDataArg, isPrintf))
  1447. return; // Literal format string found, check done!
  1448. // If there are no arguments specified, warn with -Wformat-security, otherwise
  1449. // warn only with -Wformat-nonliteral.
  1450. if (TheCall->getNumArgs() == format_idx+1)
  1451. Diag(TheCall->getArg(format_idx)->getLocStart(),
  1452. diag::warn_format_nonliteral_noargs)
  1453. << OrigFormatExpr->getSourceRange();
  1454. else
  1455. Diag(TheCall->getArg(format_idx)->getLocStart(),
  1456. diag::warn_format_nonliteral)
  1457. << OrigFormatExpr->getSourceRange();
  1458. }
  1459. namespace {
  1460. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  1461. protected:
  1462. Sema &S;
  1463. const StringLiteral *FExpr;
  1464. const Expr *OrigFormatExpr;
  1465. const unsigned FirstDataArg;
  1466. const unsigned NumDataArgs;
  1467. const bool IsObjCLiteral;
  1468. const char *Beg; // Start of format string.
  1469. const bool HasVAListArg;
  1470. const CallExpr *TheCall;
  1471. unsigned FormatIdx;
  1472. llvm::BitVector CoveredArgs;
  1473. bool usesPositionalArgs;
  1474. bool atFirstArg;
  1475. bool inFunctionCall;
  1476. public:
  1477. CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
  1478. const Expr *origFormatExpr, unsigned firstDataArg,
  1479. unsigned numDataArgs, bool isObjCLiteral,
  1480. const char *beg, bool hasVAListArg,
  1481. const CallExpr *theCall, unsigned formatIdx,
  1482. bool inFunctionCall)
  1483. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
  1484. FirstDataArg(firstDataArg),
  1485. NumDataArgs(numDataArgs),
  1486. IsObjCLiteral(isObjCLiteral), Beg(beg),
  1487. HasVAListArg(hasVAListArg),
  1488. TheCall(theCall), FormatIdx(formatIdx),
  1489. usesPositionalArgs(false), atFirstArg(true),
  1490. inFunctionCall(inFunctionCall) {
  1491. CoveredArgs.resize(numDataArgs);
  1492. CoveredArgs.reset();
  1493. }
  1494. void DoneProcessing();
  1495. void HandleIncompleteSpecifier(const char *startSpecifier,
  1496. unsigned specifierLen);
  1497. virtual void HandleInvalidPosition(const char *startSpecifier,
  1498. unsigned specifierLen,
  1499. analyze_format_string::PositionContext p);
  1500. virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
  1501. void HandleNullChar(const char *nullCharacter);
  1502. template <typename Range>
  1503. static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
  1504. const Expr *ArgumentExpr,
  1505. PartialDiagnostic PDiag,
  1506. SourceLocation StringLoc,
  1507. bool IsStringLocation, Range StringRange,
  1508. FixItHint Fixit = FixItHint());
  1509. protected:
  1510. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  1511. const char *startSpec,
  1512. unsigned specifierLen,
  1513. const char *csStart, unsigned csLen);
  1514. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  1515. const char *startSpec,
  1516. unsigned specifierLen);
  1517. SourceRange getFormatStringRange();
  1518. CharSourceRange getSpecifierRange(const char *startSpecifier,
  1519. unsigned specifierLen);
  1520. SourceLocation getLocationOfByte(const char *x);
  1521. const Expr *getDataArg(unsigned i) const;
  1522. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  1523. const analyze_format_string::ConversionSpecifier &CS,
  1524. const char *startSpecifier, unsigned specifierLen,
  1525. unsigned argIndex);
  1526. template <typename Range>
  1527. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  1528. bool IsStringLocation, Range StringRange,
  1529. FixItHint Fixit = FixItHint());
  1530. void CheckPositionalAndNonpositionalArgs(
  1531. const analyze_format_string::FormatSpecifier *FS);
  1532. };
  1533. }
  1534. SourceRange CheckFormatHandler::getFormatStringRange() {
  1535. return OrigFormatExpr->getSourceRange();
  1536. }
  1537. CharSourceRange CheckFormatHandler::
  1538. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  1539. SourceLocation Start = getLocationOfByte(startSpecifier);
  1540. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  1541. // Advance the end SourceLocation by one due to half-open ranges.
  1542. End = End.getLocWithOffset(1);
  1543. return CharSourceRange::getCharRange(Start, End);
  1544. }
  1545. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  1546. return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
  1547. }
  1548. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  1549. unsigned specifierLen){
  1550. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  1551. getLocationOfByte(startSpecifier),
  1552. /*IsStringLocation*/true,
  1553. getSpecifierRange(startSpecifier, specifierLen));
  1554. }
  1555. void
  1556. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  1557. analyze_format_string::PositionContext p) {
  1558. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  1559. << (unsigned) p,
  1560. getLocationOfByte(startPos), /*IsStringLocation*/true,
  1561. getSpecifierRange(startPos, posLen));
  1562. }
  1563. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  1564. unsigned posLen) {
  1565. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  1566. getLocationOfByte(startPos),
  1567. /*IsStringLocation*/true,
  1568. getSpecifierRange(startPos, posLen));
  1569. }
  1570. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  1571. if (!IsObjCLiteral) {
  1572. // The presence of a null character is likely an error.
  1573. EmitFormatDiagnostic(
  1574. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  1575. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  1576. getFormatStringRange());
  1577. }
  1578. }
  1579. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  1580. return TheCall->getArg(FirstDataArg + i);
  1581. }
  1582. void CheckFormatHandler::DoneProcessing() {
  1583. // Does the number of data arguments exceed the number of
  1584. // format conversions in the format string?
  1585. if (!HasVAListArg) {
  1586. // Find any arguments that weren't covered.
  1587. CoveredArgs.flip();
  1588. signed notCoveredArg = CoveredArgs.find_first();
  1589. if (notCoveredArg >= 0) {
  1590. assert((unsigned)notCoveredArg < NumDataArgs);
  1591. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
  1592. getDataArg((unsigned) notCoveredArg)->getLocStart(),
  1593. /*IsStringLocation*/false, getFormatStringRange());
  1594. }
  1595. }
  1596. }
  1597. bool
  1598. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  1599. SourceLocation Loc,
  1600. const char *startSpec,
  1601. unsigned specifierLen,
  1602. const char *csStart,
  1603. unsigned csLen) {
  1604. bool keepGoing = true;
  1605. if (argIndex < NumDataArgs) {
  1606. // Consider the argument coverered, even though the specifier doesn't
  1607. // make sense.
  1608. CoveredArgs.set(argIndex);
  1609. }
  1610. else {
  1611. // If argIndex exceeds the number of data arguments we
  1612. // don't issue a warning because that is just a cascade of warnings (and
  1613. // they may have intended '%%' anyway). We don't want to continue processing
  1614. // the format string after this point, however, as we will like just get
  1615. // gibberish when trying to match arguments.
  1616. keepGoing = false;
  1617. }
  1618. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
  1619. << StringRef(csStart, csLen),
  1620. Loc, /*IsStringLocation*/true,
  1621. getSpecifierRange(startSpec, specifierLen));
  1622. return keepGoing;
  1623. }
  1624. void
  1625. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  1626. const char *startSpec,
  1627. unsigned specifierLen) {
  1628. EmitFormatDiagnostic(
  1629. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  1630. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  1631. }
  1632. bool
  1633. CheckFormatHandler::CheckNumArgs(
  1634. const analyze_format_string::FormatSpecifier &FS,
  1635. const analyze_format_string::ConversionSpecifier &CS,
  1636. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  1637. if (argIndex >= NumDataArgs) {
  1638. PartialDiagnostic PDiag = FS.usesPositionalArg()
  1639. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  1640. << (argIndex+1) << NumDataArgs)
  1641. : S.PDiag(diag::warn_printf_insufficient_data_args);
  1642. EmitFormatDiagnostic(
  1643. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  1644. getSpecifierRange(startSpecifier, specifierLen));
  1645. return false;
  1646. }
  1647. return true;
  1648. }
  1649. template<typename Range>
  1650. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  1651. SourceLocation Loc,
  1652. bool IsStringLocation,
  1653. Range StringRange,
  1654. FixItHint FixIt) {
  1655. EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
  1656. Loc, IsStringLocation, StringRange, FixIt);
  1657. }
  1658. /// \brief If the format string is not within the funcion call, emit a note
  1659. /// so that the function call and string are in diagnostic messages.
  1660. ///
  1661. /// \param inFunctionCall if true, the format string is within the function
  1662. /// call and only one diagnostic message will be produced. Otherwise, an
  1663. /// extra note will be emitted pointing to location of the format string.
  1664. ///
  1665. /// \param ArgumentExpr the expression that is passed as the format string
  1666. /// argument in the function call. Used for getting locations when two
  1667. /// diagnostics are emitted.
  1668. ///
  1669. /// \param PDiag the callee should already have provided any strings for the
  1670. /// diagnostic message. This function only adds locations and fixits
  1671. /// to diagnostics.
  1672. ///
  1673. /// \param Loc primary location for diagnostic. If two diagnostics are
  1674. /// required, one will be at Loc and a new SourceLocation will be created for
  1675. /// the other one.
  1676. ///
  1677. /// \param IsStringLocation if true, Loc points to the format string should be
  1678. /// used for the note. Otherwise, Loc points to the argument list and will
  1679. /// be used with PDiag.
  1680. ///
  1681. /// \param StringRange some or all of the string to highlight. This is
  1682. /// templated so it can accept either a CharSourceRange or a SourceRange.
  1683. ///
  1684. /// \param Fixit optional fix it hint for the format string.
  1685. template<typename Range>
  1686. void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
  1687. const Expr *ArgumentExpr,
  1688. PartialDiagnostic PDiag,
  1689. SourceLocation Loc,
  1690. bool IsStringLocation,
  1691. Range StringRange,
  1692. FixItHint FixIt) {
  1693. if (InFunctionCall)
  1694. S.Diag(Loc, PDiag) << StringRange << FixIt;
  1695. else {
  1696. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  1697. << ArgumentExpr->getSourceRange();
  1698. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  1699. diag::note_format_string_defined)
  1700. << StringRange << FixIt;
  1701. }
  1702. }
  1703. //===--- CHECK: Printf format string checking ------------------------------===//
  1704. namespace {
  1705. class CheckPrintfHandler : public CheckFormatHandler {
  1706. public:
  1707. CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
  1708. const Expr *origFormatExpr, unsigned firstDataArg,
  1709. unsigned numDataArgs, bool isObjCLiteral,
  1710. const char *beg, bool hasVAListArg,
  1711. const CallExpr *theCall, unsigned formatIdx,
  1712. bool inFunctionCall)
  1713. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  1714. numDataArgs, isObjCLiteral, beg, hasVAListArg,
  1715. theCall, formatIdx, inFunctionCall) {}
  1716. bool HandleInvalidPrintfConversionSpecifier(
  1717. const analyze_printf::PrintfSpecifier &FS,
  1718. const char *startSpecifier,
  1719. unsigned specifierLen);
  1720. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  1721. const char *startSpecifier,
  1722. unsigned specifierLen);
  1723. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  1724. const char *startSpecifier, unsigned specifierLen);
  1725. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  1726. const analyze_printf::OptionalAmount &Amt,
  1727. unsigned type,
  1728. const char *startSpecifier, unsigned specifierLen);
  1729. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  1730. const analyze_printf::OptionalFlag &flag,
  1731. const char *startSpecifier, unsigned specifierLen);
  1732. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  1733. const analyze_printf::OptionalFlag &ignoredFlag,
  1734. const analyze_printf::OptionalFlag &flag,
  1735. const char *startSpecifier, unsigned specifierLen);
  1736. };
  1737. }
  1738. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  1739. const analyze_printf::PrintfSpecifier &FS,
  1740. const char *startSpecifier,
  1741. unsigned specifierLen) {
  1742. const analyze_printf::PrintfConversionSpecifier &CS =
  1743. FS.getConversionSpecifier();
  1744. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  1745. getLocationOfByte(CS.getStart()),
  1746. startSpecifier, specifierLen,
  1747. CS.getStart(), CS.getLength());
  1748. }
  1749. bool CheckPrintfHandler::HandleAmount(
  1750. const analyze_format_string::OptionalAmount &Amt,
  1751. unsigned k, const char *startSpecifier,
  1752. unsigned specifierLen) {
  1753. if (Amt.hasDataArgument()) {
  1754. if (!HasVAListArg) {
  1755. unsigned argIndex = Amt.getArgIndex();
  1756. if (argIndex >= NumDataArgs) {
  1757. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  1758. << k,
  1759. getLocationOfByte(Amt.getStart()),
  1760. /*IsStringLocation*/true,
  1761. getSpecifierRange(startSpecifier, specifierLen));
  1762. // Don't do any more checking. We will just emit
  1763. // spurious errors.
  1764. return false;
  1765. }
  1766. // Type check the data argument. It should be an 'int'.
  1767. // Although not in conformance with C99, we also allow the argument to be
  1768. // an 'unsigned int' as that is a reasonably safe case. GCC also
  1769. // doesn't emit a warning for that case.
  1770. CoveredArgs.set(argIndex);
  1771. const Expr *Arg = getDataArg(argIndex);
  1772. QualType T = Arg->getType();
  1773. const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
  1774. assert(ATR.isValid());
  1775. if (!ATR.matchesType(S.Context, T)) {
  1776. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  1777. << k << ATR.getRepresentativeTypeName(S.Context)
  1778. << T << Arg->getSourceRange(),
  1779. getLocationOfByte(Amt.getStart()),
  1780. /*IsStringLocation*/true,
  1781. getSpecifierRange(startSpecifier, specifierLen));
  1782. // Don't do any more checking. We will just emit
  1783. // spurious errors.
  1784. return false;
  1785. }
  1786. }
  1787. }
  1788. return true;
  1789. }
  1790. void CheckPrintfHandler::HandleInvalidAmount(
  1791. const analyze_printf::PrintfSpecifier &FS,
  1792. const analyze_printf::OptionalAmount &Amt,
  1793. unsigned type,
  1794. const char *startSpecifier,
  1795. unsigned specifierLen) {
  1796. const analyze_printf::PrintfConversionSpecifier &CS =
  1797. FS.getConversionSpecifier();
  1798. FixItHint fixit =
  1799. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  1800. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  1801. Amt.getConstantLength()))
  1802. : FixItHint();
  1803. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  1804. << type << CS.toString(),
  1805. getLocationOfByte(Amt.getStart()),
  1806. /*IsStringLocation*/true,
  1807. getSpecifierRange(startSpecifier, specifierLen),
  1808. fixit);
  1809. }
  1810. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  1811. const analyze_printf::OptionalFlag &flag,
  1812. const char *startSpecifier,
  1813. unsigned specifierLen) {
  1814. // Warn about pointless flag with a fixit removal.
  1815. const analyze_printf::PrintfConversionSpecifier &CS =
  1816. FS.getConversionSpecifier();
  1817. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  1818. << flag.toString() << CS.toString(),
  1819. getLocationOfByte(flag.getPosition()),
  1820. /*IsStringLocation*/true,
  1821. getSpecifierRange(startSpecifier, specifierLen),
  1822. FixItHint::CreateRemoval(
  1823. getSpecifierRange(flag.getPosition(), 1)));
  1824. }
  1825. void CheckPrintfHandler::HandleIgnoredFlag(
  1826. const analyze_printf::PrintfSpecifier &FS,
  1827. const analyze_printf::OptionalFlag &ignoredFlag,
  1828. const analyze_printf::OptionalFlag &flag,
  1829. const char *startSpecifier,
  1830. unsigned specifierLen) {
  1831. // Warn about ignored flag with a fixit removal.
  1832. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  1833. << ignoredFlag.toString() << flag.toString(),
  1834. getLocationOfByte(ignoredFlag.getPosition()),
  1835. /*IsStringLocation*/true,
  1836. getSpecifierRange(startSpecifier, specifierLen),
  1837. FixItHint::CreateRemoval(
  1838. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  1839. }
  1840. bool
  1841. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  1842. &FS,
  1843. const char *startSpecifier,
  1844. unsigned specifierLen) {
  1845. using namespace analyze_format_string;
  1846. using namespace analyze_printf;
  1847. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  1848. if (FS.consumesDataArgument()) {
  1849. if (atFirstArg) {
  1850. atFirstArg = false;
  1851. usesPositionalArgs = FS.usesPositionalArg();
  1852. }
  1853. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  1854. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  1855. startSpecifier, specifierLen);
  1856. return false;
  1857. }
  1858. }
  1859. // First check if the field width, precision, and conversion specifier
  1860. // have matching data arguments.
  1861. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  1862. startSpecifier, specifierLen)) {
  1863. return false;
  1864. }
  1865. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  1866. startSpecifier, specifierLen)) {
  1867. return false;
  1868. }
  1869. if (!CS.consumesDataArgument()) {
  1870. // FIXME: Technically specifying a precision or field width here
  1871. // makes no sense. Worth issuing a warning at some point.
  1872. return true;
  1873. }
  1874. // Consume the argument.
  1875. unsigned argIndex = FS.getArgIndex();
  1876. if (argIndex < NumDataArgs) {
  1877. // The check to see if the argIndex is valid will come later.
  1878. // We set the bit here because we may exit early from this
  1879. // function if we encounter some other error.
  1880. CoveredArgs.set(argIndex);
  1881. }
  1882. // Check for using an Objective-C specific conversion specifier
  1883. // in a non-ObjC literal.
  1884. if (!IsObjCLiteral && CS.isObjCArg()) {
  1885. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  1886. specifierLen);
  1887. }
  1888. // Check for invalid use of field width
  1889. if (!FS.hasValidFieldWidth()) {
  1890. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  1891. startSpecifier, specifierLen);
  1892. }
  1893. // Check for invalid use of precision
  1894. if (!FS.hasValidPrecision()) {
  1895. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  1896. startSpecifier, specifierLen);
  1897. }
  1898. // Check each flag does not conflict with any other component.
  1899. if (!FS.hasValidThousandsGroupingPrefix())
  1900. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  1901. if (!FS.hasValidLeadingZeros())
  1902. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  1903. if (!FS.hasValidPlusPrefix())
  1904. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  1905. if (!FS.hasValidSpacePrefix())
  1906. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  1907. if (!FS.hasValidAlternativeForm())
  1908. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  1909. if (!FS.hasValidLeftJustified())
  1910. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  1911. // Check that flags are not ignored by another flag
  1912. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  1913. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  1914. startSpecifier, specifierLen);
  1915. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  1916. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  1917. startSpecifier, specifierLen);
  1918. // Check the length modifier is valid with the given conversion specifier.
  1919. const LengthModifier &LM = FS.getLengthModifier();
  1920. if (!FS.hasValidLengthModifier())
  1921. EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
  1922. << LM.toString() << CS.toString(),
  1923. getLocationOfByte(LM.getStart()),
  1924. /*IsStringLocation*/true,
  1925. getSpecifierRange(startSpecifier, specifierLen),
  1926. FixItHint::CreateRemoval(
  1927. getSpecifierRange(LM.getStart(),
  1928. LM.getLength())));
  1929. // Are we using '%n'?
  1930. if (CS.getKind() == ConversionSpecifier::nArg) {
  1931. // Issue a warning about this being a possible security issue.
  1932. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
  1933. getLocationOfByte(CS.getStart()),
  1934. /*IsStringLocation*/true,
  1935. getSpecifierRange(startSpecifier, specifierLen));
  1936. // Continue checking the other format specifiers.
  1937. return true;
  1938. }
  1939. // The remaining checks depend on the data arguments.
  1940. if (HasVAListArg)
  1941. return true;
  1942. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  1943. return false;
  1944. // Now type check the data expression that matches the
  1945. // format specifier.
  1946. const Expr *Ex = getDataArg(argIndex);
  1947. const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
  1948. if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
  1949. // Check if we didn't match because of an implicit cast from a 'char'
  1950. // or 'short' to an 'int'. This is done because printf is a varargs
  1951. // function.
  1952. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
  1953. if (ICE->getType() == S.Context.IntTy) {
  1954. // All further checking is done on the subexpression.
  1955. Ex = ICE->getSubExpr();
  1956. if (ATR.matchesType(S.Context, Ex->getType()))
  1957. return true;
  1958. }
  1959. // We may be able to offer a FixItHint if it is a supported type.
  1960. PrintfSpecifier fixedFS = FS;
  1961. bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
  1962. if (success) {
  1963. // Get the fix string from the fixed format specifier
  1964. llvm::SmallString<128> buf;
  1965. llvm::raw_svector_ostream os(buf);
  1966. fixedFS.toString(os);
  1967. EmitFormatDiagnostic(
  1968. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  1969. << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
  1970. << Ex->getSourceRange(),
  1971. getLocationOfByte(CS.getStart()),
  1972. /*IsStringLocation*/true,
  1973. getSpecifierRange(startSpecifier, specifierLen),
  1974. FixItHint::CreateReplacement(
  1975. getSpecifierRange(startSpecifier, specifierLen),
  1976. os.str()));
  1977. }
  1978. else {
  1979. S.Diag(getLocationOfByte(CS.getStart()),
  1980. diag::warn_printf_conversion_argument_type_mismatch)
  1981. << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
  1982. << getSpecifierRange(startSpecifier, specifierLen)
  1983. << Ex->getSourceRange();
  1984. }
  1985. }
  1986. return true;
  1987. }
  1988. //===--- CHECK: Scanf format string checking ------------------------------===//
  1989. namespace {
  1990. class CheckScanfHandler : public CheckFormatHandler {
  1991. public:
  1992. CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
  1993. const Expr *origFormatExpr, unsigned firstDataArg,
  1994. unsigned numDataArgs, bool isObjCLiteral,
  1995. const char *beg, bool hasVAListArg,
  1996. const CallExpr *theCall, unsigned formatIdx,
  1997. bool inFunctionCall)
  1998. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  1999. numDataArgs, isObjCLiteral, beg, hasVAListArg,
  2000. theCall, formatIdx, inFunctionCall) {}
  2001. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  2002. const char *startSpecifier,
  2003. unsigned specifierLen);
  2004. bool HandleInvalidScanfConversionSpecifier(
  2005. const analyze_scanf::ScanfSpecifier &FS,
  2006. const char *startSpecifier,
  2007. unsigned specifierLen);
  2008. void HandleIncompleteScanList(const char *start, const char *end);
  2009. };
  2010. }
  2011. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  2012. const char *end) {
  2013. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  2014. getLocationOfByte(end), /*IsStringLocation*/true,
  2015. getSpecifierRange(start, end - start));
  2016. }
  2017. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  2018. const analyze_scanf::ScanfSpecifier &FS,
  2019. const char *startSpecifier,
  2020. unsigned specifierLen) {
  2021. const analyze_scanf::ScanfConversionSpecifier &CS =
  2022. FS.getConversionSpecifier();
  2023. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2024. getLocationOfByte(CS.getStart()),
  2025. startSpecifier, specifierLen,
  2026. CS.getStart(), CS.getLength());
  2027. }
  2028. bool CheckScanfHandler::HandleScanfSpecifier(
  2029. const analyze_scanf::ScanfSpecifier &FS,
  2030. const char *startSpecifier,
  2031. unsigned specifierLen) {
  2032. using namespace analyze_scanf;
  2033. using namespace analyze_format_string;
  2034. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  2035. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  2036. // be used to decide if we are using positional arguments consistently.
  2037. if (FS.consumesDataArgument()) {
  2038. if (atFirstArg) {
  2039. atFirstArg = false;
  2040. usesPositionalArgs = FS.usesPositionalArg();
  2041. }
  2042. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2043. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2044. startSpecifier, specifierLen);
  2045. return false;
  2046. }
  2047. }
  2048. // Check if the field with is non-zero.
  2049. const OptionalAmount &Amt = FS.getFieldWidth();
  2050. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  2051. if (Amt.getConstantAmount() == 0) {
  2052. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  2053. Amt.getConstantLength());
  2054. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  2055. getLocationOfByte(Amt.getStart()),
  2056. /*IsStringLocation*/true, R,
  2057. FixItHint::CreateRemoval(R));
  2058. }
  2059. }
  2060. if (!FS.consumesDataArgument()) {
  2061. // FIXME: Technically specifying a precision or field width here
  2062. // makes no sense. Worth issuing a warning at some point.
  2063. return true;
  2064. }
  2065. // Consume the argument.
  2066. unsigned argIndex = FS.getArgIndex();
  2067. if (argIndex < NumDataArgs) {
  2068. // The check to see if the argIndex is valid will come later.
  2069. // We set the bit here because we may exit early from this
  2070. // function if we encounter some other error.
  2071. CoveredArgs.set(argIndex);
  2072. }
  2073. // Check the length modifier is valid with the given conversion specifier.
  2074. const LengthModifier &LM = FS.getLengthModifier();
  2075. if (!FS.hasValidLengthModifier()) {
  2076. S.Diag(getLocationOfByte(LM.getStart()),
  2077. diag::warn_format_nonsensical_length)
  2078. << LM.toString() << CS.toString()
  2079. << getSpecifierRange(startSpecifier, specifierLen)
  2080. << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
  2081. LM.getLength()));
  2082. }
  2083. // The remaining checks depend on the data arguments.
  2084. if (HasVAListArg)
  2085. return true;
  2086. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  2087. return false;
  2088. // FIXME: Check that the argument type matches the format specifier.
  2089. return true;
  2090. }
  2091. void Sema::CheckFormatString(const StringLiteral *FExpr,
  2092. const Expr *OrigFormatExpr,
  2093. const CallExpr *TheCall, bool HasVAListArg,
  2094. unsigned format_idx, unsigned firstDataArg,
  2095. bool isPrintf, bool inFunctionCall) {
  2096. // CHECK: is the format string a wide literal?
  2097. if (!FExpr->isAscii()) {
  2098. CheckFormatHandler::EmitFormatDiagnostic(
  2099. *this, inFunctionCall, TheCall->getArg(format_idx),
  2100. PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  2101. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  2102. return;
  2103. }
  2104. // Str - The format string. NOTE: this is NOT null-terminated!
  2105. StringRef StrRef = FExpr->getString();
  2106. const char *Str = StrRef.data();
  2107. unsigned StrLen = StrRef.size();
  2108. const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
  2109. // CHECK: empty format string?
  2110. if (StrLen == 0 && numDataArgs > 0) {
  2111. CheckFormatHandler::EmitFormatDiagnostic(
  2112. *this, inFunctionCall, TheCall->getArg(format_idx),
  2113. PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  2114. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  2115. return;
  2116. }
  2117. if (isPrintf) {
  2118. CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  2119. numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
  2120. Str, HasVAListArg, TheCall, format_idx,
  2121. inFunctionCall);
  2122. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
  2123. H.DoneProcessing();
  2124. }
  2125. else {
  2126. CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  2127. numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
  2128. Str, HasVAListArg, TheCall, format_idx,
  2129. inFunctionCall);
  2130. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
  2131. H.DoneProcessing();
  2132. }
  2133. }
  2134. //===--- CHECK: Standard memory functions ---------------------------------===//
  2135. /// \brief Determine whether the given type is a dynamic class type (e.g.,
  2136. /// whether it has a vtable).
  2137. static bool isDynamicClassType(QualType T) {
  2138. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  2139. if (CXXRecordDecl *Definition = Record->getDefinition())
  2140. if (Definition->isDynamicClass())
  2141. return true;
  2142. return false;
  2143. }
  2144. /// \brief If E is a sizeof expression, returns its argument expression,
  2145. /// otherwise returns NULL.
  2146. static const Expr *getSizeOfExprArg(const Expr* E) {
  2147. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  2148. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  2149. if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
  2150. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  2151. return 0;
  2152. }
  2153. /// \brief If E is a sizeof expression, returns its argument type.
  2154. static QualType getSizeOfArgType(const Expr* E) {
  2155. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  2156. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  2157. if (SizeOf->getKind() == clang::UETT_SizeOf)
  2158. return SizeOf->getTypeOfArgument();
  2159. return QualType();
  2160. }
  2161. /// \brief Check for dangerous or invalid arguments to memset().
  2162. ///
  2163. /// This issues warnings on known problematic, dangerous or unspecified
  2164. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  2165. /// function calls.
  2166. ///
  2167. /// \param Call The call expression to diagnose.
  2168. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  2169. CheckedMemoryFunction CMF,
  2170. IdentifierInfo *FnName) {
  2171. // It is possible to have a non-standard definition of memset. Validate
  2172. // we have enough arguments, and if not, abort further checking.
  2173. unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
  2174. if (Call->getNumArgs() < ExpectedNumArgs)
  2175. return;
  2176. unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
  2177. unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
  2178. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  2179. // We have special checking when the length is a sizeof expression.
  2180. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  2181. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  2182. llvm::FoldingSetNodeID SizeOfArgID;
  2183. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  2184. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  2185. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  2186. QualType DestTy = Dest->getType();
  2187. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  2188. QualType PointeeTy = DestPtrTy->getPointeeType();
  2189. // Never warn about void type pointers. This can be used to suppress
  2190. // false positives.
  2191. if (PointeeTy->isVoidType())
  2192. continue;
  2193. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  2194. // actually comparing the expressions for equality. Because computing the
  2195. // expression IDs can be expensive, we only do this if the diagnostic is
  2196. // enabled.
  2197. if (SizeOfArg &&
  2198. Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
  2199. SizeOfArg->getExprLoc())) {
  2200. // We only compute IDs for expressions if the warning is enabled, and
  2201. // cache the sizeof arg's ID.
  2202. if (SizeOfArgID == llvm::FoldingSetNodeID())
  2203. SizeOfArg->Profile(SizeOfArgID, Context, true);
  2204. llvm::FoldingSetNodeID DestID;
  2205. Dest->Profile(DestID, Context, true);
  2206. if (DestID == SizeOfArgID) {
  2207. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  2208. // over sizeof(src) as well.
  2209. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  2210. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  2211. if (UnaryOp->getOpcode() == UO_AddrOf)
  2212. ActionIdx = 1; // If its an address-of operator, just remove it.
  2213. if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
  2214. ActionIdx = 2; // If the pointee's size is sizeof(char),
  2215. // suggest an explicit length.
  2216. unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
  2217. DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
  2218. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  2219. << FnName << DestSrcSelect << ActionIdx
  2220. << Dest->getSourceRange()
  2221. << SizeOfArg->getSourceRange());
  2222. break;
  2223. }
  2224. }
  2225. // Also check for cases where the sizeof argument is the exact same
  2226. // type as the memory argument, and where it points to a user-defined
  2227. // record type.
  2228. if (SizeOfArgTy != QualType()) {
  2229. if (PointeeTy->isRecordType() &&
  2230. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  2231. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  2232. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  2233. << FnName << SizeOfArgTy << ArgIdx
  2234. << PointeeTy << Dest->getSourceRange()
  2235. << LenExpr->getSourceRange());
  2236. break;
  2237. }
  2238. }
  2239. // Always complain about dynamic classes.
  2240. if (isDynamicClassType(PointeeTy))
  2241. DiagRuntimeBehavior(
  2242. Dest->getExprLoc(), Dest,
  2243. PDiag(diag::warn_dyn_class_memaccess)
  2244. << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
  2245. // "overwritten" if we're warning about the destination for any call
  2246. // but memcmp; otherwise a verb appropriate to the call.
  2247. << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
  2248. << Call->getCallee()->getSourceRange());
  2249. else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
  2250. DiagRuntimeBehavior(
  2251. Dest->getExprLoc(), Dest,
  2252. PDiag(diag::warn_arc_object_memaccess)
  2253. << ArgIdx << FnName << PointeeTy
  2254. << Call->getCallee()->getSourceRange());
  2255. else
  2256. continue;
  2257. DiagRuntimeBehavior(
  2258. Dest->getExprLoc(), Dest,
  2259. PDiag(diag::note_bad_memaccess_silence)
  2260. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  2261. break;
  2262. }
  2263. }
  2264. }
  2265. // A little helper routine: ignore addition and subtraction of integer literals.
  2266. // This intentionally does not ignore all integer constant expressions because
  2267. // we don't want to remove sizeof().
  2268. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  2269. Ex = Ex->IgnoreParenCasts();
  2270. for (;;) {
  2271. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  2272. if (!BO || !BO->isAdditiveOp())
  2273. break;
  2274. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  2275. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  2276. if (isa<IntegerLiteral>(RHS))
  2277. Ex = LHS;
  2278. else if (isa<IntegerLiteral>(LHS))
  2279. Ex = RHS;
  2280. else
  2281. break;
  2282. }
  2283. return Ex;
  2284. }
  2285. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  2286. // be the size of the source, instead of the destination.
  2287. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  2288. IdentifierInfo *FnName) {
  2289. // Don't crash if the user has the wrong number of arguments
  2290. if (Call->getNumArgs() != 3)
  2291. return;
  2292. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  2293. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  2294. const Expr *CompareWithSrc = NULL;
  2295. // Look for 'strlcpy(dst, x, sizeof(x))'
  2296. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  2297. CompareWithSrc = Ex;
  2298. else {
  2299. // Look for 'strlcpy(dst, x, strlen(x))'
  2300. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  2301. if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
  2302. && SizeCall->getNumArgs() == 1)
  2303. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  2304. }
  2305. }
  2306. if (!CompareWithSrc)
  2307. return;
  2308. // Determine if the argument to sizeof/strlen is equal to the source
  2309. // argument. In principle there's all kinds of things you could do
  2310. // here, for instance creating an == expression and evaluating it with
  2311. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  2312. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  2313. if (!SrcArgDRE)
  2314. return;
  2315. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  2316. if (!CompareWithSrcDRE ||
  2317. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  2318. return;
  2319. const Expr *OriginalSizeArg = Call->getArg(2);
  2320. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  2321. << OriginalSizeArg->getSourceRange() << FnName;
  2322. // Output a FIXIT hint if the destination is an array (rather than a
  2323. // pointer to an array). This could be enhanced to handle some
  2324. // pointers if we know the actual size, like if DstArg is 'array+2'
  2325. // we could say 'sizeof(array)-2'.
  2326. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  2327. QualType DstArgTy = DstArg->getType();
  2328. // Only handle constant-sized or VLAs, but not flexible members.
  2329. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
  2330. // Only issue the FIXIT for arrays of size > 1.
  2331. if (CAT->getSize().getSExtValue() <= 1)
  2332. return;
  2333. } else if (!DstArgTy->isVariableArrayType()) {
  2334. return;
  2335. }
  2336. llvm::SmallString<128> sizeString;
  2337. llvm::raw_svector_ostream OS(sizeString);
  2338. OS << "sizeof(";
  2339. DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
  2340. OS << ")";
  2341. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  2342. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  2343. OS.str());
  2344. }
  2345. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  2346. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
  2347. static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
  2348. /// CheckReturnStackAddr - Check if a return statement returns the address
  2349. /// of a stack variable.
  2350. void
  2351. Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
  2352. SourceLocation ReturnLoc) {
  2353. Expr *stackE = 0;
  2354. SmallVector<DeclRefExpr *, 8> refVars;
  2355. // Perform checking for returned stack addresses, local blocks,
  2356. // label addresses or references to temporaries.
  2357. if (lhsType->isPointerType() ||
  2358. (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  2359. stackE = EvalAddr(RetValExp, refVars);
  2360. } else if (lhsType->isReferenceType()) {
  2361. stackE = EvalVal(RetValExp, refVars);
  2362. }
  2363. if (stackE == 0)
  2364. return; // Nothing suspicious was found.
  2365. SourceLocation diagLoc;
  2366. SourceRange diagRange;
  2367. if (refVars.empty()) {
  2368. diagLoc = stackE->getLocStart();
  2369. diagRange = stackE->getSourceRange();
  2370. } else {
  2371. // We followed through a reference variable. 'stackE' contains the
  2372. // problematic expression but we will warn at the return statement pointing
  2373. // at the reference variable. We will later display the "trail" of
  2374. // reference variables using notes.
  2375. diagLoc = refVars[0]->getLocStart();
  2376. diagRange = refVars[0]->getSourceRange();
  2377. }
  2378. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
  2379. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
  2380. : diag::warn_ret_stack_addr)
  2381. << DR->getDecl()->getDeclName() << diagRange;
  2382. } else if (isa<BlockExpr>(stackE)) { // local block.
  2383. Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  2384. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  2385. Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  2386. } else { // local temporary.
  2387. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
  2388. : diag::warn_ret_local_temp_addr)
  2389. << diagRange;
  2390. }
  2391. // Display the "trail" of reference variables that we followed until we
  2392. // found the problematic expression using notes.
  2393. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  2394. VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  2395. // If this var binds to another reference var, show the range of the next
  2396. // var, otherwise the var binds to the problematic expression, in which case
  2397. // show the range of the expression.
  2398. SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
  2399. : stackE->getSourceRange();
  2400. Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  2401. << VD->getDeclName() << range;
  2402. }
  2403. }
  2404. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  2405. /// check if the expression in a return statement evaluates to an address
  2406. /// to a location on the stack, a local block, an address of a label, or a
  2407. /// reference to local temporary. The recursion is used to traverse the
  2408. /// AST of the return expression, with recursion backtracking when we
  2409. /// encounter a subexpression that (1) clearly does not lead to one of the
  2410. /// above problematic expressions (2) is something we cannot determine leads to
  2411. /// a problematic expression based on such local checking.
  2412. ///
  2413. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  2414. /// the expression that they point to. Such variables are added to the
  2415. /// 'refVars' vector so that we know what the reference variable "trail" was.
  2416. ///
  2417. /// EvalAddr processes expressions that are pointers that are used as
  2418. /// references (and not L-values). EvalVal handles all other values.
  2419. /// At the base case of the recursion is a check for the above problematic
  2420. /// expressions.
  2421. ///
  2422. /// This implementation handles:
  2423. ///
  2424. /// * pointer-to-pointer casts
  2425. /// * implicit conversions from array references to pointers
  2426. /// * taking the address of fields
  2427. /// * arbitrary interplay between "&" and "*" operators
  2428. /// * pointer arithmetic from an address of a stack variable
  2429. /// * taking the address of an array element where the array is on the stack
  2430. static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
  2431. if (E->isTypeDependent())
  2432. return NULL;
  2433. // We should only be called for evaluating pointer expressions.
  2434. assert((E->getType()->isAnyPointerType() ||
  2435. E->getType()->isBlockPointerType() ||
  2436. E->getType()->isObjCQualifiedIdType()) &&
  2437. "EvalAddr only works on pointers");
  2438. E = E->IgnoreParens();
  2439. // Our "symbolic interpreter" is just a dispatch off the currently
  2440. // viewed AST node. We then recursively traverse the AST by calling
  2441. // EvalAddr and EvalVal appropriately.
  2442. switch (E->getStmtClass()) {
  2443. case Stmt::DeclRefExprClass: {
  2444. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  2445. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  2446. // If this is a reference variable, follow through to the expression that
  2447. // it points to.
  2448. if (V->hasLocalStorage() &&
  2449. V->getType()->isReferenceType() && V->hasInit()) {
  2450. // Add the reference variable to the "trail".
  2451. refVars.push_back(DR);
  2452. return EvalAddr(V->getInit(), refVars);
  2453. }
  2454. return NULL;
  2455. }
  2456. case Stmt::UnaryOperatorClass: {
  2457. // The only unary operator that make sense to handle here
  2458. // is AddrOf. All others don't make sense as pointers.
  2459. UnaryOperator *U = cast<UnaryOperator>(E);
  2460. if (U->getOpcode() == UO_AddrOf)
  2461. return EvalVal(U->getSubExpr(), refVars);
  2462. else
  2463. return NULL;
  2464. }
  2465. case Stmt::BinaryOperatorClass: {
  2466. // Handle pointer arithmetic. All other binary operators are not valid
  2467. // in this context.
  2468. BinaryOperator *B = cast<BinaryOperator>(E);
  2469. BinaryOperatorKind op = B->getOpcode();
  2470. if (op != BO_Add && op != BO_Sub)
  2471. return NULL;
  2472. Expr *Base = B->getLHS();
  2473. // Determine which argument is the real pointer base. It could be
  2474. // the RHS argument instead of the LHS.
  2475. if (!Base->getType()->isPointerType()) Base = B->getRHS();
  2476. assert (Base->getType()->isPointerType());
  2477. return EvalAddr(Base, refVars);
  2478. }
  2479. // For conditional operators we need to see if either the LHS or RHS are
  2480. // valid DeclRefExpr*s. If one of them is valid, we return it.
  2481. case Stmt::ConditionalOperatorClass: {
  2482. ConditionalOperator *C = cast<ConditionalOperator>(E);
  2483. // Handle the GNU extension for missing LHS.
  2484. if (Expr *lhsExpr = C->getLHS()) {
  2485. // In C++, we can have a throw-expression, which has 'void' type.
  2486. if (!lhsExpr->getType()->isVoidType())
  2487. if (Expr* LHS = EvalAddr(lhsExpr, refVars))
  2488. return LHS;
  2489. }
  2490. // In C++, we can have a throw-expression, which has 'void' type.
  2491. if (C->getRHS()->getType()->isVoidType())
  2492. return NULL;
  2493. return EvalAddr(C->getRHS(), refVars);
  2494. }
  2495. case Stmt::BlockExprClass:
  2496. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  2497. return E; // local block.
  2498. return NULL;
  2499. case Stmt::AddrLabelExprClass:
  2500. return E; // address of label.
  2501. case Stmt::ExprWithCleanupsClass:
  2502. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
  2503. // For casts, we need to handle conversions from arrays to
  2504. // pointer values, and pointer-to-pointer conversions.
  2505. case Stmt::ImplicitCastExprClass:
  2506. case Stmt::CStyleCastExprClass:
  2507. case Stmt::CXXFunctionalCastExprClass:
  2508. case Stmt::ObjCBridgedCastExprClass: {
  2509. Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  2510. QualType T = SubExpr->getType();
  2511. if (SubExpr->getType()->isPointerType() ||
  2512. SubExpr->getType()->isBlockPointerType() ||
  2513. SubExpr->getType()->isObjCQualifiedIdType())
  2514. return EvalAddr(SubExpr, refVars);
  2515. else if (T->isArrayType())
  2516. return EvalVal(SubExpr, refVars);
  2517. else
  2518. return 0;
  2519. }
  2520. // C++ casts. For dynamic casts, static casts, and const casts, we
  2521. // are always converting from a pointer-to-pointer, so we just blow
  2522. // through the cast. In the case the dynamic cast doesn't fail (and
  2523. // return NULL), we take the conservative route and report cases
  2524. // where we return the address of a stack variable. For Reinterpre
  2525. // FIXME: The comment about is wrong; we're not always converting
  2526. // from pointer to pointer. I'm guessing that this code should also
  2527. // handle references to objects.
  2528. case Stmt::CXXStaticCastExprClass:
  2529. case Stmt::CXXDynamicCastExprClass:
  2530. case Stmt::CXXConstCastExprClass:
  2531. case Stmt::CXXReinterpretCastExprClass: {
  2532. Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
  2533. if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
  2534. return EvalAddr(S, refVars);
  2535. else
  2536. return NULL;
  2537. }
  2538. case Stmt::MaterializeTemporaryExprClass:
  2539. if (Expr *Result = EvalAddr(
  2540. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  2541. refVars))
  2542. return Result;
  2543. return E;
  2544. // Everything else: we simply don't reason about them.
  2545. default:
  2546. return NULL;
  2547. }
  2548. }
  2549. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  2550. /// See the comments for EvalAddr for more details.
  2551. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
  2552. do {
  2553. // We should only be called for evaluating non-pointer expressions, or
  2554. // expressions with a pointer type that are not used as references but instead
  2555. // are l-values (e.g., DeclRefExpr with a pointer type).
  2556. // Our "symbolic interpreter" is just a dispatch off the currently
  2557. // viewed AST node. We then recursively traverse the AST by calling
  2558. // EvalAddr and EvalVal appropriately.
  2559. E = E->IgnoreParens();
  2560. switch (E->getStmtClass()) {
  2561. case Stmt::ImplicitCastExprClass: {
  2562. ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  2563. if (IE->getValueKind() == VK_LValue) {
  2564. E = IE->getSubExpr();
  2565. continue;
  2566. }
  2567. return NULL;
  2568. }
  2569. case Stmt::ExprWithCleanupsClass:
  2570. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
  2571. case Stmt::DeclRefExprClass: {
  2572. // When we hit a DeclRefExpr we are looking at code that refers to a
  2573. // variable's name. If it's not a reference variable we check if it has
  2574. // local storage within the function, and if so, return the expression.
  2575. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  2576. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  2577. if (V->hasLocalStorage()) {
  2578. if (!V->getType()->isReferenceType())
  2579. return DR;
  2580. // Reference variable, follow through to the expression that
  2581. // it points to.
  2582. if (V->hasInit()) {
  2583. // Add the reference variable to the "trail".
  2584. refVars.push_back(DR);
  2585. return EvalVal(V->getInit(), refVars);
  2586. }
  2587. }
  2588. return NULL;
  2589. }
  2590. case Stmt::UnaryOperatorClass: {
  2591. // The only unary operator that make sense to handle here
  2592. // is Deref. All others don't resolve to a "name." This includes
  2593. // handling all sorts of rvalues passed to a unary operator.
  2594. UnaryOperator *U = cast<UnaryOperator>(E);
  2595. if (U->getOpcode() == UO_Deref)
  2596. return EvalAddr(U->getSubExpr(), refVars);
  2597. return NULL;
  2598. }
  2599. case Stmt::ArraySubscriptExprClass: {
  2600. // Array subscripts are potential references to data on the stack. We
  2601. // retrieve the DeclRefExpr* for the array variable if it indeed
  2602. // has local storage.
  2603. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
  2604. }
  2605. case Stmt::ConditionalOperatorClass: {
  2606. // For conditional operators we need to see if either the LHS or RHS are
  2607. // non-NULL Expr's. If one is non-NULL, we return it.
  2608. ConditionalOperator *C = cast<ConditionalOperator>(E);
  2609. // Handle the GNU extension for missing LHS.
  2610. if (Expr *lhsExpr = C->getLHS())
  2611. if (Expr *LHS = EvalVal(lhsExpr, refVars))
  2612. return LHS;
  2613. return EvalVal(C->getRHS(), refVars);
  2614. }
  2615. // Accesses to members are potential references to data on the stack.
  2616. case Stmt::MemberExprClass: {
  2617. MemberExpr *M = cast<MemberExpr>(E);
  2618. // Check for indirect access. We only want direct field accesses.
  2619. if (M->isArrow())
  2620. return NULL;
  2621. // Check whether the member type is itself a reference, in which case
  2622. // we're not going to refer to the member, but to what the member refers to.
  2623. if (M->getMemberDecl()->getType()->isReferenceType())
  2624. return NULL;
  2625. return EvalVal(M->getBase(), refVars);
  2626. }
  2627. case Stmt::MaterializeTemporaryExprClass:
  2628. if (Expr *Result = EvalVal(
  2629. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  2630. refVars))
  2631. return Result;
  2632. return E;
  2633. default:
  2634. // Check that we don't return or take the address of a reference to a
  2635. // temporary. This is only useful in C++.
  2636. if (!E->isTypeDependent() && E->isRValue())
  2637. return E;
  2638. // Everything else: we simply don't reason about them.
  2639. return NULL;
  2640. }
  2641. } while (true);
  2642. }
  2643. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  2644. /// Check for comparisons of floating point operands using != and ==.
  2645. /// Issue a warning if these are no self-comparisons, as they are not likely
  2646. /// to do what the programmer intended.
  2647. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  2648. bool EmitWarning = true;
  2649. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  2650. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  2651. // Special case: check for x == x (which is OK).
  2652. // Do not emit warnings for such cases.
  2653. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  2654. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  2655. if (DRL->getDecl() == DRR->getDecl())
  2656. EmitWarning = false;
  2657. // Special case: check for comparisons against literals that can be exactly
  2658. // represented by APFloat. In such cases, do not emit a warning. This
  2659. // is a heuristic: often comparison against such literals are used to
  2660. // detect if a value in a variable has not changed. This clearly can
  2661. // lead to false negatives.
  2662. if (EmitWarning) {
  2663. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  2664. if (FLL->isExact())
  2665. EmitWarning = false;
  2666. } else
  2667. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
  2668. if (FLR->isExact())
  2669. EmitWarning = false;
  2670. }
  2671. }
  2672. // Check for comparisons with builtin types.
  2673. if (EmitWarning)
  2674. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  2675. if (CL->isBuiltinCall())
  2676. EmitWarning = false;
  2677. if (EmitWarning)
  2678. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  2679. if (CR->isBuiltinCall())
  2680. EmitWarning = false;
  2681. // Emit the diagnostic.
  2682. if (EmitWarning)
  2683. Diag(Loc, diag::warn_floatingpoint_eq)
  2684. << LHS->getSourceRange() << RHS->getSourceRange();
  2685. }
  2686. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  2687. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  2688. namespace {
  2689. /// Structure recording the 'active' range of an integer-valued
  2690. /// expression.
  2691. struct IntRange {
  2692. /// The number of bits active in the int.
  2693. unsigned Width;
  2694. /// True if the int is known not to have negative values.
  2695. bool NonNegative;
  2696. IntRange(unsigned Width, bool NonNegative)
  2697. : Width(Width), NonNegative(NonNegative)
  2698. {}
  2699. /// Returns the range of the bool type.
  2700. static IntRange forBoolType() {
  2701. return IntRange(1, true);
  2702. }
  2703. /// Returns the range of an opaque value of the given integral type.
  2704. static IntRange forValueOfType(ASTContext &C, QualType T) {
  2705. return forValueOfCanonicalType(C,
  2706. T->getCanonicalTypeInternal().getTypePtr());
  2707. }
  2708. /// Returns the range of an opaque value of a canonical integral type.
  2709. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  2710. assert(T->isCanonicalUnqualified());
  2711. if (const VectorType *VT = dyn_cast<VectorType>(T))
  2712. T = VT->getElementType().getTypePtr();
  2713. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  2714. T = CT->getElementType().getTypePtr();
  2715. // For enum types, use the known bit width of the enumerators.
  2716. if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  2717. EnumDecl *Enum = ET->getDecl();
  2718. if (!Enum->isCompleteDefinition())
  2719. return IntRange(C.getIntWidth(QualType(T, 0)), false);
  2720. unsigned NumPositive = Enum->getNumPositiveBits();
  2721. unsigned NumNegative = Enum->getNumNegativeBits();
  2722. return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
  2723. }
  2724. const BuiltinType *BT = cast<BuiltinType>(T);
  2725. assert(BT->isInteger());
  2726. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  2727. }
  2728. /// Returns the "target" range of a canonical integral type, i.e.
  2729. /// the range of values expressible in the type.
  2730. ///
  2731. /// This matches forValueOfCanonicalType except that enums have the
  2732. /// full range of their type, not the range of their enumerators.
  2733. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  2734. assert(T->isCanonicalUnqualified());
  2735. if (const VectorType *VT = dyn_cast<VectorType>(T))
  2736. T = VT->getElementType().getTypePtr();
  2737. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  2738. T = CT->getElementType().getTypePtr();
  2739. if (const EnumType *ET = dyn_cast<EnumType>(T))
  2740. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  2741. const BuiltinType *BT = cast<BuiltinType>(T);
  2742. assert(BT->isInteger());
  2743. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  2744. }
  2745. /// Returns the supremum of two ranges: i.e. their conservative merge.
  2746. static IntRange join(IntRange L, IntRange R) {
  2747. return IntRange(std::max(L.Width, R.Width),
  2748. L.NonNegative && R.NonNegative);
  2749. }
  2750. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  2751. static IntRange meet(IntRange L, IntRange R) {
  2752. return IntRange(std::min(L.Width, R.Width),
  2753. L.NonNegative || R.NonNegative);
  2754. }
  2755. };
  2756. IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
  2757. if (value.isSigned() && value.isNegative())
  2758. return IntRange(value.getMinSignedBits(), false);
  2759. if (value.getBitWidth() > MaxWidth)
  2760. value = value.trunc(MaxWidth);
  2761. // isNonNegative() just checks the sign bit without considering
  2762. // signedness.
  2763. return IntRange(value.getActiveBits(), true);
  2764. }
  2765. IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  2766. unsigned MaxWidth) {
  2767. if (result.isInt())
  2768. return GetValueRange(C, result.getInt(), MaxWidth);
  2769. if (result.isVector()) {
  2770. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  2771. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  2772. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  2773. R = IntRange::join(R, El);
  2774. }
  2775. return R;
  2776. }
  2777. if (result.isComplexInt()) {
  2778. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  2779. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  2780. return IntRange::join(R, I);
  2781. }
  2782. // This can happen with lossless casts to intptr_t of "based" lvalues.
  2783. // Assume it might use arbitrary bits.
  2784. // FIXME: The only reason we need to pass the type in here is to get
  2785. // the sign right on this one case. It would be nice if APValue
  2786. // preserved this.
  2787. assert(result.isLValue());
  2788. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  2789. }
  2790. /// Pseudo-evaluate the given integer expression, estimating the
  2791. /// range of values it might take.
  2792. ///
  2793. /// \param MaxWidth - the width to which the value will be truncated
  2794. IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
  2795. E = E->IgnoreParens();
  2796. // Try a full evaluation first.
  2797. Expr::EvalResult result;
  2798. if (E->EvaluateAsRValue(result, C))
  2799. return GetValueRange(C, result.Val, E->getType(), MaxWidth);
  2800. // I think we only want to look through implicit casts here; if the
  2801. // user has an explicit widening cast, we should treat the value as
  2802. // being of the new, wider type.
  2803. if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  2804. if (CE->getCastKind() == CK_NoOp)
  2805. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  2806. IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
  2807. bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
  2808. // Assume that non-integer casts can span the full range of the type.
  2809. if (!isIntegerCast)
  2810. return OutputTypeRange;
  2811. IntRange SubRange
  2812. = GetExprRange(C, CE->getSubExpr(),
  2813. std::min(MaxWidth, OutputTypeRange.Width));
  2814. // Bail out if the subexpr's range is as wide as the cast type.
  2815. if (SubRange.Width >= OutputTypeRange.Width)
  2816. return OutputTypeRange;
  2817. // Otherwise, we take the smaller width, and we're non-negative if
  2818. // either the output type or the subexpr is.
  2819. return IntRange(SubRange.Width,
  2820. SubRange.NonNegative || OutputTypeRange.NonNegative);
  2821. }
  2822. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  2823. // If we can fold the condition, just take that operand.
  2824. bool CondResult;
  2825. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  2826. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  2827. : CO->getFalseExpr(),
  2828. MaxWidth);
  2829. // Otherwise, conservatively merge.
  2830. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  2831. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  2832. return IntRange::join(L, R);
  2833. }
  2834. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  2835. switch (BO->getOpcode()) {
  2836. // Boolean-valued operations are single-bit and positive.
  2837. case BO_LAnd:
  2838. case BO_LOr:
  2839. case BO_LT:
  2840. case BO_GT:
  2841. case BO_LE:
  2842. case BO_GE:
  2843. case BO_EQ:
  2844. case BO_NE:
  2845. return IntRange::forBoolType();
  2846. // The type of the assignments is the type of the LHS, so the RHS
  2847. // is not necessarily the same type.
  2848. case BO_MulAssign:
  2849. case BO_DivAssign:
  2850. case BO_RemAssign:
  2851. case BO_AddAssign:
  2852. case BO_SubAssign:
  2853. case BO_XorAssign:
  2854. case BO_OrAssign:
  2855. // TODO: bitfields?
  2856. return IntRange::forValueOfType(C, E->getType());
  2857. // Simple assignments just pass through the RHS, which will have
  2858. // been coerced to the LHS type.
  2859. case BO_Assign:
  2860. // TODO: bitfields?
  2861. return GetExprRange(C, BO->getRHS(), MaxWidth);
  2862. // Operations with opaque sources are black-listed.
  2863. case BO_PtrMemD:
  2864. case BO_PtrMemI:
  2865. return IntRange::forValueOfType(C, E->getType());
  2866. // Bitwise-and uses the *infinum* of the two source ranges.
  2867. case BO_And:
  2868. case BO_AndAssign:
  2869. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  2870. GetExprRange(C, BO->getRHS(), MaxWidth));
  2871. // Left shift gets black-listed based on a judgement call.
  2872. case BO_Shl:
  2873. // ...except that we want to treat '1 << (blah)' as logically
  2874. // positive. It's an important idiom.
  2875. if (IntegerLiteral *I
  2876. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  2877. if (I->getValue() == 1) {
  2878. IntRange R = IntRange::forValueOfType(C, E->getType());
  2879. return IntRange(R.Width, /*NonNegative*/ true);
  2880. }
  2881. }
  2882. // fallthrough
  2883. case BO_ShlAssign:
  2884. return IntRange::forValueOfType(C, E->getType());
  2885. // Right shift by a constant can narrow its left argument.
  2886. case BO_Shr:
  2887. case BO_ShrAssign: {
  2888. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  2889. // If the shift amount is a positive constant, drop the width by
  2890. // that much.
  2891. llvm::APSInt shift;
  2892. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  2893. shift.isNonNegative()) {
  2894. unsigned zext = shift.getZExtValue();
  2895. if (zext >= L.Width)
  2896. L.Width = (L.NonNegative ? 0 : 1);
  2897. else
  2898. L.Width -= zext;
  2899. }
  2900. return L;
  2901. }
  2902. // Comma acts as its right operand.
  2903. case BO_Comma:
  2904. return GetExprRange(C, BO->getRHS(), MaxWidth);
  2905. // Black-list pointer subtractions.
  2906. case BO_Sub:
  2907. if (BO->getLHS()->getType()->isPointerType())
  2908. return IntRange::forValueOfType(C, E->getType());
  2909. break;
  2910. // The width of a division result is mostly determined by the size
  2911. // of the LHS.
  2912. case BO_Div: {
  2913. // Don't 'pre-truncate' the operands.
  2914. unsigned opWidth = C.getIntWidth(E->getType());
  2915. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  2916. // If the divisor is constant, use that.
  2917. llvm::APSInt divisor;
  2918. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  2919. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  2920. if (log2 >= L.Width)
  2921. L.Width = (L.NonNegative ? 0 : 1);
  2922. else
  2923. L.Width = std::min(L.Width - log2, MaxWidth);
  2924. return L;
  2925. }
  2926. // Otherwise, just use the LHS's width.
  2927. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  2928. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  2929. }
  2930. // The result of a remainder can't be larger than the result of
  2931. // either side.
  2932. case BO_Rem: {
  2933. // Don't 'pre-truncate' the operands.
  2934. unsigned opWidth = C.getIntWidth(E->getType());
  2935. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  2936. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  2937. IntRange meet = IntRange::meet(L, R);
  2938. meet.Width = std::min(meet.Width, MaxWidth);
  2939. return meet;
  2940. }
  2941. // The default behavior is okay for these.
  2942. case BO_Mul:
  2943. case BO_Add:
  2944. case BO_Xor:
  2945. case BO_Or:
  2946. break;
  2947. }
  2948. // The default case is to treat the operation as if it were closed
  2949. // on the narrowest type that encompasses both operands.
  2950. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  2951. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  2952. return IntRange::join(L, R);
  2953. }
  2954. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  2955. switch (UO->getOpcode()) {
  2956. // Boolean-valued operations are white-listed.
  2957. case UO_LNot:
  2958. return IntRange::forBoolType();
  2959. // Operations with opaque sources are black-listed.
  2960. case UO_Deref:
  2961. case UO_AddrOf: // should be impossible
  2962. return IntRange::forValueOfType(C, E->getType());
  2963. default:
  2964. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  2965. }
  2966. }
  2967. if (dyn_cast<OffsetOfExpr>(E)) {
  2968. IntRange::forValueOfType(C, E->getType());
  2969. }
  2970. if (FieldDecl *BitField = E->getBitField())
  2971. return IntRange(BitField->getBitWidthValue(C),
  2972. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  2973. return IntRange::forValueOfType(C, E->getType());
  2974. }
  2975. IntRange GetExprRange(ASTContext &C, Expr *E) {
  2976. return GetExprRange(C, E, C.getIntWidth(E->getType()));
  2977. }
  2978. /// Checks whether the given value, which currently has the given
  2979. /// source semantics, has the same value when coerced through the
  2980. /// target semantics.
  2981. bool IsSameFloatAfterCast(const llvm::APFloat &value,
  2982. const llvm::fltSemantics &Src,
  2983. const llvm::fltSemantics &Tgt) {
  2984. llvm::APFloat truncated = value;
  2985. bool ignored;
  2986. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  2987. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  2988. return truncated.bitwiseIsEqual(value);
  2989. }
  2990. /// Checks whether the given value, which currently has the given
  2991. /// source semantics, has the same value when coerced through the
  2992. /// target semantics.
  2993. ///
  2994. /// The value might be a vector of floats (or a complex number).
  2995. bool IsSameFloatAfterCast(const APValue &value,
  2996. const llvm::fltSemantics &Src,
  2997. const llvm::fltSemantics &Tgt) {
  2998. if (value.isFloat())
  2999. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  3000. if (value.isVector()) {
  3001. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  3002. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  3003. return false;
  3004. return true;
  3005. }
  3006. assert(value.isComplexFloat());
  3007. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  3008. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  3009. }
  3010. void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  3011. static bool IsZero(Sema &S, Expr *E) {
  3012. // Suppress cases where we are comparing against an enum constant.
  3013. if (const DeclRefExpr *DR =
  3014. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  3015. if (isa<EnumConstantDecl>(DR->getDecl()))
  3016. return false;
  3017. // Suppress cases where the '0' value is expanded from a macro.
  3018. if (E->getLocStart().isMacroID())
  3019. return false;
  3020. llvm::APSInt Value;
  3021. return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
  3022. }
  3023. static bool HasEnumType(Expr *E) {
  3024. // Strip off implicit integral promotions.
  3025. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3026. if (ICE->getCastKind() != CK_IntegralCast &&
  3027. ICE->getCastKind() != CK_NoOp)
  3028. break;
  3029. E = ICE->getSubExpr();
  3030. }
  3031. return E->getType()->isEnumeralType();
  3032. }
  3033. void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
  3034. BinaryOperatorKind op = E->getOpcode();
  3035. if (E->isValueDependent())
  3036. return;
  3037. if (op == BO_LT && IsZero(S, E->getRHS())) {
  3038. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  3039. << "< 0" << "false" << HasEnumType(E->getLHS())
  3040. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3041. } else if (op == BO_GE && IsZero(S, E->getRHS())) {
  3042. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  3043. << ">= 0" << "true" << HasEnumType(E->getLHS())
  3044. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3045. } else if (op == BO_GT && IsZero(S, E->getLHS())) {
  3046. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  3047. << "0 >" << "false" << HasEnumType(E->getRHS())
  3048. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3049. } else if (op == BO_LE && IsZero(S, E->getLHS())) {
  3050. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  3051. << "0 <=" << "true" << HasEnumType(E->getRHS())
  3052. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3053. }
  3054. }
  3055. /// Analyze the operands of the given comparison. Implements the
  3056. /// fallback case from AnalyzeComparison.
  3057. void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  3058. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  3059. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  3060. }
  3061. /// \brief Implements -Wsign-compare.
  3062. ///
  3063. /// \param E the binary operator to check for warnings
  3064. void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  3065. // The type the comparison is being performed in.
  3066. QualType T = E->getLHS()->getType();
  3067. assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
  3068. && "comparison with mismatched types");
  3069. // We don't do anything special if this isn't an unsigned integral
  3070. // comparison: we're only interested in integral comparisons, and
  3071. // signed comparisons only happen in cases we don't care to warn about.
  3072. //
  3073. // We also don't care about value-dependent expressions or expressions
  3074. // whose result is a constant.
  3075. if (!T->hasUnsignedIntegerRepresentation()
  3076. || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
  3077. return AnalyzeImpConvsInComparison(S, E);
  3078. Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
  3079. Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
  3080. // Check to see if one of the (unmodified) operands is of different
  3081. // signedness.
  3082. Expr *signedOperand, *unsignedOperand;
  3083. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  3084. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  3085. "unsigned comparison between two signed integer expressions?");
  3086. signedOperand = LHS;
  3087. unsignedOperand = RHS;
  3088. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  3089. signedOperand = RHS;
  3090. unsignedOperand = LHS;
  3091. } else {
  3092. CheckTrivialUnsignedComparison(S, E);
  3093. return AnalyzeImpConvsInComparison(S, E);
  3094. }
  3095. // Otherwise, calculate the effective range of the signed operand.
  3096. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  3097. // Go ahead and analyze implicit conversions in the operands. Note
  3098. // that we skip the implicit conversions on both sides.
  3099. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  3100. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  3101. // If the signed range is non-negative, -Wsign-compare won't fire,
  3102. // but we should still check for comparisons which are always true
  3103. // or false.
  3104. if (signedRange.NonNegative)
  3105. return CheckTrivialUnsignedComparison(S, E);
  3106. // For (in)equality comparisons, if the unsigned operand is a
  3107. // constant which cannot collide with a overflowed signed operand,
  3108. // then reinterpreting the signed operand as unsigned will not
  3109. // change the result of the comparison.
  3110. if (E->isEqualityOp()) {
  3111. unsigned comparisonWidth = S.Context.getIntWidth(T);
  3112. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  3113. // We should never be unable to prove that the unsigned operand is
  3114. // non-negative.
  3115. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  3116. if (unsignedRange.Width < comparisonWidth)
  3117. return;
  3118. }
  3119. S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
  3120. << LHS->getType() << RHS->getType()
  3121. << LHS->getSourceRange() << RHS->getSourceRange();
  3122. }
  3123. /// Analyzes an attempt to assign the given value to a bitfield.
  3124. ///
  3125. /// Returns true if there was something fishy about the attempt.
  3126. bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  3127. SourceLocation InitLoc) {
  3128. assert(Bitfield->isBitField());
  3129. if (Bitfield->isInvalidDecl())
  3130. return false;
  3131. // White-list bool bitfields.
  3132. if (Bitfield->getType()->isBooleanType())
  3133. return false;
  3134. // Ignore value- or type-dependent expressions.
  3135. if (Bitfield->getBitWidth()->isValueDependent() ||
  3136. Bitfield->getBitWidth()->isTypeDependent() ||
  3137. Init->isValueDependent() ||
  3138. Init->isTypeDependent())
  3139. return false;
  3140. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  3141. Expr::EvalResult InitValue;
  3142. if (!OriginalInit->EvaluateAsRValue(InitValue, S.Context) ||
  3143. !InitValue.Val.isInt())
  3144. return false;
  3145. const llvm::APSInt &Value = InitValue.Val.getInt();
  3146. unsigned OriginalWidth = Value.getBitWidth();
  3147. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  3148. if (OriginalWidth <= FieldWidth)
  3149. return false;
  3150. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  3151. // It's fairly common to write values into signed bitfields
  3152. // that, if sign-extended, would end up becoming a different
  3153. // value. We don't want to warn about that.
  3154. if (Value.isSigned() && Value.isNegative())
  3155. TruncatedValue = TruncatedValue.sext(OriginalWidth);
  3156. else
  3157. TruncatedValue = TruncatedValue.zext(OriginalWidth);
  3158. if (Value == TruncatedValue)
  3159. return false;
  3160. std::string PrettyValue = Value.toString(10);
  3161. std::string PrettyTrunc = TruncatedValue.toString(10);
  3162. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  3163. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  3164. << Init->getSourceRange();
  3165. return true;
  3166. }
  3167. /// Analyze the given simple or compound assignment for warning-worthy
  3168. /// operations.
  3169. void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  3170. // Just recurse on the LHS.
  3171. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  3172. // We want to recurse on the RHS as normal unless we're assigning to
  3173. // a bitfield.
  3174. if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
  3175. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  3176. E->getOperatorLoc())) {
  3177. // Recurse, ignoring any implicit conversions on the RHS.
  3178. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  3179. E->getOperatorLoc());
  3180. }
  3181. }
  3182. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  3183. }
  3184. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  3185. void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  3186. SourceLocation CContext, unsigned diag) {
  3187. S.Diag(E->getExprLoc(), diag)
  3188. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  3189. }
  3190. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  3191. void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
  3192. unsigned diag) {
  3193. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
  3194. }
  3195. /// Diagnose an implicit cast from a literal expression. Does not warn when the
  3196. /// cast wouldn't lose information.
  3197. void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
  3198. SourceLocation CContext) {
  3199. // Try to convert the literal exactly to an integer. If we can, don't warn.
  3200. bool isExact = false;
  3201. const llvm::APFloat &Value = FL->getValue();
  3202. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  3203. T->hasUnsignedIntegerRepresentation());
  3204. if (Value.convertToInteger(IntegerValue,
  3205. llvm::APFloat::rmTowardZero, &isExact)
  3206. == llvm::APFloat::opOK && isExact)
  3207. return;
  3208. S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
  3209. << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
  3210. }
  3211. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  3212. if (!Range.Width) return "0";
  3213. llvm::APSInt ValueInRange = Value;
  3214. ValueInRange.setIsSigned(!Range.NonNegative);
  3215. ValueInRange = ValueInRange.trunc(Range.Width);
  3216. return ValueInRange.toString(10);
  3217. }
  3218. static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
  3219. SourceManager &smgr = S.Context.getSourceManager();
  3220. return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
  3221. }
  3222. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  3223. SourceLocation CC, bool *ICContext = 0) {
  3224. if (E->isTypeDependent() || E->isValueDependent()) return;
  3225. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  3226. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  3227. if (Source == Target) return;
  3228. if (Target->isDependentType()) return;
  3229. // If the conversion context location is invalid don't complain. We also
  3230. // don't want to emit a warning if the issue occurs from the expansion of
  3231. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  3232. // delay this check as long as possible. Once we detect we are in that
  3233. // scenario, we just return.
  3234. if (CC.isInvalid())
  3235. return;
  3236. // Diagnose implicit casts to bool.
  3237. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  3238. if (isa<StringLiteral>(E))
  3239. // Warn on string literal to bool. Checks for string literals in logical
  3240. // expressions, for instances, assert(0 && "error here"), is prevented
  3241. // by a check in AnalyzeImplicitConversions().
  3242. return DiagnoseImpCast(S, E, T, CC,
  3243. diag::warn_impcast_string_literal_to_bool);
  3244. if (Source->isFunctionType()) {
  3245. // Warn on function to bool. Checks free functions and static member
  3246. // functions. Weakly imported functions are excluded from the check,
  3247. // since it's common to test their value to check whether the linker
  3248. // found a definition for them.
  3249. ValueDecl *D = 0;
  3250. if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
  3251. D = R->getDecl();
  3252. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  3253. D = M->getMemberDecl();
  3254. }
  3255. if (D && !D->isWeak()) {
  3256. if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
  3257. S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
  3258. << F << E->getSourceRange() << SourceRange(CC);
  3259. return;
  3260. }
  3261. }
  3262. }
  3263. return; // Other casts to bool are not checked.
  3264. }
  3265. // Strip vector types.
  3266. if (isa<VectorType>(Source)) {
  3267. if (!isa<VectorType>(Target)) {
  3268. if (isFromSystemMacro(S, CC))
  3269. return;
  3270. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  3271. }
  3272. // If the vector cast is cast between two vectors of the same size, it is
  3273. // a bitcast, not a conversion.
  3274. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  3275. return;
  3276. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  3277. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  3278. }
  3279. // Strip complex types.
  3280. if (isa<ComplexType>(Source)) {
  3281. if (!isa<ComplexType>(Target)) {
  3282. if (isFromSystemMacro(S, CC))
  3283. return;
  3284. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
  3285. }
  3286. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  3287. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  3288. }
  3289. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  3290. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  3291. // If the source is floating point...
  3292. if (SourceBT && SourceBT->isFloatingPoint()) {
  3293. // ...and the target is floating point...
  3294. if (TargetBT && TargetBT->isFloatingPoint()) {
  3295. // ...then warn if we're dropping FP rank.
  3296. // Builtin FP kinds are ordered by increasing FP rank.
  3297. if (SourceBT->getKind() > TargetBT->getKind()) {
  3298. // Don't warn about float constants that are precisely
  3299. // representable in the target type.
  3300. Expr::EvalResult result;
  3301. if (E->EvaluateAsRValue(result, S.Context)) {
  3302. // Value might be a float, a float vector, or a float complex.
  3303. if (IsSameFloatAfterCast(result.Val,
  3304. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  3305. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  3306. return;
  3307. }
  3308. if (isFromSystemMacro(S, CC))
  3309. return;
  3310. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  3311. }
  3312. return;
  3313. }
  3314. // If the target is integral, always warn.
  3315. if ((TargetBT && TargetBT->isInteger())) {
  3316. if (isFromSystemMacro(S, CC))
  3317. return;
  3318. Expr *InnerE = E->IgnoreParenImpCasts();
  3319. // We also want to warn on, e.g., "int i = -1.234"
  3320. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  3321. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  3322. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  3323. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
  3324. DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
  3325. } else {
  3326. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
  3327. }
  3328. }
  3329. return;
  3330. }
  3331. if (!Source->isIntegerType() || !Target->isIntegerType())
  3332. return;
  3333. if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
  3334. == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
  3335. S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
  3336. << E->getSourceRange() << clang::SourceRange(CC);
  3337. return;
  3338. }
  3339. IntRange SourceRange = GetExprRange(S.Context, E);
  3340. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  3341. if (SourceRange.Width > TargetRange.Width) {
  3342. // If the source is a constant, use a default-on diagnostic.
  3343. // TODO: this should happen for bitfield stores, too.
  3344. llvm::APSInt Value(32);
  3345. if (E->isIntegerConstantExpr(Value, S.Context)) {
  3346. if (isFromSystemMacro(S, CC))
  3347. return;
  3348. std::string PrettySourceValue = Value.toString(10);
  3349. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  3350. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  3351. S.PDiag(diag::warn_impcast_integer_precision_constant)
  3352. << PrettySourceValue << PrettyTargetValue
  3353. << E->getType() << T << E->getSourceRange()
  3354. << clang::SourceRange(CC));
  3355. return;
  3356. }
  3357. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  3358. if (isFromSystemMacro(S, CC))
  3359. return;
  3360. if (SourceRange.Width == 64 && TargetRange.Width == 32)
  3361. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
  3362. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  3363. }
  3364. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  3365. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  3366. SourceRange.Width == TargetRange.Width)) {
  3367. if (isFromSystemMacro(S, CC))
  3368. return;
  3369. unsigned DiagID = diag::warn_impcast_integer_sign;
  3370. // Traditionally, gcc has warned about this under -Wsign-compare.
  3371. // We also want to warn about it in -Wconversion.
  3372. // So if -Wconversion is off, use a completely identical diagnostic
  3373. // in the sign-compare group.
  3374. // The conditional-checking code will
  3375. if (ICContext) {
  3376. DiagID = diag::warn_impcast_integer_sign_conditional;
  3377. *ICContext = true;
  3378. }
  3379. return DiagnoseImpCast(S, E, T, CC, DiagID);
  3380. }
  3381. // Diagnose conversions between different enumeration types.
  3382. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  3383. // type, to give us better diagnostics.
  3384. QualType SourceType = E->getType();
  3385. if (!S.getLangOptions().CPlusPlus) {
  3386. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  3387. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  3388. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  3389. SourceType = S.Context.getTypeDeclType(Enum);
  3390. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  3391. }
  3392. }
  3393. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  3394. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  3395. if ((SourceEnum->getDecl()->getIdentifier() ||
  3396. SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  3397. (TargetEnum->getDecl()->getIdentifier() ||
  3398. TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  3399. SourceEnum != TargetEnum) {
  3400. if (isFromSystemMacro(S, CC))
  3401. return;
  3402. return DiagnoseImpCast(S, E, SourceType, T, CC,
  3403. diag::warn_impcast_different_enum_types);
  3404. }
  3405. return;
  3406. }
  3407. void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
  3408. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  3409. SourceLocation CC, bool &ICContext) {
  3410. E = E->IgnoreParenImpCasts();
  3411. if (isa<ConditionalOperator>(E))
  3412. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
  3413. AnalyzeImplicitConversions(S, E, CC);
  3414. if (E->getType() != T)
  3415. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  3416. return;
  3417. }
  3418. void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
  3419. SourceLocation CC = E->getQuestionLoc();
  3420. AnalyzeImplicitConversions(S, E->getCond(), CC);
  3421. bool Suspicious = false;
  3422. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  3423. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  3424. // If -Wconversion would have warned about either of the candidates
  3425. // for a signedness conversion to the context type...
  3426. if (!Suspicious) return;
  3427. // ...but it's currently ignored...
  3428. if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
  3429. CC))
  3430. return;
  3431. // ...then check whether it would have warned about either of the
  3432. // candidates for a signedness conversion to the condition type.
  3433. if (E->getType() == T) return;
  3434. Suspicious = false;
  3435. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  3436. E->getType(), CC, &Suspicious);
  3437. if (!Suspicious)
  3438. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  3439. E->getType(), CC, &Suspicious);
  3440. }
  3441. /// AnalyzeImplicitConversions - Find and report any interesting
  3442. /// implicit conversions in the given expression. There are a couple
  3443. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  3444. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  3445. QualType T = OrigE->getType();
  3446. Expr *E = OrigE->IgnoreParenImpCasts();
  3447. if (E->isTypeDependent() || E->isValueDependent())
  3448. return;
  3449. // For conditional operators, we analyze the arguments as if they
  3450. // were being fed directly into the output.
  3451. if (isa<ConditionalOperator>(E)) {
  3452. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  3453. CheckConditionalOperator(S, CO, T);
  3454. return;
  3455. }
  3456. // Go ahead and check any implicit conversions we might have skipped.
  3457. // The non-canonical typecheck is just an optimization;
  3458. // CheckImplicitConversion will filter out dead implicit conversions.
  3459. if (E->getType() != T)
  3460. CheckImplicitConversion(S, E, T, CC);
  3461. // Now continue drilling into this expression.
  3462. // Skip past explicit casts.
  3463. if (isa<ExplicitCastExpr>(E)) {
  3464. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  3465. return AnalyzeImplicitConversions(S, E, CC);
  3466. }
  3467. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3468. // Do a somewhat different check with comparison operators.
  3469. if (BO->isComparisonOp())
  3470. return AnalyzeComparison(S, BO);
  3471. // And with assignments and compound assignments.
  3472. if (BO->isAssignmentOp())
  3473. return AnalyzeAssignment(S, BO);
  3474. }
  3475. // These break the otherwise-useful invariant below. Fortunately,
  3476. // we don't really need to recurse into them, because any internal
  3477. // expressions should have been analyzed already when they were
  3478. // built into statements.
  3479. if (isa<StmtExpr>(E)) return;
  3480. // Don't descend into unevaluated contexts.
  3481. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  3482. // Now just recurse over the expression's children.
  3483. CC = E->getExprLoc();
  3484. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  3485. bool IsLogicalOperator = BO && BO->isLogicalOp();
  3486. for (Stmt::child_range I = E->children(); I; ++I) {
  3487. Expr *ChildExpr = cast<Expr>(*I);
  3488. if (IsLogicalOperator &&
  3489. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  3490. // Ignore checking string literals that are in logical operators.
  3491. continue;
  3492. AnalyzeImplicitConversions(S, ChildExpr, CC);
  3493. }
  3494. }
  3495. } // end anonymous namespace
  3496. /// Diagnoses "dangerous" implicit conversions within the given
  3497. /// expression (which is a full expression). Implements -Wconversion
  3498. /// and -Wsign-compare.
  3499. ///
  3500. /// \param CC the "context" location of the implicit conversion, i.e.
  3501. /// the most location of the syntactic entity requiring the implicit
  3502. /// conversion
  3503. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  3504. // Don't diagnose in unevaluated contexts.
  3505. if (ExprEvalContexts.back().Context == Sema::Unevaluated)
  3506. return;
  3507. // Don't diagnose for value- or type-dependent expressions.
  3508. if (E->isTypeDependent() || E->isValueDependent())
  3509. return;
  3510. // Check for array bounds violations in cases where the check isn't triggered
  3511. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  3512. // ArraySubscriptExpr is on the RHS of a variable initialization.
  3513. CheckArrayAccess(E);
  3514. // This is not the right CC for (e.g.) a variable initialization.
  3515. AnalyzeImplicitConversions(*this, E, CC);
  3516. }
  3517. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  3518. FieldDecl *BitField,
  3519. Expr *Init) {
  3520. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  3521. }
  3522. /// CheckParmsForFunctionDef - Check that the parameters of the given
  3523. /// function are appropriate for the definition of a function. This
  3524. /// takes care of any checks that cannot be performed on the
  3525. /// declaration itself, e.g., that the types of each of the function
  3526. /// parameters are complete.
  3527. bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
  3528. bool CheckParameterNames) {
  3529. bool HasInvalidParm = false;
  3530. for (; P != PEnd; ++P) {
  3531. ParmVarDecl *Param = *P;
  3532. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  3533. // function declarator that is part of a function definition of
  3534. // that function shall not have incomplete type.
  3535. //
  3536. // This is also C++ [dcl.fct]p6.
  3537. if (!Param->isInvalidDecl() &&
  3538. RequireCompleteType(Param->getLocation(), Param->getType(),
  3539. diag::err_typecheck_decl_incomplete_type)) {
  3540. Param->setInvalidDecl();
  3541. HasInvalidParm = true;
  3542. }
  3543. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  3544. // declaration of each parameter shall include an identifier.
  3545. if (CheckParameterNames &&
  3546. Param->getIdentifier() == 0 &&
  3547. !Param->isImplicit() &&
  3548. !getLangOptions().CPlusPlus)
  3549. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  3550. // C99 6.7.5.3p12:
  3551. // If the function declarator is not part of a definition of that
  3552. // function, parameters may have incomplete type and may use the [*]
  3553. // notation in their sequences of declarator specifiers to specify
  3554. // variable length array types.
  3555. QualType PType = Param->getOriginalType();
  3556. if (const ArrayType *AT = Context.getAsArrayType(PType)) {
  3557. if (AT->getSizeModifier() == ArrayType::Star) {
  3558. // FIXME: This diagnosic should point the the '[*]' if source-location
  3559. // information is added for it.
  3560. Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
  3561. }
  3562. }
  3563. }
  3564. return HasInvalidParm;
  3565. }
  3566. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  3567. /// pointer cast increases the alignment requirements.
  3568. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  3569. // This is actually a lot of work to potentially be doing on every
  3570. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  3571. if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
  3572. TRange.getBegin())
  3573. == DiagnosticsEngine::Ignored)
  3574. return;
  3575. // Ignore dependent types.
  3576. if (T->isDependentType() || Op->getType()->isDependentType())
  3577. return;
  3578. // Require that the destination be a pointer type.
  3579. const PointerType *DestPtr = T->getAs<PointerType>();
  3580. if (!DestPtr) return;
  3581. // If the destination has alignment 1, we're done.
  3582. QualType DestPointee = DestPtr->getPointeeType();
  3583. if (DestPointee->isIncompleteType()) return;
  3584. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  3585. if (DestAlign.isOne()) return;
  3586. // Require that the source be a pointer type.
  3587. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  3588. if (!SrcPtr) return;
  3589. QualType SrcPointee = SrcPtr->getPointeeType();
  3590. // Whitelist casts from cv void*. We already implicitly
  3591. // whitelisted casts to cv void*, since they have alignment 1.
  3592. // Also whitelist casts involving incomplete types, which implicitly
  3593. // includes 'void'.
  3594. if (SrcPointee->isIncompleteType()) return;
  3595. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  3596. if (SrcAlign >= DestAlign) return;
  3597. Diag(TRange.getBegin(), diag::warn_cast_align)
  3598. << Op->getType() << T
  3599. << static_cast<unsigned>(SrcAlign.getQuantity())
  3600. << static_cast<unsigned>(DestAlign.getQuantity())
  3601. << TRange << Op->getSourceRange();
  3602. }
  3603. static const Type* getElementType(const Expr *BaseExpr) {
  3604. const Type* EltType = BaseExpr->getType().getTypePtr();
  3605. if (EltType->isAnyPointerType())
  3606. return EltType->getPointeeType().getTypePtr();
  3607. else if (EltType->isArrayType())
  3608. return EltType->getBaseElementTypeUnsafe();
  3609. return EltType;
  3610. }
  3611. /// \brief Check whether this array fits the idiom of a size-one tail padded
  3612. /// array member of a struct.
  3613. ///
  3614. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  3615. /// commonly used to emulate flexible arrays in C89 code.
  3616. static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
  3617. const NamedDecl *ND) {
  3618. if (Size != 1 || !ND) return false;
  3619. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  3620. if (!FD) return false;
  3621. // Don't consider sizes resulting from macro expansions or template argument
  3622. // substitution to form C89 tail-padded arrays.
  3623. ConstantArrayTypeLoc TL =
  3624. cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
  3625. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
  3626. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  3627. return false;
  3628. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  3629. if (!RD) return false;
  3630. if (RD->isUnion()) return false;
  3631. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  3632. if (!CRD->isStandardLayout()) return false;
  3633. }
  3634. // See if this is the last field decl in the record.
  3635. const Decl *D = FD;
  3636. while ((D = D->getNextDeclInContext()))
  3637. if (isa<FieldDecl>(D))
  3638. return false;
  3639. return true;
  3640. }
  3641. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  3642. bool isSubscript, bool AllowOnePastEnd) {
  3643. const Type* EffectiveType = getElementType(BaseExpr);
  3644. BaseExpr = BaseExpr->IgnoreParenCasts();
  3645. IndexExpr = IndexExpr->IgnoreParenCasts();
  3646. const ConstantArrayType *ArrayTy =
  3647. Context.getAsConstantArrayType(BaseExpr->getType());
  3648. if (!ArrayTy)
  3649. return;
  3650. if (IndexExpr->isValueDependent())
  3651. return;
  3652. llvm::APSInt index;
  3653. if (!IndexExpr->isIntegerConstantExpr(index, Context))
  3654. return;
  3655. const NamedDecl *ND = NULL;
  3656. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  3657. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  3658. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  3659. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  3660. if (index.isUnsigned() || !index.isNegative()) {
  3661. llvm::APInt size = ArrayTy->getSize();
  3662. if (!size.isStrictlyPositive())
  3663. return;
  3664. const Type* BaseType = getElementType(BaseExpr);
  3665. if (BaseType != EffectiveType) {
  3666. // Make sure we're comparing apples to apples when comparing index to size
  3667. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  3668. uint64_t array_typesize = Context.getTypeSize(BaseType);
  3669. // Handle ptrarith_typesize being zero, such as when casting to void*
  3670. if (!ptrarith_typesize) ptrarith_typesize = 1;
  3671. if (ptrarith_typesize != array_typesize) {
  3672. // There's a cast to a different size type involved
  3673. uint64_t ratio = array_typesize / ptrarith_typesize;
  3674. // TODO: Be smarter about handling cases where array_typesize is not a
  3675. // multiple of ptrarith_typesize
  3676. if (ptrarith_typesize * ratio == array_typesize)
  3677. size *= llvm::APInt(size.getBitWidth(), ratio);
  3678. }
  3679. }
  3680. if (size.getBitWidth() > index.getBitWidth())
  3681. index = index.sext(size.getBitWidth());
  3682. else if (size.getBitWidth() < index.getBitWidth())
  3683. size = size.sext(index.getBitWidth());
  3684. // For array subscripting the index must be less than size, but for pointer
  3685. // arithmetic also allow the index (offset) to be equal to size since
  3686. // computing the next address after the end of the array is legal and
  3687. // commonly done e.g. in C++ iterators and range-based for loops.
  3688. if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
  3689. return;
  3690. // Also don't warn for arrays of size 1 which are members of some
  3691. // structure. These are often used to approximate flexible arrays in C89
  3692. // code.
  3693. if (IsTailPaddedMemberArray(*this, size, ND))
  3694. return;
  3695. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  3696. if (isSubscript)
  3697. DiagID = diag::warn_array_index_exceeds_bounds;
  3698. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  3699. PDiag(DiagID) << index.toString(10, true)
  3700. << size.toString(10, true)
  3701. << (unsigned)size.getLimitedValue(~0U)
  3702. << IndexExpr->getSourceRange());
  3703. } else {
  3704. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  3705. if (!isSubscript) {
  3706. DiagID = diag::warn_ptr_arith_precedes_bounds;
  3707. if (index.isNegative()) index = -index;
  3708. }
  3709. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  3710. PDiag(DiagID) << index.toString(10, true)
  3711. << IndexExpr->getSourceRange());
  3712. }
  3713. if (!ND) {
  3714. // Try harder to find a NamedDecl to point at in the note.
  3715. while (const ArraySubscriptExpr *ASE =
  3716. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  3717. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  3718. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  3719. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  3720. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  3721. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  3722. }
  3723. if (ND)
  3724. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  3725. PDiag(diag::note_array_index_out_of_bounds)
  3726. << ND->getDeclName());
  3727. }
  3728. void Sema::CheckArrayAccess(const Expr *expr) {
  3729. int AllowOnePastEnd = 0;
  3730. while (expr) {
  3731. expr = expr->IgnoreParenImpCasts();
  3732. switch (expr->getStmtClass()) {
  3733. case Stmt::ArraySubscriptExprClass: {
  3734. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  3735. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
  3736. AllowOnePastEnd > 0);
  3737. return;
  3738. }
  3739. case Stmt::UnaryOperatorClass: {
  3740. // Only unwrap the * and & unary operators
  3741. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  3742. expr = UO->getSubExpr();
  3743. switch (UO->getOpcode()) {
  3744. case UO_AddrOf:
  3745. AllowOnePastEnd++;
  3746. break;
  3747. case UO_Deref:
  3748. AllowOnePastEnd--;
  3749. break;
  3750. default:
  3751. return;
  3752. }
  3753. break;
  3754. }
  3755. case Stmt::ConditionalOperatorClass: {
  3756. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  3757. if (const Expr *lhs = cond->getLHS())
  3758. CheckArrayAccess(lhs);
  3759. if (const Expr *rhs = cond->getRHS())
  3760. CheckArrayAccess(rhs);
  3761. return;
  3762. }
  3763. default:
  3764. return;
  3765. }
  3766. }
  3767. }
  3768. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  3769. namespace {
  3770. struct RetainCycleOwner {
  3771. RetainCycleOwner() : Variable(0), Indirect(false) {}
  3772. VarDecl *Variable;
  3773. SourceRange Range;
  3774. SourceLocation Loc;
  3775. bool Indirect;
  3776. void setLocsFrom(Expr *e) {
  3777. Loc = e->getExprLoc();
  3778. Range = e->getSourceRange();
  3779. }
  3780. };
  3781. }
  3782. /// Consider whether capturing the given variable can possibly lead to
  3783. /// a retain cycle.
  3784. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  3785. // In ARC, it's captured strongly iff the variable has __strong
  3786. // lifetime. In MRR, it's captured strongly if the variable is
  3787. // __block and has an appropriate type.
  3788. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  3789. return false;
  3790. owner.Variable = var;
  3791. owner.setLocsFrom(ref);
  3792. return true;
  3793. }
  3794. static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
  3795. while (true) {
  3796. e = e->IgnoreParens();
  3797. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  3798. switch (cast->getCastKind()) {
  3799. case CK_BitCast:
  3800. case CK_LValueBitCast:
  3801. case CK_LValueToRValue:
  3802. case CK_ARCReclaimReturnedObject:
  3803. e = cast->getSubExpr();
  3804. continue;
  3805. default:
  3806. return false;
  3807. }
  3808. }
  3809. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  3810. ObjCIvarDecl *ivar = ref->getDecl();
  3811. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  3812. return false;
  3813. // Try to find a retain cycle in the base.
  3814. if (!findRetainCycleOwner(ref->getBase(), owner))
  3815. return false;
  3816. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  3817. owner.Indirect = true;
  3818. return true;
  3819. }
  3820. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  3821. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  3822. if (!var) return false;
  3823. return considerVariable(var, ref, owner);
  3824. }
  3825. if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
  3826. owner.Variable = ref->getDecl();
  3827. owner.setLocsFrom(ref);
  3828. return true;
  3829. }
  3830. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  3831. if (member->isArrow()) return false;
  3832. // Don't count this as an indirect ownership.
  3833. e = member->getBase();
  3834. continue;
  3835. }
  3836. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  3837. // Only pay attention to pseudo-objects on property references.
  3838. ObjCPropertyRefExpr *pre
  3839. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  3840. ->IgnoreParens());
  3841. if (!pre) return false;
  3842. if (pre->isImplicitProperty()) return false;
  3843. ObjCPropertyDecl *property = pre->getExplicitProperty();
  3844. if (!property->isRetaining() &&
  3845. !(property->getPropertyIvarDecl() &&
  3846. property->getPropertyIvarDecl()->getType()
  3847. .getObjCLifetime() == Qualifiers::OCL_Strong))
  3848. return false;
  3849. owner.Indirect = true;
  3850. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  3851. ->getSourceExpr());
  3852. continue;
  3853. }
  3854. // Array ivars?
  3855. return false;
  3856. }
  3857. }
  3858. namespace {
  3859. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  3860. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  3861. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  3862. Variable(variable), Capturer(0) {}
  3863. VarDecl *Variable;
  3864. Expr *Capturer;
  3865. void VisitDeclRefExpr(DeclRefExpr *ref) {
  3866. if (ref->getDecl() == Variable && !Capturer)
  3867. Capturer = ref;
  3868. }
  3869. void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
  3870. if (ref->getDecl() == Variable && !Capturer)
  3871. Capturer = ref;
  3872. }
  3873. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  3874. if (Capturer) return;
  3875. Visit(ref->getBase());
  3876. if (Capturer && ref->isFreeIvar())
  3877. Capturer = ref;
  3878. }
  3879. void VisitBlockExpr(BlockExpr *block) {
  3880. // Look inside nested blocks
  3881. if (block->getBlockDecl()->capturesVariable(Variable))
  3882. Visit(block->getBlockDecl()->getBody());
  3883. }
  3884. };
  3885. }
  3886. /// Check whether the given argument is a block which captures a
  3887. /// variable.
  3888. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  3889. assert(owner.Variable && owner.Loc.isValid());
  3890. e = e->IgnoreParenCasts();
  3891. BlockExpr *block = dyn_cast<BlockExpr>(e);
  3892. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  3893. return 0;
  3894. FindCaptureVisitor visitor(S.Context, owner.Variable);
  3895. visitor.Visit(block->getBlockDecl()->getBody());
  3896. return visitor.Capturer;
  3897. }
  3898. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  3899. RetainCycleOwner &owner) {
  3900. assert(capturer);
  3901. assert(owner.Variable && owner.Loc.isValid());
  3902. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  3903. << owner.Variable << capturer->getSourceRange();
  3904. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  3905. << owner.Indirect << owner.Range;
  3906. }
  3907. /// Check for a keyword selector that starts with the word 'add' or
  3908. /// 'set'.
  3909. static bool isSetterLikeSelector(Selector sel) {
  3910. if (sel.isUnarySelector()) return false;
  3911. StringRef str = sel.getNameForSlot(0);
  3912. while (!str.empty() && str.front() == '_') str = str.substr(1);
  3913. if (str.startswith("set"))
  3914. str = str.substr(3);
  3915. else if (str.startswith("add")) {
  3916. // Specially whitelist 'addOperationWithBlock:'.
  3917. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  3918. return false;
  3919. str = str.substr(3);
  3920. }
  3921. else
  3922. return false;
  3923. if (str.empty()) return true;
  3924. return !islower(str.front());
  3925. }
  3926. /// Check a message send to see if it's likely to cause a retain cycle.
  3927. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  3928. // Only check instance methods whose selector looks like a setter.
  3929. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  3930. return;
  3931. // Try to find a variable that the receiver is strongly owned by.
  3932. RetainCycleOwner owner;
  3933. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  3934. if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
  3935. return;
  3936. } else {
  3937. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  3938. owner.Variable = getCurMethodDecl()->getSelfDecl();
  3939. owner.Loc = msg->getSuperLoc();
  3940. owner.Range = msg->getSuperLoc();
  3941. }
  3942. // Check whether the receiver is captured by any of the arguments.
  3943. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  3944. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  3945. return diagnoseRetainCycle(*this, capturer, owner);
  3946. }
  3947. /// Check a property assign to see if it's likely to cause a retain cycle.
  3948. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  3949. RetainCycleOwner owner;
  3950. if (!findRetainCycleOwner(receiver, owner))
  3951. return;
  3952. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  3953. diagnoseRetainCycle(*this, capturer, owner);
  3954. }
  3955. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  3956. QualType LHS, Expr *RHS) {
  3957. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  3958. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  3959. return false;
  3960. // strip off any implicit cast added to get to the one arc-specific
  3961. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  3962. if (cast->getCastKind() == CK_ARCConsumeObject) {
  3963. Diag(Loc, diag::warn_arc_retained_assign)
  3964. << (LT == Qualifiers::OCL_ExplicitNone)
  3965. << RHS->getSourceRange();
  3966. return true;
  3967. }
  3968. RHS = cast->getSubExpr();
  3969. }
  3970. return false;
  3971. }
  3972. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  3973. Expr *LHS, Expr *RHS) {
  3974. QualType LHSType = LHS->getType();
  3975. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  3976. return;
  3977. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  3978. // FIXME. Check for other life times.
  3979. if (LT != Qualifiers::OCL_None)
  3980. return;
  3981. if (ObjCPropertyRefExpr *PRE
  3982. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
  3983. if (PRE->isImplicitProperty())
  3984. return;
  3985. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  3986. if (!PD)
  3987. return;
  3988. unsigned Attributes = PD->getPropertyAttributes();
  3989. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
  3990. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  3991. if (cast->getCastKind() == CK_ARCConsumeObject) {
  3992. Diag(Loc, diag::warn_arc_retained_property_assign)
  3993. << RHS->getSourceRange();
  3994. return;
  3995. }
  3996. RHS = cast->getSubExpr();
  3997. }
  3998. }
  3999. }