SemaType.cpp 162 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367
  1. //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
  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 type-related semantic analysis.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/Sema/Template.h"
  15. #include "clang/Basic/OpenCL.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/ASTMutationListener.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/TypeLoc.h"
  22. #include "clang/AST/TypeLocVisitor.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/Basic/PartialDiagnostic.h"
  25. #include "clang/Basic/TargetInfo.h"
  26. #include "clang/Lex/Preprocessor.h"
  27. #include "clang/Sema/DeclSpec.h"
  28. #include "clang/Sema/DelayedDiagnostic.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. using namespace clang;
  32. /// isOmittedBlockReturnType - Return true if this declarator is missing a
  33. /// return type because this is a omitted return type on a block literal.
  34. static bool isOmittedBlockReturnType(const Declarator &D) {
  35. if (D.getContext() != Declarator::BlockLiteralContext ||
  36. D.getDeclSpec().hasTypeSpecifier())
  37. return false;
  38. if (D.getNumTypeObjects() == 0)
  39. return true; // ^{ ... }
  40. if (D.getNumTypeObjects() == 1 &&
  41. D.getTypeObject(0).Kind == DeclaratorChunk::Function)
  42. return true; // ^(int X, float Y) { ... }
  43. return false;
  44. }
  45. /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
  46. /// doesn't apply to the given type.
  47. static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
  48. QualType type) {
  49. bool useExpansionLoc = false;
  50. unsigned diagID = 0;
  51. switch (attr.getKind()) {
  52. case AttributeList::AT_objc_gc:
  53. diagID = diag::warn_pointer_attribute_wrong_type;
  54. useExpansionLoc = true;
  55. break;
  56. case AttributeList::AT_objc_ownership:
  57. diagID = diag::warn_objc_object_attribute_wrong_type;
  58. useExpansionLoc = true;
  59. break;
  60. default:
  61. // Assume everything else was a function attribute.
  62. diagID = diag::warn_function_attribute_wrong_type;
  63. break;
  64. }
  65. SourceLocation loc = attr.getLoc();
  66. StringRef name = attr.getName()->getName();
  67. // The GC attributes are usually written with macros; special-case them.
  68. if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
  69. if (attr.getParameterName()->isStr("strong")) {
  70. if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
  71. } else if (attr.getParameterName()->isStr("weak")) {
  72. if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
  73. }
  74. }
  75. S.Diag(loc, diagID) << name << type;
  76. }
  77. // objc_gc applies to Objective-C pointers or, otherwise, to the
  78. // smallest available pointer type (i.e. 'void*' in 'void**').
  79. #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
  80. case AttributeList::AT_objc_gc: \
  81. case AttributeList::AT_objc_ownership
  82. // Function type attributes.
  83. #define FUNCTION_TYPE_ATTRS_CASELIST \
  84. case AttributeList::AT_noreturn: \
  85. case AttributeList::AT_cdecl: \
  86. case AttributeList::AT_fastcall: \
  87. case AttributeList::AT_stdcall: \
  88. case AttributeList::AT_thiscall: \
  89. case AttributeList::AT_pascal: \
  90. case AttributeList::AT_regparm: \
  91. case AttributeList::AT_pcs \
  92. namespace {
  93. /// An object which stores processing state for the entire
  94. /// GetTypeForDeclarator process.
  95. class TypeProcessingState {
  96. Sema &sema;
  97. /// The declarator being processed.
  98. Declarator &declarator;
  99. /// The index of the declarator chunk we're currently processing.
  100. /// May be the total number of valid chunks, indicating the
  101. /// DeclSpec.
  102. unsigned chunkIndex;
  103. /// Whether there are non-trivial modifications to the decl spec.
  104. bool trivial;
  105. /// Whether we saved the attributes in the decl spec.
  106. bool hasSavedAttrs;
  107. /// The original set of attributes on the DeclSpec.
  108. SmallVector<AttributeList*, 2> savedAttrs;
  109. /// A list of attributes to diagnose the uselessness of when the
  110. /// processing is complete.
  111. SmallVector<AttributeList*, 2> ignoredTypeAttrs;
  112. public:
  113. TypeProcessingState(Sema &sema, Declarator &declarator)
  114. : sema(sema), declarator(declarator),
  115. chunkIndex(declarator.getNumTypeObjects()),
  116. trivial(true), hasSavedAttrs(false) {}
  117. Sema &getSema() const {
  118. return sema;
  119. }
  120. Declarator &getDeclarator() const {
  121. return declarator;
  122. }
  123. unsigned getCurrentChunkIndex() const {
  124. return chunkIndex;
  125. }
  126. void setCurrentChunkIndex(unsigned idx) {
  127. assert(idx <= declarator.getNumTypeObjects());
  128. chunkIndex = idx;
  129. }
  130. AttributeList *&getCurrentAttrListRef() const {
  131. assert(chunkIndex <= declarator.getNumTypeObjects());
  132. if (chunkIndex == declarator.getNumTypeObjects())
  133. return getMutableDeclSpec().getAttributes().getListRef();
  134. return declarator.getTypeObject(chunkIndex).getAttrListRef();
  135. }
  136. /// Save the current set of attributes on the DeclSpec.
  137. void saveDeclSpecAttrs() {
  138. // Don't try to save them multiple times.
  139. if (hasSavedAttrs) return;
  140. DeclSpec &spec = getMutableDeclSpec();
  141. for (AttributeList *attr = spec.getAttributes().getList(); attr;
  142. attr = attr->getNext())
  143. savedAttrs.push_back(attr);
  144. trivial &= savedAttrs.empty();
  145. hasSavedAttrs = true;
  146. }
  147. /// Record that we had nowhere to put the given type attribute.
  148. /// We will diagnose such attributes later.
  149. void addIgnoredTypeAttr(AttributeList &attr) {
  150. ignoredTypeAttrs.push_back(&attr);
  151. }
  152. /// Diagnose all the ignored type attributes, given that the
  153. /// declarator worked out to the given type.
  154. void diagnoseIgnoredTypeAttrs(QualType type) const {
  155. for (SmallVectorImpl<AttributeList*>::const_iterator
  156. i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
  157. i != e; ++i)
  158. diagnoseBadTypeAttribute(getSema(), **i, type);
  159. }
  160. ~TypeProcessingState() {
  161. if (trivial) return;
  162. restoreDeclSpecAttrs();
  163. }
  164. private:
  165. DeclSpec &getMutableDeclSpec() const {
  166. return const_cast<DeclSpec&>(declarator.getDeclSpec());
  167. }
  168. void restoreDeclSpecAttrs() {
  169. assert(hasSavedAttrs);
  170. if (savedAttrs.empty()) {
  171. getMutableDeclSpec().getAttributes().set(0);
  172. return;
  173. }
  174. getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
  175. for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
  176. savedAttrs[i]->setNext(savedAttrs[i+1]);
  177. savedAttrs.back()->setNext(0);
  178. }
  179. };
  180. /// Basically std::pair except that we really want to avoid an
  181. /// implicit operator= for safety concerns. It's also a minor
  182. /// link-time optimization for this to be a private type.
  183. struct AttrAndList {
  184. /// The attribute.
  185. AttributeList &first;
  186. /// The head of the list the attribute is currently in.
  187. AttributeList *&second;
  188. AttrAndList(AttributeList &attr, AttributeList *&head)
  189. : first(attr), second(head) {}
  190. };
  191. }
  192. namespace llvm {
  193. template <> struct isPodLike<AttrAndList> {
  194. static const bool value = true;
  195. };
  196. }
  197. static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
  198. attr.setNext(head);
  199. head = &attr;
  200. }
  201. static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
  202. if (head == &attr) {
  203. head = attr.getNext();
  204. return;
  205. }
  206. AttributeList *cur = head;
  207. while (true) {
  208. assert(cur && cur->getNext() && "ran out of attrs?");
  209. if (cur->getNext() == &attr) {
  210. cur->setNext(attr.getNext());
  211. return;
  212. }
  213. cur = cur->getNext();
  214. }
  215. }
  216. static void moveAttrFromListToList(AttributeList &attr,
  217. AttributeList *&fromList,
  218. AttributeList *&toList) {
  219. spliceAttrOutOfList(attr, fromList);
  220. spliceAttrIntoList(attr, toList);
  221. }
  222. static void processTypeAttrs(TypeProcessingState &state,
  223. QualType &type, bool isDeclSpec,
  224. AttributeList *attrs);
  225. static bool handleFunctionTypeAttr(TypeProcessingState &state,
  226. AttributeList &attr,
  227. QualType &type);
  228. static bool handleObjCGCTypeAttr(TypeProcessingState &state,
  229. AttributeList &attr, QualType &type);
  230. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
  231. AttributeList &attr, QualType &type);
  232. static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
  233. AttributeList &attr, QualType &type) {
  234. if (attr.getKind() == AttributeList::AT_objc_gc)
  235. return handleObjCGCTypeAttr(state, attr, type);
  236. assert(attr.getKind() == AttributeList::AT_objc_ownership);
  237. return handleObjCOwnershipTypeAttr(state, attr, type);
  238. }
  239. /// Given that an objc_gc attribute was written somewhere on a
  240. /// declaration *other* than on the declarator itself (for which, use
  241. /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
  242. /// didn't apply in whatever position it was written in, try to move
  243. /// it to a more appropriate position.
  244. static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
  245. AttributeList &attr,
  246. QualType type) {
  247. Declarator &declarator = state.getDeclarator();
  248. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  249. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  250. switch (chunk.Kind) {
  251. case DeclaratorChunk::Pointer:
  252. case DeclaratorChunk::BlockPointer:
  253. moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
  254. chunk.getAttrListRef());
  255. return;
  256. case DeclaratorChunk::Paren:
  257. case DeclaratorChunk::Array:
  258. continue;
  259. // Don't walk through these.
  260. case DeclaratorChunk::Reference:
  261. case DeclaratorChunk::Function:
  262. case DeclaratorChunk::MemberPointer:
  263. goto error;
  264. }
  265. }
  266. error:
  267. diagnoseBadTypeAttribute(state.getSema(), attr, type);
  268. }
  269. /// Distribute an objc_gc type attribute that was written on the
  270. /// declarator.
  271. static void
  272. distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
  273. AttributeList &attr,
  274. QualType &declSpecType) {
  275. Declarator &declarator = state.getDeclarator();
  276. // objc_gc goes on the innermost pointer to something that's not a
  277. // pointer.
  278. unsigned innermost = -1U;
  279. bool considerDeclSpec = true;
  280. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  281. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  282. switch (chunk.Kind) {
  283. case DeclaratorChunk::Pointer:
  284. case DeclaratorChunk::BlockPointer:
  285. innermost = i;
  286. continue;
  287. case DeclaratorChunk::Reference:
  288. case DeclaratorChunk::MemberPointer:
  289. case DeclaratorChunk::Paren:
  290. case DeclaratorChunk::Array:
  291. continue;
  292. case DeclaratorChunk::Function:
  293. considerDeclSpec = false;
  294. goto done;
  295. }
  296. }
  297. done:
  298. // That might actually be the decl spec if we weren't blocked by
  299. // anything in the declarator.
  300. if (considerDeclSpec) {
  301. if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
  302. // Splice the attribute into the decl spec. Prevents the
  303. // attribute from being applied multiple times and gives
  304. // the source-location-filler something to work with.
  305. state.saveDeclSpecAttrs();
  306. moveAttrFromListToList(attr, declarator.getAttrListRef(),
  307. declarator.getMutableDeclSpec().getAttributes().getListRef());
  308. return;
  309. }
  310. }
  311. // Otherwise, if we found an appropriate chunk, splice the attribute
  312. // into it.
  313. if (innermost != -1U) {
  314. moveAttrFromListToList(attr, declarator.getAttrListRef(),
  315. declarator.getTypeObject(innermost).getAttrListRef());
  316. return;
  317. }
  318. // Otherwise, diagnose when we're done building the type.
  319. spliceAttrOutOfList(attr, declarator.getAttrListRef());
  320. state.addIgnoredTypeAttr(attr);
  321. }
  322. /// A function type attribute was written somewhere in a declaration
  323. /// *other* than on the declarator itself or in the decl spec. Given
  324. /// that it didn't apply in whatever position it was written in, try
  325. /// to move it to a more appropriate position.
  326. static void distributeFunctionTypeAttr(TypeProcessingState &state,
  327. AttributeList &attr,
  328. QualType type) {
  329. Declarator &declarator = state.getDeclarator();
  330. // Try to push the attribute from the return type of a function to
  331. // the function itself.
  332. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  333. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  334. switch (chunk.Kind) {
  335. case DeclaratorChunk::Function:
  336. moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
  337. chunk.getAttrListRef());
  338. return;
  339. case DeclaratorChunk::Paren:
  340. case DeclaratorChunk::Pointer:
  341. case DeclaratorChunk::BlockPointer:
  342. case DeclaratorChunk::Array:
  343. case DeclaratorChunk::Reference:
  344. case DeclaratorChunk::MemberPointer:
  345. continue;
  346. }
  347. }
  348. diagnoseBadTypeAttribute(state.getSema(), attr, type);
  349. }
  350. /// Try to distribute a function type attribute to the innermost
  351. /// function chunk or type. Returns true if the attribute was
  352. /// distributed, false if no location was found.
  353. static bool
  354. distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
  355. AttributeList &attr,
  356. AttributeList *&attrList,
  357. QualType &declSpecType) {
  358. Declarator &declarator = state.getDeclarator();
  359. // Put it on the innermost function chunk, if there is one.
  360. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  361. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  362. if (chunk.Kind != DeclaratorChunk::Function) continue;
  363. moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
  364. return true;
  365. }
  366. if (handleFunctionTypeAttr(state, attr, declSpecType)) {
  367. spliceAttrOutOfList(attr, attrList);
  368. return true;
  369. }
  370. return false;
  371. }
  372. /// A function type attribute was written in the decl spec. Try to
  373. /// apply it somewhere.
  374. static void
  375. distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
  376. AttributeList &attr,
  377. QualType &declSpecType) {
  378. state.saveDeclSpecAttrs();
  379. // Try to distribute to the innermost.
  380. if (distributeFunctionTypeAttrToInnermost(state, attr,
  381. state.getCurrentAttrListRef(),
  382. declSpecType))
  383. return;
  384. // If that failed, diagnose the bad attribute when the declarator is
  385. // fully built.
  386. state.addIgnoredTypeAttr(attr);
  387. }
  388. /// A function type attribute was written on the declarator. Try to
  389. /// apply it somewhere.
  390. static void
  391. distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
  392. AttributeList &attr,
  393. QualType &declSpecType) {
  394. Declarator &declarator = state.getDeclarator();
  395. // Try to distribute to the innermost.
  396. if (distributeFunctionTypeAttrToInnermost(state, attr,
  397. declarator.getAttrListRef(),
  398. declSpecType))
  399. return;
  400. // If that failed, diagnose the bad attribute when the declarator is
  401. // fully built.
  402. spliceAttrOutOfList(attr, declarator.getAttrListRef());
  403. state.addIgnoredTypeAttr(attr);
  404. }
  405. /// \brief Given that there are attributes written on the declarator
  406. /// itself, try to distribute any type attributes to the appropriate
  407. /// declarator chunk.
  408. ///
  409. /// These are attributes like the following:
  410. /// int f ATTR;
  411. /// int (f ATTR)();
  412. /// but not necessarily this:
  413. /// int f() ATTR;
  414. static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
  415. QualType &declSpecType) {
  416. // Collect all the type attributes from the declarator itself.
  417. assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
  418. AttributeList *attr = state.getDeclarator().getAttributes();
  419. AttributeList *next;
  420. do {
  421. next = attr->getNext();
  422. switch (attr->getKind()) {
  423. OBJC_POINTER_TYPE_ATTRS_CASELIST:
  424. distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
  425. break;
  426. case AttributeList::AT_ns_returns_retained:
  427. if (!state.getSema().getLangOptions().ObjCAutoRefCount)
  428. break;
  429. // fallthrough
  430. FUNCTION_TYPE_ATTRS_CASELIST:
  431. distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
  432. break;
  433. default:
  434. break;
  435. }
  436. } while ((attr = next));
  437. }
  438. /// Add a synthetic '()' to a block-literal declarator if it is
  439. /// required, given the return type.
  440. static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
  441. QualType declSpecType) {
  442. Declarator &declarator = state.getDeclarator();
  443. // First, check whether the declarator would produce a function,
  444. // i.e. whether the innermost semantic chunk is a function.
  445. if (declarator.isFunctionDeclarator()) {
  446. // If so, make that declarator a prototyped declarator.
  447. declarator.getFunctionTypeInfo().hasPrototype = true;
  448. return;
  449. }
  450. // If there are any type objects, the type as written won't name a
  451. // function, regardless of the decl spec type. This is because a
  452. // block signature declarator is always an abstract-declarator, and
  453. // abstract-declarators can't just be parentheses chunks. Therefore
  454. // we need to build a function chunk unless there are no type
  455. // objects and the decl spec type is a function.
  456. if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
  457. return;
  458. // Note that there *are* cases with invalid declarators where
  459. // declarators consist solely of parentheses. In general, these
  460. // occur only in failed efforts to make function declarators, so
  461. // faking up the function chunk is still the right thing to do.
  462. // Otherwise, we need to fake up a function declarator.
  463. SourceLocation loc = declarator.getSourceRange().getBegin();
  464. // ...and *prepend* it to the declarator.
  465. declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
  466. /*proto*/ true,
  467. /*variadic*/ false, SourceLocation(),
  468. /*args*/ 0, 0,
  469. /*type quals*/ 0,
  470. /*ref-qualifier*/true, SourceLocation(),
  471. /*const qualifier*/SourceLocation(),
  472. /*volatile qualifier*/SourceLocation(),
  473. /*mutable qualifier*/SourceLocation(),
  474. /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
  475. /*parens*/ loc, loc,
  476. declarator));
  477. // For consistency, make sure the state still has us as processing
  478. // the decl spec.
  479. assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
  480. state.setCurrentChunkIndex(declarator.getNumTypeObjects());
  481. }
  482. /// \brief Convert the specified declspec to the appropriate type
  483. /// object.
  484. /// \param D the declarator containing the declaration specifier.
  485. /// \returns The type described by the declaration specifiers. This function
  486. /// never returns null.
  487. static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
  488. // FIXME: Should move the logic from DeclSpec::Finish to here for validity
  489. // checking.
  490. Sema &S = state.getSema();
  491. Declarator &declarator = state.getDeclarator();
  492. const DeclSpec &DS = declarator.getDeclSpec();
  493. SourceLocation DeclLoc = declarator.getIdentifierLoc();
  494. if (DeclLoc.isInvalid())
  495. DeclLoc = DS.getSourceRange().getBegin();
  496. ASTContext &Context = S.Context;
  497. QualType Result;
  498. switch (DS.getTypeSpecType()) {
  499. case DeclSpec::TST_void:
  500. Result = Context.VoidTy;
  501. break;
  502. case DeclSpec::TST_char:
  503. if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
  504. Result = Context.CharTy;
  505. else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
  506. Result = Context.SignedCharTy;
  507. else {
  508. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
  509. "Unknown TSS value");
  510. Result = Context.UnsignedCharTy;
  511. }
  512. break;
  513. case DeclSpec::TST_wchar:
  514. if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
  515. Result = Context.WCharTy;
  516. else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
  517. S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
  518. << DS.getSpecifierName(DS.getTypeSpecType());
  519. Result = Context.getSignedWCharType();
  520. } else {
  521. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
  522. "Unknown TSS value");
  523. S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
  524. << DS.getSpecifierName(DS.getTypeSpecType());
  525. Result = Context.getUnsignedWCharType();
  526. }
  527. break;
  528. case DeclSpec::TST_char16:
  529. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  530. "Unknown TSS value");
  531. Result = Context.Char16Ty;
  532. break;
  533. case DeclSpec::TST_char32:
  534. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  535. "Unknown TSS value");
  536. Result = Context.Char32Ty;
  537. break;
  538. case DeclSpec::TST_unspecified:
  539. // "<proto1,proto2>" is an objc qualified ID with a missing id.
  540. if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
  541. Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
  542. (ObjCProtocolDecl**)PQ,
  543. DS.getNumProtocolQualifiers());
  544. Result = Context.getObjCObjectPointerType(Result);
  545. break;
  546. }
  547. // If this is a missing declspec in a block literal return context, then it
  548. // is inferred from the return statements inside the block.
  549. if (isOmittedBlockReturnType(declarator)) {
  550. Result = Context.DependentTy;
  551. break;
  552. }
  553. // Unspecified typespec defaults to int in C90. However, the C90 grammar
  554. // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
  555. // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
  556. // Note that the one exception to this is function definitions, which are
  557. // allowed to be completely missing a declspec. This is handled in the
  558. // parser already though by it pretending to have seen an 'int' in this
  559. // case.
  560. if (S.getLangOptions().ImplicitInt) {
  561. // In C89 mode, we only warn if there is a completely missing declspec
  562. // when one is not allowed.
  563. if (DS.isEmpty()) {
  564. S.Diag(DeclLoc, diag::ext_missing_declspec)
  565. << DS.getSourceRange()
  566. << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
  567. }
  568. } else if (!DS.hasTypeSpecifier()) {
  569. // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
  570. // "At least one type specifier shall be given in the declaration
  571. // specifiers in each declaration, and in the specifier-qualifier list in
  572. // each struct declaration and type name."
  573. // FIXME: Does Microsoft really have the implicit int extension in C++?
  574. if (S.getLangOptions().CPlusPlus &&
  575. !S.getLangOptions().MicrosoftExt) {
  576. S.Diag(DeclLoc, diag::err_missing_type_specifier)
  577. << DS.getSourceRange();
  578. // When this occurs in C++ code, often something is very broken with the
  579. // value being declared, poison it as invalid so we don't get chains of
  580. // errors.
  581. declarator.setInvalidType(true);
  582. } else {
  583. S.Diag(DeclLoc, diag::ext_missing_type_specifier)
  584. << DS.getSourceRange();
  585. }
  586. }
  587. // FALL THROUGH.
  588. case DeclSpec::TST_int: {
  589. if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
  590. switch (DS.getTypeSpecWidth()) {
  591. case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
  592. case DeclSpec::TSW_short: Result = Context.ShortTy; break;
  593. case DeclSpec::TSW_long: Result = Context.LongTy; break;
  594. case DeclSpec::TSW_longlong:
  595. Result = Context.LongLongTy;
  596. // long long is a C99 feature.
  597. if (!S.getLangOptions().C99)
  598. S.Diag(DS.getTypeSpecWidthLoc(),
  599. S.getLangOptions().CPlusPlus0x ?
  600. diag::warn_cxx98_compat_longlong : diag::ext_longlong);
  601. break;
  602. }
  603. } else {
  604. switch (DS.getTypeSpecWidth()) {
  605. case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
  606. case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
  607. case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
  608. case DeclSpec::TSW_longlong:
  609. Result = Context.UnsignedLongLongTy;
  610. // long long is a C99 feature.
  611. if (!S.getLangOptions().C99)
  612. S.Diag(DS.getTypeSpecWidthLoc(),
  613. S.getLangOptions().CPlusPlus0x ?
  614. diag::warn_cxx98_compat_longlong : diag::ext_longlong);
  615. break;
  616. }
  617. }
  618. break;
  619. }
  620. case DeclSpec::TST_half: Result = Context.HalfTy; break;
  621. case DeclSpec::TST_float: Result = Context.FloatTy; break;
  622. case DeclSpec::TST_double:
  623. if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
  624. Result = Context.LongDoubleTy;
  625. else
  626. Result = Context.DoubleTy;
  627. if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
  628. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
  629. declarator.setInvalidType(true);
  630. }
  631. break;
  632. case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
  633. case DeclSpec::TST_decimal32: // _Decimal32
  634. case DeclSpec::TST_decimal64: // _Decimal64
  635. case DeclSpec::TST_decimal128: // _Decimal128
  636. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
  637. Result = Context.IntTy;
  638. declarator.setInvalidType(true);
  639. break;
  640. case DeclSpec::TST_class:
  641. case DeclSpec::TST_enum:
  642. case DeclSpec::TST_union:
  643. case DeclSpec::TST_struct: {
  644. TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
  645. if (!D) {
  646. // This can happen in C++ with ambiguous lookups.
  647. Result = Context.IntTy;
  648. declarator.setInvalidType(true);
  649. break;
  650. }
  651. // If the type is deprecated or unavailable, diagnose it.
  652. S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
  653. assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
  654. DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
  655. // TypeQuals handled by caller.
  656. Result = Context.getTypeDeclType(D);
  657. // In both C and C++, make an ElaboratedType.
  658. ElaboratedTypeKeyword Keyword
  659. = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
  660. Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
  661. if (D->isInvalidDecl())
  662. declarator.setInvalidType(true);
  663. break;
  664. }
  665. case DeclSpec::TST_typename: {
  666. assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
  667. DS.getTypeSpecSign() == 0 &&
  668. "Can't handle qualifiers on typedef names yet!");
  669. Result = S.GetTypeFromParser(DS.getRepAsType());
  670. if (Result.isNull())
  671. declarator.setInvalidType(true);
  672. else if (DeclSpec::ProtocolQualifierListTy PQ
  673. = DS.getProtocolQualifiers()) {
  674. if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
  675. // Silently drop any existing protocol qualifiers.
  676. // TODO: determine whether that's the right thing to do.
  677. if (ObjT->getNumProtocols())
  678. Result = ObjT->getBaseType();
  679. if (DS.getNumProtocolQualifiers())
  680. Result = Context.getObjCObjectType(Result,
  681. (ObjCProtocolDecl**) PQ,
  682. DS.getNumProtocolQualifiers());
  683. } else if (Result->isObjCIdType()) {
  684. // id<protocol-list>
  685. Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
  686. (ObjCProtocolDecl**) PQ,
  687. DS.getNumProtocolQualifiers());
  688. Result = Context.getObjCObjectPointerType(Result);
  689. } else if (Result->isObjCClassType()) {
  690. // Class<protocol-list>
  691. Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
  692. (ObjCProtocolDecl**) PQ,
  693. DS.getNumProtocolQualifiers());
  694. Result = Context.getObjCObjectPointerType(Result);
  695. } else {
  696. S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
  697. << DS.getSourceRange();
  698. declarator.setInvalidType(true);
  699. }
  700. }
  701. // TypeQuals handled by caller.
  702. break;
  703. }
  704. case DeclSpec::TST_typeofType:
  705. // FIXME: Preserve type source info.
  706. Result = S.GetTypeFromParser(DS.getRepAsType());
  707. assert(!Result.isNull() && "Didn't get a type for typeof?");
  708. if (!Result->isDependentType())
  709. if (const TagType *TT = Result->getAs<TagType>())
  710. S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
  711. // TypeQuals handled by caller.
  712. Result = Context.getTypeOfType(Result);
  713. break;
  714. case DeclSpec::TST_typeofExpr: {
  715. Expr *E = DS.getRepAsExpr();
  716. assert(E && "Didn't get an expression for typeof?");
  717. // TypeQuals handled by caller.
  718. Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
  719. if (Result.isNull()) {
  720. Result = Context.IntTy;
  721. declarator.setInvalidType(true);
  722. }
  723. break;
  724. }
  725. case DeclSpec::TST_decltype: {
  726. Expr *E = DS.getRepAsExpr();
  727. assert(E && "Didn't get an expression for decltype?");
  728. // TypeQuals handled by caller.
  729. Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
  730. if (Result.isNull()) {
  731. Result = Context.IntTy;
  732. declarator.setInvalidType(true);
  733. }
  734. break;
  735. }
  736. case DeclSpec::TST_underlyingType:
  737. Result = S.GetTypeFromParser(DS.getRepAsType());
  738. assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
  739. Result = S.BuildUnaryTransformType(Result,
  740. UnaryTransformType::EnumUnderlyingType,
  741. DS.getTypeSpecTypeLoc());
  742. if (Result.isNull()) {
  743. Result = Context.IntTy;
  744. declarator.setInvalidType(true);
  745. }
  746. break;
  747. case DeclSpec::TST_auto: {
  748. // TypeQuals handled by caller.
  749. Result = Context.getAutoType(QualType());
  750. break;
  751. }
  752. case DeclSpec::TST_unknown_anytype:
  753. Result = Context.UnknownAnyTy;
  754. break;
  755. case DeclSpec::TST_atomic:
  756. Result = S.GetTypeFromParser(DS.getRepAsType());
  757. assert(!Result.isNull() && "Didn't get a type for _Atomic?");
  758. Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
  759. if (Result.isNull()) {
  760. Result = Context.IntTy;
  761. declarator.setInvalidType(true);
  762. }
  763. break;
  764. case DeclSpec::TST_error:
  765. Result = Context.IntTy;
  766. declarator.setInvalidType(true);
  767. break;
  768. }
  769. // Handle complex types.
  770. if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
  771. if (S.getLangOptions().Freestanding)
  772. S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
  773. Result = Context.getComplexType(Result);
  774. } else if (DS.isTypeAltiVecVector()) {
  775. unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
  776. assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
  777. VectorType::VectorKind VecKind = VectorType::AltiVecVector;
  778. if (DS.isTypeAltiVecPixel())
  779. VecKind = VectorType::AltiVecPixel;
  780. else if (DS.isTypeAltiVecBool())
  781. VecKind = VectorType::AltiVecBool;
  782. Result = Context.getVectorType(Result, 128/typeSize, VecKind);
  783. }
  784. // FIXME: Imaginary.
  785. if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
  786. S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
  787. // Before we process any type attributes, synthesize a block literal
  788. // function declarator if necessary.
  789. if (declarator.getContext() == Declarator::BlockLiteralContext)
  790. maybeSynthesizeBlockSignature(state, Result);
  791. // Apply any type attributes from the decl spec. This may cause the
  792. // list of type attributes to be temporarily saved while the type
  793. // attributes are pushed around.
  794. if (AttributeList *attrs = DS.getAttributes().getList())
  795. processTypeAttrs(state, Result, true, attrs);
  796. // Apply const/volatile/restrict qualifiers to T.
  797. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  798. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  799. // or incomplete types shall not be restrict-qualified." C++ also allows
  800. // restrict-qualified references.
  801. if (TypeQuals & DeclSpec::TQ_restrict) {
  802. if (Result->isAnyPointerType() || Result->isReferenceType()) {
  803. QualType EltTy;
  804. if (Result->isObjCObjectPointerType())
  805. EltTy = Result;
  806. else
  807. EltTy = Result->isPointerType() ?
  808. Result->getAs<PointerType>()->getPointeeType() :
  809. Result->getAs<ReferenceType>()->getPointeeType();
  810. // If we have a pointer or reference, the pointee must have an object
  811. // incomplete type.
  812. if (!EltTy->isIncompleteOrObjectType()) {
  813. S.Diag(DS.getRestrictSpecLoc(),
  814. diag::err_typecheck_invalid_restrict_invalid_pointee)
  815. << EltTy << DS.getSourceRange();
  816. TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
  817. }
  818. } else {
  819. S.Diag(DS.getRestrictSpecLoc(),
  820. diag::err_typecheck_invalid_restrict_not_pointer)
  821. << Result << DS.getSourceRange();
  822. TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
  823. }
  824. }
  825. // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
  826. // of a function type includes any type qualifiers, the behavior is
  827. // undefined."
  828. if (Result->isFunctionType() && TypeQuals) {
  829. // Get some location to point at, either the C or V location.
  830. SourceLocation Loc;
  831. if (TypeQuals & DeclSpec::TQ_const)
  832. Loc = DS.getConstSpecLoc();
  833. else if (TypeQuals & DeclSpec::TQ_volatile)
  834. Loc = DS.getVolatileSpecLoc();
  835. else {
  836. assert((TypeQuals & DeclSpec::TQ_restrict) &&
  837. "Has CVR quals but not C, V, or R?");
  838. Loc = DS.getRestrictSpecLoc();
  839. }
  840. S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
  841. << Result << DS.getSourceRange();
  842. }
  843. // C++ [dcl.ref]p1:
  844. // Cv-qualified references are ill-formed except when the
  845. // cv-qualifiers are introduced through the use of a typedef
  846. // (7.1.3) or of a template type argument (14.3), in which
  847. // case the cv-qualifiers are ignored.
  848. // FIXME: Shouldn't we be checking SCS_typedef here?
  849. if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
  850. TypeQuals && Result->isReferenceType()) {
  851. TypeQuals &= ~DeclSpec::TQ_const;
  852. TypeQuals &= ~DeclSpec::TQ_volatile;
  853. }
  854. Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
  855. Result = Context.getQualifiedType(Result, Quals);
  856. }
  857. return Result;
  858. }
  859. static std::string getPrintableNameForEntity(DeclarationName Entity) {
  860. if (Entity)
  861. return Entity.getAsString();
  862. return "type name";
  863. }
  864. QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
  865. Qualifiers Qs) {
  866. // Enforce C99 6.7.3p2: "Types other than pointer types derived from
  867. // object or incomplete types shall not be restrict-qualified."
  868. if (Qs.hasRestrict()) {
  869. unsigned DiagID = 0;
  870. QualType ProblemTy;
  871. const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
  872. if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
  873. if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
  874. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  875. ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
  876. }
  877. } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
  878. if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
  879. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  880. ProblemTy = T->getAs<PointerType>()->getPointeeType();
  881. }
  882. } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
  883. if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
  884. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  885. ProblemTy = T->getAs<PointerType>()->getPointeeType();
  886. }
  887. } else if (!Ty->isDependentType()) {
  888. // FIXME: this deserves a proper diagnostic
  889. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  890. ProblemTy = T;
  891. }
  892. if (DiagID) {
  893. Diag(Loc, DiagID) << ProblemTy;
  894. Qs.removeRestrict();
  895. }
  896. }
  897. return Context.getQualifiedType(T, Qs);
  898. }
  899. /// \brief Build a paren type including \p T.
  900. QualType Sema::BuildParenType(QualType T) {
  901. return Context.getParenType(T);
  902. }
  903. /// Given that we're building a pointer or reference to the given
  904. static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
  905. SourceLocation loc,
  906. bool isReference) {
  907. // Bail out if retention is unrequired or already specified.
  908. if (!type->isObjCLifetimeType() ||
  909. type.getObjCLifetime() != Qualifiers::OCL_None)
  910. return type;
  911. Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
  912. // If the object type is const-qualified, we can safely use
  913. // __unsafe_unretained. This is safe (because there are no read
  914. // barriers), and it'll be safe to coerce anything but __weak* to
  915. // the resulting type.
  916. if (type.isConstQualified()) {
  917. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  918. // Otherwise, check whether the static type does not require
  919. // retaining. This currently only triggers for Class (possibly
  920. // protocol-qualifed, and arrays thereof).
  921. } else if (type->isObjCARCImplicitlyUnretainedType()) {
  922. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  923. // If we are in an unevaluated context, like sizeof, assume ExplicitNone and
  924. // don't give error.
  925. } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated ||
  926. S.ExprEvalContexts.back().Context == Sema::ConstantEvaluated) {
  927. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  928. // If that failed, give an error and recover using __autoreleasing.
  929. } else {
  930. // These types can show up in private ivars in system headers, so
  931. // we need this to not be an error in those cases. Instead we
  932. // want to delay.
  933. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  934. S.DelayedDiagnostics.add(
  935. sema::DelayedDiagnostic::makeForbiddenType(loc,
  936. diag::err_arc_indirect_no_ownership, type, isReference));
  937. } else {
  938. S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
  939. }
  940. implicitLifetime = Qualifiers::OCL_Autoreleasing;
  941. }
  942. assert(implicitLifetime && "didn't infer any lifetime!");
  943. Qualifiers qs;
  944. qs.addObjCLifetime(implicitLifetime);
  945. return S.Context.getQualifiedType(type, qs);
  946. }
  947. /// \brief Build a pointer type.
  948. ///
  949. /// \param T The type to which we'll be building a pointer.
  950. ///
  951. /// \param Loc The location of the entity whose type involves this
  952. /// pointer type or, if there is no such entity, the location of the
  953. /// type that will have pointer type.
  954. ///
  955. /// \param Entity The name of the entity that involves the pointer
  956. /// type, if known.
  957. ///
  958. /// \returns A suitable pointer type, if there are no
  959. /// errors. Otherwise, returns a NULL type.
  960. QualType Sema::BuildPointerType(QualType T,
  961. SourceLocation Loc, DeclarationName Entity) {
  962. if (T->isReferenceType()) {
  963. // C++ 8.3.2p4: There shall be no ... pointers to references ...
  964. Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
  965. << getPrintableNameForEntity(Entity) << T;
  966. return QualType();
  967. }
  968. assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
  969. // In ARC, it is forbidden to build pointers to unqualified pointers.
  970. if (getLangOptions().ObjCAutoRefCount)
  971. T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
  972. // Build the pointer type.
  973. return Context.getPointerType(T);
  974. }
  975. /// \brief Build a reference type.
  976. ///
  977. /// \param T The type to which we'll be building a reference.
  978. ///
  979. /// \param Loc The location of the entity whose type involves this
  980. /// reference type or, if there is no such entity, the location of the
  981. /// type that will have reference type.
  982. ///
  983. /// \param Entity The name of the entity that involves the reference
  984. /// type, if known.
  985. ///
  986. /// \returns A suitable reference type, if there are no
  987. /// errors. Otherwise, returns a NULL type.
  988. QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
  989. SourceLocation Loc,
  990. DeclarationName Entity) {
  991. assert(Context.getCanonicalType(T) != Context.OverloadTy &&
  992. "Unresolved overloaded function type");
  993. // C++0x [dcl.ref]p6:
  994. // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
  995. // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
  996. // type T, an attempt to create the type "lvalue reference to cv TR" creates
  997. // the type "lvalue reference to T", while an attempt to create the type
  998. // "rvalue reference to cv TR" creates the type TR.
  999. bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
  1000. // C++ [dcl.ref]p4: There shall be no references to references.
  1001. //
  1002. // According to C++ DR 106, references to references are only
  1003. // diagnosed when they are written directly (e.g., "int & &"),
  1004. // but not when they happen via a typedef:
  1005. //
  1006. // typedef int& intref;
  1007. // typedef intref& intref2;
  1008. //
  1009. // Parser::ParseDeclaratorInternal diagnoses the case where
  1010. // references are written directly; here, we handle the
  1011. // collapsing of references-to-references as described in C++0x.
  1012. // DR 106 and 540 introduce reference-collapsing into C++98/03.
  1013. // C++ [dcl.ref]p1:
  1014. // A declarator that specifies the type "reference to cv void"
  1015. // is ill-formed.
  1016. if (T->isVoidType()) {
  1017. Diag(Loc, diag::err_reference_to_void);
  1018. return QualType();
  1019. }
  1020. // In ARC, it is forbidden to build references to unqualified pointers.
  1021. if (getLangOptions().ObjCAutoRefCount)
  1022. T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
  1023. // Handle restrict on references.
  1024. if (LValueRef)
  1025. return Context.getLValueReferenceType(T, SpelledAsLValue);
  1026. return Context.getRValueReferenceType(T);
  1027. }
  1028. /// Check whether the specified array size makes the array type a VLA. If so,
  1029. /// return true, if not, return the size of the array in SizeVal.
  1030. static bool isArraySizeVLA(Expr *ArraySize, llvm::APSInt &SizeVal, Sema &S) {
  1031. // If the size is an ICE, it certainly isn't a VLA.
  1032. if (ArraySize->isIntegerConstantExpr(SizeVal, S.Context))
  1033. return false;
  1034. // If we're in a GNU mode (like gnu99, but not c99) accept any evaluatable
  1035. // value as an extension.
  1036. if (S.LangOpts.GNUMode && ArraySize->EvaluateAsInt(SizeVal, S.Context)) {
  1037. S.Diag(ArraySize->getLocStart(), diag::ext_vla_folded_to_constant);
  1038. return false;
  1039. }
  1040. return true;
  1041. }
  1042. /// \brief Build an array type.
  1043. ///
  1044. /// \param T The type of each element in the array.
  1045. ///
  1046. /// \param ASM C99 array size modifier (e.g., '*', 'static').
  1047. ///
  1048. /// \param ArraySize Expression describing the size of the array.
  1049. ///
  1050. /// \param Loc The location of the entity whose type involves this
  1051. /// array type or, if there is no such entity, the location of the
  1052. /// type that will have array type.
  1053. ///
  1054. /// \param Entity The name of the entity that involves the array
  1055. /// type, if known.
  1056. ///
  1057. /// \returns A suitable array type, if there are no errors. Otherwise,
  1058. /// returns a NULL type.
  1059. QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
  1060. Expr *ArraySize, unsigned Quals,
  1061. SourceRange Brackets, DeclarationName Entity) {
  1062. SourceLocation Loc = Brackets.getBegin();
  1063. if (getLangOptions().CPlusPlus) {
  1064. // C++ [dcl.array]p1:
  1065. // T is called the array element type; this type shall not be a reference
  1066. // type, the (possibly cv-qualified) type void, a function type or an
  1067. // abstract class type.
  1068. //
  1069. // Note: function types are handled in the common path with C.
  1070. if (T->isReferenceType()) {
  1071. Diag(Loc, diag::err_illegal_decl_array_of_references)
  1072. << getPrintableNameForEntity(Entity) << T;
  1073. return QualType();
  1074. }
  1075. if (T->isVoidType()) {
  1076. Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
  1077. return QualType();
  1078. }
  1079. if (RequireNonAbstractType(Brackets.getBegin(), T,
  1080. diag::err_array_of_abstract_type))
  1081. return QualType();
  1082. } else {
  1083. // C99 6.7.5.2p1: If the element type is an incomplete or function type,
  1084. // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
  1085. if (RequireCompleteType(Loc, T,
  1086. diag::err_illegal_decl_array_incomplete_type))
  1087. return QualType();
  1088. }
  1089. if (T->isFunctionType()) {
  1090. Diag(Loc, diag::err_illegal_decl_array_of_functions)
  1091. << getPrintableNameForEntity(Entity) << T;
  1092. return QualType();
  1093. }
  1094. if (T->getContainedAutoType()) {
  1095. Diag(Loc, diag::err_illegal_decl_array_of_auto)
  1096. << getPrintableNameForEntity(Entity) << T;
  1097. return QualType();
  1098. }
  1099. if (const RecordType *EltTy = T->getAs<RecordType>()) {
  1100. // If the element type is a struct or union that contains a variadic
  1101. // array, accept it as a GNU extension: C99 6.7.2.1p2.
  1102. if (EltTy->getDecl()->hasFlexibleArrayMember())
  1103. Diag(Loc, diag::ext_flexible_array_in_array) << T;
  1104. } else if (T->isObjCObjectType()) {
  1105. Diag(Loc, diag::err_objc_array_of_interfaces) << T;
  1106. return QualType();
  1107. }
  1108. // Do lvalue-to-rvalue conversions on the array size expression.
  1109. if (ArraySize && !ArraySize->isRValue()) {
  1110. ExprResult Result = DefaultLvalueConversion(ArraySize);
  1111. if (Result.isInvalid())
  1112. return QualType();
  1113. ArraySize = Result.take();
  1114. }
  1115. // C99 6.7.5.2p1: The size expression shall have integer type.
  1116. // TODO: in theory, if we were insane, we could allow contextual
  1117. // conversions to integer type here.
  1118. if (ArraySize && !ArraySize->isTypeDependent() &&
  1119. !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
  1120. Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
  1121. << ArraySize->getType() << ArraySize->getSourceRange();
  1122. return QualType();
  1123. }
  1124. llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
  1125. if (!ArraySize) {
  1126. if (ASM == ArrayType::Star)
  1127. T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
  1128. else
  1129. T = Context.getIncompleteArrayType(T, ASM, Quals);
  1130. } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
  1131. T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
  1132. } else if (!T->isDependentType() && !T->isIncompleteType() &&
  1133. !T->isConstantSizeType()) {
  1134. // C99: an array with an element type that has a non-constant-size is a VLA.
  1135. T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
  1136. } else if (isArraySizeVLA(ArraySize, ConstVal, *this)) {
  1137. // C99: an array with a non-ICE size is a VLA. We accept any expression
  1138. // that we can fold to a non-zero positive value as an extension.
  1139. T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
  1140. } else {
  1141. // C99 6.7.5.2p1: If the expression is a constant expression, it shall
  1142. // have a value greater than zero.
  1143. if (ConstVal.isSigned() && ConstVal.isNegative()) {
  1144. if (Entity)
  1145. Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
  1146. << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
  1147. else
  1148. Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
  1149. << ArraySize->getSourceRange();
  1150. return QualType();
  1151. }
  1152. if (ConstVal == 0) {
  1153. // GCC accepts zero sized static arrays. We allow them when
  1154. // we're not in a SFINAE context.
  1155. Diag(ArraySize->getLocStart(),
  1156. isSFINAEContext()? diag::err_typecheck_zero_array_size
  1157. : diag::ext_typecheck_zero_array_size)
  1158. << ArraySize->getSourceRange();
  1159. if (ASM == ArrayType::Static) {
  1160. Diag(ArraySize->getLocStart(),
  1161. diag::warn_typecheck_zero_static_array_size)
  1162. << ArraySize->getSourceRange();
  1163. ASM = ArrayType::Normal;
  1164. }
  1165. } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
  1166. !T->isIncompleteType()) {
  1167. // Is the array too large?
  1168. unsigned ActiveSizeBits
  1169. = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
  1170. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
  1171. Diag(ArraySize->getLocStart(), diag::err_array_too_large)
  1172. << ConstVal.toString(10)
  1173. << ArraySize->getSourceRange();
  1174. }
  1175. T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
  1176. }
  1177. // If this is not C99, extwarn about VLA's and C99 array size modifiers.
  1178. if (!getLangOptions().C99) {
  1179. if (T->isVariableArrayType()) {
  1180. // Prohibit the use of non-POD types in VLAs.
  1181. QualType BaseT = Context.getBaseElementType(T);
  1182. if (!T->isDependentType() &&
  1183. !BaseT.isPODType(Context) &&
  1184. !BaseT->isObjCLifetimeType()) {
  1185. Diag(Loc, diag::err_vla_non_pod)
  1186. << BaseT;
  1187. return QualType();
  1188. }
  1189. // Prohibit the use of VLAs during template argument deduction.
  1190. else if (isSFINAEContext()) {
  1191. Diag(Loc, diag::err_vla_in_sfinae);
  1192. return QualType();
  1193. }
  1194. // Just extwarn about VLAs.
  1195. else
  1196. Diag(Loc, diag::ext_vla);
  1197. } else if (ASM != ArrayType::Normal || Quals != 0)
  1198. Diag(Loc,
  1199. getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
  1200. : diag::ext_c99_array_usage) << ASM;
  1201. }
  1202. return T;
  1203. }
  1204. /// \brief Build an ext-vector type.
  1205. ///
  1206. /// Run the required checks for the extended vector type.
  1207. QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
  1208. SourceLocation AttrLoc) {
  1209. // unlike gcc's vector_size attribute, we do not allow vectors to be defined
  1210. // in conjunction with complex types (pointers, arrays, functions, etc.).
  1211. if (!T->isDependentType() &&
  1212. !T->isIntegerType() && !T->isRealFloatingType()) {
  1213. Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
  1214. return QualType();
  1215. }
  1216. if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
  1217. llvm::APSInt vecSize(32);
  1218. if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
  1219. Diag(AttrLoc, diag::err_attribute_argument_not_int)
  1220. << "ext_vector_type" << ArraySize->getSourceRange();
  1221. return QualType();
  1222. }
  1223. // unlike gcc's vector_size attribute, the size is specified as the
  1224. // number of elements, not the number of bytes.
  1225. unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
  1226. if (vectorSize == 0) {
  1227. Diag(AttrLoc, diag::err_attribute_zero_size)
  1228. << ArraySize->getSourceRange();
  1229. return QualType();
  1230. }
  1231. return Context.getExtVectorType(T, vectorSize);
  1232. }
  1233. return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
  1234. }
  1235. /// \brief Build a function type.
  1236. ///
  1237. /// This routine checks the function type according to C++ rules and
  1238. /// under the assumption that the result type and parameter types have
  1239. /// just been instantiated from a template. It therefore duplicates
  1240. /// some of the behavior of GetTypeForDeclarator, but in a much
  1241. /// simpler form that is only suitable for this narrow use case.
  1242. ///
  1243. /// \param T The return type of the function.
  1244. ///
  1245. /// \param ParamTypes The parameter types of the function. This array
  1246. /// will be modified to account for adjustments to the types of the
  1247. /// function parameters.
  1248. ///
  1249. /// \param NumParamTypes The number of parameter types in ParamTypes.
  1250. ///
  1251. /// \param Variadic Whether this is a variadic function type.
  1252. ///
  1253. /// \param Quals The cvr-qualifiers to be applied to the function type.
  1254. ///
  1255. /// \param Loc The location of the entity whose type involves this
  1256. /// function type or, if there is no such entity, the location of the
  1257. /// type that will have function type.
  1258. ///
  1259. /// \param Entity The name of the entity that involves the function
  1260. /// type, if known.
  1261. ///
  1262. /// \returns A suitable function type, if there are no
  1263. /// errors. Otherwise, returns a NULL type.
  1264. QualType Sema::BuildFunctionType(QualType T,
  1265. QualType *ParamTypes,
  1266. unsigned NumParamTypes,
  1267. bool Variadic, unsigned Quals,
  1268. RefQualifierKind RefQualifier,
  1269. SourceLocation Loc, DeclarationName Entity,
  1270. FunctionType::ExtInfo Info) {
  1271. if (T->isArrayType() || T->isFunctionType()) {
  1272. Diag(Loc, diag::err_func_returning_array_function)
  1273. << T->isFunctionType() << T;
  1274. return QualType();
  1275. }
  1276. // Functions cannot return half FP.
  1277. if (T->isHalfType()) {
  1278. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
  1279. FixItHint::CreateInsertion(Loc, "*");
  1280. return QualType();
  1281. }
  1282. bool Invalid = false;
  1283. for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
  1284. // FIXME: Loc is too inprecise here, should use proper locations for args.
  1285. QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
  1286. if (ParamType->isVoidType()) {
  1287. Diag(Loc, diag::err_param_with_void_type);
  1288. Invalid = true;
  1289. } else if (ParamType->isHalfType()) {
  1290. // Disallow half FP arguments.
  1291. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
  1292. FixItHint::CreateInsertion(Loc, "*");
  1293. Invalid = true;
  1294. }
  1295. ParamTypes[Idx] = ParamType;
  1296. }
  1297. if (Invalid)
  1298. return QualType();
  1299. FunctionProtoType::ExtProtoInfo EPI;
  1300. EPI.Variadic = Variadic;
  1301. EPI.TypeQuals = Quals;
  1302. EPI.RefQualifier = RefQualifier;
  1303. EPI.ExtInfo = Info;
  1304. return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
  1305. }
  1306. /// \brief Build a member pointer type \c T Class::*.
  1307. ///
  1308. /// \param T the type to which the member pointer refers.
  1309. /// \param Class the class type into which the member pointer points.
  1310. /// \param CVR Qualifiers applied to the member pointer type
  1311. /// \param Loc the location where this type begins
  1312. /// \param Entity the name of the entity that will have this member pointer type
  1313. ///
  1314. /// \returns a member pointer type, if successful, or a NULL type if there was
  1315. /// an error.
  1316. QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
  1317. SourceLocation Loc,
  1318. DeclarationName Entity) {
  1319. // Verify that we're not building a pointer to pointer to function with
  1320. // exception specification.
  1321. if (CheckDistantExceptionSpec(T)) {
  1322. Diag(Loc, diag::err_distant_exception_spec);
  1323. // FIXME: If we're doing this as part of template instantiation,
  1324. // we should return immediately.
  1325. // Build the type anyway, but use the canonical type so that the
  1326. // exception specifiers are stripped off.
  1327. T = Context.getCanonicalType(T);
  1328. }
  1329. // C++ 8.3.3p3: A pointer to member shall not point to ... a member
  1330. // with reference type, or "cv void."
  1331. if (T->isReferenceType()) {
  1332. Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
  1333. << (Entity? Entity.getAsString() : "type name") << T;
  1334. return QualType();
  1335. }
  1336. if (T->isVoidType()) {
  1337. Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
  1338. << (Entity? Entity.getAsString() : "type name");
  1339. return QualType();
  1340. }
  1341. if (!Class->isDependentType() && !Class->isRecordType()) {
  1342. Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
  1343. return QualType();
  1344. }
  1345. // In the Microsoft ABI, the class is allowed to be an incomplete
  1346. // type. In such cases, the compiler makes a worst-case assumption.
  1347. // We make no such assumption right now, so emit an error if the
  1348. // class isn't a complete type.
  1349. if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
  1350. RequireCompleteType(Loc, Class, diag::err_incomplete_type))
  1351. return QualType();
  1352. return Context.getMemberPointerType(T, Class.getTypePtr());
  1353. }
  1354. /// \brief Build a block pointer type.
  1355. ///
  1356. /// \param T The type to which we'll be building a block pointer.
  1357. ///
  1358. /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
  1359. ///
  1360. /// \param Loc The location of the entity whose type involves this
  1361. /// block pointer type or, if there is no such entity, the location of the
  1362. /// type that will have block pointer type.
  1363. ///
  1364. /// \param Entity The name of the entity that involves the block pointer
  1365. /// type, if known.
  1366. ///
  1367. /// \returns A suitable block pointer type, if there are no
  1368. /// errors. Otherwise, returns a NULL type.
  1369. QualType Sema::BuildBlockPointerType(QualType T,
  1370. SourceLocation Loc,
  1371. DeclarationName Entity) {
  1372. if (!T->isFunctionType()) {
  1373. Diag(Loc, diag::err_nonfunction_block_type);
  1374. return QualType();
  1375. }
  1376. return Context.getBlockPointerType(T);
  1377. }
  1378. QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
  1379. QualType QT = Ty.get();
  1380. if (QT.isNull()) {
  1381. if (TInfo) *TInfo = 0;
  1382. return QualType();
  1383. }
  1384. TypeSourceInfo *DI = 0;
  1385. if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
  1386. QT = LIT->getType();
  1387. DI = LIT->getTypeSourceInfo();
  1388. }
  1389. if (TInfo) *TInfo = DI;
  1390. return QT;
  1391. }
  1392. static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
  1393. Qualifiers::ObjCLifetime ownership,
  1394. unsigned chunkIndex);
  1395. /// Given that this is the declaration of a parameter under ARC,
  1396. /// attempt to infer attributes and such for pointer-to-whatever
  1397. /// types.
  1398. static void inferARCWriteback(TypeProcessingState &state,
  1399. QualType &declSpecType) {
  1400. Sema &S = state.getSema();
  1401. Declarator &declarator = state.getDeclarator();
  1402. // TODO: should we care about decl qualifiers?
  1403. // Check whether the declarator has the expected form. We walk
  1404. // from the inside out in order to make the block logic work.
  1405. unsigned outermostPointerIndex = 0;
  1406. bool isBlockPointer = false;
  1407. unsigned numPointers = 0;
  1408. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  1409. unsigned chunkIndex = i;
  1410. DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
  1411. switch (chunk.Kind) {
  1412. case DeclaratorChunk::Paren:
  1413. // Ignore parens.
  1414. break;
  1415. case DeclaratorChunk::Reference:
  1416. case DeclaratorChunk::Pointer:
  1417. // Count the number of pointers. Treat references
  1418. // interchangeably as pointers; if they're mis-ordered, normal
  1419. // type building will discover that.
  1420. outermostPointerIndex = chunkIndex;
  1421. numPointers++;
  1422. break;
  1423. case DeclaratorChunk::BlockPointer:
  1424. // If we have a pointer to block pointer, that's an acceptable
  1425. // indirect reference; anything else is not an application of
  1426. // the rules.
  1427. if (numPointers != 1) return;
  1428. numPointers++;
  1429. outermostPointerIndex = chunkIndex;
  1430. isBlockPointer = true;
  1431. // We don't care about pointer structure in return values here.
  1432. goto done;
  1433. case DeclaratorChunk::Array: // suppress if written (id[])?
  1434. case DeclaratorChunk::Function:
  1435. case DeclaratorChunk::MemberPointer:
  1436. return;
  1437. }
  1438. }
  1439. done:
  1440. // If we have *one* pointer, then we want to throw the qualifier on
  1441. // the declaration-specifiers, which means that it needs to be a
  1442. // retainable object type.
  1443. if (numPointers == 1) {
  1444. // If it's not a retainable object type, the rule doesn't apply.
  1445. if (!declSpecType->isObjCRetainableType()) return;
  1446. // If it already has lifetime, don't do anything.
  1447. if (declSpecType.getObjCLifetime()) return;
  1448. // Otherwise, modify the type in-place.
  1449. Qualifiers qs;
  1450. if (declSpecType->isObjCARCImplicitlyUnretainedType())
  1451. qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
  1452. else
  1453. qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
  1454. declSpecType = S.Context.getQualifiedType(declSpecType, qs);
  1455. // If we have *two* pointers, then we want to throw the qualifier on
  1456. // the outermost pointer.
  1457. } else if (numPointers == 2) {
  1458. // If we don't have a block pointer, we need to check whether the
  1459. // declaration-specifiers gave us something that will turn into a
  1460. // retainable object pointer after we slap the first pointer on it.
  1461. if (!isBlockPointer && !declSpecType->isObjCObjectType())
  1462. return;
  1463. // Look for an explicit lifetime attribute there.
  1464. DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
  1465. if (chunk.Kind != DeclaratorChunk::Pointer &&
  1466. chunk.Kind != DeclaratorChunk::BlockPointer)
  1467. return;
  1468. for (const AttributeList *attr = chunk.getAttrs(); attr;
  1469. attr = attr->getNext())
  1470. if (attr->getKind() == AttributeList::AT_objc_ownership)
  1471. return;
  1472. transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
  1473. outermostPointerIndex);
  1474. // Any other number of pointers/references does not trigger the rule.
  1475. } else return;
  1476. // TODO: mark whether we did this inference?
  1477. }
  1478. static void DiagnoseIgnoredQualifiers(unsigned Quals,
  1479. SourceLocation ConstQualLoc,
  1480. SourceLocation VolatileQualLoc,
  1481. SourceLocation RestrictQualLoc,
  1482. Sema& S) {
  1483. std::string QualStr;
  1484. unsigned NumQuals = 0;
  1485. SourceLocation Loc;
  1486. FixItHint ConstFixIt;
  1487. FixItHint VolatileFixIt;
  1488. FixItHint RestrictFixIt;
  1489. const SourceManager &SM = S.getSourceManager();
  1490. // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
  1491. // find a range and grow it to encompass all the qualifiers, regardless of
  1492. // the order in which they textually appear.
  1493. if (Quals & Qualifiers::Const) {
  1494. ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
  1495. QualStr = "const";
  1496. ++NumQuals;
  1497. if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
  1498. Loc = ConstQualLoc;
  1499. }
  1500. if (Quals & Qualifiers::Volatile) {
  1501. VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
  1502. QualStr += (NumQuals == 0 ? "volatile" : " volatile");
  1503. ++NumQuals;
  1504. if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
  1505. Loc = VolatileQualLoc;
  1506. }
  1507. if (Quals & Qualifiers::Restrict) {
  1508. RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
  1509. QualStr += (NumQuals == 0 ? "restrict" : " restrict");
  1510. ++NumQuals;
  1511. if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
  1512. Loc = RestrictQualLoc;
  1513. }
  1514. assert(NumQuals > 0 && "No known qualifiers?");
  1515. S.Diag(Loc, diag::warn_qual_return_type)
  1516. << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
  1517. }
  1518. static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
  1519. TypeSourceInfo *&ReturnTypeInfo) {
  1520. Sema &SemaRef = state.getSema();
  1521. Declarator &D = state.getDeclarator();
  1522. QualType T;
  1523. ReturnTypeInfo = 0;
  1524. // The TagDecl owned by the DeclSpec.
  1525. TagDecl *OwnedTagDecl = 0;
  1526. switch (D.getName().getKind()) {
  1527. case UnqualifiedId::IK_ImplicitSelfParam:
  1528. case UnqualifiedId::IK_OperatorFunctionId:
  1529. case UnqualifiedId::IK_Identifier:
  1530. case UnqualifiedId::IK_LiteralOperatorId:
  1531. case UnqualifiedId::IK_TemplateId:
  1532. T = ConvertDeclSpecToType(state);
  1533. if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
  1534. OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  1535. // Owned declaration is embedded in declarator.
  1536. OwnedTagDecl->setEmbeddedInDeclarator(true);
  1537. }
  1538. break;
  1539. case UnqualifiedId::IK_ConstructorName:
  1540. case UnqualifiedId::IK_ConstructorTemplateId:
  1541. case UnqualifiedId::IK_DestructorName:
  1542. // Constructors and destructors don't have return types. Use
  1543. // "void" instead.
  1544. T = SemaRef.Context.VoidTy;
  1545. break;
  1546. case UnqualifiedId::IK_ConversionFunctionId:
  1547. // The result type of a conversion function is the type that it
  1548. // converts to.
  1549. T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
  1550. &ReturnTypeInfo);
  1551. break;
  1552. }
  1553. if (D.getAttributes())
  1554. distributeTypeAttrsFromDeclarator(state, T);
  1555. // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
  1556. // In C++0x, a function declarator using 'auto' must have a trailing return
  1557. // type (this is checked later) and we can skip this. In other languages
  1558. // using auto, we need to check regardless.
  1559. if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
  1560. (!SemaRef.getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
  1561. int Error = -1;
  1562. switch (D.getContext()) {
  1563. case Declarator::KNRTypeListContext:
  1564. llvm_unreachable("K&R type lists aren't allowed in C++");
  1565. break;
  1566. case Declarator::ObjCParameterContext:
  1567. case Declarator::ObjCResultContext:
  1568. case Declarator::PrototypeContext:
  1569. Error = 0; // Function prototype
  1570. break;
  1571. case Declarator::MemberContext:
  1572. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
  1573. break;
  1574. switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
  1575. case TTK_Enum: llvm_unreachable("unhandled tag kind");
  1576. case TTK_Struct: Error = 1; /* Struct member */ break;
  1577. case TTK_Union: Error = 2; /* Union member */ break;
  1578. case TTK_Class: Error = 3; /* Class member */ break;
  1579. }
  1580. break;
  1581. case Declarator::CXXCatchContext:
  1582. case Declarator::ObjCCatchContext:
  1583. Error = 4; // Exception declaration
  1584. break;
  1585. case Declarator::TemplateParamContext:
  1586. Error = 5; // Template parameter
  1587. break;
  1588. case Declarator::BlockLiteralContext:
  1589. Error = 6; // Block literal
  1590. break;
  1591. case Declarator::TemplateTypeArgContext:
  1592. Error = 7; // Template type argument
  1593. break;
  1594. case Declarator::AliasDeclContext:
  1595. case Declarator::AliasTemplateContext:
  1596. Error = 9; // Type alias
  1597. break;
  1598. case Declarator::TypeNameContext:
  1599. Error = 11; // Generic
  1600. break;
  1601. case Declarator::FileContext:
  1602. case Declarator::BlockContext:
  1603. case Declarator::ForContext:
  1604. case Declarator::ConditionContext:
  1605. case Declarator::CXXNewContext:
  1606. break;
  1607. }
  1608. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  1609. Error = 8;
  1610. // In Objective-C it is an error to use 'auto' on a function declarator.
  1611. if (D.isFunctionDeclarator())
  1612. Error = 10;
  1613. // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
  1614. // contains a trailing return type. That is only legal at the outermost
  1615. // level. Check all declarator chunks (outermost first) anyway, to give
  1616. // better diagnostics.
  1617. if (SemaRef.getLangOptions().CPlusPlus0x && Error != -1) {
  1618. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  1619. unsigned chunkIndex = e - i - 1;
  1620. state.setCurrentChunkIndex(chunkIndex);
  1621. DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
  1622. if (DeclType.Kind == DeclaratorChunk::Function) {
  1623. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  1624. if (FTI.TrailingReturnType) {
  1625. Error = -1;
  1626. break;
  1627. }
  1628. }
  1629. }
  1630. }
  1631. if (Error != -1) {
  1632. SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  1633. diag::err_auto_not_allowed)
  1634. << Error;
  1635. T = SemaRef.Context.IntTy;
  1636. D.setInvalidType(true);
  1637. } else
  1638. SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  1639. diag::warn_cxx98_compat_auto_type_specifier);
  1640. }
  1641. if (SemaRef.getLangOptions().CPlusPlus &&
  1642. OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
  1643. // Check the contexts where C++ forbids the declaration of a new class
  1644. // or enumeration in a type-specifier-seq.
  1645. switch (D.getContext()) {
  1646. case Declarator::FileContext:
  1647. case Declarator::MemberContext:
  1648. case Declarator::BlockContext:
  1649. case Declarator::ForContext:
  1650. case Declarator::BlockLiteralContext:
  1651. // C++0x [dcl.type]p3:
  1652. // A type-specifier-seq shall not define a class or enumeration unless
  1653. // it appears in the type-id of an alias-declaration (7.1.3) that is not
  1654. // the declaration of a template-declaration.
  1655. case Declarator::AliasDeclContext:
  1656. break;
  1657. case Declarator::AliasTemplateContext:
  1658. SemaRef.Diag(OwnedTagDecl->getLocation(),
  1659. diag::err_type_defined_in_alias_template)
  1660. << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
  1661. break;
  1662. case Declarator::TypeNameContext:
  1663. case Declarator::TemplateParamContext:
  1664. case Declarator::CXXNewContext:
  1665. case Declarator::CXXCatchContext:
  1666. case Declarator::ObjCCatchContext:
  1667. case Declarator::TemplateTypeArgContext:
  1668. SemaRef.Diag(OwnedTagDecl->getLocation(),
  1669. diag::err_type_defined_in_type_specifier)
  1670. << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
  1671. break;
  1672. case Declarator::PrototypeContext:
  1673. case Declarator::ObjCParameterContext:
  1674. case Declarator::ObjCResultContext:
  1675. case Declarator::KNRTypeListContext:
  1676. // C++ [dcl.fct]p6:
  1677. // Types shall not be defined in return or parameter types.
  1678. SemaRef.Diag(OwnedTagDecl->getLocation(),
  1679. diag::err_type_defined_in_param_type)
  1680. << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
  1681. break;
  1682. case Declarator::ConditionContext:
  1683. // C++ 6.4p2:
  1684. // The type-specifier-seq shall not contain typedef and shall not declare
  1685. // a new class or enumeration.
  1686. SemaRef.Diag(OwnedTagDecl->getLocation(),
  1687. diag::err_type_defined_in_condition);
  1688. break;
  1689. }
  1690. }
  1691. return T;
  1692. }
  1693. static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
  1694. QualType declSpecType,
  1695. TypeSourceInfo *TInfo) {
  1696. QualType T = declSpecType;
  1697. Declarator &D = state.getDeclarator();
  1698. Sema &S = state.getSema();
  1699. ASTContext &Context = S.Context;
  1700. const LangOptions &LangOpts = S.getLangOptions();
  1701. bool ImplicitlyNoexcept = false;
  1702. if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
  1703. LangOpts.CPlusPlus0x) {
  1704. OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
  1705. /// In C++0x, deallocation functions (normal and array operator delete)
  1706. /// are implicitly noexcept.
  1707. if (OO == OO_Delete || OO == OO_Array_Delete)
  1708. ImplicitlyNoexcept = true;
  1709. }
  1710. // The name we're declaring, if any.
  1711. DeclarationName Name;
  1712. if (D.getIdentifier())
  1713. Name = D.getIdentifier();
  1714. // Does this declaration declare a typedef-name?
  1715. bool IsTypedefName =
  1716. D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
  1717. D.getContext() == Declarator::AliasDeclContext ||
  1718. D.getContext() == Declarator::AliasTemplateContext;
  1719. // Walk the DeclTypeInfo, building the recursive type as we go.
  1720. // DeclTypeInfos are ordered from the identifier out, which is
  1721. // opposite of what we want :).
  1722. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  1723. unsigned chunkIndex = e - i - 1;
  1724. state.setCurrentChunkIndex(chunkIndex);
  1725. DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
  1726. switch (DeclType.Kind) {
  1727. default: llvm_unreachable("Unknown decltype!");
  1728. case DeclaratorChunk::Paren:
  1729. T = S.BuildParenType(T);
  1730. break;
  1731. case DeclaratorChunk::BlockPointer:
  1732. // If blocks are disabled, emit an error.
  1733. if (!LangOpts.Blocks)
  1734. S.Diag(DeclType.Loc, diag::err_blocks_disable);
  1735. T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
  1736. if (DeclType.Cls.TypeQuals)
  1737. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
  1738. break;
  1739. case DeclaratorChunk::Pointer:
  1740. // Verify that we're not building a pointer to pointer to function with
  1741. // exception specification.
  1742. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  1743. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  1744. D.setInvalidType(true);
  1745. // Build the type anyway.
  1746. }
  1747. if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
  1748. T = Context.getObjCObjectPointerType(T);
  1749. if (DeclType.Ptr.TypeQuals)
  1750. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
  1751. break;
  1752. }
  1753. T = S.BuildPointerType(T, DeclType.Loc, Name);
  1754. if (DeclType.Ptr.TypeQuals)
  1755. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
  1756. break;
  1757. case DeclaratorChunk::Reference: {
  1758. // Verify that we're not building a reference to pointer to function with
  1759. // exception specification.
  1760. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  1761. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  1762. D.setInvalidType(true);
  1763. // Build the type anyway.
  1764. }
  1765. T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
  1766. Qualifiers Quals;
  1767. if (DeclType.Ref.HasRestrict)
  1768. T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
  1769. break;
  1770. }
  1771. case DeclaratorChunk::Array: {
  1772. // Verify that we're not building an array of pointers to function with
  1773. // exception specification.
  1774. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  1775. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  1776. D.setInvalidType(true);
  1777. // Build the type anyway.
  1778. }
  1779. DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
  1780. Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
  1781. ArrayType::ArraySizeModifier ASM;
  1782. if (ATI.isStar)
  1783. ASM = ArrayType::Star;
  1784. else if (ATI.hasStatic)
  1785. ASM = ArrayType::Static;
  1786. else
  1787. ASM = ArrayType::Normal;
  1788. if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
  1789. // FIXME: This check isn't quite right: it allows star in prototypes
  1790. // for function definitions, and disallows some edge cases detailed
  1791. // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
  1792. S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
  1793. ASM = ArrayType::Normal;
  1794. D.setInvalidType(true);
  1795. }
  1796. T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
  1797. SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
  1798. break;
  1799. }
  1800. case DeclaratorChunk::Function: {
  1801. // If the function declarator has a prototype (i.e. it is not () and
  1802. // does not have a K&R-style identifier list), then the arguments are part
  1803. // of the type, otherwise the argument list is ().
  1804. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  1805. // Check for auto functions and trailing return type and adjust the
  1806. // return type accordingly.
  1807. if (!D.isInvalidType()) {
  1808. // trailing-return-type is only required if we're declaring a function,
  1809. // and not, for instance, a pointer to a function.
  1810. if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
  1811. !FTI.TrailingReturnType && chunkIndex == 0) {
  1812. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  1813. diag::err_auto_missing_trailing_return);
  1814. T = Context.IntTy;
  1815. D.setInvalidType(true);
  1816. } else if (FTI.TrailingReturnType) {
  1817. // T must be exactly 'auto' at this point. See CWG issue 681.
  1818. if (isa<ParenType>(T)) {
  1819. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  1820. diag::err_trailing_return_in_parens)
  1821. << T << D.getDeclSpec().getSourceRange();
  1822. D.setInvalidType(true);
  1823. } else if (T.hasQualifiers() || !isa<AutoType>(T)) {
  1824. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  1825. diag::err_trailing_return_without_auto)
  1826. << T << D.getDeclSpec().getSourceRange();
  1827. D.setInvalidType(true);
  1828. }
  1829. T = S.GetTypeFromParser(
  1830. ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
  1831. &TInfo);
  1832. }
  1833. }
  1834. // C99 6.7.5.3p1: The return type may not be a function or array type.
  1835. // For conversion functions, we'll diagnose this particular error later.
  1836. if ((T->isArrayType() || T->isFunctionType()) &&
  1837. (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
  1838. unsigned diagID = diag::err_func_returning_array_function;
  1839. // Last processing chunk in block context means this function chunk
  1840. // represents the block.
  1841. if (chunkIndex == 0 &&
  1842. D.getContext() == Declarator::BlockLiteralContext)
  1843. diagID = diag::err_block_returning_array_function;
  1844. S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
  1845. T = Context.IntTy;
  1846. D.setInvalidType(true);
  1847. }
  1848. // Do not allow returning half FP value.
  1849. // FIXME: This really should be in BuildFunctionType.
  1850. if (T->isHalfType()) {
  1851. S.Diag(D.getIdentifierLoc(),
  1852. diag::err_parameters_retval_cannot_have_fp16_type) << 1
  1853. << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
  1854. D.setInvalidType(true);
  1855. }
  1856. // cv-qualifiers on return types are pointless except when the type is a
  1857. // class type in C++.
  1858. if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
  1859. (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
  1860. (!LangOpts.CPlusPlus || !T->isDependentType())) {
  1861. assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
  1862. DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
  1863. assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
  1864. DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
  1865. DiagnoseIgnoredQualifiers(PTI.TypeQuals,
  1866. SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
  1867. SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
  1868. SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
  1869. S);
  1870. } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
  1871. (!LangOpts.CPlusPlus ||
  1872. (!T->isDependentType() && !T->isRecordType()))) {
  1873. DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
  1874. D.getDeclSpec().getConstSpecLoc(),
  1875. D.getDeclSpec().getVolatileSpecLoc(),
  1876. D.getDeclSpec().getRestrictSpecLoc(),
  1877. S);
  1878. }
  1879. if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
  1880. // C++ [dcl.fct]p6:
  1881. // Types shall not be defined in return or parameter types.
  1882. TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  1883. if (Tag->isCompleteDefinition())
  1884. S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
  1885. << Context.getTypeDeclType(Tag);
  1886. }
  1887. // Exception specs are not allowed in typedefs. Complain, but add it
  1888. // anyway.
  1889. if (IsTypedefName && FTI.getExceptionSpecType())
  1890. S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
  1891. << (D.getContext() == Declarator::AliasDeclContext ||
  1892. D.getContext() == Declarator::AliasTemplateContext);
  1893. if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
  1894. // Simple void foo(), where the incoming T is the result type.
  1895. T = Context.getFunctionNoProtoType(T);
  1896. } else {
  1897. // We allow a zero-parameter variadic function in C if the
  1898. // function is marked with the "overloadable" attribute. Scan
  1899. // for this attribute now.
  1900. if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
  1901. bool Overloadable = false;
  1902. for (const AttributeList *Attrs = D.getAttributes();
  1903. Attrs; Attrs = Attrs->getNext()) {
  1904. if (Attrs->getKind() == AttributeList::AT_overloadable) {
  1905. Overloadable = true;
  1906. break;
  1907. }
  1908. }
  1909. if (!Overloadable)
  1910. S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
  1911. }
  1912. if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
  1913. // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
  1914. // definition.
  1915. S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
  1916. D.setInvalidType(true);
  1917. break;
  1918. }
  1919. FunctionProtoType::ExtProtoInfo EPI;
  1920. EPI.Variadic = FTI.isVariadic;
  1921. EPI.TypeQuals = FTI.TypeQuals;
  1922. EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
  1923. : FTI.RefQualifierIsLValueRef? RQ_LValue
  1924. : RQ_RValue;
  1925. // Otherwise, we have a function with an argument list that is
  1926. // potentially variadic.
  1927. SmallVector<QualType, 16> ArgTys;
  1928. ArgTys.reserve(FTI.NumArgs);
  1929. SmallVector<bool, 16> ConsumedArguments;
  1930. ConsumedArguments.reserve(FTI.NumArgs);
  1931. bool HasAnyConsumedArguments = false;
  1932. for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
  1933. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
  1934. QualType ArgTy = Param->getType();
  1935. assert(!ArgTy.isNull() && "Couldn't parse type?");
  1936. // Adjust the parameter type.
  1937. assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
  1938. "Unadjusted type?");
  1939. // Look for 'void'. void is allowed only as a single argument to a
  1940. // function with no other parameters (C99 6.7.5.3p10). We record
  1941. // int(void) as a FunctionProtoType with an empty argument list.
  1942. if (ArgTy->isVoidType()) {
  1943. // If this is something like 'float(int, void)', reject it. 'void'
  1944. // is an incomplete type (C99 6.2.5p19) and function decls cannot
  1945. // have arguments of incomplete type.
  1946. if (FTI.NumArgs != 1 || FTI.isVariadic) {
  1947. S.Diag(DeclType.Loc, diag::err_void_only_param);
  1948. ArgTy = Context.IntTy;
  1949. Param->setType(ArgTy);
  1950. } else if (FTI.ArgInfo[i].Ident) {
  1951. // Reject, but continue to parse 'int(void abc)'.
  1952. S.Diag(FTI.ArgInfo[i].IdentLoc,
  1953. diag::err_param_with_void_type);
  1954. ArgTy = Context.IntTy;
  1955. Param->setType(ArgTy);
  1956. } else {
  1957. // Reject, but continue to parse 'float(const void)'.
  1958. if (ArgTy.hasQualifiers())
  1959. S.Diag(DeclType.Loc, diag::err_void_param_qualified);
  1960. // Do not add 'void' to the ArgTys list.
  1961. break;
  1962. }
  1963. } else if (ArgTy->isHalfType()) {
  1964. // Disallow half FP arguments.
  1965. // FIXME: This really should be in BuildFunctionType.
  1966. S.Diag(Param->getLocation(),
  1967. diag::err_parameters_retval_cannot_have_fp16_type) << 0
  1968. << FixItHint::CreateInsertion(Param->getLocation(), "*");
  1969. D.setInvalidType();
  1970. } else if (!FTI.hasPrototype) {
  1971. if (ArgTy->isPromotableIntegerType()) {
  1972. ArgTy = Context.getPromotedIntegerType(ArgTy);
  1973. Param->setKNRPromoted(true);
  1974. } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
  1975. if (BTy->getKind() == BuiltinType::Float) {
  1976. ArgTy = Context.DoubleTy;
  1977. Param->setKNRPromoted(true);
  1978. }
  1979. }
  1980. }
  1981. if (LangOpts.ObjCAutoRefCount) {
  1982. bool Consumed = Param->hasAttr<NSConsumedAttr>();
  1983. ConsumedArguments.push_back(Consumed);
  1984. HasAnyConsumedArguments |= Consumed;
  1985. }
  1986. ArgTys.push_back(ArgTy);
  1987. }
  1988. if (HasAnyConsumedArguments)
  1989. EPI.ConsumedArguments = ConsumedArguments.data();
  1990. SmallVector<QualType, 4> Exceptions;
  1991. EPI.ExceptionSpecType = FTI.getExceptionSpecType();
  1992. if (FTI.getExceptionSpecType() == EST_Dynamic) {
  1993. Exceptions.reserve(FTI.NumExceptions);
  1994. for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
  1995. // FIXME: Preserve type source info.
  1996. QualType ET = S.GetTypeFromParser(FTI.Exceptions[ei].Ty);
  1997. // Check that the type is valid for an exception spec, and
  1998. // drop it if not.
  1999. if (!S.CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
  2000. Exceptions.push_back(ET);
  2001. }
  2002. EPI.NumExceptions = Exceptions.size();
  2003. EPI.Exceptions = Exceptions.data();
  2004. } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
  2005. // If an error occurred, there's no expression here.
  2006. if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
  2007. assert((NoexceptExpr->isTypeDependent() ||
  2008. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  2009. Context.BoolTy) &&
  2010. "Parser should have made sure that the expression is boolean");
  2011. SourceLocation ErrLoc;
  2012. llvm::APSInt Dummy;
  2013. if (!NoexceptExpr->isValueDependent() &&
  2014. !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
  2015. /*evaluated*/false))
  2016. S.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
  2017. << NoexceptExpr->getSourceRange();
  2018. else
  2019. EPI.NoexceptExpr = NoexceptExpr;
  2020. }
  2021. } else if (FTI.getExceptionSpecType() == EST_None &&
  2022. ImplicitlyNoexcept && chunkIndex == 0) {
  2023. // Only the outermost chunk is marked noexcept, of course.
  2024. EPI.ExceptionSpecType = EST_BasicNoexcept;
  2025. }
  2026. T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
  2027. }
  2028. break;
  2029. }
  2030. case DeclaratorChunk::MemberPointer:
  2031. // The scope spec must refer to a class, or be dependent.
  2032. CXXScopeSpec &SS = DeclType.Mem.Scope();
  2033. QualType ClsType;
  2034. if (SS.isInvalid()) {
  2035. // Avoid emitting extra errors if we already errored on the scope.
  2036. D.setInvalidType(true);
  2037. } else if (S.isDependentScopeSpecifier(SS) ||
  2038. dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
  2039. NestedNameSpecifier *NNS
  2040. = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
  2041. NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
  2042. switch (NNS->getKind()) {
  2043. case NestedNameSpecifier::Identifier:
  2044. ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
  2045. NNS->getAsIdentifier());
  2046. break;
  2047. case NestedNameSpecifier::Namespace:
  2048. case NestedNameSpecifier::NamespaceAlias:
  2049. case NestedNameSpecifier::Global:
  2050. llvm_unreachable("Nested-name-specifier must name a type");
  2051. break;
  2052. case NestedNameSpecifier::TypeSpec:
  2053. case NestedNameSpecifier::TypeSpecWithTemplate:
  2054. ClsType = QualType(NNS->getAsType(), 0);
  2055. // Note: if the NNS has a prefix and ClsType is a nondependent
  2056. // TemplateSpecializationType, then the NNS prefix is NOT included
  2057. // in ClsType; hence we wrap ClsType into an ElaboratedType.
  2058. // NOTE: in particular, no wrap occurs if ClsType already is an
  2059. // Elaborated, DependentName, or DependentTemplateSpecialization.
  2060. if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
  2061. ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
  2062. break;
  2063. }
  2064. } else {
  2065. S.Diag(DeclType.Mem.Scope().getBeginLoc(),
  2066. diag::err_illegal_decl_mempointer_in_nonclass)
  2067. << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
  2068. << DeclType.Mem.Scope().getRange();
  2069. D.setInvalidType(true);
  2070. }
  2071. if (!ClsType.isNull())
  2072. T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
  2073. if (T.isNull()) {
  2074. T = Context.IntTy;
  2075. D.setInvalidType(true);
  2076. } else if (DeclType.Mem.TypeQuals) {
  2077. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
  2078. }
  2079. break;
  2080. }
  2081. if (T.isNull()) {
  2082. D.setInvalidType(true);
  2083. T = Context.IntTy;
  2084. }
  2085. // See if there are any attributes on this declarator chunk.
  2086. if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
  2087. processTypeAttrs(state, T, false, attrs);
  2088. }
  2089. if (LangOpts.CPlusPlus && T->isFunctionType()) {
  2090. const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
  2091. assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
  2092. // C++ 8.3.5p4:
  2093. // A cv-qualifier-seq shall only be part of the function type
  2094. // for a nonstatic member function, the function type to which a pointer
  2095. // to member refers, or the top-level function type of a function typedef
  2096. // declaration.
  2097. //
  2098. // Core issue 547 also allows cv-qualifiers on function types that are
  2099. // top-level template type arguments.
  2100. bool FreeFunction;
  2101. if (!D.getCXXScopeSpec().isSet()) {
  2102. FreeFunction = (D.getContext() != Declarator::MemberContext ||
  2103. D.getDeclSpec().isFriendSpecified());
  2104. } else {
  2105. DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
  2106. FreeFunction = (DC && !DC->isRecord());
  2107. }
  2108. // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
  2109. // function that is not a constructor declares that function to be const.
  2110. if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
  2111. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static &&
  2112. D.getName().getKind() != UnqualifiedId::IK_ConstructorName &&
  2113. D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId &&
  2114. !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
  2115. // Rebuild function type adding a 'const' qualifier.
  2116. FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
  2117. EPI.TypeQuals |= DeclSpec::TQ_const;
  2118. T = Context.getFunctionType(FnTy->getResultType(),
  2119. FnTy->arg_type_begin(),
  2120. FnTy->getNumArgs(), EPI);
  2121. }
  2122. // C++0x [dcl.fct]p6:
  2123. // A ref-qualifier shall only be part of the function type for a
  2124. // non-static member function, the function type to which a pointer to
  2125. // member refers, or the top-level function type of a function typedef
  2126. // declaration.
  2127. if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
  2128. !(D.getContext() == Declarator::TemplateTypeArgContext &&
  2129. !D.isFunctionDeclarator()) && !IsTypedefName &&
  2130. (FreeFunction ||
  2131. D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
  2132. if (D.getContext() == Declarator::TemplateTypeArgContext) {
  2133. // Accept qualified function types as template type arguments as a GNU
  2134. // extension. This is also the subject of C++ core issue 547.
  2135. std::string Quals;
  2136. if (FnTy->getTypeQuals() != 0)
  2137. Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
  2138. switch (FnTy->getRefQualifier()) {
  2139. case RQ_None:
  2140. break;
  2141. case RQ_LValue:
  2142. if (!Quals.empty())
  2143. Quals += ' ';
  2144. Quals += '&';
  2145. break;
  2146. case RQ_RValue:
  2147. if (!Quals.empty())
  2148. Quals += ' ';
  2149. Quals += "&&";
  2150. break;
  2151. }
  2152. S.Diag(D.getIdentifierLoc(),
  2153. diag::ext_qualified_function_type_template_arg)
  2154. << Quals;
  2155. } else {
  2156. if (FnTy->getTypeQuals() != 0) {
  2157. if (D.isFunctionDeclarator()) {
  2158. SourceRange Range = D.getIdentifierLoc();
  2159. for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
  2160. const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
  2161. if (Chunk.Kind == DeclaratorChunk::Function &&
  2162. Chunk.Fun.TypeQuals != 0) {
  2163. switch (Chunk.Fun.TypeQuals) {
  2164. case Qualifiers::Const:
  2165. Range = Chunk.Fun.getConstQualifierLoc();
  2166. break;
  2167. case Qualifiers::Volatile:
  2168. Range = Chunk.Fun.getVolatileQualifierLoc();
  2169. break;
  2170. case Qualifiers::Const | Qualifiers::Volatile: {
  2171. SourceLocation CLoc = Chunk.Fun.getConstQualifierLoc();
  2172. SourceLocation VLoc = Chunk.Fun.getVolatileQualifierLoc();
  2173. if (S.getSourceManager()
  2174. .isBeforeInTranslationUnit(CLoc, VLoc)) {
  2175. Range = SourceRange(CLoc, VLoc);
  2176. } else {
  2177. Range = SourceRange(VLoc, CLoc);
  2178. }
  2179. }
  2180. break;
  2181. }
  2182. break;
  2183. }
  2184. }
  2185. S.Diag(Range.getBegin(), diag::err_invalid_qualified_function_type)
  2186. << FixItHint::CreateRemoval(Range);
  2187. } else
  2188. S.Diag(D.getIdentifierLoc(),
  2189. diag::err_invalid_qualified_typedef_function_type_use)
  2190. << FreeFunction;
  2191. }
  2192. if (FnTy->getRefQualifier()) {
  2193. if (D.isFunctionDeclarator()) {
  2194. SourceLocation Loc = D.getIdentifierLoc();
  2195. for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
  2196. const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
  2197. if (Chunk.Kind == DeclaratorChunk::Function &&
  2198. Chunk.Fun.hasRefQualifier()) {
  2199. Loc = Chunk.Fun.getRefQualifierLoc();
  2200. break;
  2201. }
  2202. }
  2203. S.Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
  2204. << (FnTy->getRefQualifier() == RQ_LValue)
  2205. << FixItHint::CreateRemoval(Loc);
  2206. } else {
  2207. S.Diag(D.getIdentifierLoc(),
  2208. diag::err_invalid_ref_qualifier_typedef_function_type_use)
  2209. << FreeFunction
  2210. << (FnTy->getRefQualifier() == RQ_LValue);
  2211. }
  2212. }
  2213. // Strip the cv-qualifiers and ref-qualifiers from the type.
  2214. FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
  2215. EPI.TypeQuals = 0;
  2216. EPI.RefQualifier = RQ_None;
  2217. T = Context.getFunctionType(FnTy->getResultType(),
  2218. FnTy->arg_type_begin(),
  2219. FnTy->getNumArgs(), EPI);
  2220. }
  2221. }
  2222. }
  2223. // Apply any undistributed attributes from the declarator.
  2224. if (!T.isNull())
  2225. if (AttributeList *attrs = D.getAttributes())
  2226. processTypeAttrs(state, T, false, attrs);
  2227. // Diagnose any ignored type attributes.
  2228. if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
  2229. // C++0x [dcl.constexpr]p9:
  2230. // A constexpr specifier used in an object declaration declares the object
  2231. // as const.
  2232. if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
  2233. T.addConst();
  2234. }
  2235. // If there was an ellipsis in the declarator, the declaration declares a
  2236. // parameter pack whose type may be a pack expansion type.
  2237. if (D.hasEllipsis() && !T.isNull()) {
  2238. // C++0x [dcl.fct]p13:
  2239. // A declarator-id or abstract-declarator containing an ellipsis shall
  2240. // only be used in a parameter-declaration. Such a parameter-declaration
  2241. // is a parameter pack (14.5.3). [...]
  2242. switch (D.getContext()) {
  2243. case Declarator::PrototypeContext:
  2244. // C++0x [dcl.fct]p13:
  2245. // [...] When it is part of a parameter-declaration-clause, the
  2246. // parameter pack is a function parameter pack (14.5.3). The type T
  2247. // of the declarator-id of the function parameter pack shall contain
  2248. // a template parameter pack; each template parameter pack in T is
  2249. // expanded by the function parameter pack.
  2250. //
  2251. // We represent function parameter packs as function parameters whose
  2252. // type is a pack expansion.
  2253. if (!T->containsUnexpandedParameterPack()) {
  2254. S.Diag(D.getEllipsisLoc(),
  2255. diag::err_function_parameter_pack_without_parameter_packs)
  2256. << T << D.getSourceRange();
  2257. D.setEllipsisLoc(SourceLocation());
  2258. } else {
  2259. T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
  2260. }
  2261. break;
  2262. case Declarator::TemplateParamContext:
  2263. // C++0x [temp.param]p15:
  2264. // If a template-parameter is a [...] is a parameter-declaration that
  2265. // declares a parameter pack (8.3.5), then the template-parameter is a
  2266. // template parameter pack (14.5.3).
  2267. //
  2268. // Note: core issue 778 clarifies that, if there are any unexpanded
  2269. // parameter packs in the type of the non-type template parameter, then
  2270. // it expands those parameter packs.
  2271. if (T->containsUnexpandedParameterPack())
  2272. T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
  2273. else
  2274. S.Diag(D.getEllipsisLoc(),
  2275. LangOpts.CPlusPlus0x
  2276. ? diag::warn_cxx98_compat_variadic_templates
  2277. : diag::ext_variadic_templates);
  2278. break;
  2279. case Declarator::FileContext:
  2280. case Declarator::KNRTypeListContext:
  2281. case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
  2282. case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
  2283. case Declarator::TypeNameContext:
  2284. case Declarator::CXXNewContext:
  2285. case Declarator::AliasDeclContext:
  2286. case Declarator::AliasTemplateContext:
  2287. case Declarator::MemberContext:
  2288. case Declarator::BlockContext:
  2289. case Declarator::ForContext:
  2290. case Declarator::ConditionContext:
  2291. case Declarator::CXXCatchContext:
  2292. case Declarator::ObjCCatchContext:
  2293. case Declarator::BlockLiteralContext:
  2294. case Declarator::TemplateTypeArgContext:
  2295. // FIXME: We may want to allow parameter packs in block-literal contexts
  2296. // in the future.
  2297. S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
  2298. D.setEllipsisLoc(SourceLocation());
  2299. break;
  2300. }
  2301. }
  2302. if (T.isNull())
  2303. return Context.getNullTypeSourceInfo();
  2304. else if (D.isInvalidType())
  2305. return Context.getTrivialTypeSourceInfo(T);
  2306. return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
  2307. }
  2308. /// GetTypeForDeclarator - Convert the type for the specified
  2309. /// declarator to Type instances.
  2310. ///
  2311. /// The result of this call will never be null, but the associated
  2312. /// type may be a null type if there's an unrecoverable error.
  2313. TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
  2314. // Determine the type of the declarator. Not all forms of declarator
  2315. // have a type.
  2316. TypeProcessingState state(*this, D);
  2317. TypeSourceInfo *ReturnTypeInfo = 0;
  2318. QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
  2319. if (T.isNull())
  2320. return Context.getNullTypeSourceInfo();
  2321. if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount)
  2322. inferARCWriteback(state, T);
  2323. return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
  2324. }
  2325. static void transferARCOwnershipToDeclSpec(Sema &S,
  2326. QualType &declSpecTy,
  2327. Qualifiers::ObjCLifetime ownership) {
  2328. if (declSpecTy->isObjCRetainableType() &&
  2329. declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
  2330. Qualifiers qs;
  2331. qs.addObjCLifetime(ownership);
  2332. declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
  2333. }
  2334. }
  2335. static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
  2336. Qualifiers::ObjCLifetime ownership,
  2337. unsigned chunkIndex) {
  2338. Sema &S = state.getSema();
  2339. Declarator &D = state.getDeclarator();
  2340. // Look for an explicit lifetime attribute.
  2341. DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
  2342. for (const AttributeList *attr = chunk.getAttrs(); attr;
  2343. attr = attr->getNext())
  2344. if (attr->getKind() == AttributeList::AT_objc_ownership)
  2345. return;
  2346. const char *attrStr = 0;
  2347. switch (ownership) {
  2348. case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
  2349. case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
  2350. case Qualifiers::OCL_Strong: attrStr = "strong"; break;
  2351. case Qualifiers::OCL_Weak: attrStr = "weak"; break;
  2352. case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
  2353. }
  2354. // If there wasn't one, add one (with an invalid source location
  2355. // so that we don't make an AttributedType for it).
  2356. AttributeList *attr = D.getAttributePool()
  2357. .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
  2358. /*scope*/ 0, SourceLocation(),
  2359. &S.Context.Idents.get(attrStr), SourceLocation(),
  2360. /*args*/ 0, 0,
  2361. /*declspec*/ false, /*C++0x*/ false);
  2362. spliceAttrIntoList(*attr, chunk.getAttrListRef());
  2363. // TODO: mark whether we did this inference?
  2364. }
  2365. /// \brief Used for transfering ownership in casts resulting in l-values.
  2366. static void transferARCOwnership(TypeProcessingState &state,
  2367. QualType &declSpecTy,
  2368. Qualifiers::ObjCLifetime ownership) {
  2369. Sema &S = state.getSema();
  2370. Declarator &D = state.getDeclarator();
  2371. int inner = -1;
  2372. bool hasIndirection = false;
  2373. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  2374. DeclaratorChunk &chunk = D.getTypeObject(i);
  2375. switch (chunk.Kind) {
  2376. case DeclaratorChunk::Paren:
  2377. // Ignore parens.
  2378. break;
  2379. case DeclaratorChunk::Array:
  2380. case DeclaratorChunk::Reference:
  2381. case DeclaratorChunk::Pointer:
  2382. if (inner != -1)
  2383. hasIndirection = true;
  2384. inner = i;
  2385. break;
  2386. case DeclaratorChunk::BlockPointer:
  2387. if (inner != -1)
  2388. transferARCOwnershipToDeclaratorChunk(state, ownership, i);
  2389. return;
  2390. case DeclaratorChunk::Function:
  2391. case DeclaratorChunk::MemberPointer:
  2392. return;
  2393. }
  2394. }
  2395. if (inner == -1)
  2396. return;
  2397. DeclaratorChunk &chunk = D.getTypeObject(inner);
  2398. if (chunk.Kind == DeclaratorChunk::Pointer) {
  2399. if (declSpecTy->isObjCRetainableType())
  2400. return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
  2401. if (declSpecTy->isObjCObjectType() && hasIndirection)
  2402. return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
  2403. } else {
  2404. assert(chunk.Kind == DeclaratorChunk::Array ||
  2405. chunk.Kind == DeclaratorChunk::Reference);
  2406. return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
  2407. }
  2408. }
  2409. TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
  2410. TypeProcessingState state(*this, D);
  2411. TypeSourceInfo *ReturnTypeInfo = 0;
  2412. QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
  2413. if (declSpecTy.isNull())
  2414. return Context.getNullTypeSourceInfo();
  2415. if (getLangOptions().ObjCAutoRefCount) {
  2416. Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
  2417. if (ownership != Qualifiers::OCL_None)
  2418. transferARCOwnership(state, declSpecTy, ownership);
  2419. }
  2420. return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
  2421. }
  2422. /// Map an AttributedType::Kind to an AttributeList::Kind.
  2423. static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
  2424. switch (kind) {
  2425. case AttributedType::attr_address_space:
  2426. return AttributeList::AT_address_space;
  2427. case AttributedType::attr_regparm:
  2428. return AttributeList::AT_regparm;
  2429. case AttributedType::attr_vector_size:
  2430. return AttributeList::AT_vector_size;
  2431. case AttributedType::attr_neon_vector_type:
  2432. return AttributeList::AT_neon_vector_type;
  2433. case AttributedType::attr_neon_polyvector_type:
  2434. return AttributeList::AT_neon_polyvector_type;
  2435. case AttributedType::attr_objc_gc:
  2436. return AttributeList::AT_objc_gc;
  2437. case AttributedType::attr_objc_ownership:
  2438. return AttributeList::AT_objc_ownership;
  2439. case AttributedType::attr_noreturn:
  2440. return AttributeList::AT_noreturn;
  2441. case AttributedType::attr_cdecl:
  2442. return AttributeList::AT_cdecl;
  2443. case AttributedType::attr_fastcall:
  2444. return AttributeList::AT_fastcall;
  2445. case AttributedType::attr_stdcall:
  2446. return AttributeList::AT_stdcall;
  2447. case AttributedType::attr_thiscall:
  2448. return AttributeList::AT_thiscall;
  2449. case AttributedType::attr_pascal:
  2450. return AttributeList::AT_pascal;
  2451. case AttributedType::attr_pcs:
  2452. return AttributeList::AT_pcs;
  2453. }
  2454. llvm_unreachable("unexpected attribute kind!");
  2455. return AttributeList::Kind();
  2456. }
  2457. static void fillAttributedTypeLoc(AttributedTypeLoc TL,
  2458. const AttributeList *attrs) {
  2459. AttributedType::Kind kind = TL.getAttrKind();
  2460. assert(attrs && "no type attributes in the expected location!");
  2461. AttributeList::Kind parsedKind = getAttrListKind(kind);
  2462. while (attrs->getKind() != parsedKind) {
  2463. attrs = attrs->getNext();
  2464. assert(attrs && "no matching attribute in expected location!");
  2465. }
  2466. TL.setAttrNameLoc(attrs->getLoc());
  2467. if (TL.hasAttrExprOperand())
  2468. TL.setAttrExprOperand(attrs->getArg(0));
  2469. else if (TL.hasAttrEnumOperand())
  2470. TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
  2471. // FIXME: preserve this information to here.
  2472. if (TL.hasAttrOperand())
  2473. TL.setAttrOperandParensRange(SourceRange());
  2474. }
  2475. namespace {
  2476. class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
  2477. ASTContext &Context;
  2478. const DeclSpec &DS;
  2479. public:
  2480. TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
  2481. : Context(Context), DS(DS) {}
  2482. void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  2483. fillAttributedTypeLoc(TL, DS.getAttributes().getList());
  2484. Visit(TL.getModifiedLoc());
  2485. }
  2486. void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  2487. Visit(TL.getUnqualifiedLoc());
  2488. }
  2489. void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  2490. TL.setNameLoc(DS.getTypeSpecTypeLoc());
  2491. }
  2492. void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  2493. TL.setNameLoc(DS.getTypeSpecTypeLoc());
  2494. }
  2495. void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  2496. // Handle the base type, which might not have been written explicitly.
  2497. if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
  2498. TL.setHasBaseTypeAsWritten(false);
  2499. TL.getBaseLoc().initialize(Context, SourceLocation());
  2500. } else {
  2501. TL.setHasBaseTypeAsWritten(true);
  2502. Visit(TL.getBaseLoc());
  2503. }
  2504. // Protocol qualifiers.
  2505. if (DS.getProtocolQualifiers()) {
  2506. assert(TL.getNumProtocols() > 0);
  2507. assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
  2508. TL.setLAngleLoc(DS.getProtocolLAngleLoc());
  2509. TL.setRAngleLoc(DS.getSourceRange().getEnd());
  2510. for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
  2511. TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
  2512. } else {
  2513. assert(TL.getNumProtocols() == 0);
  2514. TL.setLAngleLoc(SourceLocation());
  2515. TL.setRAngleLoc(SourceLocation());
  2516. }
  2517. }
  2518. void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  2519. TL.setStarLoc(SourceLocation());
  2520. Visit(TL.getPointeeLoc());
  2521. }
  2522. void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
  2523. TypeSourceInfo *TInfo = 0;
  2524. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2525. // If we got no declarator info from previous Sema routines,
  2526. // just fill with the typespec loc.
  2527. if (!TInfo) {
  2528. TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
  2529. return;
  2530. }
  2531. TypeLoc OldTL = TInfo->getTypeLoc();
  2532. if (TInfo->getType()->getAs<ElaboratedType>()) {
  2533. ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
  2534. TemplateSpecializationTypeLoc NamedTL =
  2535. cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
  2536. TL.copy(NamedTL);
  2537. }
  2538. else
  2539. TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
  2540. }
  2541. void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  2542. assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
  2543. TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
  2544. TL.setParensRange(DS.getTypeofParensRange());
  2545. }
  2546. void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  2547. assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
  2548. TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
  2549. TL.setParensRange(DS.getTypeofParensRange());
  2550. assert(DS.getRepAsType());
  2551. TypeSourceInfo *TInfo = 0;
  2552. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2553. TL.setUnderlyingTInfo(TInfo);
  2554. }
  2555. void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  2556. // FIXME: This holds only because we only have one unary transform.
  2557. assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
  2558. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  2559. TL.setParensRange(DS.getTypeofParensRange());
  2560. assert(DS.getRepAsType());
  2561. TypeSourceInfo *TInfo = 0;
  2562. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2563. TL.setUnderlyingTInfo(TInfo);
  2564. }
  2565. void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  2566. // By default, use the source location of the type specifier.
  2567. TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
  2568. if (TL.needsExtraLocalData()) {
  2569. // Set info for the written builtin specifiers.
  2570. TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
  2571. // Try to have a meaningful source location.
  2572. if (TL.getWrittenSignSpec() != TSS_unspecified)
  2573. // Sign spec loc overrides the others (e.g., 'unsigned long').
  2574. TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
  2575. else if (TL.getWrittenWidthSpec() != TSW_unspecified)
  2576. // Width spec loc overrides type spec loc (e.g., 'short int').
  2577. TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
  2578. }
  2579. }
  2580. void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  2581. ElaboratedTypeKeyword Keyword
  2582. = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
  2583. if (DS.getTypeSpecType() == TST_typename) {
  2584. TypeSourceInfo *TInfo = 0;
  2585. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2586. if (TInfo) {
  2587. TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
  2588. return;
  2589. }
  2590. }
  2591. TL.setKeywordLoc(Keyword != ETK_None
  2592. ? DS.getTypeSpecTypeLoc()
  2593. : SourceLocation());
  2594. const CXXScopeSpec& SS = DS.getTypeSpecScope();
  2595. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  2596. Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
  2597. }
  2598. void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  2599. ElaboratedTypeKeyword Keyword
  2600. = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
  2601. if (DS.getTypeSpecType() == TST_typename) {
  2602. TypeSourceInfo *TInfo = 0;
  2603. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2604. if (TInfo) {
  2605. TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
  2606. return;
  2607. }
  2608. }
  2609. TL.setKeywordLoc(Keyword != ETK_None
  2610. ? DS.getTypeSpecTypeLoc()
  2611. : SourceLocation());
  2612. const CXXScopeSpec& SS = DS.getTypeSpecScope();
  2613. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  2614. TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
  2615. }
  2616. void VisitDependentTemplateSpecializationTypeLoc(
  2617. DependentTemplateSpecializationTypeLoc TL) {
  2618. ElaboratedTypeKeyword Keyword
  2619. = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
  2620. if (Keyword == ETK_Typename) {
  2621. TypeSourceInfo *TInfo = 0;
  2622. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2623. if (TInfo) {
  2624. TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
  2625. TInfo->getTypeLoc()));
  2626. return;
  2627. }
  2628. }
  2629. TL.initializeLocal(Context, SourceLocation());
  2630. TL.setKeywordLoc(Keyword != ETK_None
  2631. ? DS.getTypeSpecTypeLoc()
  2632. : SourceLocation());
  2633. const CXXScopeSpec& SS = DS.getTypeSpecScope();
  2634. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  2635. TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
  2636. }
  2637. void VisitTagTypeLoc(TagTypeLoc TL) {
  2638. TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
  2639. }
  2640. void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  2641. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  2642. TL.setParensRange(DS.getTypeofParensRange());
  2643. TypeSourceInfo *TInfo = 0;
  2644. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2645. TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
  2646. }
  2647. void VisitTypeLoc(TypeLoc TL) {
  2648. // FIXME: add other typespec types and change this to an assert.
  2649. TL.initialize(Context, DS.getTypeSpecTypeLoc());
  2650. }
  2651. };
  2652. class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
  2653. ASTContext &Context;
  2654. const DeclaratorChunk &Chunk;
  2655. public:
  2656. DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
  2657. : Context(Context), Chunk(Chunk) {}
  2658. void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  2659. llvm_unreachable("qualified type locs not expected here!");
  2660. }
  2661. void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  2662. fillAttributedTypeLoc(TL, Chunk.getAttrs());
  2663. }
  2664. void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  2665. assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
  2666. TL.setCaretLoc(Chunk.Loc);
  2667. }
  2668. void VisitPointerTypeLoc(PointerTypeLoc TL) {
  2669. assert(Chunk.Kind == DeclaratorChunk::Pointer);
  2670. TL.setStarLoc(Chunk.Loc);
  2671. }
  2672. void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  2673. assert(Chunk.Kind == DeclaratorChunk::Pointer);
  2674. TL.setStarLoc(Chunk.Loc);
  2675. }
  2676. void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  2677. assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
  2678. const CXXScopeSpec& SS = Chunk.Mem.Scope();
  2679. NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
  2680. const Type* ClsTy = TL.getClass();
  2681. QualType ClsQT = QualType(ClsTy, 0);
  2682. TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
  2683. // Now copy source location info into the type loc component.
  2684. TypeLoc ClsTL = ClsTInfo->getTypeLoc();
  2685. switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
  2686. case NestedNameSpecifier::Identifier:
  2687. assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
  2688. {
  2689. DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
  2690. DNTLoc.setKeywordLoc(SourceLocation());
  2691. DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
  2692. DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
  2693. }
  2694. break;
  2695. case NestedNameSpecifier::TypeSpec:
  2696. case NestedNameSpecifier::TypeSpecWithTemplate:
  2697. if (isa<ElaboratedType>(ClsTy)) {
  2698. ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
  2699. ETLoc.setKeywordLoc(SourceLocation());
  2700. ETLoc.setQualifierLoc(NNSLoc.getPrefix());
  2701. TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
  2702. NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
  2703. } else {
  2704. ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
  2705. }
  2706. break;
  2707. case NestedNameSpecifier::Namespace:
  2708. case NestedNameSpecifier::NamespaceAlias:
  2709. case NestedNameSpecifier::Global:
  2710. llvm_unreachable("Nested-name-specifier must name a type");
  2711. break;
  2712. }
  2713. // Finally fill in MemberPointerLocInfo fields.
  2714. TL.setStarLoc(Chunk.Loc);
  2715. TL.setClassTInfo(ClsTInfo);
  2716. }
  2717. void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  2718. assert(Chunk.Kind == DeclaratorChunk::Reference);
  2719. // 'Amp' is misleading: this might have been originally
  2720. /// spelled with AmpAmp.
  2721. TL.setAmpLoc(Chunk.Loc);
  2722. }
  2723. void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  2724. assert(Chunk.Kind == DeclaratorChunk::Reference);
  2725. assert(!Chunk.Ref.LValueRef);
  2726. TL.setAmpAmpLoc(Chunk.Loc);
  2727. }
  2728. void VisitArrayTypeLoc(ArrayTypeLoc TL) {
  2729. assert(Chunk.Kind == DeclaratorChunk::Array);
  2730. TL.setLBracketLoc(Chunk.Loc);
  2731. TL.setRBracketLoc(Chunk.EndLoc);
  2732. TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
  2733. }
  2734. void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  2735. assert(Chunk.Kind == DeclaratorChunk::Function);
  2736. TL.setLocalRangeBegin(Chunk.Loc);
  2737. TL.setLocalRangeEnd(Chunk.EndLoc);
  2738. TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
  2739. const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
  2740. for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
  2741. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
  2742. TL.setArg(tpi++, Param);
  2743. }
  2744. // FIXME: exception specs
  2745. }
  2746. void VisitParenTypeLoc(ParenTypeLoc TL) {
  2747. assert(Chunk.Kind == DeclaratorChunk::Paren);
  2748. TL.setLParenLoc(Chunk.Loc);
  2749. TL.setRParenLoc(Chunk.EndLoc);
  2750. }
  2751. void VisitTypeLoc(TypeLoc TL) {
  2752. llvm_unreachable("unsupported TypeLoc kind in declarator!");
  2753. }
  2754. };
  2755. }
  2756. /// \brief Create and instantiate a TypeSourceInfo with type source information.
  2757. ///
  2758. /// \param T QualType referring to the type as written in source code.
  2759. ///
  2760. /// \param ReturnTypeInfo For declarators whose return type does not show
  2761. /// up in the normal place in the declaration specifiers (such as a C++
  2762. /// conversion function), this pointer will refer to a type source information
  2763. /// for that return type.
  2764. TypeSourceInfo *
  2765. Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
  2766. TypeSourceInfo *ReturnTypeInfo) {
  2767. TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
  2768. UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
  2769. // Handle parameter packs whose type is a pack expansion.
  2770. if (isa<PackExpansionType>(T)) {
  2771. cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
  2772. CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
  2773. }
  2774. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  2775. while (isa<AttributedTypeLoc>(CurrTL)) {
  2776. AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
  2777. fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
  2778. CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
  2779. }
  2780. DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
  2781. CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
  2782. }
  2783. // If we have different source information for the return type, use
  2784. // that. This really only applies to C++ conversion functions.
  2785. if (ReturnTypeInfo) {
  2786. TypeLoc TL = ReturnTypeInfo->getTypeLoc();
  2787. assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
  2788. memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
  2789. } else {
  2790. TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
  2791. }
  2792. return TInfo;
  2793. }
  2794. /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
  2795. ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
  2796. // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
  2797. // and Sema during declaration parsing. Try deallocating/caching them when
  2798. // it's appropriate, instead of allocating them and keeping them around.
  2799. LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
  2800. TypeAlignment);
  2801. new (LocT) LocInfoType(T, TInfo);
  2802. assert(LocT->getTypeClass() != T->getTypeClass() &&
  2803. "LocInfoType's TypeClass conflicts with an existing Type class");
  2804. return ParsedType::make(QualType(LocT, 0));
  2805. }
  2806. void LocInfoType::getAsStringInternal(std::string &Str,
  2807. const PrintingPolicy &Policy) const {
  2808. llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
  2809. " was used directly instead of getting the QualType through"
  2810. " GetTypeFromParser");
  2811. }
  2812. TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
  2813. // C99 6.7.6: Type names have no identifier. This is already validated by
  2814. // the parser.
  2815. assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
  2816. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  2817. QualType T = TInfo->getType();
  2818. if (D.isInvalidType())
  2819. return true;
  2820. // Make sure there are no unused decl attributes on the declarator.
  2821. // We don't want to do this for ObjC parameters because we're going
  2822. // to apply them to the actual parameter declaration.
  2823. if (D.getContext() != Declarator::ObjCParameterContext)
  2824. checkUnusedDeclAttributes(D);
  2825. if (getLangOptions().CPlusPlus) {
  2826. // Check that there are no default arguments (C++ only).
  2827. CheckExtraCXXDefaultArguments(D);
  2828. }
  2829. return CreateParsedType(T, TInfo);
  2830. }
  2831. ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
  2832. QualType T = Context.getObjCInstanceType();
  2833. TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  2834. return CreateParsedType(T, TInfo);
  2835. }
  2836. //===----------------------------------------------------------------------===//
  2837. // Type Attribute Processing
  2838. //===----------------------------------------------------------------------===//
  2839. /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
  2840. /// specified type. The attribute contains 1 argument, the id of the address
  2841. /// space for the type.
  2842. static void HandleAddressSpaceTypeAttribute(QualType &Type,
  2843. const AttributeList &Attr, Sema &S){
  2844. // If this type is already address space qualified, reject it.
  2845. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
  2846. // qualifiers for two or more different address spaces."
  2847. if (Type.getAddressSpace()) {
  2848. S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
  2849. Attr.setInvalid();
  2850. return;
  2851. }
  2852. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
  2853. // qualified by an address-space qualifier."
  2854. if (Type->isFunctionType()) {
  2855. S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
  2856. Attr.setInvalid();
  2857. return;
  2858. }
  2859. // Check the attribute arguments.
  2860. if (Attr.getNumArgs() != 1) {
  2861. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  2862. Attr.setInvalid();
  2863. return;
  2864. }
  2865. Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
  2866. llvm::APSInt addrSpace(32);
  2867. if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
  2868. !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
  2869. S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
  2870. << ASArgExpr->getSourceRange();
  2871. Attr.setInvalid();
  2872. return;
  2873. }
  2874. // Bounds checking.
  2875. if (addrSpace.isSigned()) {
  2876. if (addrSpace.isNegative()) {
  2877. S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
  2878. << ASArgExpr->getSourceRange();
  2879. Attr.setInvalid();
  2880. return;
  2881. }
  2882. addrSpace.setIsSigned(false);
  2883. }
  2884. llvm::APSInt max(addrSpace.getBitWidth());
  2885. max = Qualifiers::MaxAddressSpace;
  2886. if (addrSpace > max) {
  2887. S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
  2888. << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
  2889. Attr.setInvalid();
  2890. return;
  2891. }
  2892. unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
  2893. Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
  2894. }
  2895. /// handleObjCOwnershipTypeAttr - Process an objc_ownership
  2896. /// attribute on the specified type.
  2897. ///
  2898. /// Returns 'true' if the attribute was handled.
  2899. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
  2900. AttributeList &attr,
  2901. QualType &type) {
  2902. bool NonObjCPointer = false;
  2903. if (!type->isDependentType()) {
  2904. if (const PointerType *ptr = type->getAs<PointerType>()) {
  2905. QualType pointee = ptr->getPointeeType();
  2906. if (pointee->isObjCRetainableType() || pointee->isPointerType())
  2907. return false;
  2908. // It is important not to lose the source info that there was an attribute
  2909. // applied to non-objc pointer. We will create an attributed type but
  2910. // its type will be the same as the original type.
  2911. NonObjCPointer = true;
  2912. } else if (!type->isObjCRetainableType()) {
  2913. return false;
  2914. }
  2915. }
  2916. Sema &S = state.getSema();
  2917. SourceLocation AttrLoc = attr.getLoc();
  2918. if (AttrLoc.isMacroID())
  2919. AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
  2920. if (type.getQualifiers().getObjCLifetime()) {
  2921. S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
  2922. << type;
  2923. return true;
  2924. }
  2925. if (!attr.getParameterName()) {
  2926. S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
  2927. << "objc_ownership" << 1;
  2928. attr.setInvalid();
  2929. return true;
  2930. }
  2931. Qualifiers::ObjCLifetime lifetime;
  2932. if (attr.getParameterName()->isStr("none"))
  2933. lifetime = Qualifiers::OCL_ExplicitNone;
  2934. else if (attr.getParameterName()->isStr("strong"))
  2935. lifetime = Qualifiers::OCL_Strong;
  2936. else if (attr.getParameterName()->isStr("weak"))
  2937. lifetime = Qualifiers::OCL_Weak;
  2938. else if (attr.getParameterName()->isStr("autoreleasing"))
  2939. lifetime = Qualifiers::OCL_Autoreleasing;
  2940. else {
  2941. S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
  2942. << "objc_ownership" << attr.getParameterName();
  2943. attr.setInvalid();
  2944. return true;
  2945. }
  2946. // Consume lifetime attributes without further comment outside of
  2947. // ARC mode.
  2948. if (!S.getLangOptions().ObjCAutoRefCount)
  2949. return true;
  2950. if (NonObjCPointer) {
  2951. StringRef name = attr.getName()->getName();
  2952. switch (lifetime) {
  2953. case Qualifiers::OCL_None:
  2954. case Qualifiers::OCL_ExplicitNone:
  2955. break;
  2956. case Qualifiers::OCL_Strong: name = "__strong"; break;
  2957. case Qualifiers::OCL_Weak: name = "__weak"; break;
  2958. case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
  2959. }
  2960. S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
  2961. << name << type;
  2962. }
  2963. Qualifiers qs;
  2964. qs.setObjCLifetime(lifetime);
  2965. QualType origType = type;
  2966. if (!NonObjCPointer)
  2967. type = S.Context.getQualifiedType(type, qs);
  2968. // If we have a valid source location for the attribute, use an
  2969. // AttributedType instead.
  2970. if (AttrLoc.isValid())
  2971. type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
  2972. origType, type);
  2973. // Forbid __weak if the runtime doesn't support it.
  2974. if (lifetime == Qualifiers::OCL_Weak &&
  2975. !S.getLangOptions().ObjCRuntimeHasWeak && !NonObjCPointer) {
  2976. // Actually, delay this until we know what we're parsing.
  2977. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  2978. S.DelayedDiagnostics.add(
  2979. sema::DelayedDiagnostic::makeForbiddenType(
  2980. S.getSourceManager().getExpansionLoc(AttrLoc),
  2981. diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
  2982. } else {
  2983. S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
  2984. }
  2985. attr.setInvalid();
  2986. return true;
  2987. }
  2988. // Forbid __weak for class objects marked as
  2989. // objc_arc_weak_reference_unavailable
  2990. if (lifetime == Qualifiers::OCL_Weak) {
  2991. QualType T = type;
  2992. while (const PointerType *ptr = T->getAs<PointerType>())
  2993. T = ptr->getPointeeType();
  2994. if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
  2995. ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
  2996. if (Class->isArcWeakrefUnavailable()) {
  2997. S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
  2998. S.Diag(ObjT->getInterfaceDecl()->getLocation(),
  2999. diag::note_class_declared);
  3000. }
  3001. }
  3002. }
  3003. return true;
  3004. }
  3005. /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
  3006. /// attribute on the specified type. Returns true to indicate that
  3007. /// the attribute was handled, false to indicate that the type does
  3008. /// not permit the attribute.
  3009. static bool handleObjCGCTypeAttr(TypeProcessingState &state,
  3010. AttributeList &attr,
  3011. QualType &type) {
  3012. Sema &S = state.getSema();
  3013. // Delay if this isn't some kind of pointer.
  3014. if (!type->isPointerType() &&
  3015. !type->isObjCObjectPointerType() &&
  3016. !type->isBlockPointerType())
  3017. return false;
  3018. if (type.getObjCGCAttr() != Qualifiers::GCNone) {
  3019. S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
  3020. attr.setInvalid();
  3021. return true;
  3022. }
  3023. // Check the attribute arguments.
  3024. if (!attr.getParameterName()) {
  3025. S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
  3026. << "objc_gc" << 1;
  3027. attr.setInvalid();
  3028. return true;
  3029. }
  3030. Qualifiers::GC GCAttr;
  3031. if (attr.getNumArgs() != 0) {
  3032. S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  3033. attr.setInvalid();
  3034. return true;
  3035. }
  3036. if (attr.getParameterName()->isStr("weak"))
  3037. GCAttr = Qualifiers::Weak;
  3038. else if (attr.getParameterName()->isStr("strong"))
  3039. GCAttr = Qualifiers::Strong;
  3040. else {
  3041. S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
  3042. << "objc_gc" << attr.getParameterName();
  3043. attr.setInvalid();
  3044. return true;
  3045. }
  3046. QualType origType = type;
  3047. type = S.Context.getObjCGCQualType(origType, GCAttr);
  3048. // Make an attributed type to preserve the source information.
  3049. if (attr.getLoc().isValid())
  3050. type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
  3051. origType, type);
  3052. return true;
  3053. }
  3054. namespace {
  3055. /// A helper class to unwrap a type down to a function for the
  3056. /// purposes of applying attributes there.
  3057. ///
  3058. /// Use:
  3059. /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
  3060. /// if (unwrapped.isFunctionType()) {
  3061. /// const FunctionType *fn = unwrapped.get();
  3062. /// // change fn somehow
  3063. /// T = unwrapped.wrap(fn);
  3064. /// }
  3065. struct FunctionTypeUnwrapper {
  3066. enum WrapKind {
  3067. Desugar,
  3068. Parens,
  3069. Pointer,
  3070. BlockPointer,
  3071. Reference,
  3072. MemberPointer
  3073. };
  3074. QualType Original;
  3075. const FunctionType *Fn;
  3076. SmallVector<unsigned char /*WrapKind*/, 8> Stack;
  3077. FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
  3078. while (true) {
  3079. const Type *Ty = T.getTypePtr();
  3080. if (isa<FunctionType>(Ty)) {
  3081. Fn = cast<FunctionType>(Ty);
  3082. return;
  3083. } else if (isa<ParenType>(Ty)) {
  3084. T = cast<ParenType>(Ty)->getInnerType();
  3085. Stack.push_back(Parens);
  3086. } else if (isa<PointerType>(Ty)) {
  3087. T = cast<PointerType>(Ty)->getPointeeType();
  3088. Stack.push_back(Pointer);
  3089. } else if (isa<BlockPointerType>(Ty)) {
  3090. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3091. Stack.push_back(BlockPointer);
  3092. } else if (isa<MemberPointerType>(Ty)) {
  3093. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3094. Stack.push_back(MemberPointer);
  3095. } else if (isa<ReferenceType>(Ty)) {
  3096. T = cast<ReferenceType>(Ty)->getPointeeType();
  3097. Stack.push_back(Reference);
  3098. } else {
  3099. const Type *DTy = Ty->getUnqualifiedDesugaredType();
  3100. if (Ty == DTy) {
  3101. Fn = 0;
  3102. return;
  3103. }
  3104. T = QualType(DTy, 0);
  3105. Stack.push_back(Desugar);
  3106. }
  3107. }
  3108. }
  3109. bool isFunctionType() const { return (Fn != 0); }
  3110. const FunctionType *get() const { return Fn; }
  3111. QualType wrap(Sema &S, const FunctionType *New) {
  3112. // If T wasn't modified from the unwrapped type, do nothing.
  3113. if (New == get()) return Original;
  3114. Fn = New;
  3115. return wrap(S.Context, Original, 0);
  3116. }
  3117. private:
  3118. QualType wrap(ASTContext &C, QualType Old, unsigned I) {
  3119. if (I == Stack.size())
  3120. return C.getQualifiedType(Fn, Old.getQualifiers());
  3121. // Build up the inner type, applying the qualifiers from the old
  3122. // type to the new type.
  3123. SplitQualType SplitOld = Old.split();
  3124. // As a special case, tail-recurse if there are no qualifiers.
  3125. if (SplitOld.second.empty())
  3126. return wrap(C, SplitOld.first, I);
  3127. return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
  3128. }
  3129. QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
  3130. if (I == Stack.size()) return QualType(Fn, 0);
  3131. switch (static_cast<WrapKind>(Stack[I++])) {
  3132. case Desugar:
  3133. // This is the point at which we potentially lose source
  3134. // information.
  3135. return wrap(C, Old->getUnqualifiedDesugaredType(), I);
  3136. case Parens: {
  3137. QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
  3138. return C.getParenType(New);
  3139. }
  3140. case Pointer: {
  3141. QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
  3142. return C.getPointerType(New);
  3143. }
  3144. case BlockPointer: {
  3145. QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
  3146. return C.getBlockPointerType(New);
  3147. }
  3148. case MemberPointer: {
  3149. const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
  3150. QualType New = wrap(C, OldMPT->getPointeeType(), I);
  3151. return C.getMemberPointerType(New, OldMPT->getClass());
  3152. }
  3153. case Reference: {
  3154. const ReferenceType *OldRef = cast<ReferenceType>(Old);
  3155. QualType New = wrap(C, OldRef->getPointeeType(), I);
  3156. if (isa<LValueReferenceType>(OldRef))
  3157. return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
  3158. else
  3159. return C.getRValueReferenceType(New);
  3160. }
  3161. }
  3162. llvm_unreachable("unknown wrapping kind");
  3163. return QualType();
  3164. }
  3165. };
  3166. }
  3167. /// Process an individual function attribute. Returns true to
  3168. /// indicate that the attribute was handled, false if it wasn't.
  3169. static bool handleFunctionTypeAttr(TypeProcessingState &state,
  3170. AttributeList &attr,
  3171. QualType &type) {
  3172. Sema &S = state.getSema();
  3173. FunctionTypeUnwrapper unwrapped(S, type);
  3174. if (attr.getKind() == AttributeList::AT_noreturn) {
  3175. if (S.CheckNoReturnAttr(attr))
  3176. return true;
  3177. // Delay if this is not a function type.
  3178. if (!unwrapped.isFunctionType())
  3179. return false;
  3180. // Otherwise we can process right away.
  3181. FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
  3182. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  3183. return true;
  3184. }
  3185. // ns_returns_retained is not always a type attribute, but if we got
  3186. // here, we're treating it as one right now.
  3187. if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
  3188. assert(S.getLangOptions().ObjCAutoRefCount &&
  3189. "ns_returns_retained treated as type attribute in non-ARC");
  3190. if (attr.getNumArgs()) return true;
  3191. // Delay if this is not a function type.
  3192. if (!unwrapped.isFunctionType())
  3193. return false;
  3194. FunctionType::ExtInfo EI
  3195. = unwrapped.get()->getExtInfo().withProducesResult(true);
  3196. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  3197. return true;
  3198. }
  3199. if (attr.getKind() == AttributeList::AT_regparm) {
  3200. unsigned value;
  3201. if (S.CheckRegparmAttr(attr, value))
  3202. return true;
  3203. // Delay if this is not a function type.
  3204. if (!unwrapped.isFunctionType())
  3205. return false;
  3206. // Diagnose regparm with fastcall.
  3207. const FunctionType *fn = unwrapped.get();
  3208. CallingConv CC = fn->getCallConv();
  3209. if (CC == CC_X86FastCall) {
  3210. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  3211. << FunctionType::getNameForCallConv(CC)
  3212. << "regparm";
  3213. attr.setInvalid();
  3214. return true;
  3215. }
  3216. FunctionType::ExtInfo EI =
  3217. unwrapped.get()->getExtInfo().withRegParm(value);
  3218. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  3219. return true;
  3220. }
  3221. // Otherwise, a calling convention.
  3222. CallingConv CC;
  3223. if (S.CheckCallingConvAttr(attr, CC))
  3224. return true;
  3225. // Delay if the type didn't work out to a function.
  3226. if (!unwrapped.isFunctionType()) return false;
  3227. const FunctionType *fn = unwrapped.get();
  3228. CallingConv CCOld = fn->getCallConv();
  3229. if (S.Context.getCanonicalCallConv(CC) ==
  3230. S.Context.getCanonicalCallConv(CCOld)) {
  3231. FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
  3232. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  3233. return true;
  3234. }
  3235. if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
  3236. // Should we diagnose reapplications of the same convention?
  3237. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  3238. << FunctionType::getNameForCallConv(CC)
  3239. << FunctionType::getNameForCallConv(CCOld);
  3240. attr.setInvalid();
  3241. return true;
  3242. }
  3243. // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
  3244. if (CC == CC_X86FastCall) {
  3245. if (isa<FunctionNoProtoType>(fn)) {
  3246. S.Diag(attr.getLoc(), diag::err_cconv_knr)
  3247. << FunctionType::getNameForCallConv(CC);
  3248. attr.setInvalid();
  3249. return true;
  3250. }
  3251. const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
  3252. if (FnP->isVariadic()) {
  3253. S.Diag(attr.getLoc(), diag::err_cconv_varargs)
  3254. << FunctionType::getNameForCallConv(CC);
  3255. attr.setInvalid();
  3256. return true;
  3257. }
  3258. // Also diagnose fastcall with regparm.
  3259. if (fn->getHasRegParm()) {
  3260. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  3261. << "regparm"
  3262. << FunctionType::getNameForCallConv(CC);
  3263. attr.setInvalid();
  3264. return true;
  3265. }
  3266. }
  3267. FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
  3268. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  3269. return true;
  3270. }
  3271. /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
  3272. static void HandleOpenCLImageAccessAttribute(QualType& CurType,
  3273. const AttributeList &Attr,
  3274. Sema &S) {
  3275. // Check the attribute arguments.
  3276. if (Attr.getNumArgs() != 1) {
  3277. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  3278. Attr.setInvalid();
  3279. return;
  3280. }
  3281. Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
  3282. llvm::APSInt arg(32);
  3283. if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
  3284. !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
  3285. S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
  3286. << "opencl_image_access" << sizeExpr->getSourceRange();
  3287. Attr.setInvalid();
  3288. return;
  3289. }
  3290. unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
  3291. switch (iarg) {
  3292. case CLIA_read_only:
  3293. case CLIA_write_only:
  3294. case CLIA_read_write:
  3295. // Implemented in a separate patch
  3296. break;
  3297. default:
  3298. // Implemented in a separate patch
  3299. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
  3300. << sizeExpr->getSourceRange();
  3301. Attr.setInvalid();
  3302. break;
  3303. }
  3304. }
  3305. /// HandleVectorSizeAttribute - this attribute is only applicable to integral
  3306. /// and float scalars, although arrays, pointers, and function return values are
  3307. /// allowed in conjunction with this construct. Aggregates with this attribute
  3308. /// are invalid, even if they are of the same size as a corresponding scalar.
  3309. /// The raw attribute should contain precisely 1 argument, the vector size for
  3310. /// the variable, measured in bytes. If curType and rawAttr are well formed,
  3311. /// this routine will return a new vector type.
  3312. static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
  3313. Sema &S) {
  3314. // Check the attribute arguments.
  3315. if (Attr.getNumArgs() != 1) {
  3316. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  3317. Attr.setInvalid();
  3318. return;
  3319. }
  3320. Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
  3321. llvm::APSInt vecSize(32);
  3322. if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
  3323. !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
  3324. S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
  3325. << "vector_size" << sizeExpr->getSourceRange();
  3326. Attr.setInvalid();
  3327. return;
  3328. }
  3329. // the base type must be integer or float, and can't already be a vector.
  3330. if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
  3331. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
  3332. Attr.setInvalid();
  3333. return;
  3334. }
  3335. unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
  3336. // vecSize is specified in bytes - convert to bits.
  3337. unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
  3338. // the vector size needs to be an integral multiple of the type size.
  3339. if (vectorSize % typeSize) {
  3340. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
  3341. << sizeExpr->getSourceRange();
  3342. Attr.setInvalid();
  3343. return;
  3344. }
  3345. if (vectorSize == 0) {
  3346. S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
  3347. << sizeExpr->getSourceRange();
  3348. Attr.setInvalid();
  3349. return;
  3350. }
  3351. // Success! Instantiate the vector type, the number of elements is > 0, and
  3352. // not required to be a power of 2, unlike GCC.
  3353. CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
  3354. VectorType::GenericVector);
  3355. }
  3356. /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
  3357. /// a type.
  3358. static void HandleExtVectorTypeAttr(QualType &CurType,
  3359. const AttributeList &Attr,
  3360. Sema &S) {
  3361. Expr *sizeExpr;
  3362. // Special case where the argument is a template id.
  3363. if (Attr.getParameterName()) {
  3364. CXXScopeSpec SS;
  3365. UnqualifiedId id;
  3366. id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
  3367. ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, id, false,
  3368. false);
  3369. if (Size.isInvalid())
  3370. return;
  3371. sizeExpr = Size.get();
  3372. } else {
  3373. // check the attribute arguments.
  3374. if (Attr.getNumArgs() != 1) {
  3375. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  3376. return;
  3377. }
  3378. sizeExpr = Attr.getArg(0);
  3379. }
  3380. // Create the vector type.
  3381. QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
  3382. if (!T.isNull())
  3383. CurType = T;
  3384. }
  3385. /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
  3386. /// "neon_polyvector_type" attributes are used to create vector types that
  3387. /// are mangled according to ARM's ABI. Otherwise, these types are identical
  3388. /// to those created with the "vector_size" attribute. Unlike "vector_size"
  3389. /// the argument to these Neon attributes is the number of vector elements,
  3390. /// not the vector size in bytes. The vector width and element type must
  3391. /// match one of the standard Neon vector types.
  3392. static void HandleNeonVectorTypeAttr(QualType& CurType,
  3393. const AttributeList &Attr, Sema &S,
  3394. VectorType::VectorKind VecKind,
  3395. const char *AttrName) {
  3396. // Check the attribute arguments.
  3397. if (Attr.getNumArgs() != 1) {
  3398. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  3399. Attr.setInvalid();
  3400. return;
  3401. }
  3402. // The number of elements must be an ICE.
  3403. Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
  3404. llvm::APSInt numEltsInt(32);
  3405. if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
  3406. !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
  3407. S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
  3408. << AttrName << numEltsExpr->getSourceRange();
  3409. Attr.setInvalid();
  3410. return;
  3411. }
  3412. // Only certain element types are supported for Neon vectors.
  3413. const BuiltinType* BTy = CurType->getAs<BuiltinType>();
  3414. if (!BTy ||
  3415. (VecKind == VectorType::NeonPolyVector &&
  3416. BTy->getKind() != BuiltinType::SChar &&
  3417. BTy->getKind() != BuiltinType::Short) ||
  3418. (BTy->getKind() != BuiltinType::SChar &&
  3419. BTy->getKind() != BuiltinType::UChar &&
  3420. BTy->getKind() != BuiltinType::Short &&
  3421. BTy->getKind() != BuiltinType::UShort &&
  3422. BTy->getKind() != BuiltinType::Int &&
  3423. BTy->getKind() != BuiltinType::UInt &&
  3424. BTy->getKind() != BuiltinType::LongLong &&
  3425. BTy->getKind() != BuiltinType::ULongLong &&
  3426. BTy->getKind() != BuiltinType::Float)) {
  3427. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
  3428. Attr.setInvalid();
  3429. return;
  3430. }
  3431. // The total size of the vector must be 64 or 128 bits.
  3432. unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
  3433. unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
  3434. unsigned vecSize = typeSize * numElts;
  3435. if (vecSize != 64 && vecSize != 128) {
  3436. S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
  3437. Attr.setInvalid();
  3438. return;
  3439. }
  3440. CurType = S.Context.getVectorType(CurType, numElts, VecKind);
  3441. }
  3442. static void processTypeAttrs(TypeProcessingState &state, QualType &type,
  3443. bool isDeclSpec, AttributeList *attrs) {
  3444. // Scan through and apply attributes to this type where it makes sense. Some
  3445. // attributes (such as __address_space__, __vector_size__, etc) apply to the
  3446. // type, but others can be present in the type specifiers even though they
  3447. // apply to the decl. Here we apply type attributes and ignore the rest.
  3448. AttributeList *next;
  3449. do {
  3450. AttributeList &attr = *attrs;
  3451. next = attr.getNext();
  3452. // Skip attributes that were marked to be invalid.
  3453. if (attr.isInvalid())
  3454. continue;
  3455. // If this is an attribute we can handle, do so now,
  3456. // otherwise, add it to the FnAttrs list for rechaining.
  3457. switch (attr.getKind()) {
  3458. default: break;
  3459. case AttributeList::AT_may_alias:
  3460. // FIXME: This attribute needs to actually be handled, but if we ignore
  3461. // it it breaks large amounts of Linux software.
  3462. attr.setUsedAsTypeAttr();
  3463. break;
  3464. case AttributeList::AT_address_space:
  3465. HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
  3466. attr.setUsedAsTypeAttr();
  3467. break;
  3468. OBJC_POINTER_TYPE_ATTRS_CASELIST:
  3469. if (!handleObjCPointerTypeAttr(state, attr, type))
  3470. distributeObjCPointerTypeAttr(state, attr, type);
  3471. attr.setUsedAsTypeAttr();
  3472. break;
  3473. case AttributeList::AT_vector_size:
  3474. HandleVectorSizeAttr(type, attr, state.getSema());
  3475. attr.setUsedAsTypeAttr();
  3476. break;
  3477. case AttributeList::AT_ext_vector_type:
  3478. if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
  3479. != DeclSpec::SCS_typedef)
  3480. HandleExtVectorTypeAttr(type, attr, state.getSema());
  3481. attr.setUsedAsTypeAttr();
  3482. break;
  3483. case AttributeList::AT_neon_vector_type:
  3484. HandleNeonVectorTypeAttr(type, attr, state.getSema(),
  3485. VectorType::NeonVector, "neon_vector_type");
  3486. attr.setUsedAsTypeAttr();
  3487. break;
  3488. case AttributeList::AT_neon_polyvector_type:
  3489. HandleNeonVectorTypeAttr(type, attr, state.getSema(),
  3490. VectorType::NeonPolyVector,
  3491. "neon_polyvector_type");
  3492. attr.setUsedAsTypeAttr();
  3493. break;
  3494. case AttributeList::AT_opencl_image_access:
  3495. HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
  3496. attr.setUsedAsTypeAttr();
  3497. break;
  3498. case AttributeList::AT_ns_returns_retained:
  3499. if (!state.getSema().getLangOptions().ObjCAutoRefCount)
  3500. break;
  3501. // fallthrough into the function attrs
  3502. FUNCTION_TYPE_ATTRS_CASELIST:
  3503. attr.setUsedAsTypeAttr();
  3504. // Never process function type attributes as part of the
  3505. // declaration-specifiers.
  3506. if (isDeclSpec)
  3507. distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
  3508. // Otherwise, handle the possible delays.
  3509. else if (!handleFunctionTypeAttr(state, attr, type))
  3510. distributeFunctionTypeAttr(state, attr, type);
  3511. break;
  3512. }
  3513. } while ((attrs = next));
  3514. }
  3515. /// \brief Ensure that the type of the given expression is complete.
  3516. ///
  3517. /// This routine checks whether the expression \p E has a complete type. If the
  3518. /// expression refers to an instantiable construct, that instantiation is
  3519. /// performed as needed to complete its type. Furthermore
  3520. /// Sema::RequireCompleteType is called for the expression's type (or in the
  3521. /// case of a reference type, the referred-to type).
  3522. ///
  3523. /// \param E The expression whose type is required to be complete.
  3524. /// \param PD The partial diagnostic that will be printed out if the type cannot
  3525. /// be completed.
  3526. ///
  3527. /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
  3528. /// otherwise.
  3529. bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
  3530. std::pair<SourceLocation,
  3531. PartialDiagnostic> Note) {
  3532. QualType T = E->getType();
  3533. // Fast path the case where the type is already complete.
  3534. if (!T->isIncompleteType())
  3535. return false;
  3536. // Incomplete array types may be completed by the initializer attached to
  3537. // their definitions. For static data members of class templates we need to
  3538. // instantiate the definition to get this initializer and complete the type.
  3539. if (T->isIncompleteArrayType()) {
  3540. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3541. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  3542. if (Var->isStaticDataMember() &&
  3543. Var->getInstantiatedFromStaticDataMember()) {
  3544. MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
  3545. assert(MSInfo && "Missing member specialization information?");
  3546. if (MSInfo->getTemplateSpecializationKind()
  3547. != TSK_ExplicitSpecialization) {
  3548. // If we don't already have a point of instantiation, this is it.
  3549. if (MSInfo->getPointOfInstantiation().isInvalid()) {
  3550. MSInfo->setPointOfInstantiation(E->getLocStart());
  3551. // This is a modification of an existing AST node. Notify
  3552. // listeners.
  3553. if (ASTMutationListener *L = getASTMutationListener())
  3554. L->StaticDataMemberInstantiated(Var);
  3555. }
  3556. InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
  3557. // Update the type to the newly instantiated definition's type both
  3558. // here and within the expression.
  3559. if (VarDecl *Def = Var->getDefinition()) {
  3560. DRE->setDecl(Def);
  3561. T = Def->getType();
  3562. DRE->setType(T);
  3563. E->setType(T);
  3564. }
  3565. }
  3566. // We still go on to try to complete the type independently, as it
  3567. // may also require instantiations or diagnostics if it remains
  3568. // incomplete.
  3569. }
  3570. }
  3571. }
  3572. }
  3573. // FIXME: Are there other cases which require instantiating something other
  3574. // than the type to complete the type of an expression?
  3575. // Look through reference types and complete the referred type.
  3576. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  3577. T = Ref->getPointeeType();
  3578. return RequireCompleteType(E->getExprLoc(), T, PD, Note);
  3579. }
  3580. /// @brief Ensure that the type T is a complete type.
  3581. ///
  3582. /// This routine checks whether the type @p T is complete in any
  3583. /// context where a complete type is required. If @p T is a complete
  3584. /// type, returns false. If @p T is a class template specialization,
  3585. /// this routine then attempts to perform class template
  3586. /// instantiation. If instantiation fails, or if @p T is incomplete
  3587. /// and cannot be completed, issues the diagnostic @p diag (giving it
  3588. /// the type @p T) and returns true.
  3589. ///
  3590. /// @param Loc The location in the source that the incomplete type
  3591. /// diagnostic should refer to.
  3592. ///
  3593. /// @param T The type that this routine is examining for completeness.
  3594. ///
  3595. /// @param PD The partial diagnostic that will be printed out if T is not a
  3596. /// complete type.
  3597. ///
  3598. /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
  3599. /// @c false otherwise.
  3600. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  3601. const PartialDiagnostic &PD,
  3602. std::pair<SourceLocation,
  3603. PartialDiagnostic> Note) {
  3604. unsigned diag = PD.getDiagID();
  3605. // FIXME: Add this assertion to make sure we always get instantiation points.
  3606. // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
  3607. // FIXME: Add this assertion to help us flush out problems with
  3608. // checking for dependent types and type-dependent expressions.
  3609. //
  3610. // assert(!T->isDependentType() &&
  3611. // "Can't ask whether a dependent type is complete");
  3612. // If we have a complete type, we're done.
  3613. if (!T->isIncompleteType())
  3614. return false;
  3615. const TagType *Tag = T->getAs<TagType>();
  3616. const ObjCInterfaceType *IFace = 0;
  3617. if (Tag) {
  3618. // Avoid diagnosing invalid decls as incomplete.
  3619. if (Tag->getDecl()->isInvalidDecl())
  3620. return true;
  3621. // Give the external AST source a chance to complete the type.
  3622. if (Tag->getDecl()->hasExternalLexicalStorage()) {
  3623. Context.getExternalSource()->CompleteType(Tag->getDecl());
  3624. if (!Tag->isIncompleteType())
  3625. return false;
  3626. }
  3627. }
  3628. else if ((IFace = T->getAs<ObjCInterfaceType>())) {
  3629. // Avoid diagnosing invalid decls as incomplete.
  3630. if (IFace->getDecl()->isInvalidDecl())
  3631. return true;
  3632. // Give the external AST source a chance to complete the type.
  3633. if (IFace->getDecl()->hasExternalLexicalStorage()) {
  3634. Context.getExternalSource()->CompleteType(IFace->getDecl());
  3635. if (!IFace->isIncompleteType())
  3636. return false;
  3637. }
  3638. }
  3639. // If we have a class template specialization or a class member of a
  3640. // class template specialization, or an array with known size of such,
  3641. // try to instantiate it.
  3642. QualType MaybeTemplate = T;
  3643. if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
  3644. MaybeTemplate = Array->getElementType();
  3645. if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
  3646. if (ClassTemplateSpecializationDecl *ClassTemplateSpec
  3647. = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
  3648. if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
  3649. return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
  3650. TSK_ImplicitInstantiation,
  3651. /*Complain=*/diag != 0);
  3652. } else if (CXXRecordDecl *Rec
  3653. = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
  3654. if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
  3655. MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
  3656. assert(MSInfo && "Missing member specialization information?");
  3657. // This record was instantiated from a class within a template.
  3658. if (MSInfo->getTemplateSpecializationKind()
  3659. != TSK_ExplicitSpecialization)
  3660. return InstantiateClass(Loc, Rec, Pattern,
  3661. getTemplateInstantiationArgs(Rec),
  3662. TSK_ImplicitInstantiation,
  3663. /*Complain=*/diag != 0);
  3664. }
  3665. }
  3666. }
  3667. if (diag == 0)
  3668. return true;
  3669. // We have an incomplete type. Produce a diagnostic.
  3670. Diag(Loc, PD) << T;
  3671. // If we have a note, produce it.
  3672. if (!Note.first.isInvalid())
  3673. Diag(Note.first, Note.second);
  3674. // If the type was a forward declaration of a class/struct/union
  3675. // type, produce a note.
  3676. if (Tag && !Tag->getDecl()->isInvalidDecl())
  3677. Diag(Tag->getDecl()->getLocation(),
  3678. Tag->isBeingDefined() ? diag::note_type_being_defined
  3679. : diag::note_forward_declaration)
  3680. << QualType(Tag, 0);
  3681. // If the Objective-C class was a forward declaration, produce a note.
  3682. if (IFace && !IFace->getDecl()->isInvalidDecl())
  3683. Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
  3684. return true;
  3685. }
  3686. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  3687. const PartialDiagnostic &PD) {
  3688. return RequireCompleteType(Loc, T, PD,
  3689. std::make_pair(SourceLocation(), PDiag(0)));
  3690. }
  3691. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  3692. unsigned DiagID) {
  3693. return RequireCompleteType(Loc, T, PDiag(DiagID),
  3694. std::make_pair(SourceLocation(), PDiag(0)));
  3695. }
  3696. /// @brief Ensure that the type T is a literal type.
  3697. ///
  3698. /// This routine checks whether the type @p T is a literal type. If @p T is an
  3699. /// incomplete type, an attempt is made to complete it. If @p T is a literal
  3700. /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
  3701. /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
  3702. /// it the type @p T), along with notes explaining why the type is not a
  3703. /// literal type, and returns true.
  3704. ///
  3705. /// @param Loc The location in the source that the non-literal type
  3706. /// diagnostic should refer to.
  3707. ///
  3708. /// @param T The type that this routine is examining for literalness.
  3709. ///
  3710. /// @param PD The partial diagnostic that will be printed out if T is not a
  3711. /// literal type.
  3712. ///
  3713. /// @param AllowIncompleteType If true, an incomplete type will be considered
  3714. /// acceptable.
  3715. ///
  3716. /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
  3717. /// @c false otherwise.
  3718. bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
  3719. const PartialDiagnostic &PD,
  3720. bool AllowIncompleteType) {
  3721. assert(!T->isDependentType() && "type should not be dependent");
  3722. bool Incomplete = RequireCompleteType(Loc, T, 0);
  3723. if (T->isLiteralType() || (AllowIncompleteType && Incomplete))
  3724. return false;
  3725. if (PD.getDiagID() == 0)
  3726. return true;
  3727. Diag(Loc, PD) << T;
  3728. if (T->isVariableArrayType())
  3729. return true;
  3730. const RecordType *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>();
  3731. if (!RT)
  3732. return true;
  3733. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  3734. // If the class has virtual base classes, then it's not an aggregate, and
  3735. // cannot have any constexpr constructors, so is non-literal. This is better
  3736. // to diagnose than the resulting absence of constexpr constructors.
  3737. if (RD->getNumVBases()) {
  3738. Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
  3739. << RD->isStruct() << RD->getNumVBases();
  3740. for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
  3741. E = RD->vbases_end(); I != E; ++I)
  3742. Diag(I->getSourceRange().getBegin(),
  3743. diag::note_constexpr_virtual_base_here) << I->getSourceRange();
  3744. } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor()) {
  3745. Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
  3746. switch (RD->getTemplateSpecializationKind()) {
  3747. case TSK_Undeclared:
  3748. case TSK_ExplicitSpecialization:
  3749. break;
  3750. case TSK_ImplicitInstantiation:
  3751. case TSK_ExplicitInstantiationDeclaration:
  3752. case TSK_ExplicitInstantiationDefinition:
  3753. // If the base template had constexpr constructors which were
  3754. // instantiated as non-constexpr constructors, explain why.
  3755. for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
  3756. E = RD->ctor_end(); I != E; ++I) {
  3757. if ((*I)->isCopyConstructor() || (*I)->isMoveConstructor())
  3758. continue;
  3759. FunctionDecl *Base = (*I)->getInstantiatedFromMemberFunction();
  3760. if (Base && Base->isConstexpr())
  3761. CheckConstexprFunctionDecl(*I, CCK_NoteNonConstexprInstantiation);
  3762. }
  3763. }
  3764. } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
  3765. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  3766. E = RD->bases_end(); I != E; ++I) {
  3767. if (!I->getType()->isLiteralType()) {
  3768. Diag(I->getSourceRange().getBegin(),
  3769. diag::note_non_literal_base_class)
  3770. << RD << I->getType() << I->getSourceRange();
  3771. return true;
  3772. }
  3773. }
  3774. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  3775. E = RD->field_end(); I != E; ++I) {
  3776. if (!(*I)->getType()->isLiteralType()) {
  3777. Diag((*I)->getLocation(), diag::note_non_literal_field)
  3778. << RD << (*I) << (*I)->getType();
  3779. return true;
  3780. } else if ((*I)->isMutable()) {
  3781. Diag((*I)->getLocation(), diag::note_non_literal_mutable_field) << RD;
  3782. return true;
  3783. }
  3784. }
  3785. } else if (!RD->hasTrivialDestructor()) {
  3786. // All fields and bases are of literal types, so have trivial destructors.
  3787. // If this class's destructor is non-trivial it must be user-declared.
  3788. CXXDestructorDecl *Dtor = RD->getDestructor();
  3789. assert(Dtor && "class has literal fields and bases but no dtor?");
  3790. if (!Dtor)
  3791. return true;
  3792. Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
  3793. diag::note_non_literal_user_provided_dtor :
  3794. diag::note_non_literal_nontrivial_dtor) << RD;
  3795. }
  3796. return true;
  3797. }
  3798. /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
  3799. /// and qualified by the nested-name-specifier contained in SS.
  3800. QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
  3801. const CXXScopeSpec &SS, QualType T) {
  3802. if (T.isNull())
  3803. return T;
  3804. NestedNameSpecifier *NNS;
  3805. if (SS.isValid())
  3806. NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
  3807. else {
  3808. if (Keyword == ETK_None)
  3809. return T;
  3810. NNS = 0;
  3811. }
  3812. return Context.getElaboratedType(Keyword, NNS, T);
  3813. }
  3814. QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
  3815. ExprResult ER = CheckPlaceholderExpr(E);
  3816. if (ER.isInvalid()) return QualType();
  3817. E = ER.take();
  3818. if (!E->isTypeDependent()) {
  3819. QualType T = E->getType();
  3820. if (const TagType *TT = T->getAs<TagType>())
  3821. DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
  3822. }
  3823. return Context.getTypeOfExprType(E);
  3824. }
  3825. QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
  3826. ExprResult ER = CheckPlaceholderExpr(E);
  3827. if (ER.isInvalid()) return QualType();
  3828. E = ER.take();
  3829. return Context.getDecltypeType(E);
  3830. }
  3831. QualType Sema::BuildUnaryTransformType(QualType BaseType,
  3832. UnaryTransformType::UTTKind UKind,
  3833. SourceLocation Loc) {
  3834. switch (UKind) {
  3835. case UnaryTransformType::EnumUnderlyingType:
  3836. if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
  3837. Diag(Loc, diag::err_only_enums_have_underlying_types);
  3838. return QualType();
  3839. } else {
  3840. QualType Underlying = BaseType;
  3841. if (!BaseType->isDependentType()) {
  3842. EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
  3843. assert(ED && "EnumType has no EnumDecl");
  3844. DiagnoseUseOfDecl(ED, Loc);
  3845. Underlying = ED->getIntegerType();
  3846. }
  3847. assert(!Underlying.isNull());
  3848. return Context.getUnaryTransformType(BaseType, Underlying,
  3849. UnaryTransformType::EnumUnderlyingType);
  3850. }
  3851. }
  3852. llvm_unreachable("unknown unary transform type");
  3853. }
  3854. QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
  3855. if (!T->isDependentType()) {
  3856. int DisallowedKind = -1;
  3857. if (T->isIncompleteType())
  3858. // FIXME: It isn't entirely clear whether incomplete atomic types
  3859. // are allowed or not; for simplicity, ban them for the moment.
  3860. DisallowedKind = 0;
  3861. else if (T->isArrayType())
  3862. DisallowedKind = 1;
  3863. else if (T->isFunctionType())
  3864. DisallowedKind = 2;
  3865. else if (T->isReferenceType())
  3866. DisallowedKind = 3;
  3867. else if (T->isAtomicType())
  3868. DisallowedKind = 4;
  3869. else if (T.hasQualifiers())
  3870. DisallowedKind = 5;
  3871. else if (!T.isTriviallyCopyableType(Context))
  3872. // Some other non-trivially-copyable type (probably a C++ class)
  3873. DisallowedKind = 6;
  3874. if (DisallowedKind != -1) {
  3875. Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
  3876. return QualType();
  3877. }
  3878. // FIXME: Do we need any handling for ARC here?
  3879. }
  3880. // Build the pointer type.
  3881. return Context.getAtomicType(T);
  3882. }