SemaChecking.cpp 180 KB

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