xref: /llvm-project/clang/lib/Basic/SourceManager.cpp (revision 1eaa70a612aa748c214858bef25e3fb79dbcb5c8)
1 //===--- SourceManager.cpp - Track and cache source files -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the SourceManager interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/SourceManager.h"
15 #include "clang/Basic/FileManager.h"
16 #include "llvm/Support/Compiler.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/System/Path.h"
19 #include "llvm/Bitcode/Serialize.h"
20 #include "llvm/Bitcode/Deserialize.h"
21 #include "llvm/Support/Streams.h"
22 #include <algorithm>
23 using namespace clang;
24 using namespace SrcMgr;
25 using llvm::MemoryBuffer;
26 
27 //===--------------------------------------------------------------------===//
28 // SourceManager Helper Classes
29 //===--------------------------------------------------------------------===//
30 
31 ContentCache::~ContentCache() {
32   delete Buffer;
33 }
34 
35 /// getSizeBytesMapped - Returns the number of bytes actually mapped for
36 ///  this ContentCache.  This can be 0 if the MemBuffer was not actually
37 ///  instantiated.
38 unsigned ContentCache::getSizeBytesMapped() const {
39   return Buffer ? Buffer->getBufferSize() : 0;
40 }
41 
42 /// getSize - Returns the size of the content encapsulated by this ContentCache.
43 ///  This can be the size of the source file or the size of an arbitrary
44 ///  scratch buffer.  If the ContentCache encapsulates a source file, that
45 ///  file is not lazily brought in from disk to satisfy this query.
46 unsigned ContentCache::getSize() const {
47   return Entry ? Entry->getSize() : Buffer->getBufferSize();
48 }
49 
50 const llvm::MemoryBuffer *ContentCache::getBuffer() const {
51   // Lazily create the Buffer for ContentCaches that wrap files.
52   if (!Buffer && Entry) {
53     // FIXME: Should we support a way to not have to do this check over
54     //   and over if we cannot open the file?
55     Buffer = MemoryBuffer::getFile(Entry->getName(), 0, Entry->getSize());
56   }
57   return Buffer;
58 }
59 
60 //===--------------------------------------------------------------------===//
61 // Line Table Implementation
62 //===--------------------------------------------------------------------===//
63 
64 namespace clang {
65 /// LineTableInfo - This class is used to hold and unique data used to
66 /// represent #line information.
67 class LineTableInfo {
68   /// FilenameIDs - This map is used to assign unique IDs to filenames in
69   /// #line directives.  This allows us to unique the filenames that
70   /// frequently reoccur and reference them with indices.  FilenameIDs holds
71   /// the mapping from string -> ID, and FilenamesByID holds the mapping of ID
72   /// to string.
73   llvm::StringMap<unsigned, llvm::BumpPtrAllocator> FilenameIDs;
74   std::vector<llvm::StringMapEntry<unsigned>*> FilenamesByID;
75 public:
76   LineTableInfo() {
77   }
78 
79   void clear() {
80     FilenameIDs.clear();
81     FilenamesByID.clear();
82   }
83 
84   ~LineTableInfo() {}
85 
86   unsigned getLineTableFilenameID(const char *Ptr, unsigned Len);
87 
88 };
89 } // namespace clang
90 
91 
92 
93 
94 unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
95   // Look up the filename in the string table, returning the pre-existing value
96   // if it exists.
97   llvm::StringMapEntry<unsigned> &Entry =
98     FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
99   if (Entry.getValue() != ~0U)
100     return Entry.getValue();
101 
102   // Otherwise, assign this the next available ID.
103   Entry.setValue(FilenamesByID.size());
104   FilenamesByID.push_back(&Entry);
105   return FilenamesByID.size()-1;
106 }
107 
108 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
109 ///
110 unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
111   if (LineTable == 0)
112     LineTable = new LineTableInfo();
113   return LineTable->getLineTableFilenameID(Ptr, Len);
114 }
115 
116 
117 /// AddLineNote - Add a line note to the line table for the FileID and offset
118 /// specified by Loc.  If FilenameID is -1, it is considered to be
119 /// unspecified.
120 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
121                                 int FilenameID) {
122 
123 }
124 
125 
126 //===--------------------------------------------------------------------===//
127 // Private 'Create' methods.
128 //===--------------------------------------------------------------------===//
129 
130 SourceManager::~SourceManager() {
131   delete LineTable;
132 
133   // Delete FileEntry objects corresponding to content caches.  Since the actual
134   // content cache objects are bump pointer allocated, we just have to run the
135   // dtors, but we call the deallocate method for completeness.
136   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
137     MemBufferInfos[i]->~ContentCache();
138     ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
139   }
140   for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
141        I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
142     I->second->~ContentCache();
143     ContentCacheAlloc.Deallocate(I->second);
144   }
145 }
146 
147 void SourceManager::clearIDTables() {
148   MainFileID = FileID();
149   SLocEntryTable.clear();
150   LastLineNoFileIDQuery = FileID();
151   LastLineNoContentCache = 0;
152   LastFileIDLookup = FileID();
153 
154   if (LineTable)
155     LineTable->clear();
156 
157   // Use up FileID #0 as an invalid instantiation.
158   NextOffset = 0;
159   createInstantiationLoc(SourceLocation(), SourceLocation(), 1);
160 }
161 
162 /// getOrCreateContentCache - Create or return a cached ContentCache for the
163 /// specified file.
164 const ContentCache *
165 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
166   assert(FileEnt && "Didn't specify a file entry to use?");
167 
168   // Do we already have information about this file?
169   ContentCache *&Entry = FileInfos[FileEnt];
170   if (Entry) return Entry;
171 
172   // Nope, create a new Cache entry.  Make sure it is at least 8-byte aligned
173   // so that FileInfo can use the low 3 bits of the pointer for its own
174   // nefarious purposes.
175   unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
176   EntryAlign = std::max(8U, EntryAlign);
177   Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
178   new (Entry) ContentCache(FileEnt);
179   return Entry;
180 }
181 
182 
183 /// createMemBufferContentCache - Create a new ContentCache for the specified
184 ///  memory buffer.  This does no caching.
185 const ContentCache*
186 SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
187   // Add a new ContentCache to the MemBufferInfos list and return it.  Make sure
188   // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
189   // the pointer for its own nefarious purposes.
190   unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
191   EntryAlign = std::max(8U, EntryAlign);
192   ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
193   new (Entry) ContentCache();
194   MemBufferInfos.push_back(Entry);
195   Entry->setBuffer(Buffer);
196   return Entry;
197 }
198 
199 //===----------------------------------------------------------------------===//
200 // Methods to create new FileID's and instantiations.
201 //===----------------------------------------------------------------------===//
202 
203 /// createFileID - Create a new fileID for the specified ContentCache and
204 /// include position.  This works regardless of whether the ContentCache
205 /// corresponds to a file or some other input source.
206 FileID SourceManager::createFileID(const ContentCache *File,
207                                    SourceLocation IncludePos,
208                                    SrcMgr::CharacteristicKind FileCharacter) {
209   SLocEntryTable.push_back(SLocEntry::get(NextOffset,
210                                           FileInfo::get(IncludePos, File,
211                                                         FileCharacter)));
212   unsigned FileSize = File->getSize();
213   assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
214   NextOffset += FileSize+1;
215 
216   // Set LastFileIDLookup to the newly created file.  The next getFileID call is
217   // almost guaranteed to be from that file.
218   return LastFileIDLookup = FileID::get(SLocEntryTable.size()-1);
219 }
220 
221 /// createInstantiationLoc - Return a new SourceLocation that encodes the fact
222 /// that a token from SpellingLoc should actually be referenced from
223 /// InstantiationLoc.
224 SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
225                                                      SourceLocation InstantLoc,
226                                                      unsigned TokLength) {
227   SLocEntryTable.push_back(SLocEntry::get(NextOffset,
228                                           InstantiationInfo::get(InstantLoc,
229                                                                  SpellingLoc)));
230   assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
231   NextOffset += TokLength+1;
232   return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
233 }
234 
235 /// getBufferData - Return a pointer to the start and end of the source buffer
236 /// data for the specified FileID.
237 std::pair<const char*, const char*>
238 SourceManager::getBufferData(FileID FID) const {
239   const llvm::MemoryBuffer *Buf = getBuffer(FID);
240   return std::make_pair(Buf->getBufferStart(), Buf->getBufferEnd());
241 }
242 
243 
244 //===--------------------------------------------------------------------===//
245 // SourceLocation manipulation methods.
246 //===--------------------------------------------------------------------===//
247 
248 /// getFileIDSlow - Return the FileID for a SourceLocation.  This is a very hot
249 /// method that is used for all SourceManager queries that start with a
250 /// SourceLocation object.  It is responsible for finding the entry in
251 /// SLocEntryTable which contains the specified location.
252 ///
253 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
254   assert(SLocOffset && "Invalid FileID");
255 
256   // After the first and second level caches, I see two common sorts of
257   // behavior: 1) a lot of searched FileID's are "near" the cached file location
258   // or are "near" the cached instantiation location.  2) others are just
259   // completely random and may be a very long way away.
260   //
261   // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
262   // then we fall back to a less cache efficient, but more scalable, binary
263   // search to find the location.
264 
265   // See if this is near the file point - worst case we start scanning from the
266   // most newly created FileID.
267   std::vector<SrcMgr::SLocEntry>::const_iterator I;
268 
269   if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
270     // Neither loc prunes our search.
271     I = SLocEntryTable.end();
272   } else {
273     // Perhaps it is near the file point.
274     I = SLocEntryTable.begin()+LastFileIDLookup.ID;
275   }
276 
277   // Find the FileID that contains this.  "I" is an iterator that points to a
278   // FileID whose offset is known to be larger than SLocOffset.
279   unsigned NumProbes = 0;
280   while (1) {
281     --I;
282     if (I->getOffset() <= SLocOffset) {
283 #if 0
284       printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
285              I-SLocEntryTable.begin(),
286              I->isInstantiation() ? "inst" : "file",
287              LastFileIDLookup.ID,  int(SLocEntryTable.end()-I));
288 #endif
289       FileID Res = FileID::get(I-SLocEntryTable.begin());
290 
291       // If this isn't an instantiation, remember it.  We have good locality
292       // across FileID lookups.
293       if (!I->isInstantiation())
294         LastFileIDLookup = Res;
295       NumLinearScans += NumProbes+1;
296       return Res;
297     }
298     if (++NumProbes == 8)
299       break;
300   }
301 
302   // Convert "I" back into an index.  We know that it is an entry whose index is
303   // larger than the offset we are looking for.
304   unsigned GreaterIndex = I-SLocEntryTable.begin();
305   // LessIndex - This is the lower bound of the range that we're searching.
306   // We know that the offset corresponding to the FileID is is less than
307   // SLocOffset.
308   unsigned LessIndex = 0;
309   NumProbes = 0;
310   while (1) {
311     unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
312     unsigned MidOffset = SLocEntryTable[MiddleIndex].getOffset();
313 
314     ++NumProbes;
315 
316     // If the offset of the midpoint is too large, chop the high side of the
317     // range to the midpoint.
318     if (MidOffset > SLocOffset) {
319       GreaterIndex = MiddleIndex;
320       continue;
321     }
322 
323     // If the middle index contains the value, succeed and return.
324     if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
325 #if 0
326       printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
327              I-SLocEntryTable.begin(),
328              I->isInstantiation() ? "inst" : "file",
329              LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
330 #endif
331       FileID Res = FileID::get(MiddleIndex);
332 
333       // If this isn't an instantiation, remember it.  We have good locality
334       // across FileID lookups.
335       if (!I->isInstantiation())
336         LastFileIDLookup = Res;
337       NumBinaryProbes += NumProbes;
338       return Res;
339     }
340 
341     // Otherwise, move the low-side up to the middle index.
342     LessIndex = MiddleIndex;
343   }
344 }
345 
346 SourceLocation SourceManager::
347 getInstantiationLocSlowCase(SourceLocation Loc) const {
348   do {
349     std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
350     Loc =getSLocEntry(LocInfo.first).getInstantiation().getInstantiationLoc();
351     Loc = Loc.getFileLocWithOffset(LocInfo.second);
352   } while (!Loc.isFileID());
353 
354   return Loc;
355 }
356 
357 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
358   do {
359     std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
360     Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
361     Loc = Loc.getFileLocWithOffset(LocInfo.second);
362   } while (!Loc.isFileID());
363   return Loc;
364 }
365 
366 
367 std::pair<FileID, unsigned>
368 SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
369                                                      unsigned Offset) const {
370   // If this is an instantiation record, walk through all the instantiation
371   // points.
372   FileID FID;
373   SourceLocation Loc;
374   do {
375     Loc = E->getInstantiation().getInstantiationLoc();
376 
377     FID = getFileID(Loc);
378     E = &getSLocEntry(FID);
379     Offset += Loc.getOffset()-E->getOffset();
380   } while (!Loc.isFileID());
381 
382   return std::make_pair(FID, Offset);
383 }
384 
385 std::pair<FileID, unsigned>
386 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
387                                                 unsigned Offset) const {
388   // If this is an instantiation record, walk through all the instantiation
389   // points.
390   FileID FID;
391   SourceLocation Loc;
392   do {
393     Loc = E->getInstantiation().getSpellingLoc();
394 
395     FID = getFileID(Loc);
396     E = &getSLocEntry(FID);
397     Offset += Loc.getOffset()-E->getOffset();
398   } while (!Loc.isFileID());
399 
400   return std::make_pair(FID, Offset);
401 }
402 
403 
404 //===----------------------------------------------------------------------===//
405 // Queries about the code at a SourceLocation.
406 //===----------------------------------------------------------------------===//
407 
408 /// getCharacterData - Return a pointer to the start of the specified location
409 /// in the appropriate MemoryBuffer.
410 const char *SourceManager::getCharacterData(SourceLocation SL) const {
411   // Note that this is a hot function in the getSpelling() path, which is
412   // heavily used by -E mode.
413   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
414 
415   // Note that calling 'getBuffer()' may lazily page in a source file.
416   return getSLocEntry(LocInfo.first).getFile().getContentCache()
417               ->getBuffer()->getBufferStart() + LocInfo.second;
418 }
419 
420 
421 /// getColumnNumber - Return the column # for the specified file position.
422 /// this is significantly cheaper to compute than the line number.  This returns
423 /// zero if the column number isn't known.
424 unsigned SourceManager::getColumnNumber(SourceLocation Loc) const {
425   if (Loc.isInvalid()) return 0;
426   assert(Loc.isFileID() && "Don't know what part of instantiation loc to get");
427 
428   std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
429   unsigned FilePos = LocInfo.second;
430 
431   const char *Buf = getBuffer(LocInfo.first)->getBufferStart();
432 
433   unsigned LineStart = FilePos;
434   while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
435     --LineStart;
436   return FilePos-LineStart+1;
437 }
438 
439 static void ComputeLineNumbers(ContentCache* FI,
440                                llvm::BumpPtrAllocator &Alloc) DISABLE_INLINE;
441 static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){
442   // Note that calling 'getBuffer()' may lazily page in the file.
443   const MemoryBuffer *Buffer = FI->getBuffer();
444 
445   // Find the file offsets of all of the *physical* source lines.  This does
446   // not look at trigraphs, escaped newlines, or anything else tricky.
447   std::vector<unsigned> LineOffsets;
448 
449   // Line #1 starts at char 0.
450   LineOffsets.push_back(0);
451 
452   const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
453   const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
454   unsigned Offs = 0;
455   while (1) {
456     // Skip over the contents of the line.
457     // TODO: Vectorize this?  This is very performance sensitive for programs
458     // with lots of diagnostics and in -E mode.
459     const unsigned char *NextBuf = (const unsigned char *)Buf;
460     while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
461       ++NextBuf;
462     Offs += NextBuf-Buf;
463     Buf = NextBuf;
464 
465     if (Buf[0] == '\n' || Buf[0] == '\r') {
466       // If this is \n\r or \r\n, skip both characters.
467       if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
468         ++Offs, ++Buf;
469       ++Offs, ++Buf;
470       LineOffsets.push_back(Offs);
471     } else {
472       // Otherwise, this is a null.  If end of file, exit.
473       if (Buf == End) break;
474       // Otherwise, skip the null.
475       ++Offs, ++Buf;
476     }
477   }
478 
479   // Copy the offsets into the FileInfo structure.
480   FI->NumLines = LineOffsets.size();
481   FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
482   std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
483 }
484 
485 /// getLineNumber - Given a SourceLocation, return the spelling line number
486 /// for the position indicated.  This requires building and caching a table of
487 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
488 /// about to emit a diagnostic.
489 unsigned SourceManager::getLineNumber(SourceLocation Loc) const {
490   if (Loc.isInvalid()) return 0;
491   assert(Loc.isFileID() && "Don't know what part of instantiation loc to get");
492 
493   std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
494 
495   ContentCache *Content;
496   if (LastLineNoFileIDQuery == LocInfo.first)
497     Content = LastLineNoContentCache;
498   else
499     Content = const_cast<ContentCache*>(getSLocEntry(LocInfo.first)
500                                         .getFile().getContentCache());
501 
502   // If this is the first use of line information for this buffer, compute the
503   /// SourceLineCache for it on demand.
504   if (Content->SourceLineCache == 0)
505     ComputeLineNumbers(Content, ContentCacheAlloc);
506 
507   // Okay, we know we have a line number table.  Do a binary search to find the
508   // line number that this character position lands on.
509   unsigned *SourceLineCache = Content->SourceLineCache;
510   unsigned *SourceLineCacheStart = SourceLineCache;
511   unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
512 
513   unsigned QueriedFilePos = LocInfo.second+1;
514 
515   // If the previous query was to the same file, we know both the file pos from
516   // that query and the line number returned.  This allows us to narrow the
517   // search space from the entire file to something near the match.
518   if (LastLineNoFileIDQuery == LocInfo.first) {
519     if (QueriedFilePos >= LastLineNoFilePos) {
520       SourceLineCache = SourceLineCache+LastLineNoResult-1;
521 
522       // The query is likely to be nearby the previous one.  Here we check to
523       // see if it is within 5, 10 or 20 lines.  It can be far away in cases
524       // where big comment blocks and vertical whitespace eat up lines but
525       // contribute no tokens.
526       if (SourceLineCache+5 < SourceLineCacheEnd) {
527         if (SourceLineCache[5] > QueriedFilePos)
528           SourceLineCacheEnd = SourceLineCache+5;
529         else if (SourceLineCache+10 < SourceLineCacheEnd) {
530           if (SourceLineCache[10] > QueriedFilePos)
531             SourceLineCacheEnd = SourceLineCache+10;
532           else if (SourceLineCache+20 < SourceLineCacheEnd) {
533             if (SourceLineCache[20] > QueriedFilePos)
534               SourceLineCacheEnd = SourceLineCache+20;
535           }
536         }
537       }
538     } else {
539       SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
540     }
541   }
542 
543   // If the spread is large, do a "radix" test as our initial guess, based on
544   // the assumption that lines average to approximately the same length.
545   // NOTE: This is currently disabled, as it does not appear to be profitable in
546   // initial measurements.
547   if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
548     unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
549 
550     // Take a stab at guessing where it is.
551     unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
552 
553     // Check for -10 and +10 lines.
554     unsigned LowerBound = std::max(int(ApproxPos-10), 0);
555     unsigned UpperBound = std::min(ApproxPos+10, FileLen);
556 
557     // If the computed lower bound is less than the query location, move it in.
558     if (SourceLineCache < SourceLineCacheStart+LowerBound &&
559         SourceLineCacheStart[LowerBound] < QueriedFilePos)
560       SourceLineCache = SourceLineCacheStart+LowerBound;
561 
562     // If the computed upper bound is greater than the query location, move it.
563     if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
564         SourceLineCacheStart[UpperBound] >= QueriedFilePos)
565       SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
566   }
567 
568   unsigned *Pos
569     = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
570   unsigned LineNo = Pos-SourceLineCacheStart;
571 
572   LastLineNoFileIDQuery = LocInfo.first;
573   LastLineNoContentCache = Content;
574   LastLineNoFilePos = QueriedFilePos;
575   LastLineNoResult = LineNo;
576   return LineNo;
577 }
578 
579 /// getPresumedLoc - This method returns the "presumed" location of a
580 /// SourceLocation specifies.  A "presumed location" can be modified by #line
581 /// or GNU line marker directives.  This provides a view on the data that a
582 /// user should see in diagnostics, for example.
583 ///
584 /// Note that a presumed location is always given as the instantiation point
585 /// of an instantiation location, not at the spelling location.
586 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
587   if (Loc.isInvalid()) return PresumedLoc();
588 
589   // Presumed locations are always for instantiation points.
590   Loc = getInstantiationLoc(Loc);
591 
592   // FIXME: Could just decompose Loc once!
593 
594   const SrcMgr::FileInfo &FI = getSLocEntry(getFileID(Loc)).getFile();
595   const SrcMgr::ContentCache *C = FI.getContentCache();
596 
597   // To get the source name, first consult the FileEntry (if one exists) before
598   // the MemBuffer as this will avoid unnecessarily paging in the MemBuffer.
599   const char *Filename =
600     C->Entry ? C->Entry->getName() : C->getBuffer()->getBufferIdentifier();
601 
602   return PresumedLoc(Filename, getLineNumber(Loc), getColumnNumber(Loc),
603                      FI.getIncludeLoc());
604 }
605 
606 //===----------------------------------------------------------------------===//
607 // Other miscellaneous methods.
608 //===----------------------------------------------------------------------===//
609 
610 
611 /// PrintStats - Print statistics to stderr.
612 ///
613 void SourceManager::PrintStats() const {
614   llvm::cerr << "\n*** Source Manager Stats:\n";
615   llvm::cerr << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
616              << " mem buffers mapped.\n";
617   llvm::cerr << SLocEntryTable.size() << " SLocEntry's allocated, "
618              << NextOffset << "B of Sloc address space used.\n";
619 
620   unsigned NumLineNumsComputed = 0;
621   unsigned NumFileBytesMapped = 0;
622   for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
623     NumLineNumsComputed += I->second->SourceLineCache != 0;
624     NumFileBytesMapped  += I->second->getSizeBytesMapped();
625   }
626 
627   llvm::cerr << NumFileBytesMapped << " bytes of files mapped, "
628              << NumLineNumsComputed << " files with line #'s computed.\n";
629   llvm::cerr << "FileID scans: " << NumLinearScans << " linear, "
630              << NumBinaryProbes << " binary.\n";
631 }
632 
633 //===----------------------------------------------------------------------===//
634 // Serialization.
635 //===----------------------------------------------------------------------===//
636 
637 void ContentCache::Emit(llvm::Serializer& S) const {
638   S.FlushRecord();
639   S.EmitPtr(this);
640 
641   if (Entry) {
642     llvm::sys::Path Fname(Buffer->getBufferIdentifier());
643 
644     if (Fname.isAbsolute())
645       S.EmitCStr(Fname.c_str());
646     else {
647       // Create an absolute path.
648       // FIXME: This will potentially contain ".." and "." in the path.
649       llvm::sys::Path path = llvm::sys::Path::GetCurrentDirectory();
650       path.appendComponent(Fname.c_str());
651       S.EmitCStr(path.c_str());
652     }
653   }
654   else {
655     const char* p = Buffer->getBufferStart();
656     const char* e = Buffer->getBufferEnd();
657 
658     S.EmitInt(e-p);
659 
660     for ( ; p != e; ++p)
661       S.EmitInt(*p);
662   }
663 
664   S.FlushRecord();
665 }
666 
667 void ContentCache::ReadToSourceManager(llvm::Deserializer& D,
668                                        SourceManager& SMgr,
669                                        FileManager* FMgr,
670                                        std::vector<char>& Buf) {
671   if (FMgr) {
672     llvm::SerializedPtrID PtrID = D.ReadPtrID();
673     D.ReadCStr(Buf,false);
674 
675     // Create/fetch the FileEntry.
676     const char* start = &Buf[0];
677     const FileEntry* E = FMgr->getFile(start,start+Buf.size());
678 
679     // FIXME: Ideally we want a lazy materialization of the ContentCache
680     //  anyway, because we don't want to read in source files unless this
681     //  is absolutely needed.
682     if (!E)
683       D.RegisterPtr(PtrID,NULL);
684     else
685       // Get the ContextCache object and register it with the deserializer.
686       D.RegisterPtr(PtrID, SMgr.getOrCreateContentCache(E));
687     return;
688   }
689 
690   // Register the ContextCache object with the deserializer.
691   /* FIXME:
692   ContentCache *Entry
693   SMgr.MemBufferInfos.push_back(ContentCache());
694    = const_cast<ContentCache&>(SMgr.MemBufferInfos.back());
695   D.RegisterPtr(&Entry);
696 
697   // Create the buffer.
698   unsigned Size = D.ReadInt();
699   Entry.Buffer = MemoryBuffer::getNewUninitMemBuffer(Size);
700 
701   // Read the contents of the buffer.
702   char* p = const_cast<char*>(Entry.Buffer->getBufferStart());
703   for (unsigned i = 0; i < Size ; ++i)
704     p[i] = D.ReadInt();
705    */
706 }
707 
708 void SourceManager::Emit(llvm::Serializer& S) const {
709   S.EnterBlock();
710   S.EmitPtr(this);
711   S.EmitInt(MainFileID.getOpaqueValue());
712 
713   // Emit: FileInfos.  Just emit the file name.
714   S.EnterBlock();
715 
716   // FIXME: Emit FileInfos.
717   //std::for_each(FileInfos.begin(), FileInfos.end(),
718   //              S.MakeEmitter<ContentCache>());
719 
720   S.ExitBlock();
721 
722   // Emit: MemBufferInfos
723   S.EnterBlock();
724 
725   /* FIXME: EMIT.
726   std::for_each(MemBufferInfos.begin(), MemBufferInfos.end(),
727                 S.MakeEmitter<ContentCache>());
728    */
729 
730   S.ExitBlock();
731 
732   // FIXME: Emit SLocEntryTable.
733 
734   S.ExitBlock();
735 }
736 
737 SourceManager*
738 SourceManager::CreateAndRegister(llvm::Deserializer& D, FileManager& FMgr){
739   SourceManager *M = new SourceManager();
740   D.RegisterPtr(M);
741 
742   // Read: the FileID of the main source file of the translation unit.
743   M->MainFileID = FileID::get(D.ReadInt());
744 
745   std::vector<char> Buf;
746 
747   /*{ // FIXME Read: FileInfos.
748     llvm::Deserializer::Location BLoc = D.getCurrentBlockLocation();
749     while (!D.FinishedBlock(BLoc))
750     ContentCache::ReadToSourceManager(D,*M,&FMgr,Buf);
751   }*/
752 
753   { // Read: MemBufferInfos.
754     llvm::Deserializer::Location BLoc = D.getCurrentBlockLocation();
755     while (!D.FinishedBlock(BLoc))
756     ContentCache::ReadToSourceManager(D,*M,NULL,Buf);
757   }
758 
759   // FIXME: Read SLocEntryTable.
760 
761   return M;
762 }
763