PCHReader.cpp 135 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838
  1. //===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
  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 defines the PCHReader class, which reads a precompiled header.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Frontend/PCHReader.h"
  14. #include "clang/Frontend/FrontendDiagnostic.h"
  15. #include "clang/Frontend/PCHDeserializationListener.h"
  16. #include "clang/Frontend/Utils.h"
  17. #include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
  18. #include "clang/AST/ASTConsumer.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/Type.h"
  22. #include "clang/AST/TypeLocVisitor.h"
  23. #include "clang/Lex/MacroInfo.h"
  24. #include "clang/Lex/PreprocessingRecord.h"
  25. #include "clang/Lex/Preprocessor.h"
  26. #include "clang/Lex/HeaderSearch.h"
  27. #include "clang/Basic/OnDiskHashTable.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/SourceManagerInternals.h"
  30. #include "clang/Basic/FileManager.h"
  31. #include "clang/Basic/TargetInfo.h"
  32. #include "clang/Basic/Version.h"
  33. #include "llvm/ADT/StringExtras.h"
  34. #include "llvm/Bitcode/BitstreamReader.h"
  35. #include "llvm/Support/MemoryBuffer.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/System/Path.h"
  38. #include <algorithm>
  39. #include <iterator>
  40. #include <cstdio>
  41. #include <sys/stat.h>
  42. using namespace clang;
  43. //===----------------------------------------------------------------------===//
  44. // PCH reader validator implementation
  45. //===----------------------------------------------------------------------===//
  46. PCHReaderListener::~PCHReaderListener() {}
  47. bool
  48. PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
  49. const LangOptions &PPLangOpts = PP.getLangOptions();
  50. #define PARSE_LANGOPT_BENIGN(Option)
  51. #define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
  52. if (PPLangOpts.Option != LangOpts.Option) { \
  53. Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
  54. return true; \
  55. }
  56. PARSE_LANGOPT_BENIGN(Trigraphs);
  57. PARSE_LANGOPT_BENIGN(BCPLComment);
  58. PARSE_LANGOPT_BENIGN(DollarIdents);
  59. PARSE_LANGOPT_BENIGN(AsmPreprocessor);
  60. PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
  61. PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
  62. PARSE_LANGOPT_BENIGN(ImplicitInt);
  63. PARSE_LANGOPT_BENIGN(Digraphs);
  64. PARSE_LANGOPT_BENIGN(HexFloats);
  65. PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
  66. PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
  67. PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
  68. PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
  69. PARSE_LANGOPT_BENIGN(CXXOperatorName);
  70. PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
  71. PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
  72. PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
  73. PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
  74. PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
  75. diag::warn_pch_no_constant_cfstrings);
  76. PARSE_LANGOPT_BENIGN(PascalStrings);
  77. PARSE_LANGOPT_BENIGN(WritableStrings);
  78. PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
  79. diag::warn_pch_lax_vector_conversions);
  80. PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
  81. PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
  82. PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
  83. PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
  84. PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
  85. PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
  86. PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
  87. diag::warn_pch_thread_safe_statics);
  88. PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
  89. PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
  90. PARSE_LANGOPT_BENIGN(EmitAllDecls);
  91. PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
  92. PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
  93. PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
  94. diag::warn_pch_heinous_extensions);
  95. // FIXME: Most of the options below are benign if the macro wasn't
  96. // used. Unfortunately, this means that a PCH compiled without
  97. // optimization can't be used with optimization turned on, even
  98. // though the only thing that changes is whether __OPTIMIZE__ was
  99. // defined... but if __OPTIMIZE__ never showed up in the header, it
  100. // doesn't matter. We could consider making this some special kind
  101. // of check.
  102. PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
  103. PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
  104. PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
  105. PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
  106. PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
  107. PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
  108. PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
  109. PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
  110. PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
  111. if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
  112. Reader.Diag(diag::warn_pch_gc_mode)
  113. << LangOpts.getGCMode() << PPLangOpts.getGCMode();
  114. return true;
  115. }
  116. PARSE_LANGOPT_BENIGN(getVisibilityMode());
  117. PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
  118. diag::warn_pch_stack_protector);
  119. PARSE_LANGOPT_BENIGN(InstantiationDepth);
  120. PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
  121. PARSE_LANGOPT_BENIGN(CatchUndefined);
  122. PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
  123. PARSE_LANGOPT_BENIGN(SpellChecking);
  124. #undef PARSE_LANGOPT_IMPORTANT
  125. #undef PARSE_LANGOPT_BENIGN
  126. return false;
  127. }
  128. bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
  129. if (Triple == PP.getTargetInfo().getTriple().str())
  130. return false;
  131. Reader.Diag(diag::warn_pch_target_triple)
  132. << Triple << PP.getTargetInfo().getTriple().str();
  133. return true;
  134. }
  135. struct EmptyStringRef {
  136. bool operator ()(llvm::StringRef r) const { return r.empty(); }
  137. };
  138. struct EmptyBlock {
  139. bool operator ()(const PCHPredefinesBlock &r) const { return r.Data.empty(); }
  140. };
  141. static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
  142. PCHPredefinesBlocks R) {
  143. // First, sum up the lengths.
  144. unsigned LL = 0, RL = 0;
  145. for (unsigned I = 0, N = L.size(); I != N; ++I) {
  146. LL += L[I].size();
  147. }
  148. for (unsigned I = 0, N = R.size(); I != N; ++I) {
  149. RL += R[I].Data.size();
  150. }
  151. if (LL != RL)
  152. return false;
  153. if (LL == 0 && RL == 0)
  154. return true;
  155. // Kick out empty parts, they confuse the algorithm below.
  156. L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
  157. R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
  158. // Do it the hard way. At this point, both vectors must be non-empty.
  159. llvm::StringRef LR = L[0], RR = R[0].Data;
  160. unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
  161. (void) RN;
  162. for (;;) {
  163. // Compare the current pieces.
  164. if (LR.size() == RR.size()) {
  165. // If they're the same length, it's pretty easy.
  166. if (LR != RR)
  167. return false;
  168. // Both pieces are done, advance.
  169. ++LI;
  170. ++RI;
  171. // If either string is done, they're both done, since they're the same
  172. // length.
  173. if (LI == LN) {
  174. assert(RI == RN && "Strings not the same length after all?");
  175. return true;
  176. }
  177. LR = L[LI];
  178. RR = R[RI].Data;
  179. } else if (LR.size() < RR.size()) {
  180. // Right piece is longer.
  181. if (!RR.startswith(LR))
  182. return false;
  183. ++LI;
  184. assert(LI != LN && "Strings not the same length after all?");
  185. RR = RR.substr(LR.size());
  186. LR = L[LI];
  187. } else {
  188. // Left piece is longer.
  189. if (!LR.startswith(RR))
  190. return false;
  191. ++RI;
  192. assert(RI != RN && "Strings not the same length after all?");
  193. LR = LR.substr(RR.size());
  194. RR = R[RI].Data;
  195. }
  196. }
  197. }
  198. static std::pair<FileID, llvm::StringRef::size_type>
  199. FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
  200. std::pair<FileID, llvm::StringRef::size_type> Res;
  201. for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
  202. Res.second = Buffers[I].Data.find(MacroDef);
  203. if (Res.second != llvm::StringRef::npos) {
  204. Res.first = Buffers[I].BufferID;
  205. break;
  206. }
  207. }
  208. return Res;
  209. }
  210. bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
  211. llvm::StringRef OriginalFileName,
  212. std::string &SuggestedPredefines) {
  213. // We are in the context of an implicit include, so the predefines buffer will
  214. // have a #include entry for the PCH file itself (as normalized by the
  215. // preprocessor initialization). Find it and skip over it in the checking
  216. // below.
  217. llvm::SmallString<256> PCHInclude;
  218. PCHInclude += "#include \"";
  219. PCHInclude += NormalizeDashIncludePath(OriginalFileName);
  220. PCHInclude += "\"\n";
  221. std::pair<llvm::StringRef,llvm::StringRef> Split =
  222. llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
  223. llvm::StringRef Left = Split.first, Right = Split.second;
  224. if (Left == PP.getPredefines()) {
  225. Error("Missing PCH include entry!");
  226. return true;
  227. }
  228. // If the concatenation of all the PCH buffers is equal to the adjusted
  229. // command line, we're done.
  230. // We build a SmallVector of the command line here, because we'll eventually
  231. // need to support an arbitrary amount of pieces anyway (when we have chained
  232. // PCH reading).
  233. llvm::SmallVector<llvm::StringRef, 2> CommandLine;
  234. CommandLine.push_back(Left);
  235. CommandLine.push_back(Right);
  236. if (EqualConcatenations(CommandLine, Buffers))
  237. return false;
  238. SourceManager &SourceMgr = PP.getSourceManager();
  239. // The predefines buffers are different. Determine what the differences are,
  240. // and whether they require us to reject the PCH file.
  241. llvm::SmallVector<llvm::StringRef, 8> PCHLines;
  242. for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
  243. Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  244. llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
  245. Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  246. Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  247. // Sort both sets of predefined buffer lines, since we allow some extra
  248. // definitions and they may appear at any point in the output.
  249. std::sort(CmdLineLines.begin(), CmdLineLines.end());
  250. std::sort(PCHLines.begin(), PCHLines.end());
  251. // Determine which predefines that were used to build the PCH file are missing
  252. // from the command line.
  253. std::vector<llvm::StringRef> MissingPredefines;
  254. std::set_difference(PCHLines.begin(), PCHLines.end(),
  255. CmdLineLines.begin(), CmdLineLines.end(),
  256. std::back_inserter(MissingPredefines));
  257. bool MissingDefines = false;
  258. bool ConflictingDefines = false;
  259. for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
  260. llvm::StringRef Missing = MissingPredefines[I];
  261. if (!Missing.startswith("#define ")) {
  262. Reader.Diag(diag::warn_pch_compiler_options_mismatch);
  263. return true;
  264. }
  265. // This is a macro definition. Determine the name of the macro we're
  266. // defining.
  267. std::string::size_type StartOfMacroName = strlen("#define ");
  268. std::string::size_type EndOfMacroName
  269. = Missing.find_first_of("( \n\r", StartOfMacroName);
  270. assert(EndOfMacroName != std::string::npos &&
  271. "Couldn't find the end of the macro name");
  272. llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
  273. // Determine whether this macro was given a different definition on the
  274. // command line.
  275. std::string MacroDefStart = "#define " + MacroName.str();
  276. std::string::size_type MacroDefLen = MacroDefStart.size();
  277. llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
  278. = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
  279. MacroDefStart);
  280. for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
  281. if (!ConflictPos->startswith(MacroDefStart)) {
  282. // Different macro; we're done.
  283. ConflictPos = CmdLineLines.end();
  284. break;
  285. }
  286. assert(ConflictPos->size() > MacroDefLen &&
  287. "Invalid #define in predefines buffer?");
  288. if ((*ConflictPos)[MacroDefLen] != ' ' &&
  289. (*ConflictPos)[MacroDefLen] != '(')
  290. continue; // Longer macro name; keep trying.
  291. // We found a conflicting macro definition.
  292. break;
  293. }
  294. if (ConflictPos != CmdLineLines.end()) {
  295. Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
  296. << MacroName;
  297. // Show the definition of this macro within the PCH file.
  298. std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
  299. FindMacro(Buffers, Missing);
  300. assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
  301. SourceLocation PCHMissingLoc =
  302. SourceMgr.getLocForStartOfFile(MacroLoc.first)
  303. .getFileLocWithOffset(MacroLoc.second);
  304. Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
  305. ConflictingDefines = true;
  306. continue;
  307. }
  308. // If the macro doesn't conflict, then we'll just pick up the macro
  309. // definition from the PCH file. Warn the user that they made a mistake.
  310. if (ConflictingDefines)
  311. continue; // Don't complain if there are already conflicting defs
  312. if (!MissingDefines) {
  313. Reader.Diag(diag::warn_cmdline_missing_macro_defs);
  314. MissingDefines = true;
  315. }
  316. // Show the definition of this macro within the PCH file.
  317. std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
  318. FindMacro(Buffers, Missing);
  319. assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
  320. SourceLocation PCHMissingLoc =
  321. SourceMgr.getLocForStartOfFile(MacroLoc.first)
  322. .getFileLocWithOffset(MacroLoc.second);
  323. Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
  324. }
  325. if (ConflictingDefines)
  326. return true;
  327. // Determine what predefines were introduced based on command-line
  328. // parameters that were not present when building the PCH
  329. // file. Extra #defines are okay, so long as the identifiers being
  330. // defined were not used within the precompiled header.
  331. std::vector<llvm::StringRef> ExtraPredefines;
  332. std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
  333. PCHLines.begin(), PCHLines.end(),
  334. std::back_inserter(ExtraPredefines));
  335. for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
  336. llvm::StringRef &Extra = ExtraPredefines[I];
  337. if (!Extra.startswith("#define ")) {
  338. Reader.Diag(diag::warn_pch_compiler_options_mismatch);
  339. return true;
  340. }
  341. // This is an extra macro definition. Determine the name of the
  342. // macro we're defining.
  343. std::string::size_type StartOfMacroName = strlen("#define ");
  344. std::string::size_type EndOfMacroName
  345. = Extra.find_first_of("( \n\r", StartOfMacroName);
  346. assert(EndOfMacroName != std::string::npos &&
  347. "Couldn't find the end of the macro name");
  348. llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
  349. // Check whether this name was used somewhere in the PCH file. If
  350. // so, defining it as a macro could change behavior, so we reject
  351. // the PCH file.
  352. if (IdentifierInfo *II = Reader.get(MacroName)) {
  353. Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
  354. return true;
  355. }
  356. // Add this definition to the suggested predefines buffer.
  357. SuggestedPredefines += Extra;
  358. SuggestedPredefines += '\n';
  359. }
  360. // If we get here, it's because the predefines buffer had compatible
  361. // contents. Accept the PCH file.
  362. return false;
  363. }
  364. void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
  365. unsigned ID) {
  366. PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
  367. ++NumHeaderInfos;
  368. }
  369. void PCHValidator::ReadCounter(unsigned Value) {
  370. PP.setCounterValue(Value);
  371. }
  372. //===----------------------------------------------------------------------===//
  373. // PCH reader implementation
  374. //===----------------------------------------------------------------------===//
  375. PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
  376. const char *isysroot, bool DisableValidation)
  377. : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
  378. SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
  379. Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
  380. Consumer(0), isysroot(isysroot), DisableValidation(DisableValidation),
  381. NumStatHits(0), NumStatMisses(0), NumSLocEntriesRead(0),
  382. TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
  383. NumMacrosRead(0), TotalNumMacros(0), NumSelectorsRead(0),
  384. NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
  385. TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
  386. TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
  387. TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
  388. RelocatablePCH = false;
  389. }
  390. PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
  391. Diagnostic &Diags, const char *isysroot,
  392. bool DisableValidation)
  393. : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
  394. Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
  395. isysroot(isysroot), DisableValidation(DisableValidation), NumStatHits(0),
  396. NumStatMisses(0), NumSLocEntriesRead(0), TotalNumSLocEntries(0),
  397. NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
  398. TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
  399. NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
  400. NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
  401. NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
  402. NumCurrentElementsDeserializing(0) {
  403. RelocatablePCH = false;
  404. }
  405. PCHReader::~PCHReader() {
  406. for (unsigned i = 0, e = Chain.size(); i != e; ++i)
  407. delete Chain[e - i - 1];
  408. }
  409. PCHReader::PerFileData::PerFileData()
  410. : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
  411. LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
  412. IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0),
  413. LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
  414. NumPreallocatedPreprocessingEntities(0), SelectorLookupTable(0),
  415. SelectorLookupTableData(0), SelectorOffsets(0), LocalNumSelectors(0)
  416. {}
  417. void
  418. PCHReader::setDeserializationListener(PCHDeserializationListener *Listener) {
  419. DeserializationListener = Listener;
  420. if (DeserializationListener)
  421. DeserializationListener->SetReader(this);
  422. }
  423. namespace {
  424. class PCHSelectorLookupTrait {
  425. PCHReader &Reader;
  426. public:
  427. struct data_type {
  428. pch::SelectorID ID;
  429. ObjCMethodList Instance, Factory;
  430. };
  431. typedef Selector external_key_type;
  432. typedef external_key_type internal_key_type;
  433. explicit PCHSelectorLookupTrait(PCHReader &Reader) : Reader(Reader) { }
  434. static bool EqualKey(const internal_key_type& a,
  435. const internal_key_type& b) {
  436. return a == b;
  437. }
  438. static unsigned ComputeHash(Selector Sel) {
  439. unsigned N = Sel.getNumArgs();
  440. if (N == 0)
  441. ++N;
  442. unsigned R = 5381;
  443. for (unsigned I = 0; I != N; ++I)
  444. if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
  445. R = llvm::HashString(II->getName(), R);
  446. return R;
  447. }
  448. // This hopefully will just get inlined and removed by the optimizer.
  449. static const internal_key_type&
  450. GetInternalKey(const external_key_type& x) { return x; }
  451. static std::pair<unsigned, unsigned>
  452. ReadKeyDataLength(const unsigned char*& d) {
  453. using namespace clang::io;
  454. unsigned KeyLen = ReadUnalignedLE16(d);
  455. unsigned DataLen = ReadUnalignedLE16(d);
  456. return std::make_pair(KeyLen, DataLen);
  457. }
  458. internal_key_type ReadKey(const unsigned char* d, unsigned) {
  459. using namespace clang::io;
  460. SelectorTable &SelTable = Reader.getContext()->Selectors;
  461. unsigned N = ReadUnalignedLE16(d);
  462. IdentifierInfo *FirstII
  463. = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
  464. if (N == 0)
  465. return SelTable.getNullarySelector(FirstII);
  466. else if (N == 1)
  467. return SelTable.getUnarySelector(FirstII);
  468. llvm::SmallVector<IdentifierInfo *, 16> Args;
  469. Args.push_back(FirstII);
  470. for (unsigned I = 1; I != N; ++I)
  471. Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
  472. return SelTable.getSelector(N, Args.data());
  473. }
  474. data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
  475. using namespace clang::io;
  476. data_type Result;
  477. Result.ID = ReadUnalignedLE32(d);
  478. unsigned NumInstanceMethods = ReadUnalignedLE16(d);
  479. unsigned NumFactoryMethods = ReadUnalignedLE16(d);
  480. // Load instance methods
  481. ObjCMethodList *Prev = 0;
  482. for (unsigned I = 0; I != NumInstanceMethods; ++I) {
  483. ObjCMethodDecl *Method
  484. = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
  485. if (!Result.Instance.Method) {
  486. // This is the first method, which is the easy case.
  487. Result.Instance.Method = Method;
  488. Prev = &Result.Instance;
  489. continue;
  490. }
  491. ObjCMethodList *Mem =
  492. Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
  493. Prev->Next = new (Mem) ObjCMethodList(Method, 0);
  494. Prev = Prev->Next;
  495. }
  496. // Load factory methods
  497. Prev = 0;
  498. for (unsigned I = 0; I != NumFactoryMethods; ++I) {
  499. ObjCMethodDecl *Method
  500. = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
  501. if (!Result.Factory.Method) {
  502. // This is the first method, which is the easy case.
  503. Result.Factory.Method = Method;
  504. Prev = &Result.Factory;
  505. continue;
  506. }
  507. ObjCMethodList *Mem =
  508. Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
  509. Prev->Next = new (Mem) ObjCMethodList(Method, 0);
  510. Prev = Prev->Next;
  511. }
  512. return Result;
  513. }
  514. };
  515. } // end anonymous namespace
  516. /// \brief The on-disk hash table used for the global method pool.
  517. typedef OnDiskChainedHashTable<PCHSelectorLookupTrait>
  518. PCHSelectorLookupTable;
  519. namespace {
  520. class PCHIdentifierLookupTrait {
  521. PCHReader &Reader;
  522. llvm::BitstreamCursor &Stream;
  523. // If we know the IdentifierInfo in advance, it is here and we will
  524. // not build a new one. Used when deserializing information about an
  525. // identifier that was constructed before the PCH file was read.
  526. IdentifierInfo *KnownII;
  527. public:
  528. typedef IdentifierInfo * data_type;
  529. typedef const std::pair<const char*, unsigned> external_key_type;
  530. typedef external_key_type internal_key_type;
  531. PCHIdentifierLookupTrait(PCHReader &Reader, llvm::BitstreamCursor &Stream,
  532. IdentifierInfo *II = 0)
  533. : Reader(Reader), Stream(Stream), KnownII(II) { }
  534. static bool EqualKey(const internal_key_type& a,
  535. const internal_key_type& b) {
  536. return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
  537. : false;
  538. }
  539. static unsigned ComputeHash(const internal_key_type& a) {
  540. return llvm::HashString(llvm::StringRef(a.first, a.second));
  541. }
  542. // This hopefully will just get inlined and removed by the optimizer.
  543. static const internal_key_type&
  544. GetInternalKey(const external_key_type& x) { return x; }
  545. static std::pair<unsigned, unsigned>
  546. ReadKeyDataLength(const unsigned char*& d) {
  547. using namespace clang::io;
  548. unsigned DataLen = ReadUnalignedLE16(d);
  549. unsigned KeyLen = ReadUnalignedLE16(d);
  550. return std::make_pair(KeyLen, DataLen);
  551. }
  552. static std::pair<const char*, unsigned>
  553. ReadKey(const unsigned char* d, unsigned n) {
  554. assert(n >= 2 && d[n-1] == '\0');
  555. return std::make_pair((const char*) d, n-1);
  556. }
  557. IdentifierInfo *ReadData(const internal_key_type& k,
  558. const unsigned char* d,
  559. unsigned DataLen) {
  560. using namespace clang::io;
  561. pch::IdentID ID = ReadUnalignedLE32(d);
  562. bool IsInteresting = ID & 0x01;
  563. // Wipe out the "is interesting" bit.
  564. ID = ID >> 1;
  565. if (!IsInteresting) {
  566. // For uninteresting identifiers, just build the IdentifierInfo
  567. // and associate it with the persistent ID.
  568. IdentifierInfo *II = KnownII;
  569. if (!II)
  570. II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
  571. Reader.SetIdentifierInfo(ID, II);
  572. II->setIsFromPCH();
  573. return II;
  574. }
  575. unsigned Bits = ReadUnalignedLE16(d);
  576. bool CPlusPlusOperatorKeyword = Bits & 0x01;
  577. Bits >>= 1;
  578. bool Poisoned = Bits & 0x01;
  579. Bits >>= 1;
  580. bool ExtensionToken = Bits & 0x01;
  581. Bits >>= 1;
  582. bool hasMacroDefinition = Bits & 0x01;
  583. Bits >>= 1;
  584. unsigned ObjCOrBuiltinID = Bits & 0x3FF;
  585. Bits >>= 10;
  586. assert(Bits == 0 && "Extra bits in the identifier?");
  587. DataLen -= 6;
  588. // Build the IdentifierInfo itself and link the identifier ID with
  589. // the new IdentifierInfo.
  590. IdentifierInfo *II = KnownII;
  591. if (!II)
  592. II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
  593. Reader.SetIdentifierInfo(ID, II);
  594. // Set or check the various bits in the IdentifierInfo structure.
  595. // FIXME: Load token IDs lazily, too?
  596. II->setObjCOrBuiltinID(ObjCOrBuiltinID);
  597. assert(II->isExtensionToken() == ExtensionToken &&
  598. "Incorrect extension token flag");
  599. (void)ExtensionToken;
  600. II->setIsPoisoned(Poisoned);
  601. assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
  602. "Incorrect C++ operator keyword flag");
  603. (void)CPlusPlusOperatorKeyword;
  604. // If this identifier is a macro, deserialize the macro
  605. // definition.
  606. if (hasMacroDefinition) {
  607. uint32_t Offset = ReadUnalignedLE32(d);
  608. Reader.ReadMacroRecord(Stream, Offset);
  609. DataLen -= 4;
  610. }
  611. // Read all of the declarations visible at global scope with this
  612. // name.
  613. if (Reader.getContext() == 0) return II;
  614. if (DataLen > 0) {
  615. llvm::SmallVector<uint32_t, 4> DeclIDs;
  616. for (; DataLen > 0; DataLen -= 4)
  617. DeclIDs.push_back(ReadUnalignedLE32(d));
  618. Reader.SetGloballyVisibleDecls(II, DeclIDs);
  619. }
  620. II->setIsFromPCH();
  621. return II;
  622. }
  623. };
  624. } // end anonymous namespace
  625. /// \brief The on-disk hash table used to contain information about
  626. /// all of the identifiers in the program.
  627. typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
  628. PCHIdentifierLookupTable;
  629. void PCHReader::Error(const char *Msg) {
  630. Diag(diag::err_fe_pch_malformed) << Msg;
  631. }
  632. /// \brief Check the contents of the concatenation of all predefines buffers in
  633. /// the PCH chain against the contents of the predefines buffer of the current
  634. /// compiler invocation.
  635. ///
  636. /// The contents should be the same. If not, then some command-line option
  637. /// changed the preprocessor state and we must probably reject the PCH file.
  638. ///
  639. /// \returns true if there was a mismatch (in which case the PCH file
  640. /// should be ignored), or false otherwise.
  641. bool PCHReader::CheckPredefinesBuffers() {
  642. if (Listener)
  643. return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
  644. ActualOriginalFileName,
  645. SuggestedPredefines);
  646. return false;
  647. }
  648. //===----------------------------------------------------------------------===//
  649. // Source Manager Deserialization
  650. //===----------------------------------------------------------------------===//
  651. /// \brief Read the line table in the source manager block.
  652. /// \returns true if ther was an error.
  653. bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
  654. unsigned Idx = 0;
  655. LineTableInfo &LineTable = SourceMgr.getLineTable();
  656. // Parse the file names
  657. std::map<int, int> FileIDs;
  658. for (int I = 0, N = Record[Idx++]; I != N; ++I) {
  659. // Extract the file name
  660. unsigned FilenameLen = Record[Idx++];
  661. std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
  662. Idx += FilenameLen;
  663. MaybeAddSystemRootToFilename(Filename);
  664. FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
  665. Filename.size());
  666. }
  667. // Parse the line entries
  668. std::vector<LineEntry> Entries;
  669. while (Idx < Record.size()) {
  670. int FID = Record[Idx++];
  671. // Extract the line entries
  672. unsigned NumEntries = Record[Idx++];
  673. assert(NumEntries && "Numentries is 00000");
  674. Entries.clear();
  675. Entries.reserve(NumEntries);
  676. for (unsigned I = 0; I != NumEntries; ++I) {
  677. unsigned FileOffset = Record[Idx++];
  678. unsigned LineNo = Record[Idx++];
  679. int FilenameID = FileIDs[Record[Idx++]];
  680. SrcMgr::CharacteristicKind FileKind
  681. = (SrcMgr::CharacteristicKind)Record[Idx++];
  682. unsigned IncludeOffset = Record[Idx++];
  683. Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
  684. FileKind, IncludeOffset));
  685. }
  686. LineTable.AddEntry(FID, Entries);
  687. }
  688. return false;
  689. }
  690. namespace {
  691. class PCHStatData {
  692. public:
  693. const bool hasStat;
  694. const ino_t ino;
  695. const dev_t dev;
  696. const mode_t mode;
  697. const time_t mtime;
  698. const off_t size;
  699. PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
  700. : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
  701. PCHStatData()
  702. : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
  703. };
  704. class PCHStatLookupTrait {
  705. public:
  706. typedef const char *external_key_type;
  707. typedef const char *internal_key_type;
  708. typedef PCHStatData data_type;
  709. static unsigned ComputeHash(const char *path) {
  710. return llvm::HashString(path);
  711. }
  712. static internal_key_type GetInternalKey(const char *path) { return path; }
  713. static bool EqualKey(internal_key_type a, internal_key_type b) {
  714. return strcmp(a, b) == 0;
  715. }
  716. static std::pair<unsigned, unsigned>
  717. ReadKeyDataLength(const unsigned char*& d) {
  718. unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
  719. unsigned DataLen = (unsigned) *d++;
  720. return std::make_pair(KeyLen + 1, DataLen);
  721. }
  722. static internal_key_type ReadKey(const unsigned char *d, unsigned) {
  723. return (const char *)d;
  724. }
  725. static data_type ReadData(const internal_key_type, const unsigned char *d,
  726. unsigned /*DataLen*/) {
  727. using namespace clang::io;
  728. if (*d++ == 1)
  729. return data_type();
  730. ino_t ino = (ino_t) ReadUnalignedLE32(d);
  731. dev_t dev = (dev_t) ReadUnalignedLE32(d);
  732. mode_t mode = (mode_t) ReadUnalignedLE16(d);
  733. time_t mtime = (time_t) ReadUnalignedLE64(d);
  734. off_t size = (off_t) ReadUnalignedLE64(d);
  735. return data_type(ino, dev, mode, mtime, size);
  736. }
  737. };
  738. /// \brief stat() cache for precompiled headers.
  739. ///
  740. /// This cache is very similar to the stat cache used by pretokenized
  741. /// headers.
  742. class PCHStatCache : public StatSysCallCache {
  743. typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
  744. CacheTy *Cache;
  745. unsigned &NumStatHits, &NumStatMisses;
  746. public:
  747. PCHStatCache(const unsigned char *Buckets,
  748. const unsigned char *Base,
  749. unsigned &NumStatHits,
  750. unsigned &NumStatMisses)
  751. : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
  752. Cache = CacheTy::Create(Buckets, Base);
  753. }
  754. ~PCHStatCache() { delete Cache; }
  755. int stat(const char *path, struct stat *buf) {
  756. // Do the lookup for the file's data in the PCH file.
  757. CacheTy::iterator I = Cache->find(path);
  758. // If we don't get a hit in the PCH file just forward to 'stat'.
  759. if (I == Cache->end()) {
  760. ++NumStatMisses;
  761. return StatSysCallCache::stat(path, buf);
  762. }
  763. ++NumStatHits;
  764. PCHStatData Data = *I;
  765. if (!Data.hasStat)
  766. return 1;
  767. buf->st_ino = Data.ino;
  768. buf->st_dev = Data.dev;
  769. buf->st_mtime = Data.mtime;
  770. buf->st_mode = Data.mode;
  771. buf->st_size = Data.size;
  772. return 0;
  773. }
  774. };
  775. } // end anonymous namespace
  776. /// \brief Read a source manager block
  777. PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
  778. using namespace SrcMgr;
  779. llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
  780. // Set the source-location entry cursor to the current position in
  781. // the stream. This cursor will be used to read the contents of the
  782. // source manager block initially, and then lazily read
  783. // source-location entries as needed.
  784. SLocEntryCursor = F.Stream;
  785. // The stream itself is going to skip over the source manager block.
  786. if (F.Stream.SkipBlock()) {
  787. Error("malformed block record in PCH file");
  788. return Failure;
  789. }
  790. // Enter the source manager block.
  791. if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
  792. Error("malformed source manager block record in PCH file");
  793. return Failure;
  794. }
  795. RecordData Record;
  796. while (true) {
  797. unsigned Code = SLocEntryCursor.ReadCode();
  798. if (Code == llvm::bitc::END_BLOCK) {
  799. if (SLocEntryCursor.ReadBlockEnd()) {
  800. Error("error at end of Source Manager block in PCH file");
  801. return Failure;
  802. }
  803. return Success;
  804. }
  805. if (Code == llvm::bitc::ENTER_SUBBLOCK) {
  806. // No known subblocks, always skip them.
  807. SLocEntryCursor.ReadSubBlockID();
  808. if (SLocEntryCursor.SkipBlock()) {
  809. Error("malformed block record in PCH file");
  810. return Failure;
  811. }
  812. continue;
  813. }
  814. if (Code == llvm::bitc::DEFINE_ABBREV) {
  815. SLocEntryCursor.ReadAbbrevRecord();
  816. continue;
  817. }
  818. // Read a record.
  819. const char *BlobStart;
  820. unsigned BlobLen;
  821. Record.clear();
  822. switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
  823. default: // Default behavior: ignore.
  824. break;
  825. case pch::SM_LINE_TABLE:
  826. if (ParseLineTable(Record))
  827. return Failure;
  828. break;
  829. case pch::SM_SLOC_FILE_ENTRY:
  830. case pch::SM_SLOC_BUFFER_ENTRY:
  831. case pch::SM_SLOC_INSTANTIATION_ENTRY:
  832. // Once we hit one of the source location entries, we're done.
  833. return Success;
  834. }
  835. }
  836. }
  837. /// \brief Get a cursor that's correctly positioned for reading the source
  838. /// location entry with the given ID.
  839. llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
  840. assert(ID != 0 && ID <= TotalNumSLocEntries &&
  841. "SLocCursorForID should only be called for real IDs.");
  842. ID -= 1;
  843. PerFileData *F = 0;
  844. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  845. F = Chain[N - I - 1];
  846. if (ID < F->LocalNumSLocEntries)
  847. break;
  848. ID -= F->LocalNumSLocEntries;
  849. }
  850. assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
  851. F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
  852. return F->SLocEntryCursor;
  853. }
  854. /// \brief Read in the source location entry with the given ID.
  855. PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
  856. if (ID == 0)
  857. return Success;
  858. if (ID > TotalNumSLocEntries) {
  859. Error("source location entry ID out-of-range for PCH file");
  860. return Failure;
  861. }
  862. llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
  863. ++NumSLocEntriesRead;
  864. unsigned Code = SLocEntryCursor.ReadCode();
  865. if (Code == llvm::bitc::END_BLOCK ||
  866. Code == llvm::bitc::ENTER_SUBBLOCK ||
  867. Code == llvm::bitc::DEFINE_ABBREV) {
  868. Error("incorrectly-formatted source location entry in PCH file");
  869. return Failure;
  870. }
  871. RecordData Record;
  872. const char *BlobStart;
  873. unsigned BlobLen;
  874. switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
  875. default:
  876. Error("incorrectly-formatted source location entry in PCH file");
  877. return Failure;
  878. case pch::SM_SLOC_FILE_ENTRY: {
  879. std::string Filename(BlobStart, BlobStart + BlobLen);
  880. MaybeAddSystemRootToFilename(Filename);
  881. const FileEntry *File = FileMgr.getFile(Filename);
  882. if (File == 0) {
  883. std::string ErrorStr = "could not find file '";
  884. ErrorStr += Filename;
  885. ErrorStr += "' referenced by PCH file";
  886. Error(ErrorStr.c_str());
  887. return Failure;
  888. }
  889. if (Record.size() < 10) {
  890. Error("source location entry is incorrect");
  891. return Failure;
  892. }
  893. if (!DisableValidation &&
  894. ((off_t)Record[4] != File->getSize()
  895. #if !defined(LLVM_ON_WIN32)
  896. // In our regression testing, the Windows file system seems to
  897. // have inconsistent modification times that sometimes
  898. // erroneously trigger this error-handling path.
  899. || (time_t)Record[5] != File->getModificationTime()
  900. #endif
  901. )) {
  902. Diag(diag::err_fe_pch_file_modified)
  903. << Filename;
  904. return Failure;
  905. }
  906. FileID FID = SourceMgr.createFileID(File,
  907. SourceLocation::getFromRawEncoding(Record[1]),
  908. (SrcMgr::CharacteristicKind)Record[2],
  909. ID, Record[0]);
  910. if (Record[3])
  911. const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
  912. .setHasLineDirectives();
  913. // Reconstruct header-search information for this file.
  914. HeaderFileInfo HFI;
  915. HFI.isImport = Record[6];
  916. HFI.DirInfo = Record[7];
  917. HFI.NumIncludes = Record[8];
  918. HFI.ControllingMacroID = Record[9];
  919. if (Listener)
  920. Listener->ReadHeaderFileInfo(HFI, File->getUID());
  921. break;
  922. }
  923. case pch::SM_SLOC_BUFFER_ENTRY: {
  924. const char *Name = BlobStart;
  925. unsigned Offset = Record[0];
  926. unsigned Code = SLocEntryCursor.ReadCode();
  927. Record.clear();
  928. unsigned RecCode
  929. = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
  930. if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
  931. Error("PCH record has invalid code");
  932. return Failure;
  933. }
  934. llvm::MemoryBuffer *Buffer
  935. = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
  936. Name);
  937. FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
  938. if (strcmp(Name, "<built-in>") == 0) {
  939. PCHPredefinesBlock Block = {
  940. BufferID,
  941. llvm::StringRef(BlobStart, BlobLen - 1)
  942. };
  943. PCHPredefinesBuffers.push_back(Block);
  944. }
  945. break;
  946. }
  947. case pch::SM_SLOC_INSTANTIATION_ENTRY: {
  948. SourceLocation SpellingLoc
  949. = SourceLocation::getFromRawEncoding(Record[1]);
  950. SourceMgr.createInstantiationLoc(SpellingLoc,
  951. SourceLocation::getFromRawEncoding(Record[2]),
  952. SourceLocation::getFromRawEncoding(Record[3]),
  953. Record[4],
  954. ID,
  955. Record[0]);
  956. break;
  957. }
  958. }
  959. return Success;
  960. }
  961. /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
  962. /// specified cursor. Read the abbreviations that are at the top of the block
  963. /// and then leave the cursor pointing into the block.
  964. bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
  965. unsigned BlockID) {
  966. if (Cursor.EnterSubBlock(BlockID)) {
  967. Error("malformed block record in PCH file");
  968. return Failure;
  969. }
  970. while (true) {
  971. unsigned Code = Cursor.ReadCode();
  972. // We expect all abbrevs to be at the start of the block.
  973. if (Code != llvm::bitc::DEFINE_ABBREV)
  974. return false;
  975. Cursor.ReadAbbrevRecord();
  976. }
  977. }
  978. void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
  979. assert(PP && "Forgot to set Preprocessor ?");
  980. // Keep track of where we are in the stream, then jump back there
  981. // after reading this macro.
  982. SavedStreamPosition SavedPosition(Stream);
  983. Stream.JumpToBit(Offset);
  984. RecordData Record;
  985. llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
  986. MacroInfo *Macro = 0;
  987. while (true) {
  988. unsigned Code = Stream.ReadCode();
  989. switch (Code) {
  990. case llvm::bitc::END_BLOCK:
  991. return;
  992. case llvm::bitc::ENTER_SUBBLOCK:
  993. // No known subblocks, always skip them.
  994. Stream.ReadSubBlockID();
  995. if (Stream.SkipBlock()) {
  996. Error("malformed block record in PCH file");
  997. return;
  998. }
  999. continue;
  1000. case llvm::bitc::DEFINE_ABBREV:
  1001. Stream.ReadAbbrevRecord();
  1002. continue;
  1003. default: break;
  1004. }
  1005. // Read a record.
  1006. Record.clear();
  1007. pch::PreprocessorRecordTypes RecType =
  1008. (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
  1009. switch (RecType) {
  1010. case pch::PP_MACRO_OBJECT_LIKE:
  1011. case pch::PP_MACRO_FUNCTION_LIKE: {
  1012. // If we already have a macro, that means that we've hit the end
  1013. // of the definition of the macro we were looking for. We're
  1014. // done.
  1015. if (Macro)
  1016. return;
  1017. IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
  1018. if (II == 0) {
  1019. Error("macro must have a name in PCH file");
  1020. return;
  1021. }
  1022. SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
  1023. bool isUsed = Record[2];
  1024. MacroInfo *MI = PP->AllocateMacroInfo(Loc);
  1025. MI->setIsUsed(isUsed);
  1026. MI->setIsFromPCH();
  1027. unsigned NextIndex = 3;
  1028. if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
  1029. // Decode function-like macro info.
  1030. bool isC99VarArgs = Record[3];
  1031. bool isGNUVarArgs = Record[4];
  1032. MacroArgs.clear();
  1033. unsigned NumArgs = Record[5];
  1034. NextIndex = 6 + NumArgs;
  1035. for (unsigned i = 0; i != NumArgs; ++i)
  1036. MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
  1037. // Install function-like macro info.
  1038. MI->setIsFunctionLike();
  1039. if (isC99VarArgs) MI->setIsC99Varargs();
  1040. if (isGNUVarArgs) MI->setIsGNUVarargs();
  1041. MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
  1042. PP->getPreprocessorAllocator());
  1043. }
  1044. // Finally, install the macro.
  1045. PP->setMacroInfo(II, MI);
  1046. // Remember that we saw this macro last so that we add the tokens that
  1047. // form its body to it.
  1048. Macro = MI;
  1049. if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
  1050. // We have a macro definition. Load it now.
  1051. PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
  1052. getMacroDefinition(Record[NextIndex]));
  1053. }
  1054. ++NumMacrosRead;
  1055. break;
  1056. }
  1057. case pch::PP_TOKEN: {
  1058. // If we see a TOKEN before a PP_MACRO_*, then the file is
  1059. // erroneous, just pretend we didn't see this.
  1060. if (Macro == 0) break;
  1061. Token Tok;
  1062. Tok.startToken();
  1063. Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
  1064. Tok.setLength(Record[1]);
  1065. if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
  1066. Tok.setIdentifierInfo(II);
  1067. Tok.setKind((tok::TokenKind)Record[3]);
  1068. Tok.setFlag((Token::TokenFlags)Record[4]);
  1069. Macro->AddTokenToBody(Tok);
  1070. break;
  1071. }
  1072. case pch::PP_MACRO_INSTANTIATION: {
  1073. // If we already have a macro, that means that we've hit the end
  1074. // of the definition of the macro we were looking for. We're
  1075. // done.
  1076. if (Macro)
  1077. return;
  1078. if (!PP->getPreprocessingRecord()) {
  1079. Error("missing preprocessing record in PCH file");
  1080. return;
  1081. }
  1082. PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
  1083. if (PPRec.getPreprocessedEntity(Record[0]))
  1084. return;
  1085. MacroInstantiation *MI
  1086. = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
  1087. SourceRange(
  1088. SourceLocation::getFromRawEncoding(Record[1]),
  1089. SourceLocation::getFromRawEncoding(Record[2])),
  1090. getMacroDefinition(Record[4]));
  1091. PPRec.SetPreallocatedEntity(Record[0], MI);
  1092. return;
  1093. }
  1094. case pch::PP_MACRO_DEFINITION: {
  1095. // If we already have a macro, that means that we've hit the end
  1096. // of the definition of the macro we were looking for. We're
  1097. // done.
  1098. if (Macro)
  1099. return;
  1100. if (!PP->getPreprocessingRecord()) {
  1101. Error("missing preprocessing record in PCH file");
  1102. return;
  1103. }
  1104. PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
  1105. if (PPRec.getPreprocessedEntity(Record[0]))
  1106. return;
  1107. if (Record[1] >= MacroDefinitionsLoaded.size()) {
  1108. Error("out-of-bounds macro definition record");
  1109. return;
  1110. }
  1111. MacroDefinition *MD
  1112. = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
  1113. SourceLocation::getFromRawEncoding(Record[5]),
  1114. SourceRange(
  1115. SourceLocation::getFromRawEncoding(Record[2]),
  1116. SourceLocation::getFromRawEncoding(Record[3])));
  1117. PPRec.SetPreallocatedEntity(Record[0], MD);
  1118. MacroDefinitionsLoaded[Record[1]] = MD;
  1119. return;
  1120. }
  1121. }
  1122. }
  1123. }
  1124. void PCHReader::ReadDefinedMacros() {
  1125. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  1126. llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
  1127. // If there was no preprocessor block, skip this file.
  1128. if (!MacroCursor.getBitStreamReader())
  1129. continue;
  1130. llvm::BitstreamCursor Cursor = MacroCursor;
  1131. if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
  1132. Error("malformed preprocessor block record in PCH file");
  1133. return;
  1134. }
  1135. RecordData Record;
  1136. while (true) {
  1137. unsigned Code = Cursor.ReadCode();
  1138. if (Code == llvm::bitc::END_BLOCK) {
  1139. if (Cursor.ReadBlockEnd()) {
  1140. Error("error at end of preprocessor block in PCH file");
  1141. return;
  1142. }
  1143. break;
  1144. }
  1145. if (Code == llvm::bitc::ENTER_SUBBLOCK) {
  1146. // No known subblocks, always skip them.
  1147. Cursor.ReadSubBlockID();
  1148. if (Cursor.SkipBlock()) {
  1149. Error("malformed block record in PCH file");
  1150. return;
  1151. }
  1152. continue;
  1153. }
  1154. if (Code == llvm::bitc::DEFINE_ABBREV) {
  1155. Cursor.ReadAbbrevRecord();
  1156. continue;
  1157. }
  1158. // Read a record.
  1159. const char *BlobStart;
  1160. unsigned BlobLen;
  1161. Record.clear();
  1162. switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
  1163. default: // Default behavior: ignore.
  1164. break;
  1165. case pch::PP_MACRO_OBJECT_LIKE:
  1166. case pch::PP_MACRO_FUNCTION_LIKE:
  1167. DecodeIdentifierInfo(Record[0]);
  1168. break;
  1169. case pch::PP_TOKEN:
  1170. // Ignore tokens.
  1171. break;
  1172. case pch::PP_MACRO_INSTANTIATION:
  1173. case pch::PP_MACRO_DEFINITION:
  1174. // Read the macro record.
  1175. ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
  1176. break;
  1177. }
  1178. }
  1179. }
  1180. }
  1181. MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
  1182. if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
  1183. return 0;
  1184. if (!MacroDefinitionsLoaded[ID]) {
  1185. unsigned Index = ID;
  1186. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  1187. PerFileData &F = *Chain[N - I - 1];
  1188. if (Index < F.LocalNumMacroDefinitions) {
  1189. ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
  1190. break;
  1191. }
  1192. Index -= F.LocalNumMacroDefinitions;
  1193. }
  1194. assert(MacroDefinitionsLoaded[ID] && "Broken chain");
  1195. }
  1196. return MacroDefinitionsLoaded[ID];
  1197. }
  1198. /// \brief If we are loading a relocatable PCH file, and the filename is
  1199. /// not an absolute path, add the system root to the beginning of the file
  1200. /// name.
  1201. void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
  1202. // If this is not a relocatable PCH file, there's nothing to do.
  1203. if (!RelocatablePCH)
  1204. return;
  1205. if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
  1206. return;
  1207. if (isysroot == 0) {
  1208. // If no system root was given, default to '/'
  1209. Filename.insert(Filename.begin(), '/');
  1210. return;
  1211. }
  1212. unsigned Length = strlen(isysroot);
  1213. if (isysroot[Length - 1] != '/')
  1214. Filename.insert(Filename.begin(), '/');
  1215. Filename.insert(Filename.begin(), isysroot, isysroot + Length);
  1216. }
  1217. PCHReader::PCHReadResult
  1218. PCHReader::ReadPCHBlock(PerFileData &F) {
  1219. llvm::BitstreamCursor &Stream = F.Stream;
  1220. if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
  1221. Error("malformed block record in PCH file");
  1222. return Failure;
  1223. }
  1224. // Read all of the records and blocks for the PCH file.
  1225. RecordData Record;
  1226. bool First = true;
  1227. while (!Stream.AtEndOfStream()) {
  1228. unsigned Code = Stream.ReadCode();
  1229. if (Code == llvm::bitc::END_BLOCK) {
  1230. if (Stream.ReadBlockEnd()) {
  1231. Error("error at end of module block in PCH file");
  1232. return Failure;
  1233. }
  1234. return Success;
  1235. }
  1236. if (Code == llvm::bitc::ENTER_SUBBLOCK) {
  1237. switch (Stream.ReadSubBlockID()) {
  1238. case pch::DECLTYPES_BLOCK_ID:
  1239. // We lazily load the decls block, but we want to set up the
  1240. // DeclsCursor cursor to point into it. Clone our current bitcode
  1241. // cursor to it, enter the block and read the abbrevs in that block.
  1242. // With the main cursor, we just skip over it.
  1243. F.DeclsCursor = Stream;
  1244. if (Stream.SkipBlock() || // Skip with the main cursor.
  1245. // Read the abbrevs.
  1246. ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
  1247. Error("malformed block record in PCH file");
  1248. return Failure;
  1249. }
  1250. break;
  1251. case pch::PREPROCESSOR_BLOCK_ID:
  1252. F.MacroCursor = Stream;
  1253. if (PP)
  1254. PP->setExternalSource(this);
  1255. if (Stream.SkipBlock()) {
  1256. Error("malformed block record in PCH file");
  1257. return Failure;
  1258. }
  1259. break;
  1260. case pch::SOURCE_MANAGER_BLOCK_ID:
  1261. switch (ReadSourceManagerBlock(F)) {
  1262. case Success:
  1263. break;
  1264. case Failure:
  1265. Error("malformed source manager block in PCH file");
  1266. return Failure;
  1267. case IgnorePCH:
  1268. return IgnorePCH;
  1269. }
  1270. break;
  1271. }
  1272. First = false;
  1273. continue;
  1274. }
  1275. if (Code == llvm::bitc::DEFINE_ABBREV) {
  1276. Stream.ReadAbbrevRecord();
  1277. continue;
  1278. }
  1279. // Read and process a record.
  1280. Record.clear();
  1281. const char *BlobStart = 0;
  1282. unsigned BlobLen = 0;
  1283. switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
  1284. &BlobStart, &BlobLen)) {
  1285. default: // Default behavior: ignore.
  1286. break;
  1287. case pch::METADATA: {
  1288. if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
  1289. Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
  1290. : diag::warn_pch_version_too_new);
  1291. return IgnorePCH;
  1292. }
  1293. RelocatablePCH = Record[4];
  1294. if (Listener) {
  1295. std::string TargetTriple(BlobStart, BlobLen);
  1296. if (Listener->ReadTargetTriple(TargetTriple))
  1297. return IgnorePCH;
  1298. }
  1299. break;
  1300. }
  1301. case pch::CHAINED_METADATA: {
  1302. if (!First) {
  1303. Error("CHAINED_METADATA is not first record in block");
  1304. return Failure;
  1305. }
  1306. if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
  1307. Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
  1308. : diag::warn_pch_version_too_new);
  1309. return IgnorePCH;
  1310. }
  1311. // Load the chained file.
  1312. switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
  1313. case Failure: return Failure;
  1314. // If we have to ignore the dependency, we'll have to ignore this too.
  1315. case IgnorePCH: return IgnorePCH;
  1316. case Success: break;
  1317. }
  1318. break;
  1319. }
  1320. case pch::TYPE_OFFSET:
  1321. if (F.LocalNumTypes != 0) {
  1322. Error("duplicate TYPE_OFFSET record in PCH file");
  1323. return Failure;
  1324. }
  1325. F.TypeOffsets = (const uint32_t *)BlobStart;
  1326. F.LocalNumTypes = Record[0];
  1327. break;
  1328. case pch::DECL_OFFSET:
  1329. if (F.LocalNumDecls != 0) {
  1330. Error("duplicate DECL_OFFSET record in PCH file");
  1331. return Failure;
  1332. }
  1333. F.DeclOffsets = (const uint32_t *)BlobStart;
  1334. F.LocalNumDecls = Record[0];
  1335. break;
  1336. case pch::TU_UPDATE_LEXICAL: {
  1337. DeclContextInfo Info = {
  1338. /* No visible information */ 0, 0,
  1339. reinterpret_cast<const pch::DeclID *>(BlobStart),
  1340. BlobLen / sizeof(pch::DeclID)
  1341. };
  1342. DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
  1343. break;
  1344. }
  1345. case pch::REDECLS_UPDATE_LATEST: {
  1346. assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
  1347. for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
  1348. pch::DeclID First = Record[i], Latest = Record[i+1];
  1349. assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
  1350. Latest > FirstLatestDeclIDs[First]) &&
  1351. "The new latest is supposed to come after the previous latest");
  1352. FirstLatestDeclIDs[First] = Latest;
  1353. }
  1354. break;
  1355. }
  1356. case pch::LANGUAGE_OPTIONS:
  1357. if (ParseLanguageOptions(Record) && !DisableValidation)
  1358. return IgnorePCH;
  1359. break;
  1360. case pch::IDENTIFIER_TABLE:
  1361. F.IdentifierTableData = BlobStart;
  1362. if (Record[0]) {
  1363. F.IdentifierLookupTable
  1364. = PCHIdentifierLookupTable::Create(
  1365. (const unsigned char *)F.IdentifierTableData + Record[0],
  1366. (const unsigned char *)F.IdentifierTableData,
  1367. PCHIdentifierLookupTrait(*this, F.Stream));
  1368. if (PP)
  1369. PP->getIdentifierTable().setExternalIdentifierLookup(this);
  1370. }
  1371. break;
  1372. case pch::IDENTIFIER_OFFSET:
  1373. if (F.LocalNumIdentifiers != 0) {
  1374. Error("duplicate IDENTIFIER_OFFSET record in PCH file");
  1375. return Failure;
  1376. }
  1377. F.IdentifierOffsets = (const uint32_t *)BlobStart;
  1378. F.LocalNumIdentifiers = Record[0];
  1379. break;
  1380. case pch::EXTERNAL_DEFINITIONS:
  1381. // Optimization for the first block.
  1382. if (ExternalDefinitions.empty())
  1383. ExternalDefinitions.swap(Record);
  1384. else
  1385. ExternalDefinitions.insert(ExternalDefinitions.end(),
  1386. Record.begin(), Record.end());
  1387. break;
  1388. case pch::SPECIAL_TYPES:
  1389. // Optimization for the first block
  1390. if (SpecialTypes.empty())
  1391. SpecialTypes.swap(Record);
  1392. else
  1393. SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
  1394. break;
  1395. case pch::STATISTICS:
  1396. TotalNumStatements += Record[0];
  1397. TotalNumMacros += Record[1];
  1398. TotalLexicalDeclContexts += Record[2];
  1399. TotalVisibleDeclContexts += Record[3];
  1400. break;
  1401. case pch::TENTATIVE_DEFINITIONS:
  1402. // Optimization for the first block.
  1403. if (TentativeDefinitions.empty())
  1404. TentativeDefinitions.swap(Record);
  1405. else
  1406. TentativeDefinitions.insert(TentativeDefinitions.end(),
  1407. Record.begin(), Record.end());
  1408. break;
  1409. case pch::UNUSED_STATIC_FUNCS:
  1410. // Optimization for the first block.
  1411. if (UnusedStaticFuncs.empty())
  1412. UnusedStaticFuncs.swap(Record);
  1413. else
  1414. UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
  1415. Record.begin(), Record.end());
  1416. break;
  1417. case pch::WEAK_UNDECLARED_IDENTIFIERS:
  1418. // Later blocks overwrite earlier ones.
  1419. WeakUndeclaredIdentifiers.swap(Record);
  1420. break;
  1421. case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
  1422. // Optimization for the first block.
  1423. if (LocallyScopedExternalDecls.empty())
  1424. LocallyScopedExternalDecls.swap(Record);
  1425. else
  1426. LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
  1427. Record.begin(), Record.end());
  1428. break;
  1429. case pch::SELECTOR_OFFSETS:
  1430. F.SelectorOffsets = (const uint32_t *)BlobStart;
  1431. F.LocalNumSelectors = Record[0];
  1432. break;
  1433. case pch::METHOD_POOL:
  1434. F.SelectorLookupTableData = (const unsigned char *)BlobStart;
  1435. if (Record[0])
  1436. F.SelectorLookupTable
  1437. = PCHSelectorLookupTable::Create(
  1438. F.SelectorLookupTableData + Record[0],
  1439. F.SelectorLookupTableData,
  1440. PCHSelectorLookupTrait(*this));
  1441. TotalNumMethodPoolEntries += Record[1];
  1442. break;
  1443. case pch::REFERENCED_SELECTOR_POOL: {
  1444. ReferencedSelectorsData.insert(ReferencedSelectorsData.end(),
  1445. Record.begin(), Record.end());
  1446. break;
  1447. }
  1448. case pch::PP_COUNTER_VALUE:
  1449. if (!Record.empty() && Listener)
  1450. Listener->ReadCounter(Record[0]);
  1451. break;
  1452. case pch::SOURCE_LOCATION_OFFSETS:
  1453. F.SLocOffsets = (const uint32_t *)BlobStart;
  1454. F.LocalNumSLocEntries = Record[0];
  1455. // We cannot delay this until all PCHs are loaded, because then source
  1456. // location preloads would also have to be delayed.
  1457. TotalNumSLocEntries += F.LocalNumSLocEntries;
  1458. SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
  1459. break;
  1460. case pch::SOURCE_LOCATION_PRELOADS:
  1461. for (unsigned I = 0, N = Record.size(); I != N; ++I) {
  1462. PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
  1463. if (Result != Success)
  1464. return Result;
  1465. }
  1466. break;
  1467. case pch::STAT_CACHE: {
  1468. PCHStatCache *MyStatCache =
  1469. new PCHStatCache((const unsigned char *)BlobStart + Record[0],
  1470. (const unsigned char *)BlobStart,
  1471. NumStatHits, NumStatMisses);
  1472. FileMgr.addStatCache(MyStatCache);
  1473. F.StatCache = MyStatCache;
  1474. break;
  1475. }
  1476. case pch::EXT_VECTOR_DECLS:
  1477. // Optimization for the first block.
  1478. if (ExtVectorDecls.empty())
  1479. ExtVectorDecls.swap(Record);
  1480. else
  1481. ExtVectorDecls.insert(ExtVectorDecls.end(),
  1482. Record.begin(), Record.end());
  1483. break;
  1484. case pch::VTABLE_USES:
  1485. // Later tables overwrite earlier ones.
  1486. VTableUses.swap(Record);
  1487. break;
  1488. case pch::DYNAMIC_CLASSES:
  1489. // Optimization for the first block.
  1490. if (DynamicClasses.empty())
  1491. DynamicClasses.swap(Record);
  1492. else
  1493. DynamicClasses.insert(DynamicClasses.end(),
  1494. Record.begin(), Record.end());
  1495. break;
  1496. case pch::PENDING_IMPLICIT_INSTANTIATIONS:
  1497. // Optimization for the first block.
  1498. if (PendingImplicitInstantiations.empty())
  1499. PendingImplicitInstantiations.swap(Record);
  1500. else
  1501. PendingImplicitInstantiations.insert(
  1502. PendingImplicitInstantiations.end(), Record.begin(), Record.end());
  1503. break;
  1504. case pch::SEMA_DECL_REFS:
  1505. // Later tables overwrite earlier ones.
  1506. SemaDeclRefs.swap(Record);
  1507. break;
  1508. case pch::ORIGINAL_FILE_NAME:
  1509. // The primary PCH will be the last to get here, so it will be the one
  1510. // that's used.
  1511. ActualOriginalFileName.assign(BlobStart, BlobLen);
  1512. OriginalFileName = ActualOriginalFileName;
  1513. MaybeAddSystemRootToFilename(OriginalFileName);
  1514. break;
  1515. case pch::VERSION_CONTROL_BRANCH_REVISION: {
  1516. const std::string &CurBranch = getClangFullRepositoryVersion();
  1517. llvm::StringRef PCHBranch(BlobStart, BlobLen);
  1518. if (llvm::StringRef(CurBranch) != PCHBranch && !DisableValidation) {
  1519. Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
  1520. return IgnorePCH;
  1521. }
  1522. break;
  1523. }
  1524. case pch::MACRO_DEFINITION_OFFSETS:
  1525. F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
  1526. F.NumPreallocatedPreprocessingEntities = Record[0];
  1527. F.LocalNumMacroDefinitions = Record[1];
  1528. break;
  1529. }
  1530. First = false;
  1531. }
  1532. Error("premature end of bitstream in PCH file");
  1533. return Failure;
  1534. }
  1535. PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
  1536. switch(ReadPCHCore(FileName)) {
  1537. case Failure: return Failure;
  1538. case IgnorePCH: return IgnorePCH;
  1539. case Success: break;
  1540. }
  1541. // Here comes stuff that we only do once the entire chain is loaded.
  1542. // Allocate space for loaded identifiers, decls and types.
  1543. unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
  1544. TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
  1545. TotalNumSelectors = 0;
  1546. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  1547. TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
  1548. TotalNumTypes += Chain[I]->LocalNumTypes;
  1549. TotalNumDecls += Chain[I]->LocalNumDecls;
  1550. TotalNumPreallocatedPreprocessingEntities +=
  1551. Chain[I]->NumPreallocatedPreprocessingEntities;
  1552. TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
  1553. TotalNumSelectors += Chain[I]->LocalNumSelectors;
  1554. }
  1555. IdentifiersLoaded.resize(TotalNumIdentifiers);
  1556. TypesLoaded.resize(TotalNumTypes);
  1557. DeclsLoaded.resize(TotalNumDecls);
  1558. MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
  1559. if (PP) {
  1560. if (TotalNumIdentifiers > 0)
  1561. PP->getHeaderSearchInfo().SetExternalLookup(this);
  1562. if (TotalNumPreallocatedPreprocessingEntities > 0) {
  1563. if (!PP->getPreprocessingRecord())
  1564. PP->createPreprocessingRecord();
  1565. PP->getPreprocessingRecord()->SetExternalSource(*this,
  1566. TotalNumPreallocatedPreprocessingEntities);
  1567. }
  1568. }
  1569. SelectorsLoaded.resize(TotalNumSelectors);
  1570. // Check the predefines buffers.
  1571. if (!DisableValidation && CheckPredefinesBuffers())
  1572. return IgnorePCH;
  1573. if (PP) {
  1574. // Initialization of keywords and pragmas occurs before the
  1575. // PCH file is read, so there may be some identifiers that were
  1576. // loaded into the IdentifierTable before we intercepted the
  1577. // creation of identifiers. Iterate through the list of known
  1578. // identifiers and determine whether we have to establish
  1579. // preprocessor definitions or top-level identifier declaration
  1580. // chains for those identifiers.
  1581. //
  1582. // We copy the IdentifierInfo pointers to a small vector first,
  1583. // since de-serializing declarations or macro definitions can add
  1584. // new entries into the identifier table, invalidating the
  1585. // iterators.
  1586. llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
  1587. for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
  1588. IdEnd = PP->getIdentifierTable().end();
  1589. Id != IdEnd; ++Id)
  1590. Identifiers.push_back(Id->second);
  1591. // We need to search the tables in all files.
  1592. for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
  1593. PCHIdentifierLookupTable *IdTable
  1594. = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
  1595. // Not all PCH files necessarily have identifier tables, only the useful
  1596. // ones.
  1597. if (!IdTable)
  1598. continue;
  1599. for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
  1600. IdentifierInfo *II = Identifiers[I];
  1601. // Look in the on-disk hash tables for an entry for this identifier
  1602. PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
  1603. std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
  1604. PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
  1605. if (Pos == IdTable->end())
  1606. continue;
  1607. // Dereferencing the iterator has the effect of populating the
  1608. // IdentifierInfo node with the various declarations it needs.
  1609. (void)*Pos;
  1610. }
  1611. }
  1612. }
  1613. if (Context)
  1614. InitializeContext(*Context);
  1615. return Success;
  1616. }
  1617. PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
  1618. Chain.push_back(new PerFileData());
  1619. PerFileData &F = *Chain.back();
  1620. // Set the PCH file name.
  1621. F.FileName = FileName;
  1622. // Open the PCH file.
  1623. //
  1624. // FIXME: This shouldn't be here, we should just take a raw_ostream.
  1625. std::string ErrStr;
  1626. F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
  1627. if (!F.Buffer) {
  1628. Error(ErrStr.c_str());
  1629. return IgnorePCH;
  1630. }
  1631. // Initialize the stream
  1632. F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
  1633. (const unsigned char *)F.Buffer->getBufferEnd());
  1634. llvm::BitstreamCursor &Stream = F.Stream;
  1635. Stream.init(F.StreamFile);
  1636. F.SizeInBits = F.Buffer->getBufferSize() * 8;
  1637. // Sniff for the signature.
  1638. if (Stream.Read(8) != 'C' ||
  1639. Stream.Read(8) != 'P' ||
  1640. Stream.Read(8) != 'C' ||
  1641. Stream.Read(8) != 'H') {
  1642. Diag(diag::err_not_a_pch_file) << FileName;
  1643. return Failure;
  1644. }
  1645. while (!Stream.AtEndOfStream()) {
  1646. unsigned Code = Stream.ReadCode();
  1647. if (Code != llvm::bitc::ENTER_SUBBLOCK) {
  1648. Error("invalid record at top-level of PCH file");
  1649. return Failure;
  1650. }
  1651. unsigned BlockID = Stream.ReadSubBlockID();
  1652. // We only know the PCH subblock ID.
  1653. switch (BlockID) {
  1654. case llvm::bitc::BLOCKINFO_BLOCK_ID:
  1655. if (Stream.ReadBlockInfoBlock()) {
  1656. Error("malformed BlockInfoBlock in PCH file");
  1657. return Failure;
  1658. }
  1659. break;
  1660. case pch::PCH_BLOCK_ID:
  1661. switch (ReadPCHBlock(F)) {
  1662. case Success:
  1663. break;
  1664. case Failure:
  1665. return Failure;
  1666. case IgnorePCH:
  1667. // FIXME: We could consider reading through to the end of this
  1668. // PCH block, skipping subblocks, to see if there are other
  1669. // PCH blocks elsewhere.
  1670. // Clear out any preallocated source location entries, so that
  1671. // the source manager does not try to resolve them later.
  1672. SourceMgr.ClearPreallocatedSLocEntries();
  1673. // Remove the stat cache.
  1674. if (F.StatCache)
  1675. FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
  1676. return IgnorePCH;
  1677. }
  1678. break;
  1679. default:
  1680. if (Stream.SkipBlock()) {
  1681. Error("malformed block record in PCH file");
  1682. return Failure;
  1683. }
  1684. break;
  1685. }
  1686. }
  1687. return Success;
  1688. }
  1689. void PCHReader::setPreprocessor(Preprocessor &pp) {
  1690. PP = &pp;
  1691. unsigned TotalNum = 0;
  1692. for (unsigned I = 0, N = Chain.size(); I != N; ++I)
  1693. TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
  1694. if (TotalNum) {
  1695. if (!PP->getPreprocessingRecord())
  1696. PP->createPreprocessingRecord();
  1697. PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
  1698. }
  1699. }
  1700. void PCHReader::InitializeContext(ASTContext &Ctx) {
  1701. Context = &Ctx;
  1702. assert(Context && "Passed null context!");
  1703. assert(PP && "Forgot to set Preprocessor ?");
  1704. PP->getIdentifierTable().setExternalIdentifierLookup(this);
  1705. PP->getHeaderSearchInfo().SetExternalLookup(this);
  1706. PP->setExternalSource(this);
  1707. // Load the translation unit declaration
  1708. GetTranslationUnitDecl();
  1709. // Load the special types.
  1710. Context->setBuiltinVaListType(
  1711. GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
  1712. if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
  1713. Context->setObjCIdType(GetType(Id));
  1714. if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
  1715. Context->setObjCSelType(GetType(Sel));
  1716. if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
  1717. Context->setObjCProtoType(GetType(Proto));
  1718. if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
  1719. Context->setObjCClassType(GetType(Class));
  1720. if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
  1721. Context->setCFConstantStringType(GetType(String));
  1722. if (unsigned FastEnum
  1723. = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
  1724. Context->setObjCFastEnumerationStateType(GetType(FastEnum));
  1725. if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
  1726. QualType FileType = GetType(File);
  1727. if (FileType.isNull()) {
  1728. Error("FILE type is NULL");
  1729. return;
  1730. }
  1731. if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
  1732. Context->setFILEDecl(Typedef->getDecl());
  1733. else {
  1734. const TagType *Tag = FileType->getAs<TagType>();
  1735. if (!Tag) {
  1736. Error("Invalid FILE type in PCH file");
  1737. return;
  1738. }
  1739. Context->setFILEDecl(Tag->getDecl());
  1740. }
  1741. }
  1742. if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
  1743. QualType Jmp_bufType = GetType(Jmp_buf);
  1744. if (Jmp_bufType.isNull()) {
  1745. Error("jmp_bug type is NULL");
  1746. return;
  1747. }
  1748. if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
  1749. Context->setjmp_bufDecl(Typedef->getDecl());
  1750. else {
  1751. const TagType *Tag = Jmp_bufType->getAs<TagType>();
  1752. if (!Tag) {
  1753. Error("Invalid jmp_bug type in PCH file");
  1754. return;
  1755. }
  1756. Context->setjmp_bufDecl(Tag->getDecl());
  1757. }
  1758. }
  1759. if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
  1760. QualType Sigjmp_bufType = GetType(Sigjmp_buf);
  1761. if (Sigjmp_bufType.isNull()) {
  1762. Error("sigjmp_buf type is NULL");
  1763. return;
  1764. }
  1765. if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
  1766. Context->setsigjmp_bufDecl(Typedef->getDecl());
  1767. else {
  1768. const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
  1769. assert(Tag && "Invalid sigjmp_buf type in PCH file");
  1770. Context->setsigjmp_bufDecl(Tag->getDecl());
  1771. }
  1772. }
  1773. if (unsigned ObjCIdRedef
  1774. = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
  1775. Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
  1776. if (unsigned ObjCClassRedef
  1777. = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
  1778. Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
  1779. if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
  1780. Context->setBlockDescriptorType(GetType(String));
  1781. if (unsigned String
  1782. = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
  1783. Context->setBlockDescriptorExtendedType(GetType(String));
  1784. if (unsigned ObjCSelRedef
  1785. = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
  1786. Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
  1787. if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
  1788. Context->setNSConstantStringType(GetType(String));
  1789. if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
  1790. Context->setInt128Installed();
  1791. }
  1792. /// \brief Retrieve the name of the original source file name
  1793. /// directly from the PCH file, without actually loading the PCH
  1794. /// file.
  1795. std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
  1796. Diagnostic &Diags) {
  1797. // Open the PCH file.
  1798. std::string ErrStr;
  1799. llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
  1800. Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
  1801. if (!Buffer) {
  1802. Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
  1803. return std::string();
  1804. }
  1805. // Initialize the stream
  1806. llvm::BitstreamReader StreamFile;
  1807. llvm::BitstreamCursor Stream;
  1808. StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
  1809. (const unsigned char *)Buffer->getBufferEnd());
  1810. Stream.init(StreamFile);
  1811. // Sniff for the signature.
  1812. if (Stream.Read(8) != 'C' ||
  1813. Stream.Read(8) != 'P' ||
  1814. Stream.Read(8) != 'C' ||
  1815. Stream.Read(8) != 'H') {
  1816. Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
  1817. return std::string();
  1818. }
  1819. RecordData Record;
  1820. while (!Stream.AtEndOfStream()) {
  1821. unsigned Code = Stream.ReadCode();
  1822. if (Code == llvm::bitc::ENTER_SUBBLOCK) {
  1823. unsigned BlockID = Stream.ReadSubBlockID();
  1824. // We only know the PCH subblock ID.
  1825. switch (BlockID) {
  1826. case pch::PCH_BLOCK_ID:
  1827. if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
  1828. Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
  1829. return std::string();
  1830. }
  1831. break;
  1832. default:
  1833. if (Stream.SkipBlock()) {
  1834. Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
  1835. return std::string();
  1836. }
  1837. break;
  1838. }
  1839. continue;
  1840. }
  1841. if (Code == llvm::bitc::END_BLOCK) {
  1842. if (Stream.ReadBlockEnd()) {
  1843. Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
  1844. return std::string();
  1845. }
  1846. continue;
  1847. }
  1848. if (Code == llvm::bitc::DEFINE_ABBREV) {
  1849. Stream.ReadAbbrevRecord();
  1850. continue;
  1851. }
  1852. Record.clear();
  1853. const char *BlobStart = 0;
  1854. unsigned BlobLen = 0;
  1855. if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
  1856. == pch::ORIGINAL_FILE_NAME)
  1857. return std::string(BlobStart, BlobLen);
  1858. }
  1859. return std::string();
  1860. }
  1861. /// \brief Parse the record that corresponds to a LangOptions data
  1862. /// structure.
  1863. ///
  1864. /// This routine compares the language options used to generate the
  1865. /// PCH file against the language options set for the current
  1866. /// compilation. For each option, we classify differences between the
  1867. /// two compiler states as either "benign" or "important". Benign
  1868. /// differences don't matter, and we accept them without complaint
  1869. /// (and without modifying the language options). Differences between
  1870. /// the states for important options cause the PCH file to be
  1871. /// unusable, so we emit a warning and return true to indicate that
  1872. /// there was an error.
  1873. ///
  1874. /// \returns true if the PCH file is unacceptable, false otherwise.
  1875. bool PCHReader::ParseLanguageOptions(
  1876. const llvm::SmallVectorImpl<uint64_t> &Record) {
  1877. if (Listener) {
  1878. LangOptions LangOpts;
  1879. #define PARSE_LANGOPT(Option) \
  1880. LangOpts.Option = Record[Idx]; \
  1881. ++Idx
  1882. unsigned Idx = 0;
  1883. PARSE_LANGOPT(Trigraphs);
  1884. PARSE_LANGOPT(BCPLComment);
  1885. PARSE_LANGOPT(DollarIdents);
  1886. PARSE_LANGOPT(AsmPreprocessor);
  1887. PARSE_LANGOPT(GNUMode);
  1888. PARSE_LANGOPT(GNUKeywords);
  1889. PARSE_LANGOPT(ImplicitInt);
  1890. PARSE_LANGOPT(Digraphs);
  1891. PARSE_LANGOPT(HexFloats);
  1892. PARSE_LANGOPT(C99);
  1893. PARSE_LANGOPT(Microsoft);
  1894. PARSE_LANGOPT(CPlusPlus);
  1895. PARSE_LANGOPT(CPlusPlus0x);
  1896. PARSE_LANGOPT(CXXOperatorNames);
  1897. PARSE_LANGOPT(ObjC1);
  1898. PARSE_LANGOPT(ObjC2);
  1899. PARSE_LANGOPT(ObjCNonFragileABI);
  1900. PARSE_LANGOPT(ObjCNonFragileABI2);
  1901. PARSE_LANGOPT(NoConstantCFStrings);
  1902. PARSE_LANGOPT(PascalStrings);
  1903. PARSE_LANGOPT(WritableStrings);
  1904. PARSE_LANGOPT(LaxVectorConversions);
  1905. PARSE_LANGOPT(AltiVec);
  1906. PARSE_LANGOPT(Exceptions);
  1907. PARSE_LANGOPT(SjLjExceptions);
  1908. PARSE_LANGOPT(NeXTRuntime);
  1909. PARSE_LANGOPT(Freestanding);
  1910. PARSE_LANGOPT(NoBuiltin);
  1911. PARSE_LANGOPT(ThreadsafeStatics);
  1912. PARSE_LANGOPT(POSIXThreads);
  1913. PARSE_LANGOPT(Blocks);
  1914. PARSE_LANGOPT(EmitAllDecls);
  1915. PARSE_LANGOPT(MathErrno);
  1916. LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
  1917. Record[Idx++]);
  1918. PARSE_LANGOPT(HeinousExtensions);
  1919. PARSE_LANGOPT(Optimize);
  1920. PARSE_LANGOPT(OptimizeSize);
  1921. PARSE_LANGOPT(Static);
  1922. PARSE_LANGOPT(PICLevel);
  1923. PARSE_LANGOPT(GNUInline);
  1924. PARSE_LANGOPT(NoInline);
  1925. PARSE_LANGOPT(AccessControl);
  1926. PARSE_LANGOPT(CharIsSigned);
  1927. PARSE_LANGOPT(ShortWChar);
  1928. LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
  1929. LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
  1930. LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
  1931. Record[Idx++]);
  1932. PARSE_LANGOPT(InstantiationDepth);
  1933. PARSE_LANGOPT(OpenCL);
  1934. PARSE_LANGOPT(CatchUndefined);
  1935. // FIXME: Missing ElideConstructors?!
  1936. #undef PARSE_LANGOPT
  1937. return Listener->ReadLanguageOptions(LangOpts);
  1938. }
  1939. return false;
  1940. }
  1941. void PCHReader::ReadPreprocessedEntities() {
  1942. ReadDefinedMacros();
  1943. }
  1944. /// \brief Get the correct cursor and offset for loading a type.
  1945. PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
  1946. PerFileData *F = 0;
  1947. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  1948. F = Chain[N - I - 1];
  1949. if (Index < F->LocalNumTypes)
  1950. break;
  1951. Index -= F->LocalNumTypes;
  1952. }
  1953. assert(F && F->LocalNumTypes > Index && "Broken chain");
  1954. return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
  1955. }
  1956. /// \brief Read and return the type with the given index..
  1957. ///
  1958. /// The index is the type ID, shifted and minus the number of predefs. This
  1959. /// routine actually reads the record corresponding to the type at the given
  1960. /// location. It is a helper routine for GetType, which deals with reading type
  1961. /// IDs.
  1962. QualType PCHReader::ReadTypeRecord(unsigned Index) {
  1963. RecordLocation Loc = TypeCursorForIndex(Index);
  1964. llvm::BitstreamCursor &DeclsCursor = *Loc.first;
  1965. // Keep track of where we are in the stream, then jump back there
  1966. // after reading this type.
  1967. SavedStreamPosition SavedPosition(DeclsCursor);
  1968. ReadingKindTracker ReadingKind(Read_Type, *this);
  1969. // Note that we are loading a type record.
  1970. Deserializing AType(this);
  1971. DeclsCursor.JumpToBit(Loc.second);
  1972. RecordData Record;
  1973. unsigned Code = DeclsCursor.ReadCode();
  1974. switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
  1975. case pch::TYPE_EXT_QUAL: {
  1976. if (Record.size() != 2) {
  1977. Error("Incorrect encoding of extended qualifier type");
  1978. return QualType();
  1979. }
  1980. QualType Base = GetType(Record[0]);
  1981. Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
  1982. return Context->getQualifiedType(Base, Quals);
  1983. }
  1984. case pch::TYPE_COMPLEX: {
  1985. if (Record.size() != 1) {
  1986. Error("Incorrect encoding of complex type");
  1987. return QualType();
  1988. }
  1989. QualType ElemType = GetType(Record[0]);
  1990. return Context->getComplexType(ElemType);
  1991. }
  1992. case pch::TYPE_POINTER: {
  1993. if (Record.size() != 1) {
  1994. Error("Incorrect encoding of pointer type");
  1995. return QualType();
  1996. }
  1997. QualType PointeeType = GetType(Record[0]);
  1998. return Context->getPointerType(PointeeType);
  1999. }
  2000. case pch::TYPE_BLOCK_POINTER: {
  2001. if (Record.size() != 1) {
  2002. Error("Incorrect encoding of block pointer type");
  2003. return QualType();
  2004. }
  2005. QualType PointeeType = GetType(Record[0]);
  2006. return Context->getBlockPointerType(PointeeType);
  2007. }
  2008. case pch::TYPE_LVALUE_REFERENCE: {
  2009. if (Record.size() != 1) {
  2010. Error("Incorrect encoding of lvalue reference type");
  2011. return QualType();
  2012. }
  2013. QualType PointeeType = GetType(Record[0]);
  2014. return Context->getLValueReferenceType(PointeeType);
  2015. }
  2016. case pch::TYPE_RVALUE_REFERENCE: {
  2017. if (Record.size() != 1) {
  2018. Error("Incorrect encoding of rvalue reference type");
  2019. return QualType();
  2020. }
  2021. QualType PointeeType = GetType(Record[0]);
  2022. return Context->getRValueReferenceType(PointeeType);
  2023. }
  2024. case pch::TYPE_MEMBER_POINTER: {
  2025. if (Record.size() != 2) {
  2026. Error("Incorrect encoding of member pointer type");
  2027. return QualType();
  2028. }
  2029. QualType PointeeType = GetType(Record[0]);
  2030. QualType ClassType = GetType(Record[1]);
  2031. return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
  2032. }
  2033. case pch::TYPE_CONSTANT_ARRAY: {
  2034. QualType ElementType = GetType(Record[0]);
  2035. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  2036. unsigned IndexTypeQuals = Record[2];
  2037. unsigned Idx = 3;
  2038. llvm::APInt Size = ReadAPInt(Record, Idx);
  2039. return Context->getConstantArrayType(ElementType, Size,
  2040. ASM, IndexTypeQuals);
  2041. }
  2042. case pch::TYPE_INCOMPLETE_ARRAY: {
  2043. QualType ElementType = GetType(Record[0]);
  2044. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  2045. unsigned IndexTypeQuals = Record[2];
  2046. return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
  2047. }
  2048. case pch::TYPE_VARIABLE_ARRAY: {
  2049. QualType ElementType = GetType(Record[0]);
  2050. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  2051. unsigned IndexTypeQuals = Record[2];
  2052. SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
  2053. SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
  2054. return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
  2055. ASM, IndexTypeQuals,
  2056. SourceRange(LBLoc, RBLoc));
  2057. }
  2058. case pch::TYPE_VECTOR: {
  2059. if (Record.size() != 3) {
  2060. Error("incorrect encoding of vector type in PCH file");
  2061. return QualType();
  2062. }
  2063. QualType ElementType = GetType(Record[0]);
  2064. unsigned NumElements = Record[1];
  2065. unsigned AltiVecSpec = Record[2];
  2066. return Context->getVectorType(ElementType, NumElements,
  2067. (VectorType::AltiVecSpecific)AltiVecSpec);
  2068. }
  2069. case pch::TYPE_EXT_VECTOR: {
  2070. if (Record.size() != 3) {
  2071. Error("incorrect encoding of extended vector type in PCH file");
  2072. return QualType();
  2073. }
  2074. QualType ElementType = GetType(Record[0]);
  2075. unsigned NumElements = Record[1];
  2076. return Context->getExtVectorType(ElementType, NumElements);
  2077. }
  2078. case pch::TYPE_FUNCTION_NO_PROTO: {
  2079. if (Record.size() != 4) {
  2080. Error("incorrect encoding of no-proto function type");
  2081. return QualType();
  2082. }
  2083. QualType ResultType = GetType(Record[0]);
  2084. FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
  2085. return Context->getFunctionNoProtoType(ResultType, Info);
  2086. }
  2087. case pch::TYPE_FUNCTION_PROTO: {
  2088. QualType ResultType = GetType(Record[0]);
  2089. bool NoReturn = Record[1];
  2090. unsigned RegParm = Record[2];
  2091. CallingConv CallConv = (CallingConv)Record[3];
  2092. unsigned Idx = 4;
  2093. unsigned NumParams = Record[Idx++];
  2094. llvm::SmallVector<QualType, 16> ParamTypes;
  2095. for (unsigned I = 0; I != NumParams; ++I)
  2096. ParamTypes.push_back(GetType(Record[Idx++]));
  2097. bool isVariadic = Record[Idx++];
  2098. unsigned Quals = Record[Idx++];
  2099. bool hasExceptionSpec = Record[Idx++];
  2100. bool hasAnyExceptionSpec = Record[Idx++];
  2101. unsigned NumExceptions = Record[Idx++];
  2102. llvm::SmallVector<QualType, 2> Exceptions;
  2103. for (unsigned I = 0; I != NumExceptions; ++I)
  2104. Exceptions.push_back(GetType(Record[Idx++]));
  2105. return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
  2106. isVariadic, Quals, hasExceptionSpec,
  2107. hasAnyExceptionSpec, NumExceptions,
  2108. Exceptions.data(),
  2109. FunctionType::ExtInfo(NoReturn, RegParm,
  2110. CallConv));
  2111. }
  2112. case pch::TYPE_UNRESOLVED_USING:
  2113. return Context->getTypeDeclType(
  2114. cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
  2115. case pch::TYPE_TYPEDEF: {
  2116. if (Record.size() != 2) {
  2117. Error("incorrect encoding of typedef type");
  2118. return QualType();
  2119. }
  2120. TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
  2121. QualType Canonical = GetType(Record[1]);
  2122. return Context->getTypedefType(Decl, Canonical);
  2123. }
  2124. case pch::TYPE_TYPEOF_EXPR:
  2125. return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
  2126. case pch::TYPE_TYPEOF: {
  2127. if (Record.size() != 1) {
  2128. Error("incorrect encoding of typeof(type) in PCH file");
  2129. return QualType();
  2130. }
  2131. QualType UnderlyingType = GetType(Record[0]);
  2132. return Context->getTypeOfType(UnderlyingType);
  2133. }
  2134. case pch::TYPE_DECLTYPE:
  2135. return Context->getDecltypeType(ReadExpr(DeclsCursor));
  2136. case pch::TYPE_RECORD: {
  2137. if (Record.size() != 2) {
  2138. Error("incorrect encoding of record type");
  2139. return QualType();
  2140. }
  2141. bool IsDependent = Record[0];
  2142. QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
  2143. T->Dependent = IsDependent;
  2144. return T;
  2145. }
  2146. case pch::TYPE_ENUM: {
  2147. if (Record.size() != 2) {
  2148. Error("incorrect encoding of enum type");
  2149. return QualType();
  2150. }
  2151. bool IsDependent = Record[0];
  2152. QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
  2153. T->Dependent = IsDependent;
  2154. return T;
  2155. }
  2156. case pch::TYPE_ELABORATED: {
  2157. unsigned Idx = 0;
  2158. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  2159. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
  2160. QualType NamedType = GetType(Record[Idx++]);
  2161. return Context->getElaboratedType(Keyword, NNS, NamedType);
  2162. }
  2163. case pch::TYPE_OBJC_INTERFACE: {
  2164. unsigned Idx = 0;
  2165. ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
  2166. return Context->getObjCInterfaceType(ItfD);
  2167. }
  2168. case pch::TYPE_OBJC_OBJECT: {
  2169. unsigned Idx = 0;
  2170. QualType Base = GetType(Record[Idx++]);
  2171. unsigned NumProtos = Record[Idx++];
  2172. llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
  2173. for (unsigned I = 0; I != NumProtos; ++I)
  2174. Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
  2175. return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
  2176. }
  2177. case pch::TYPE_OBJC_OBJECT_POINTER: {
  2178. unsigned Idx = 0;
  2179. QualType Pointee = GetType(Record[Idx++]);
  2180. return Context->getObjCObjectPointerType(Pointee);
  2181. }
  2182. case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
  2183. unsigned Idx = 0;
  2184. QualType Parm = GetType(Record[Idx++]);
  2185. QualType Replacement = GetType(Record[Idx++]);
  2186. return
  2187. Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
  2188. Replacement);
  2189. }
  2190. case pch::TYPE_INJECTED_CLASS_NAME: {
  2191. CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
  2192. QualType TST = GetType(Record[1]); // probably derivable
  2193. // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
  2194. // for PCH reading, too much interdependencies.
  2195. return
  2196. QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
  2197. }
  2198. case pch::TYPE_TEMPLATE_TYPE_PARM: {
  2199. unsigned Idx = 0;
  2200. unsigned Depth = Record[Idx++];
  2201. unsigned Index = Record[Idx++];
  2202. bool Pack = Record[Idx++];
  2203. IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
  2204. return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
  2205. }
  2206. case pch::TYPE_DEPENDENT_NAME: {
  2207. unsigned Idx = 0;
  2208. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  2209. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
  2210. const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
  2211. QualType Canon = GetType(Record[Idx++]);
  2212. return Context->getDependentNameType(Keyword, NNS, Name, Canon);
  2213. }
  2214. case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
  2215. unsigned Idx = 0;
  2216. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  2217. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
  2218. const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
  2219. unsigned NumArgs = Record[Idx++];
  2220. llvm::SmallVector<TemplateArgument, 8> Args;
  2221. Args.reserve(NumArgs);
  2222. while (NumArgs--)
  2223. Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
  2224. return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
  2225. Args.size(), Args.data());
  2226. }
  2227. case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
  2228. unsigned Idx = 0;
  2229. // ArrayType
  2230. QualType ElementType = GetType(Record[Idx++]);
  2231. ArrayType::ArraySizeModifier ASM
  2232. = (ArrayType::ArraySizeModifier)Record[Idx++];
  2233. unsigned IndexTypeQuals = Record[Idx++];
  2234. // DependentSizedArrayType
  2235. Expr *NumElts = ReadExpr(DeclsCursor);
  2236. SourceRange Brackets = ReadSourceRange(Record, Idx);
  2237. return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
  2238. IndexTypeQuals, Brackets);
  2239. }
  2240. case pch::TYPE_TEMPLATE_SPECIALIZATION: {
  2241. unsigned Idx = 0;
  2242. bool IsDependent = Record[Idx++];
  2243. TemplateName Name = ReadTemplateName(Record, Idx);
  2244. llvm::SmallVector<TemplateArgument, 8> Args;
  2245. ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
  2246. QualType Canon = GetType(Record[Idx++]);
  2247. QualType T;
  2248. if (Canon.isNull())
  2249. T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
  2250. Args.size());
  2251. else
  2252. T = Context->getTemplateSpecializationType(Name, Args.data(),
  2253. Args.size(), Canon);
  2254. T->Dependent = IsDependent;
  2255. return T;
  2256. }
  2257. }
  2258. // Suppress a GCC warning
  2259. return QualType();
  2260. }
  2261. namespace {
  2262. class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
  2263. PCHReader &Reader;
  2264. llvm::BitstreamCursor &DeclsCursor;
  2265. const PCHReader::RecordData &Record;
  2266. unsigned &Idx;
  2267. public:
  2268. TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
  2269. const PCHReader::RecordData &Record, unsigned &Idx)
  2270. : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
  2271. // We want compile-time assurance that we've enumerated all of
  2272. // these, so unfortunately we have to declare them first, then
  2273. // define them out-of-line.
  2274. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  2275. #define TYPELOC(CLASS, PARENT) \
  2276. void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
  2277. #include "clang/AST/TypeLocNodes.def"
  2278. void VisitFunctionTypeLoc(FunctionTypeLoc);
  2279. void VisitArrayTypeLoc(ArrayTypeLoc);
  2280. };
  2281. }
  2282. void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  2283. // nothing to do
  2284. }
  2285. void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  2286. TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2287. if (TL.needsExtraLocalData()) {
  2288. TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
  2289. TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
  2290. TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
  2291. TL.setModeAttr(Record[Idx++]);
  2292. }
  2293. }
  2294. void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
  2295. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2296. }
  2297. void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
  2298. TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2299. }
  2300. void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  2301. TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2302. }
  2303. void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  2304. TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2305. }
  2306. void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  2307. TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2308. }
  2309. void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  2310. TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2311. }
  2312. void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  2313. TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2314. TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2315. if (Record[Idx++])
  2316. TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
  2317. else
  2318. TL.setSizeExpr(0);
  2319. }
  2320. void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
  2321. VisitArrayTypeLoc(TL);
  2322. }
  2323. void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
  2324. VisitArrayTypeLoc(TL);
  2325. }
  2326. void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
  2327. VisitArrayTypeLoc(TL);
  2328. }
  2329. void TypeLocReader::VisitDependentSizedArrayTypeLoc(
  2330. DependentSizedArrayTypeLoc TL) {
  2331. VisitArrayTypeLoc(TL);
  2332. }
  2333. void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
  2334. DependentSizedExtVectorTypeLoc TL) {
  2335. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2336. }
  2337. void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
  2338. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2339. }
  2340. void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
  2341. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2342. }
  2343. void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  2344. TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2345. TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2346. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
  2347. TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
  2348. }
  2349. }
  2350. void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
  2351. VisitFunctionTypeLoc(TL);
  2352. }
  2353. void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
  2354. VisitFunctionTypeLoc(TL);
  2355. }
  2356. void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  2357. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2358. }
  2359. void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  2360. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2361. }
  2362. void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  2363. TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2364. TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2365. TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2366. }
  2367. void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  2368. TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2369. TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2370. TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2371. TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
  2372. }
  2373. void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  2374. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2375. }
  2376. void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
  2377. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2378. }
  2379. void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
  2380. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2381. }
  2382. void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  2383. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2384. }
  2385. void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
  2386. SubstTemplateTypeParmTypeLoc TL) {
  2387. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2388. }
  2389. void TypeLocReader::VisitTemplateSpecializationTypeLoc(
  2390. TemplateSpecializationTypeLoc TL) {
  2391. TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2392. TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2393. TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2394. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  2395. TL.setArgLocInfo(i,
  2396. Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
  2397. DeclsCursor, Record, Idx));
  2398. }
  2399. void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  2400. TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2401. TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
  2402. }
  2403. void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  2404. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2405. }
  2406. void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  2407. TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2408. TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
  2409. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2410. }
  2411. void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
  2412. DependentTemplateSpecializationTypeLoc TL) {
  2413. TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2414. TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
  2415. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2416. TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2417. TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2418. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
  2419. TL.setArgLocInfo(I,
  2420. Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
  2421. DeclsCursor, Record, Idx));
  2422. }
  2423. void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  2424. TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2425. }
  2426. void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  2427. TL.setHasBaseTypeAsWritten(Record[Idx++]);
  2428. TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2429. TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2430. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  2431. TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
  2432. }
  2433. void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  2434. TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
  2435. }
  2436. TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
  2437. const RecordData &Record,
  2438. unsigned &Idx) {
  2439. QualType InfoTy = GetType(Record[Idx++]);
  2440. if (InfoTy.isNull())
  2441. return 0;
  2442. TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
  2443. TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
  2444. for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
  2445. TLR.Visit(TL);
  2446. return TInfo;
  2447. }
  2448. QualType PCHReader::GetType(pch::TypeID ID) {
  2449. unsigned FastQuals = ID & Qualifiers::FastMask;
  2450. unsigned Index = ID >> Qualifiers::FastWidth;
  2451. if (Index < pch::NUM_PREDEF_TYPE_IDS) {
  2452. QualType T;
  2453. switch ((pch::PredefinedTypeIDs)Index) {
  2454. case pch::PREDEF_TYPE_NULL_ID: return QualType();
  2455. case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
  2456. case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
  2457. case pch::PREDEF_TYPE_CHAR_U_ID:
  2458. case pch::PREDEF_TYPE_CHAR_S_ID:
  2459. // FIXME: Check that the signedness of CharTy is correct!
  2460. T = Context->CharTy;
  2461. break;
  2462. case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
  2463. case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
  2464. case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
  2465. case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
  2466. case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
  2467. case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
  2468. case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
  2469. case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
  2470. case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
  2471. case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
  2472. case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
  2473. case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
  2474. case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
  2475. case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
  2476. case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
  2477. case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
  2478. case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
  2479. case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
  2480. case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
  2481. case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
  2482. case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
  2483. case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
  2484. case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
  2485. case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
  2486. }
  2487. assert(!T.isNull() && "Unknown predefined type");
  2488. return T.withFastQualifiers(FastQuals);
  2489. }
  2490. Index -= pch::NUM_PREDEF_TYPE_IDS;
  2491. assert(Index < TypesLoaded.size() && "Type index out-of-range");
  2492. if (TypesLoaded[Index].isNull()) {
  2493. TypesLoaded[Index] = ReadTypeRecord(Index);
  2494. TypesLoaded[Index]->setFromPCH();
  2495. if (DeserializationListener)
  2496. DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
  2497. TypesLoaded[Index]);
  2498. }
  2499. return TypesLoaded[Index].withFastQualifiers(FastQuals);
  2500. }
  2501. TemplateArgumentLocInfo
  2502. PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
  2503. llvm::BitstreamCursor &DeclsCursor,
  2504. const RecordData &Record,
  2505. unsigned &Index) {
  2506. switch (Kind) {
  2507. case TemplateArgument::Expression:
  2508. return ReadExpr(DeclsCursor);
  2509. case TemplateArgument::Type:
  2510. return GetTypeSourceInfo(DeclsCursor, Record, Index);
  2511. case TemplateArgument::Template: {
  2512. SourceRange QualifierRange = ReadSourceRange(Record, Index);
  2513. SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
  2514. return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
  2515. }
  2516. case TemplateArgument::Null:
  2517. case TemplateArgument::Integral:
  2518. case TemplateArgument::Declaration:
  2519. case TemplateArgument::Pack:
  2520. return TemplateArgumentLocInfo();
  2521. }
  2522. llvm_unreachable("unexpected template argument loc");
  2523. return TemplateArgumentLocInfo();
  2524. }
  2525. TemplateArgumentLoc
  2526. PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
  2527. const RecordData &Record, unsigned &Index) {
  2528. TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
  2529. if (Arg.getKind() == TemplateArgument::Expression) {
  2530. if (Record[Index++]) // bool InfoHasSameExpr.
  2531. return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
  2532. }
  2533. return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
  2534. DeclsCursor,
  2535. Record, Index));
  2536. }
  2537. Decl *PCHReader::GetExternalDecl(uint32_t ID) {
  2538. return GetDecl(ID);
  2539. }
  2540. TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
  2541. if (!DeclsLoaded[0]) {
  2542. ReadDeclRecord(0, 0);
  2543. if (DeserializationListener)
  2544. DeserializationListener->DeclRead(1, DeclsLoaded[0]);
  2545. }
  2546. return cast<TranslationUnitDecl>(DeclsLoaded[0]);
  2547. }
  2548. Decl *PCHReader::GetDecl(pch::DeclID ID) {
  2549. if (ID == 0)
  2550. return 0;
  2551. if (ID > DeclsLoaded.size()) {
  2552. Error("declaration ID out-of-range for PCH file");
  2553. return 0;
  2554. }
  2555. unsigned Index = ID - 1;
  2556. if (!DeclsLoaded[Index]) {
  2557. ReadDeclRecord(Index, ID);
  2558. if (DeserializationListener)
  2559. DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
  2560. }
  2561. return DeclsLoaded[Index];
  2562. }
  2563. /// \brief Resolve the offset of a statement into a statement.
  2564. ///
  2565. /// This operation will read a new statement from the external
  2566. /// source each time it is called, and is meant to be used via a
  2567. /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
  2568. Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
  2569. // Offset here is a global offset across the entire chain.
  2570. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  2571. PerFileData &F = *Chain[N - I - 1];
  2572. if (Offset < F.SizeInBits) {
  2573. // Since we know that this statement is part of a decl, make sure to use
  2574. // the decl cursor to read it.
  2575. F.DeclsCursor.JumpToBit(Offset);
  2576. return ReadStmtFromStream(F.DeclsCursor);
  2577. }
  2578. Offset -= F.SizeInBits;
  2579. }
  2580. llvm_unreachable("Broken chain");
  2581. }
  2582. bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
  2583. llvm::SmallVectorImpl<Decl*> &Decls) {
  2584. assert(DC->hasExternalLexicalStorage() &&
  2585. "DeclContext has no lexical decls in storage");
  2586. // There might be lexical decls in multiple parts of the chain, for the TU
  2587. // at least.
  2588. DeclContextInfos &Infos = DeclContextOffsets[DC];
  2589. for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
  2590. I != E; ++I) {
  2591. // IDs can be 0 if this context doesn't contain declarations.
  2592. if (!I->LexicalDecls)
  2593. continue;
  2594. // Load all of the declaration IDs
  2595. for (const pch::DeclID *ID = I->LexicalDecls,
  2596. *IDE = ID + I->NumLexicalDecls;
  2597. ID != IDE; ++ID)
  2598. Decls.push_back(GetDecl(*ID));
  2599. }
  2600. ++NumLexicalDeclContextsRead;
  2601. return false;
  2602. }
  2603. DeclContext::lookup_result
  2604. PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
  2605. DeclarationName Name) {
  2606. assert(DC->hasExternalVisibleStorage() &&
  2607. "DeclContext has no visible decls in storage");
  2608. llvm::SmallVector<VisibleDeclaration, 64> Decls;
  2609. // There might be lexical decls in multiple parts of the chain, for the TU
  2610. // and namespaces.
  2611. DeclContextInfos &Infos = DeclContextOffsets[DC];
  2612. for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
  2613. I != E; ++I) {
  2614. uint64_t Offset = I->OffsetToVisibleDecls;
  2615. if (Offset == 0)
  2616. continue;
  2617. llvm::BitstreamCursor &DeclsCursor = *I->Stream;
  2618. // Keep track of where we are in the stream, then jump back there
  2619. // after reading this context.
  2620. SavedStreamPosition SavedPosition(DeclsCursor);
  2621. // Load the record containing all of the declarations visible in
  2622. // this context.
  2623. DeclsCursor.JumpToBit(Offset);
  2624. RecordData Record;
  2625. unsigned Code = DeclsCursor.ReadCode();
  2626. unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
  2627. if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
  2628. Error("Expected visible block");
  2629. return DeclContext::lookup_result(DeclContext::lookup_iterator(),
  2630. DeclContext::lookup_iterator());
  2631. }
  2632. if (Record.empty())
  2633. continue;
  2634. unsigned Idx = 0;
  2635. while (Idx < Record.size()) {
  2636. Decls.push_back(VisibleDeclaration());
  2637. Decls.back().Name = ReadDeclarationName(Record, Idx);
  2638. unsigned Size = Record[Idx++];
  2639. llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
  2640. LoadedDecls.reserve(Size);
  2641. for (unsigned J = 0; J < Size; ++J)
  2642. LoadedDecls.push_back(Record[Idx++]);
  2643. }
  2644. }
  2645. ++NumVisibleDeclContextsRead;
  2646. SetExternalVisibleDecls(DC, Decls);
  2647. return const_cast<DeclContext*>(DC)->lookup(Name);
  2648. }
  2649. void PCHReader::PassInterestingDeclsToConsumer() {
  2650. assert(Consumer);
  2651. while (!InterestingDecls.empty()) {
  2652. DeclGroupRef DG(InterestingDecls.front());
  2653. InterestingDecls.pop_front();
  2654. Consumer->HandleTopLevelDecl(DG);
  2655. }
  2656. }
  2657. void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
  2658. this->Consumer = Consumer;
  2659. if (!Consumer)
  2660. return;
  2661. for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
  2662. // Force deserialization of this decl, which will cause it to be queued for
  2663. // passing to the consumer.
  2664. GetDecl(ExternalDefinitions[I]);
  2665. }
  2666. PassInterestingDeclsToConsumer();
  2667. }
  2668. void PCHReader::PrintStats() {
  2669. std::fprintf(stderr, "*** PCH Statistics:\n");
  2670. unsigned NumTypesLoaded
  2671. = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
  2672. QualType());
  2673. unsigned NumDeclsLoaded
  2674. = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
  2675. (Decl *)0);
  2676. unsigned NumIdentifiersLoaded
  2677. = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
  2678. IdentifiersLoaded.end(),
  2679. (IdentifierInfo *)0);
  2680. unsigned NumSelectorsLoaded
  2681. = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
  2682. SelectorsLoaded.end(),
  2683. Selector());
  2684. std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
  2685. std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
  2686. if (TotalNumSLocEntries)
  2687. std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
  2688. NumSLocEntriesRead, TotalNumSLocEntries,
  2689. ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
  2690. if (!TypesLoaded.empty())
  2691. std::fprintf(stderr, " %u/%u types read (%f%%)\n",
  2692. NumTypesLoaded, (unsigned)TypesLoaded.size(),
  2693. ((float)NumTypesLoaded/TypesLoaded.size() * 100));
  2694. if (!DeclsLoaded.empty())
  2695. std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
  2696. NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
  2697. ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
  2698. if (!IdentifiersLoaded.empty())
  2699. std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
  2700. NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
  2701. ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
  2702. if (!SelectorsLoaded.empty())
  2703. std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
  2704. NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
  2705. ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
  2706. if (TotalNumStatements)
  2707. std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
  2708. NumStatementsRead, TotalNumStatements,
  2709. ((float)NumStatementsRead/TotalNumStatements * 100));
  2710. if (TotalNumMacros)
  2711. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  2712. NumMacrosRead, TotalNumMacros,
  2713. ((float)NumMacrosRead/TotalNumMacros * 100));
  2714. if (TotalLexicalDeclContexts)
  2715. std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
  2716. NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
  2717. ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
  2718. * 100));
  2719. if (TotalVisibleDeclContexts)
  2720. std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
  2721. NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
  2722. ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
  2723. * 100));
  2724. if (TotalNumMethodPoolEntries) {
  2725. std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
  2726. NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
  2727. ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
  2728. * 100));
  2729. std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
  2730. }
  2731. std::fprintf(stderr, "\n");
  2732. }
  2733. void PCHReader::InitializeSema(Sema &S) {
  2734. SemaObj = &S;
  2735. S.ExternalSource = this;
  2736. // Makes sure any declarations that were deserialized "too early"
  2737. // still get added to the identifier's declaration chains.
  2738. for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
  2739. SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
  2740. SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
  2741. }
  2742. PreloadedDecls.clear();
  2743. // If there were any tentative definitions, deserialize them and add
  2744. // them to Sema's list of tentative definitions.
  2745. for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
  2746. VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
  2747. SemaObj->TentativeDefinitions.push_back(Var);
  2748. }
  2749. // If there were any unused static functions, deserialize them and add to
  2750. // Sema's list of unused static functions.
  2751. for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
  2752. FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
  2753. SemaObj->UnusedStaticFuncs.push_back(FD);
  2754. }
  2755. // If there were any weak undeclared identifiers, deserialize them and add to
  2756. // Sema's list of weak undeclared identifiers.
  2757. if (!WeakUndeclaredIdentifiers.empty()) {
  2758. unsigned Idx = 0;
  2759. for (unsigned I = 0, N = WeakUndeclaredIdentifiers[Idx++]; I != N; ++I) {
  2760. IdentifierInfo *WeakId = GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
  2761. IdentifierInfo *AliasId=GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
  2762. SourceLocation Loc = ReadSourceLocation(WeakUndeclaredIdentifiers, Idx);
  2763. bool Used = WeakUndeclaredIdentifiers[Idx++];
  2764. Sema::WeakInfo WI(AliasId, Loc);
  2765. WI.setUsed(Used);
  2766. SemaObj->WeakUndeclaredIdentifiers.insert(std::make_pair(WeakId, WI));
  2767. }
  2768. }
  2769. // If there were any locally-scoped external declarations,
  2770. // deserialize them and add them to Sema's table of locally-scoped
  2771. // external declarations.
  2772. for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
  2773. NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
  2774. SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
  2775. }
  2776. // If there were any ext_vector type declarations, deserialize them
  2777. // and add them to Sema's vector of such declarations.
  2778. for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
  2779. SemaObj->ExtVectorDecls.push_back(
  2780. cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
  2781. // FIXME: Do VTable uses and dynamic classes deserialize too much ?
  2782. // Can we cut them down before writing them ?
  2783. // If there were any VTable uses, deserialize the information and add it
  2784. // to Sema's vector and map of VTable uses.
  2785. if (!VTableUses.empty()) {
  2786. unsigned Idx = 0;
  2787. for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
  2788. CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
  2789. SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
  2790. bool DefinitionRequired = VTableUses[Idx++];
  2791. SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
  2792. SemaObj->VTablesUsed[Class] = DefinitionRequired;
  2793. }
  2794. }
  2795. // If there were any dynamic classes declarations, deserialize them
  2796. // and add them to Sema's vector of such declarations.
  2797. for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
  2798. SemaObj->DynamicClasses.push_back(
  2799. cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
  2800. // If there were any pending implicit instantiations, deserialize them
  2801. // and add them to Sema's queue of such instantiations.
  2802. assert(PendingImplicitInstantiations.size() % 2 == 0 &&
  2803. "Expected pairs of entries");
  2804. for (unsigned Idx = 0, N = PendingImplicitInstantiations.size(); Idx < N;) {
  2805. ValueDecl *D=cast<ValueDecl>(GetDecl(PendingImplicitInstantiations[Idx++]));
  2806. SourceLocation Loc = ReadSourceLocation(PendingImplicitInstantiations, Idx);
  2807. SemaObj->PendingImplicitInstantiations.push_back(std::make_pair(D, Loc));
  2808. }
  2809. // Load the offsets of the declarations that Sema references.
  2810. // They will be lazily deserialized when needed.
  2811. if (!SemaDeclRefs.empty()) {
  2812. assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
  2813. SemaObj->StdNamespace = SemaDeclRefs[0];
  2814. SemaObj->StdBadAlloc = SemaDeclRefs[1];
  2815. }
  2816. // If there are @selector references added them to its pool. This is for
  2817. // implementation of -Wselector.
  2818. if (!ReferencedSelectorsData.empty()) {
  2819. unsigned int DataSize = ReferencedSelectorsData.size()-1;
  2820. unsigned I = 0;
  2821. while (I < DataSize) {
  2822. Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
  2823. SourceLocation SelLoc =
  2824. SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
  2825. SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
  2826. }
  2827. }
  2828. }
  2829. IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
  2830. // Try to find this name within our on-disk hash tables. We start with the
  2831. // most recent one, since that one contains the most up-to-date info.
  2832. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  2833. PCHIdentifierLookupTable *IdTable
  2834. = (PCHIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
  2835. if (!IdTable)
  2836. continue;
  2837. std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
  2838. PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
  2839. if (Pos == IdTable->end())
  2840. continue;
  2841. // Dereferencing the iterator has the effect of building the
  2842. // IdentifierInfo node and populating it with the various
  2843. // declarations it needs.
  2844. return *Pos;
  2845. }
  2846. return 0;
  2847. }
  2848. std::pair<ObjCMethodList, ObjCMethodList>
  2849. PCHReader::ReadMethodPool(Selector Sel) {
  2850. // Find this selector in a hash table. We want to find the most recent entry.
  2851. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  2852. PerFileData &F = *Chain[I];
  2853. if (!F.SelectorLookupTable)
  2854. continue;
  2855. PCHSelectorLookupTable *PoolTable
  2856. = (PCHSelectorLookupTable*)F.SelectorLookupTable;
  2857. PCHSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
  2858. if (Pos != PoolTable->end()) {
  2859. ++NumSelectorsRead;
  2860. // FIXME: Not quite happy with the statistics here. We probably should
  2861. // disable this tracking when called via LoadSelector.
  2862. // Also, should entries without methods count as misses?
  2863. ++NumMethodPoolEntriesRead;
  2864. PCHSelectorLookupTrait::data_type Data = *Pos;
  2865. if (DeserializationListener)
  2866. DeserializationListener->SelectorRead(Data.ID, Sel);
  2867. return std::make_pair(Data.Instance, Data.Factory);
  2868. }
  2869. }
  2870. ++NumMethodPoolMisses;
  2871. return std::pair<ObjCMethodList, ObjCMethodList>();
  2872. }
  2873. void PCHReader::LoadSelector(Selector Sel) {
  2874. // It would be complicated to avoid reading the methods anyway. So don't.
  2875. ReadMethodPool(Sel);
  2876. }
  2877. void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
  2878. assert(ID && "Non-zero identifier ID required");
  2879. assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
  2880. IdentifiersLoaded[ID - 1] = II;
  2881. if (DeserializationListener)
  2882. DeserializationListener->IdentifierRead(ID, II);
  2883. }
  2884. /// \brief Set the globally-visible declarations associated with the given
  2885. /// identifier.
  2886. ///
  2887. /// If the PCH reader is currently in a state where the given declaration IDs
  2888. /// cannot safely be resolved, they are queued until it is safe to resolve
  2889. /// them.
  2890. ///
  2891. /// \param II an IdentifierInfo that refers to one or more globally-visible
  2892. /// declarations.
  2893. ///
  2894. /// \param DeclIDs the set of declaration IDs with the name @p II that are
  2895. /// visible at global scope.
  2896. ///
  2897. /// \param Nonrecursive should be true to indicate that the caller knows that
  2898. /// this call is non-recursive, and therefore the globally-visible declarations
  2899. /// will not be placed onto the pending queue.
  2900. void
  2901. PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
  2902. const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
  2903. bool Nonrecursive) {
  2904. if (NumCurrentElementsDeserializing && !Nonrecursive) {
  2905. PendingIdentifierInfos.push_back(PendingIdentifierInfo());
  2906. PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
  2907. PII.II = II;
  2908. for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
  2909. PII.DeclIDs.push_back(DeclIDs[I]);
  2910. return;
  2911. }
  2912. for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
  2913. NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
  2914. if (SemaObj) {
  2915. // Introduce this declaration into the translation-unit scope
  2916. // and add it to the declaration chain for this identifier, so
  2917. // that (unqualified) name lookup will find it.
  2918. SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
  2919. SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
  2920. } else {
  2921. // Queue this declaration so that it will be added to the
  2922. // translation unit scope and identifier's declaration chain
  2923. // once a Sema object is known.
  2924. PreloadedDecls.push_back(D);
  2925. }
  2926. }
  2927. }
  2928. IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
  2929. if (ID == 0)
  2930. return 0;
  2931. if (IdentifiersLoaded.empty()) {
  2932. Error("no identifier table in PCH file");
  2933. return 0;
  2934. }
  2935. assert(PP && "Forgot to set Preprocessor ?");
  2936. ID -= 1;
  2937. if (!IdentifiersLoaded[ID]) {
  2938. unsigned Index = ID;
  2939. const char *Str = 0;
  2940. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  2941. PerFileData *F = Chain[N - I - 1];
  2942. if (Index < F->LocalNumIdentifiers) {
  2943. uint32_t Offset = F->IdentifierOffsets[Index];
  2944. Str = F->IdentifierTableData + Offset;
  2945. break;
  2946. }
  2947. Index -= F->LocalNumIdentifiers;
  2948. }
  2949. assert(Str && "Broken Chain");
  2950. // All of the strings in the PCH file are preceded by a 16-bit
  2951. // length. Extract that 16-bit length to avoid having to execute
  2952. // strlen().
  2953. // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
  2954. // unsigned integers. This is important to avoid integer overflow when
  2955. // we cast them to 'unsigned'.
  2956. const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
  2957. unsigned StrLen = (((unsigned) StrLenPtr[0])
  2958. | (((unsigned) StrLenPtr[1]) << 8)) - 1;
  2959. IdentifiersLoaded[ID]
  2960. = &PP->getIdentifierTable().get(Str, StrLen);
  2961. if (DeserializationListener)
  2962. DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
  2963. }
  2964. return IdentifiersLoaded[ID];
  2965. }
  2966. void PCHReader::ReadSLocEntry(unsigned ID) {
  2967. ReadSLocEntryRecord(ID);
  2968. }
  2969. Selector PCHReader::DecodeSelector(unsigned ID) {
  2970. if (ID == 0)
  2971. return Selector();
  2972. if (ID > SelectorsLoaded.size()) {
  2973. Error("selector ID out of range in PCH file");
  2974. return Selector();
  2975. }
  2976. if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
  2977. // Load this selector from the selector table.
  2978. unsigned Idx = ID - 1;
  2979. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  2980. PerFileData &F = *Chain[N - I - 1];
  2981. if (Idx < F.LocalNumSelectors) {
  2982. PCHSelectorLookupTrait Trait(*this);
  2983. SelectorsLoaded[ID - 1] =
  2984. Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
  2985. if (DeserializationListener)
  2986. DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
  2987. break;
  2988. }
  2989. Idx -= F.LocalNumSelectors;
  2990. }
  2991. }
  2992. return SelectorsLoaded[ID - 1];
  2993. }
  2994. Selector PCHReader::GetExternalSelector(uint32_t ID) {
  2995. return DecodeSelector(ID);
  2996. }
  2997. uint32_t PCHReader::GetNumExternalSelectors() {
  2998. // ID 0 (the null selector) is considered an external selector.
  2999. return getTotalNumSelectors() + 1;
  3000. }
  3001. DeclarationName
  3002. PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
  3003. DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
  3004. switch (Kind) {
  3005. case DeclarationName::Identifier:
  3006. return DeclarationName(GetIdentifierInfo(Record, Idx));
  3007. case DeclarationName::ObjCZeroArgSelector:
  3008. case DeclarationName::ObjCOneArgSelector:
  3009. case DeclarationName::ObjCMultiArgSelector:
  3010. return DeclarationName(GetSelector(Record, Idx));
  3011. case DeclarationName::CXXConstructorName:
  3012. return Context->DeclarationNames.getCXXConstructorName(
  3013. Context->getCanonicalType(GetType(Record[Idx++])));
  3014. case DeclarationName::CXXDestructorName:
  3015. return Context->DeclarationNames.getCXXDestructorName(
  3016. Context->getCanonicalType(GetType(Record[Idx++])));
  3017. case DeclarationName::CXXConversionFunctionName:
  3018. return Context->DeclarationNames.getCXXConversionFunctionName(
  3019. Context->getCanonicalType(GetType(Record[Idx++])));
  3020. case DeclarationName::CXXOperatorName:
  3021. return Context->DeclarationNames.getCXXOperatorName(
  3022. (OverloadedOperatorKind)Record[Idx++]);
  3023. case DeclarationName::CXXLiteralOperatorName:
  3024. return Context->DeclarationNames.getCXXLiteralOperatorName(
  3025. GetIdentifierInfo(Record, Idx));
  3026. case DeclarationName::CXXUsingDirective:
  3027. return DeclarationName::getUsingDirectiveName();
  3028. }
  3029. // Required to silence GCC warning
  3030. return DeclarationName();
  3031. }
  3032. TemplateName
  3033. PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
  3034. TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
  3035. switch (Kind) {
  3036. case TemplateName::Template:
  3037. return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
  3038. case TemplateName::OverloadedTemplate: {
  3039. unsigned size = Record[Idx++];
  3040. UnresolvedSet<8> Decls;
  3041. while (size--)
  3042. Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
  3043. return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
  3044. }
  3045. case TemplateName::QualifiedTemplate: {
  3046. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
  3047. bool hasTemplKeyword = Record[Idx++];
  3048. TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
  3049. return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
  3050. }
  3051. case TemplateName::DependentTemplate: {
  3052. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
  3053. if (Record[Idx++]) // isIdentifier
  3054. return Context->getDependentTemplateName(NNS,
  3055. GetIdentifierInfo(Record, Idx));
  3056. return Context->getDependentTemplateName(NNS,
  3057. (OverloadedOperatorKind)Record[Idx++]);
  3058. }
  3059. }
  3060. assert(0 && "Unhandled template name kind!");
  3061. return TemplateName();
  3062. }
  3063. TemplateArgument
  3064. PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
  3065. const RecordData &Record, unsigned &Idx) {
  3066. switch ((TemplateArgument::ArgKind)Record[Idx++]) {
  3067. case TemplateArgument::Null:
  3068. return TemplateArgument();
  3069. case TemplateArgument::Type:
  3070. return TemplateArgument(GetType(Record[Idx++]));
  3071. case TemplateArgument::Declaration:
  3072. return TemplateArgument(GetDecl(Record[Idx++]));
  3073. case TemplateArgument::Integral: {
  3074. llvm::APSInt Value = ReadAPSInt(Record, Idx);
  3075. QualType T = GetType(Record[Idx++]);
  3076. return TemplateArgument(Value, T);
  3077. }
  3078. case TemplateArgument::Template:
  3079. return TemplateArgument(ReadTemplateName(Record, Idx));
  3080. case TemplateArgument::Expression:
  3081. return TemplateArgument(ReadExpr(DeclsCursor));
  3082. case TemplateArgument::Pack: {
  3083. unsigned NumArgs = Record[Idx++];
  3084. llvm::SmallVector<TemplateArgument, 8> Args;
  3085. Args.reserve(NumArgs);
  3086. while (NumArgs--)
  3087. Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
  3088. TemplateArgument TemplArg;
  3089. TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
  3090. return TemplArg;
  3091. }
  3092. }
  3093. assert(0 && "Unhandled template argument kind!");
  3094. return TemplateArgument();
  3095. }
  3096. TemplateParameterList *
  3097. PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
  3098. SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
  3099. SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
  3100. SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
  3101. unsigned NumParams = Record[Idx++];
  3102. llvm::SmallVector<NamedDecl *, 16> Params;
  3103. Params.reserve(NumParams);
  3104. while (NumParams--)
  3105. Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
  3106. TemplateParameterList* TemplateParams =
  3107. TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
  3108. Params.data(), Params.size(), RAngleLoc);
  3109. return TemplateParams;
  3110. }
  3111. void
  3112. PCHReader::
  3113. ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
  3114. llvm::BitstreamCursor &DeclsCursor,
  3115. const RecordData &Record, unsigned &Idx) {
  3116. unsigned NumTemplateArgs = Record[Idx++];
  3117. TemplArgs.reserve(NumTemplateArgs);
  3118. while (NumTemplateArgs--)
  3119. TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
  3120. }
  3121. /// \brief Read a UnresolvedSet structure.
  3122. void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
  3123. const RecordData &Record, unsigned &Idx) {
  3124. unsigned NumDecls = Record[Idx++];
  3125. while (NumDecls--) {
  3126. NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
  3127. AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
  3128. Set.addDecl(D, AS);
  3129. }
  3130. }
  3131. CXXBaseSpecifier
  3132. PCHReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
  3133. const RecordData &Record, unsigned &Idx) {
  3134. bool isVirtual = static_cast<bool>(Record[Idx++]);
  3135. bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
  3136. AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
  3137. TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
  3138. SourceRange Range = ReadSourceRange(Record, Idx);
  3139. return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
  3140. }
  3141. std::pair<CXXBaseOrMemberInitializer **, unsigned>
  3142. PCHReader::ReadCXXBaseOrMemberInitializers(llvm::BitstreamCursor &Cursor,
  3143. const RecordData &Record,
  3144. unsigned &Idx) {
  3145. CXXBaseOrMemberInitializer **BaseOrMemberInitializers = 0;
  3146. unsigned NumInitializers = Record[Idx++];
  3147. if (NumInitializers) {
  3148. ASTContext &C = *getContext();
  3149. BaseOrMemberInitializers
  3150. = new (C) CXXBaseOrMemberInitializer*[NumInitializers];
  3151. for (unsigned i=0; i != NumInitializers; ++i) {
  3152. TypeSourceInfo *BaseClassInfo = 0;
  3153. bool IsBaseVirtual = false;
  3154. FieldDecl *Member = 0;
  3155. bool IsBaseInitializer = Record[Idx++];
  3156. if (IsBaseInitializer) {
  3157. BaseClassInfo = GetTypeSourceInfo(Cursor, Record, Idx);
  3158. IsBaseVirtual = Record[Idx++];
  3159. } else {
  3160. Member = cast<FieldDecl>(GetDecl(Record[Idx++]));
  3161. }
  3162. SourceLocation MemberLoc = ReadSourceLocation(Record, Idx);
  3163. Expr *Init = ReadExpr(Cursor);
  3164. FieldDecl *AnonUnionMember
  3165. = cast_or_null<FieldDecl>(GetDecl(Record[Idx++]));
  3166. SourceLocation LParenLoc = ReadSourceLocation(Record, Idx);
  3167. SourceLocation RParenLoc = ReadSourceLocation(Record, Idx);
  3168. bool IsWritten = Record[Idx++];
  3169. unsigned SourceOrderOrNumArrayIndices;
  3170. llvm::SmallVector<VarDecl *, 8> Indices;
  3171. if (IsWritten) {
  3172. SourceOrderOrNumArrayIndices = Record[Idx++];
  3173. } else {
  3174. SourceOrderOrNumArrayIndices = Record[Idx++];
  3175. Indices.reserve(SourceOrderOrNumArrayIndices);
  3176. for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
  3177. Indices.push_back(cast<VarDecl>(GetDecl(Record[Idx++])));
  3178. }
  3179. CXXBaseOrMemberInitializer *BOMInit;
  3180. if (IsBaseInitializer) {
  3181. BOMInit = new (C) CXXBaseOrMemberInitializer(C, BaseClassInfo,
  3182. IsBaseVirtual, LParenLoc,
  3183. Init, RParenLoc);
  3184. } else if (IsWritten) {
  3185. BOMInit = new (C) CXXBaseOrMemberInitializer(C, Member, MemberLoc,
  3186. LParenLoc, Init, RParenLoc);
  3187. } else {
  3188. BOMInit = CXXBaseOrMemberInitializer::Create(C, Member, MemberLoc,
  3189. LParenLoc, Init, RParenLoc,
  3190. Indices.data(),
  3191. Indices.size());
  3192. }
  3193. BOMInit->setAnonUnionMember(AnonUnionMember);
  3194. BaseOrMemberInitializers[i] = BOMInit;
  3195. }
  3196. }
  3197. return std::make_pair(BaseOrMemberInitializers, NumInitializers);
  3198. }
  3199. NestedNameSpecifier *
  3200. PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
  3201. unsigned N = Record[Idx++];
  3202. NestedNameSpecifier *NNS = 0, *Prev = 0;
  3203. for (unsigned I = 0; I != N; ++I) {
  3204. NestedNameSpecifier::SpecifierKind Kind
  3205. = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
  3206. switch (Kind) {
  3207. case NestedNameSpecifier::Identifier: {
  3208. IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
  3209. NNS = NestedNameSpecifier::Create(*Context, Prev, II);
  3210. break;
  3211. }
  3212. case NestedNameSpecifier::Namespace: {
  3213. NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
  3214. NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
  3215. break;
  3216. }
  3217. case NestedNameSpecifier::TypeSpec:
  3218. case NestedNameSpecifier::TypeSpecWithTemplate: {
  3219. Type *T = GetType(Record[Idx++]).getTypePtr();
  3220. bool Template = Record[Idx++];
  3221. NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
  3222. break;
  3223. }
  3224. case NestedNameSpecifier::Global: {
  3225. NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
  3226. // No associated value, and there can't be a prefix.
  3227. break;
  3228. }
  3229. }
  3230. Prev = NNS;
  3231. }
  3232. return NNS;
  3233. }
  3234. SourceRange
  3235. PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
  3236. SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
  3237. SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
  3238. return SourceRange(beg, end);
  3239. }
  3240. /// \brief Read an integral value
  3241. llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
  3242. unsigned BitWidth = Record[Idx++];
  3243. unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
  3244. llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
  3245. Idx += NumWords;
  3246. return Result;
  3247. }
  3248. /// \brief Read a signed integral value
  3249. llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
  3250. bool isUnsigned = Record[Idx++];
  3251. return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
  3252. }
  3253. /// \brief Read a floating-point value
  3254. llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
  3255. return llvm::APFloat(ReadAPInt(Record, Idx));
  3256. }
  3257. // \brief Read a string
  3258. std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
  3259. unsigned Len = Record[Idx++];
  3260. std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
  3261. Idx += Len;
  3262. return Result;
  3263. }
  3264. CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
  3265. unsigned &Idx) {
  3266. CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
  3267. return CXXTemporary::Create(*Context, Decl);
  3268. }
  3269. DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
  3270. return Diag(SourceLocation(), DiagID);
  3271. }
  3272. DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
  3273. return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
  3274. }
  3275. /// \brief Retrieve the identifier table associated with the
  3276. /// preprocessor.
  3277. IdentifierTable &PCHReader::getIdentifierTable() {
  3278. assert(PP && "Forgot to set Preprocessor ?");
  3279. return PP->getIdentifierTable();
  3280. }
  3281. /// \brief Record that the given ID maps to the given switch-case
  3282. /// statement.
  3283. void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
  3284. assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
  3285. SwitchCaseStmts[ID] = SC;
  3286. }
  3287. /// \brief Retrieve the switch-case statement with the given ID.
  3288. SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
  3289. assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
  3290. return SwitchCaseStmts[ID];
  3291. }
  3292. /// \brief Record that the given label statement has been
  3293. /// deserialized and has the given ID.
  3294. void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
  3295. assert(LabelStmts.find(ID) == LabelStmts.end() &&
  3296. "Deserialized label twice");
  3297. LabelStmts[ID] = S;
  3298. // If we've already seen any goto statements that point to this
  3299. // label, resolve them now.
  3300. typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
  3301. std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
  3302. for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
  3303. Goto->second->setLabel(S);
  3304. UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
  3305. // If we've already seen any address-label statements that point to
  3306. // this label, resolve them now.
  3307. typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
  3308. std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
  3309. = UnresolvedAddrLabelExprs.equal_range(ID);
  3310. for (AddrLabelIter AddrLabel = AddrLabels.first;
  3311. AddrLabel != AddrLabels.second; ++AddrLabel)
  3312. AddrLabel->second->setLabel(S);
  3313. UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
  3314. }
  3315. /// \brief Set the label of the given statement to the label
  3316. /// identified by ID.
  3317. ///
  3318. /// Depending on the order in which the label and other statements
  3319. /// referencing that label occur, this operation may complete
  3320. /// immediately (updating the statement) or it may queue the
  3321. /// statement to be back-patched later.
  3322. void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
  3323. std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
  3324. if (Label != LabelStmts.end()) {
  3325. // We've already seen this label, so set the label of the goto and
  3326. // we're done.
  3327. S->setLabel(Label->second);
  3328. } else {
  3329. // We haven't seen this label yet, so add this goto to the set of
  3330. // unresolved goto statements.
  3331. UnresolvedGotoStmts.insert(std::make_pair(ID, S));
  3332. }
  3333. }
  3334. /// \brief Set the label of the given expression to the label
  3335. /// identified by ID.
  3336. ///
  3337. /// Depending on the order in which the label and other statements
  3338. /// referencing that label occur, this operation may complete
  3339. /// immediately (updating the statement) or it may queue the
  3340. /// statement to be back-patched later.
  3341. void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
  3342. std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
  3343. if (Label != LabelStmts.end()) {
  3344. // We've already seen this label, so set the label of the
  3345. // label-address expression and we're done.
  3346. S->setLabel(Label->second);
  3347. } else {
  3348. // We haven't seen this label yet, so add this label-address
  3349. // expression to the set of unresolved label-address expressions.
  3350. UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
  3351. }
  3352. }
  3353. void PCHReader::FinishedDeserializing() {
  3354. assert(NumCurrentElementsDeserializing &&
  3355. "FinishedDeserializing not paired with StartedDeserializing");
  3356. if (NumCurrentElementsDeserializing == 1) {
  3357. // If any identifiers with corresponding top-level declarations have
  3358. // been loaded, load those declarations now.
  3359. while (!PendingIdentifierInfos.empty()) {
  3360. SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
  3361. PendingIdentifierInfos.front().DeclIDs, true);
  3362. PendingIdentifierInfos.pop_front();
  3363. }
  3364. // We are not in recursive loading, so it's safe to pass the "interesting"
  3365. // decls to the consumer.
  3366. if (Consumer)
  3367. PassInterestingDeclsToConsumer();
  3368. }
  3369. --NumCurrentElementsDeserializing;
  3370. }