PCHReader.cpp 120 KB

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