xref: /freebsd-src/contrib/llvm-project/clang/lib/Basic/SourceManager.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===- SourceManager.cpp - Track and cache source files -------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric //  This file implements the SourceManager interface.
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
14*0b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
15*0b57cec5SDimitry Andric #include "clang/Basic/FileManager.h"
16*0b57cec5SDimitry Andric #include "clang/Basic/LLVM.h"
17*0b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
18*0b57cec5SDimitry Andric #include "clang/Basic/SourceManagerInternals.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
20*0b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
21*0b57cec5SDimitry Andric #include "llvm/ADT/None.h"
22*0b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
23*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
24*0b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
25*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
26*0b57cec5SDimitry Andric #include "llvm/Support/Allocator.h"
27*0b57cec5SDimitry Andric #include "llvm/Support/Capacity.h"
28*0b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
29*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
30*0b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
31*0b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
32*0b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
33*0b57cec5SDimitry Andric #include "llvm/Support/Path.h"
34*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
35*0b57cec5SDimitry Andric #include <algorithm>
36*0b57cec5SDimitry Andric #include <cassert>
37*0b57cec5SDimitry Andric #include <cstddef>
38*0b57cec5SDimitry Andric #include <cstdint>
39*0b57cec5SDimitry Andric #include <memory>
40*0b57cec5SDimitry Andric #include <tuple>
41*0b57cec5SDimitry Andric #include <utility>
42*0b57cec5SDimitry Andric #include <vector>
43*0b57cec5SDimitry Andric 
44*0b57cec5SDimitry Andric using namespace clang;
45*0b57cec5SDimitry Andric using namespace SrcMgr;
46*0b57cec5SDimitry Andric using llvm::MemoryBuffer;
47*0b57cec5SDimitry Andric 
48*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
49*0b57cec5SDimitry Andric // SourceManager Helper Classes
50*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
51*0b57cec5SDimitry Andric 
52*0b57cec5SDimitry Andric ContentCache::~ContentCache() {
53*0b57cec5SDimitry Andric   if (shouldFreeBuffer())
54*0b57cec5SDimitry Andric     delete Buffer.getPointer();
55*0b57cec5SDimitry Andric }
56*0b57cec5SDimitry Andric 
57*0b57cec5SDimitry Andric /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
58*0b57cec5SDimitry Andric /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
59*0b57cec5SDimitry Andric unsigned ContentCache::getSizeBytesMapped() const {
60*0b57cec5SDimitry Andric   return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
61*0b57cec5SDimitry Andric }
62*0b57cec5SDimitry Andric 
63*0b57cec5SDimitry Andric /// Returns the kind of memory used to back the memory buffer for
64*0b57cec5SDimitry Andric /// this content cache.  This is used for performance analysis.
65*0b57cec5SDimitry Andric llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
66*0b57cec5SDimitry Andric   assert(Buffer.getPointer());
67*0b57cec5SDimitry Andric 
68*0b57cec5SDimitry Andric   // Should be unreachable, but keep for sanity.
69*0b57cec5SDimitry Andric   if (!Buffer.getPointer())
70*0b57cec5SDimitry Andric     return llvm::MemoryBuffer::MemoryBuffer_Malloc;
71*0b57cec5SDimitry Andric 
72*0b57cec5SDimitry Andric   const llvm::MemoryBuffer *buf = Buffer.getPointer();
73*0b57cec5SDimitry Andric   return buf->getBufferKind();
74*0b57cec5SDimitry Andric }
75*0b57cec5SDimitry Andric 
76*0b57cec5SDimitry Andric /// getSize - Returns the size of the content encapsulated by this ContentCache.
77*0b57cec5SDimitry Andric ///  This can be the size of the source file or the size of an arbitrary
78*0b57cec5SDimitry Andric ///  scratch buffer.  If the ContentCache encapsulates a source file, that
79*0b57cec5SDimitry Andric ///  file is not lazily brought in from disk to satisfy this query.
80*0b57cec5SDimitry Andric unsigned ContentCache::getSize() const {
81*0b57cec5SDimitry Andric   return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
82*0b57cec5SDimitry Andric                              : (unsigned) ContentsEntry->getSize();
83*0b57cec5SDimitry Andric }
84*0b57cec5SDimitry Andric 
85*0b57cec5SDimitry Andric void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree) {
86*0b57cec5SDimitry Andric   if (B && B == Buffer.getPointer()) {
87*0b57cec5SDimitry Andric     assert(0 && "Replacing with the same buffer");
88*0b57cec5SDimitry Andric     Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
89*0b57cec5SDimitry Andric     return;
90*0b57cec5SDimitry Andric   }
91*0b57cec5SDimitry Andric 
92*0b57cec5SDimitry Andric   if (shouldFreeBuffer())
93*0b57cec5SDimitry Andric     delete Buffer.getPointer();
94*0b57cec5SDimitry Andric   Buffer.setPointer(B);
95*0b57cec5SDimitry Andric   Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0);
96*0b57cec5SDimitry Andric }
97*0b57cec5SDimitry Andric 
98*0b57cec5SDimitry Andric const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
99*0b57cec5SDimitry Andric                                                   const SourceManager &SM,
100*0b57cec5SDimitry Andric                                                   SourceLocation Loc,
101*0b57cec5SDimitry Andric                                                   bool *Invalid) const {
102*0b57cec5SDimitry Andric   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
103*0b57cec5SDimitry Andric   // computed it, just return what we have.
104*0b57cec5SDimitry Andric   if (Buffer.getPointer() || !ContentsEntry) {
105*0b57cec5SDimitry Andric     if (Invalid)
106*0b57cec5SDimitry Andric       *Invalid = isBufferInvalid();
107*0b57cec5SDimitry Andric 
108*0b57cec5SDimitry Andric     return Buffer.getPointer();
109*0b57cec5SDimitry Andric   }
110*0b57cec5SDimitry Andric 
111*0b57cec5SDimitry Andric   // Check that the file's size fits in an 'unsigned' (with room for a
112*0b57cec5SDimitry Andric   // past-the-end value). This is deeply regrettable, but various parts of
113*0b57cec5SDimitry Andric   // Clang (including elsewhere in this file!) use 'unsigned' to represent file
114*0b57cec5SDimitry Andric   // offsets, line numbers, string literal lengths, and so on, and fail
115*0b57cec5SDimitry Andric   // miserably on large source files.
116*0b57cec5SDimitry Andric   if ((uint64_t)ContentsEntry->getSize() >=
117*0b57cec5SDimitry Andric       std::numeric_limits<unsigned>::max()) {
118*0b57cec5SDimitry Andric     // We can't make a memory buffer of the required size, so just make a small
119*0b57cec5SDimitry Andric     // one. We should never hit a situation where we've already parsed to a
120*0b57cec5SDimitry Andric     // later offset of the file, so it shouldn't matter that the buffer is
121*0b57cec5SDimitry Andric     // smaller than the file.
122*0b57cec5SDimitry Andric     Buffer.setPointer(
123*0b57cec5SDimitry Andric         llvm::MemoryBuffer::getMemBuffer("", ContentsEntry->getName())
124*0b57cec5SDimitry Andric             .release());
125*0b57cec5SDimitry Andric     if (Diag.isDiagnosticInFlight())
126*0b57cec5SDimitry Andric       Diag.SetDelayedDiagnostic(diag::err_file_too_large,
127*0b57cec5SDimitry Andric                                 ContentsEntry->getName());
128*0b57cec5SDimitry Andric     else
129*0b57cec5SDimitry Andric       Diag.Report(Loc, diag::err_file_too_large)
130*0b57cec5SDimitry Andric         << ContentsEntry->getName();
131*0b57cec5SDimitry Andric 
132*0b57cec5SDimitry Andric     Buffer.setInt(Buffer.getInt() | InvalidFlag);
133*0b57cec5SDimitry Andric     if (Invalid) *Invalid = true;
134*0b57cec5SDimitry Andric     return Buffer.getPointer();
135*0b57cec5SDimitry Andric   }
136*0b57cec5SDimitry Andric 
137*0b57cec5SDimitry Andric   bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
138*0b57cec5SDimitry Andric   auto BufferOrError =
139*0b57cec5SDimitry Andric       SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
140*0b57cec5SDimitry Andric 
141*0b57cec5SDimitry Andric   // If we were unable to open the file, then we are in an inconsistent
142*0b57cec5SDimitry Andric   // situation where the content cache referenced a file which no longer
143*0b57cec5SDimitry Andric   // exists. Most likely, we were using a stat cache with an invalid entry but
144*0b57cec5SDimitry Andric   // the file could also have been removed during processing. Since we can't
145*0b57cec5SDimitry Andric   // really deal with this situation, just create an empty buffer.
146*0b57cec5SDimitry Andric   //
147*0b57cec5SDimitry Andric   // FIXME: This is definitely not ideal, but our immediate clients can't
148*0b57cec5SDimitry Andric   // currently handle returning a null entry here. Ideally we should detect
149*0b57cec5SDimitry Andric   // that we are in an inconsistent situation and error out as quickly as
150*0b57cec5SDimitry Andric   // possible.
151*0b57cec5SDimitry Andric   if (!BufferOrError) {
152*0b57cec5SDimitry Andric     StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
153*0b57cec5SDimitry Andric     auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
154*0b57cec5SDimitry Andric         ContentsEntry->getSize(), "<invalid>");
155*0b57cec5SDimitry Andric     char *Ptr = BackupBuffer->getBufferStart();
156*0b57cec5SDimitry Andric     for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
157*0b57cec5SDimitry Andric       Ptr[i] = FillStr[i % FillStr.size()];
158*0b57cec5SDimitry Andric     Buffer.setPointer(BackupBuffer.release());
159*0b57cec5SDimitry Andric 
160*0b57cec5SDimitry Andric     if (Diag.isDiagnosticInFlight())
161*0b57cec5SDimitry Andric       Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
162*0b57cec5SDimitry Andric                                 ContentsEntry->getName(),
163*0b57cec5SDimitry Andric                                 BufferOrError.getError().message());
164*0b57cec5SDimitry Andric     else
165*0b57cec5SDimitry Andric       Diag.Report(Loc, diag::err_cannot_open_file)
166*0b57cec5SDimitry Andric           << ContentsEntry->getName() << BufferOrError.getError().message();
167*0b57cec5SDimitry Andric 
168*0b57cec5SDimitry Andric     Buffer.setInt(Buffer.getInt() | InvalidFlag);
169*0b57cec5SDimitry Andric 
170*0b57cec5SDimitry Andric     if (Invalid) *Invalid = true;
171*0b57cec5SDimitry Andric     return Buffer.getPointer();
172*0b57cec5SDimitry Andric   }
173*0b57cec5SDimitry Andric 
174*0b57cec5SDimitry Andric   Buffer.setPointer(BufferOrError->release());
175*0b57cec5SDimitry Andric 
176*0b57cec5SDimitry Andric   // Check that the file's size is the same as in the file entry (which may
177*0b57cec5SDimitry Andric   // have come from a stat cache).
178*0b57cec5SDimitry Andric   if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
179*0b57cec5SDimitry Andric     if (Diag.isDiagnosticInFlight())
180*0b57cec5SDimitry Andric       Diag.SetDelayedDiagnostic(diag::err_file_modified,
181*0b57cec5SDimitry Andric                                 ContentsEntry->getName());
182*0b57cec5SDimitry Andric     else
183*0b57cec5SDimitry Andric       Diag.Report(Loc, diag::err_file_modified)
184*0b57cec5SDimitry Andric         << ContentsEntry->getName();
185*0b57cec5SDimitry Andric 
186*0b57cec5SDimitry Andric     Buffer.setInt(Buffer.getInt() | InvalidFlag);
187*0b57cec5SDimitry Andric     if (Invalid) *Invalid = true;
188*0b57cec5SDimitry Andric     return Buffer.getPointer();
189*0b57cec5SDimitry Andric   }
190*0b57cec5SDimitry Andric 
191*0b57cec5SDimitry Andric   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
192*0b57cec5SDimitry Andric   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
193*0b57cec5SDimitry Andric   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
194*0b57cec5SDimitry Andric   StringRef BufStr = Buffer.getPointer()->getBuffer();
195*0b57cec5SDimitry Andric   const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
196*0b57cec5SDimitry Andric     .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
197*0b57cec5SDimitry Andric                                                   "UTF-32 (BE)")
198*0b57cec5SDimitry Andric     .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
199*0b57cec5SDimitry Andric                                                   "UTF-32 (LE)")
200*0b57cec5SDimitry Andric     .StartsWith("\xFE\xFF", "UTF-16 (BE)")
201*0b57cec5SDimitry Andric     .StartsWith("\xFF\xFE", "UTF-16 (LE)")
202*0b57cec5SDimitry Andric     .StartsWith("\x2B\x2F\x76", "UTF-7")
203*0b57cec5SDimitry Andric     .StartsWith("\xF7\x64\x4C", "UTF-1")
204*0b57cec5SDimitry Andric     .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
205*0b57cec5SDimitry Andric     .StartsWith("\x0E\xFE\xFF", "SCSU")
206*0b57cec5SDimitry Andric     .StartsWith("\xFB\xEE\x28", "BOCU-1")
207*0b57cec5SDimitry Andric     .StartsWith("\x84\x31\x95\x33", "GB-18030")
208*0b57cec5SDimitry Andric     .Default(nullptr);
209*0b57cec5SDimitry Andric 
210*0b57cec5SDimitry Andric   if (InvalidBOM) {
211*0b57cec5SDimitry Andric     Diag.Report(Loc, diag::err_unsupported_bom)
212*0b57cec5SDimitry Andric       << InvalidBOM << ContentsEntry->getName();
213*0b57cec5SDimitry Andric     Buffer.setInt(Buffer.getInt() | InvalidFlag);
214*0b57cec5SDimitry Andric   }
215*0b57cec5SDimitry Andric 
216*0b57cec5SDimitry Andric   if (Invalid)
217*0b57cec5SDimitry Andric     *Invalid = isBufferInvalid();
218*0b57cec5SDimitry Andric 
219*0b57cec5SDimitry Andric   return Buffer.getPointer();
220*0b57cec5SDimitry Andric }
221*0b57cec5SDimitry Andric 
222*0b57cec5SDimitry Andric unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
223*0b57cec5SDimitry Andric   auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
224*0b57cec5SDimitry Andric   if (IterBool.second)
225*0b57cec5SDimitry Andric     FilenamesByID.push_back(&*IterBool.first);
226*0b57cec5SDimitry Andric   return IterBool.first->second;
227*0b57cec5SDimitry Andric }
228*0b57cec5SDimitry Andric 
229*0b57cec5SDimitry Andric /// Add a line note to the line table that indicates that there is a \#line or
230*0b57cec5SDimitry Andric /// GNU line marker at the specified FID/Offset location which changes the
231*0b57cec5SDimitry Andric /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
232*0b57cec5SDimitry Andric /// change the presumed \#include stack.  If it is 1, this is a file entry, if
233*0b57cec5SDimitry Andric /// it is 2 then this is a file exit. FileKind specifies whether this is a
234*0b57cec5SDimitry Andric /// system header or extern C system header.
235*0b57cec5SDimitry Andric void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
236*0b57cec5SDimitry Andric                                 int FilenameID, unsigned EntryExit,
237*0b57cec5SDimitry Andric                                 SrcMgr::CharacteristicKind FileKind) {
238*0b57cec5SDimitry Andric   std::vector<LineEntry> &Entries = LineEntries[FID];
239*0b57cec5SDimitry Andric 
240*0b57cec5SDimitry Andric   // An unspecified FilenameID means use the last filename if available, or the
241*0b57cec5SDimitry Andric   // main source file otherwise.
242*0b57cec5SDimitry Andric   if (FilenameID == -1 && !Entries.empty())
243*0b57cec5SDimitry Andric     FilenameID = Entries.back().FilenameID;
244*0b57cec5SDimitry Andric 
245*0b57cec5SDimitry Andric   assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
246*0b57cec5SDimitry Andric          "Adding line entries out of order!");
247*0b57cec5SDimitry Andric 
248*0b57cec5SDimitry Andric   unsigned IncludeOffset = 0;
249*0b57cec5SDimitry Andric   if (EntryExit == 0) {  // No #include stack change.
250*0b57cec5SDimitry Andric     IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
251*0b57cec5SDimitry Andric   } else if (EntryExit == 1) {
252*0b57cec5SDimitry Andric     IncludeOffset = Offset-1;
253*0b57cec5SDimitry Andric   } else if (EntryExit == 2) {
254*0b57cec5SDimitry Andric     assert(!Entries.empty() && Entries.back().IncludeOffset &&
255*0b57cec5SDimitry Andric        "PPDirectives should have caught case when popping empty include stack");
256*0b57cec5SDimitry Andric 
257*0b57cec5SDimitry Andric     // Get the include loc of the last entries' include loc as our include loc.
258*0b57cec5SDimitry Andric     IncludeOffset = 0;
259*0b57cec5SDimitry Andric     if (const LineEntry *PrevEntry =
260*0b57cec5SDimitry Andric           FindNearestLineEntry(FID, Entries.back().IncludeOffset))
261*0b57cec5SDimitry Andric       IncludeOffset = PrevEntry->IncludeOffset;
262*0b57cec5SDimitry Andric   }
263*0b57cec5SDimitry Andric 
264*0b57cec5SDimitry Andric   Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
265*0b57cec5SDimitry Andric                                    IncludeOffset));
266*0b57cec5SDimitry Andric }
267*0b57cec5SDimitry Andric 
268*0b57cec5SDimitry Andric /// FindNearestLineEntry - Find the line entry nearest to FID that is before
269*0b57cec5SDimitry Andric /// it.  If there is no line entry before Offset in FID, return null.
270*0b57cec5SDimitry Andric const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
271*0b57cec5SDimitry Andric                                                      unsigned Offset) {
272*0b57cec5SDimitry Andric   const std::vector<LineEntry> &Entries = LineEntries[FID];
273*0b57cec5SDimitry Andric   assert(!Entries.empty() && "No #line entries for this FID after all!");
274*0b57cec5SDimitry Andric 
275*0b57cec5SDimitry Andric   // It is very common for the query to be after the last #line, check this
276*0b57cec5SDimitry Andric   // first.
277*0b57cec5SDimitry Andric   if (Entries.back().FileOffset <= Offset)
278*0b57cec5SDimitry Andric     return &Entries.back();
279*0b57cec5SDimitry Andric 
280*0b57cec5SDimitry Andric   // Do a binary search to find the maximal element that is still before Offset.
281*0b57cec5SDimitry Andric   std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
282*0b57cec5SDimitry Andric   if (I == Entries.begin())
283*0b57cec5SDimitry Andric     return nullptr;
284*0b57cec5SDimitry Andric   return &*--I;
285*0b57cec5SDimitry Andric }
286*0b57cec5SDimitry Andric 
287*0b57cec5SDimitry Andric /// Add a new line entry that has already been encoded into
288*0b57cec5SDimitry Andric /// the internal representation of the line table.
289*0b57cec5SDimitry Andric void LineTableInfo::AddEntry(FileID FID,
290*0b57cec5SDimitry Andric                              const std::vector<LineEntry> &Entries) {
291*0b57cec5SDimitry Andric   LineEntries[FID] = Entries;
292*0b57cec5SDimitry Andric }
293*0b57cec5SDimitry Andric 
294*0b57cec5SDimitry Andric /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
295*0b57cec5SDimitry Andric unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
296*0b57cec5SDimitry Andric   return getLineTable().getLineTableFilenameID(Name);
297*0b57cec5SDimitry Andric }
298*0b57cec5SDimitry Andric 
299*0b57cec5SDimitry Andric /// AddLineNote - Add a line note to the line table for the FileID and offset
300*0b57cec5SDimitry Andric /// specified by Loc.  If FilenameID is -1, it is considered to be
301*0b57cec5SDimitry Andric /// unspecified.
302*0b57cec5SDimitry Andric void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
303*0b57cec5SDimitry Andric                                 int FilenameID, bool IsFileEntry,
304*0b57cec5SDimitry Andric                                 bool IsFileExit,
305*0b57cec5SDimitry Andric                                 SrcMgr::CharacteristicKind FileKind) {
306*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
307*0b57cec5SDimitry Andric 
308*0b57cec5SDimitry Andric   bool Invalid = false;
309*0b57cec5SDimitry Andric   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
310*0b57cec5SDimitry Andric   if (!Entry.isFile() || Invalid)
311*0b57cec5SDimitry Andric     return;
312*0b57cec5SDimitry Andric 
313*0b57cec5SDimitry Andric   const SrcMgr::FileInfo &FileInfo = Entry.getFile();
314*0b57cec5SDimitry Andric 
315*0b57cec5SDimitry Andric   // Remember that this file has #line directives now if it doesn't already.
316*0b57cec5SDimitry Andric   const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
317*0b57cec5SDimitry Andric 
318*0b57cec5SDimitry Andric   (void) getLineTable();
319*0b57cec5SDimitry Andric 
320*0b57cec5SDimitry Andric   unsigned EntryExit = 0;
321*0b57cec5SDimitry Andric   if (IsFileEntry)
322*0b57cec5SDimitry Andric     EntryExit = 1;
323*0b57cec5SDimitry Andric   else if (IsFileExit)
324*0b57cec5SDimitry Andric     EntryExit = 2;
325*0b57cec5SDimitry Andric 
326*0b57cec5SDimitry Andric   LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
327*0b57cec5SDimitry Andric                          EntryExit, FileKind);
328*0b57cec5SDimitry Andric }
329*0b57cec5SDimitry Andric 
330*0b57cec5SDimitry Andric LineTableInfo &SourceManager::getLineTable() {
331*0b57cec5SDimitry Andric   if (!LineTable)
332*0b57cec5SDimitry Andric     LineTable.reset(new LineTableInfo());
333*0b57cec5SDimitry Andric   return *LineTable;
334*0b57cec5SDimitry Andric }
335*0b57cec5SDimitry Andric 
336*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
337*0b57cec5SDimitry Andric // Private 'Create' methods.
338*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
339*0b57cec5SDimitry Andric 
340*0b57cec5SDimitry Andric SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
341*0b57cec5SDimitry Andric                              bool UserFilesAreVolatile)
342*0b57cec5SDimitry Andric   : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
343*0b57cec5SDimitry Andric   clearIDTables();
344*0b57cec5SDimitry Andric   Diag.setSourceManager(this);
345*0b57cec5SDimitry Andric }
346*0b57cec5SDimitry Andric 
347*0b57cec5SDimitry Andric SourceManager::~SourceManager() {
348*0b57cec5SDimitry Andric   // Delete FileEntry objects corresponding to content caches.  Since the actual
349*0b57cec5SDimitry Andric   // content cache objects are bump pointer allocated, we just have to run the
350*0b57cec5SDimitry Andric   // dtors, but we call the deallocate method for completeness.
351*0b57cec5SDimitry Andric   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
352*0b57cec5SDimitry Andric     if (MemBufferInfos[i]) {
353*0b57cec5SDimitry Andric       MemBufferInfos[i]->~ContentCache();
354*0b57cec5SDimitry Andric       ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
355*0b57cec5SDimitry Andric     }
356*0b57cec5SDimitry Andric   }
357*0b57cec5SDimitry Andric   for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
358*0b57cec5SDimitry Andric        I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
359*0b57cec5SDimitry Andric     if (I->second) {
360*0b57cec5SDimitry Andric       I->second->~ContentCache();
361*0b57cec5SDimitry Andric       ContentCacheAlloc.Deallocate(I->second);
362*0b57cec5SDimitry Andric     }
363*0b57cec5SDimitry Andric   }
364*0b57cec5SDimitry Andric }
365*0b57cec5SDimitry Andric 
366*0b57cec5SDimitry Andric void SourceManager::clearIDTables() {
367*0b57cec5SDimitry Andric   MainFileID = FileID();
368*0b57cec5SDimitry Andric   LocalSLocEntryTable.clear();
369*0b57cec5SDimitry Andric   LoadedSLocEntryTable.clear();
370*0b57cec5SDimitry Andric   SLocEntryLoaded.clear();
371*0b57cec5SDimitry Andric   LastLineNoFileIDQuery = FileID();
372*0b57cec5SDimitry Andric   LastLineNoContentCache = nullptr;
373*0b57cec5SDimitry Andric   LastFileIDLookup = FileID();
374*0b57cec5SDimitry Andric 
375*0b57cec5SDimitry Andric   if (LineTable)
376*0b57cec5SDimitry Andric     LineTable->clear();
377*0b57cec5SDimitry Andric 
378*0b57cec5SDimitry Andric   // Use up FileID #0 as an invalid expansion.
379*0b57cec5SDimitry Andric   NextLocalOffset = 0;
380*0b57cec5SDimitry Andric   CurrentLoadedOffset = MaxLoadedOffset;
381*0b57cec5SDimitry Andric   createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
382*0b57cec5SDimitry Andric }
383*0b57cec5SDimitry Andric 
384*0b57cec5SDimitry Andric void SourceManager::initializeForReplay(const SourceManager &Old) {
385*0b57cec5SDimitry Andric   assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
386*0b57cec5SDimitry Andric 
387*0b57cec5SDimitry Andric   auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
388*0b57cec5SDimitry Andric     auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
389*0b57cec5SDimitry Andric     Clone->OrigEntry = Cache->OrigEntry;
390*0b57cec5SDimitry Andric     Clone->ContentsEntry = Cache->ContentsEntry;
391*0b57cec5SDimitry Andric     Clone->BufferOverridden = Cache->BufferOverridden;
392*0b57cec5SDimitry Andric     Clone->IsSystemFile = Cache->IsSystemFile;
393*0b57cec5SDimitry Andric     Clone->IsTransient = Cache->IsTransient;
394*0b57cec5SDimitry Andric     Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
395*0b57cec5SDimitry Andric     return Clone;
396*0b57cec5SDimitry Andric   };
397*0b57cec5SDimitry Andric 
398*0b57cec5SDimitry Andric   // Ensure all SLocEntries are loaded from the external source.
399*0b57cec5SDimitry Andric   for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
400*0b57cec5SDimitry Andric     if (!Old.SLocEntryLoaded[I])
401*0b57cec5SDimitry Andric       Old.loadSLocEntry(I, nullptr);
402*0b57cec5SDimitry Andric 
403*0b57cec5SDimitry Andric   // Inherit any content cache data from the old source manager.
404*0b57cec5SDimitry Andric   for (auto &FileInfo : Old.FileInfos) {
405*0b57cec5SDimitry Andric     SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
406*0b57cec5SDimitry Andric     if (Slot)
407*0b57cec5SDimitry Andric       continue;
408*0b57cec5SDimitry Andric     Slot = CloneContentCache(FileInfo.second);
409*0b57cec5SDimitry Andric   }
410*0b57cec5SDimitry Andric }
411*0b57cec5SDimitry Andric 
412*0b57cec5SDimitry Andric /// getOrCreateContentCache - Create or return a cached ContentCache for the
413*0b57cec5SDimitry Andric /// specified file.
414*0b57cec5SDimitry Andric const ContentCache *
415*0b57cec5SDimitry Andric SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
416*0b57cec5SDimitry Andric                                        bool isSystemFile) {
417*0b57cec5SDimitry Andric   assert(FileEnt && "Didn't specify a file entry to use?");
418*0b57cec5SDimitry Andric 
419*0b57cec5SDimitry Andric   // Do we already have information about this file?
420*0b57cec5SDimitry Andric   ContentCache *&Entry = FileInfos[FileEnt];
421*0b57cec5SDimitry Andric   if (Entry) return Entry;
422*0b57cec5SDimitry Andric 
423*0b57cec5SDimitry Andric   // Nope, create a new Cache entry.
424*0b57cec5SDimitry Andric   Entry = ContentCacheAlloc.Allocate<ContentCache>();
425*0b57cec5SDimitry Andric 
426*0b57cec5SDimitry Andric   if (OverriddenFilesInfo) {
427*0b57cec5SDimitry Andric     // If the file contents are overridden with contents from another file,
428*0b57cec5SDimitry Andric     // pass that file to ContentCache.
429*0b57cec5SDimitry Andric     llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
430*0b57cec5SDimitry Andric         overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
431*0b57cec5SDimitry Andric     if (overI == OverriddenFilesInfo->OverriddenFiles.end())
432*0b57cec5SDimitry Andric       new (Entry) ContentCache(FileEnt);
433*0b57cec5SDimitry Andric     else
434*0b57cec5SDimitry Andric       new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
435*0b57cec5SDimitry Andric                                                               : overI->second,
436*0b57cec5SDimitry Andric                                overI->second);
437*0b57cec5SDimitry Andric   } else {
438*0b57cec5SDimitry Andric     new (Entry) ContentCache(FileEnt);
439*0b57cec5SDimitry Andric   }
440*0b57cec5SDimitry Andric 
441*0b57cec5SDimitry Andric   Entry->IsSystemFile = isSystemFile;
442*0b57cec5SDimitry Andric   Entry->IsTransient = FilesAreTransient;
443*0b57cec5SDimitry Andric 
444*0b57cec5SDimitry Andric   return Entry;
445*0b57cec5SDimitry Andric }
446*0b57cec5SDimitry Andric 
447*0b57cec5SDimitry Andric /// Create a new ContentCache for the specified memory buffer.
448*0b57cec5SDimitry Andric /// This does no caching.
449*0b57cec5SDimitry Andric const ContentCache *
450*0b57cec5SDimitry Andric SourceManager::createMemBufferContentCache(const llvm::MemoryBuffer *Buffer,
451*0b57cec5SDimitry Andric                                            bool DoNotFree) {
452*0b57cec5SDimitry Andric   // Add a new ContentCache to the MemBufferInfos list and return it.
453*0b57cec5SDimitry Andric   ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
454*0b57cec5SDimitry Andric   new (Entry) ContentCache();
455*0b57cec5SDimitry Andric   MemBufferInfos.push_back(Entry);
456*0b57cec5SDimitry Andric   Entry->replaceBuffer(Buffer, DoNotFree);
457*0b57cec5SDimitry Andric   return Entry;
458*0b57cec5SDimitry Andric }
459*0b57cec5SDimitry Andric 
460*0b57cec5SDimitry Andric const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
461*0b57cec5SDimitry Andric                                                       bool *Invalid) const {
462*0b57cec5SDimitry Andric   assert(!SLocEntryLoaded[Index]);
463*0b57cec5SDimitry Andric   if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
464*0b57cec5SDimitry Andric     if (Invalid)
465*0b57cec5SDimitry Andric       *Invalid = true;
466*0b57cec5SDimitry Andric     // If the file of the SLocEntry changed we could still have loaded it.
467*0b57cec5SDimitry Andric     if (!SLocEntryLoaded[Index]) {
468*0b57cec5SDimitry Andric       // Try to recover; create a SLocEntry so the rest of clang can handle it.
469*0b57cec5SDimitry Andric       LoadedSLocEntryTable[Index] = SLocEntry::get(0,
470*0b57cec5SDimitry Andric                                  FileInfo::get(SourceLocation(),
471*0b57cec5SDimitry Andric                                                getFakeContentCacheForRecovery(),
472*0b57cec5SDimitry Andric                                                SrcMgr::C_User));
473*0b57cec5SDimitry Andric     }
474*0b57cec5SDimitry Andric   }
475*0b57cec5SDimitry Andric 
476*0b57cec5SDimitry Andric   return LoadedSLocEntryTable[Index];
477*0b57cec5SDimitry Andric }
478*0b57cec5SDimitry Andric 
479*0b57cec5SDimitry Andric std::pair<int, unsigned>
480*0b57cec5SDimitry Andric SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
481*0b57cec5SDimitry Andric                                          unsigned TotalSize) {
482*0b57cec5SDimitry Andric   assert(ExternalSLocEntries && "Don't have an external sloc source");
483*0b57cec5SDimitry Andric   // Make sure we're not about to run out of source locations.
484*0b57cec5SDimitry Andric   if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
485*0b57cec5SDimitry Andric     return std::make_pair(0, 0);
486*0b57cec5SDimitry Andric   LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
487*0b57cec5SDimitry Andric   SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
488*0b57cec5SDimitry Andric   CurrentLoadedOffset -= TotalSize;
489*0b57cec5SDimitry Andric   int ID = LoadedSLocEntryTable.size();
490*0b57cec5SDimitry Andric   return std::make_pair(-ID - 1, CurrentLoadedOffset);
491*0b57cec5SDimitry Andric }
492*0b57cec5SDimitry Andric 
493*0b57cec5SDimitry Andric /// As part of recovering from missing or changed content, produce a
494*0b57cec5SDimitry Andric /// fake, non-empty buffer.
495*0b57cec5SDimitry Andric llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
496*0b57cec5SDimitry Andric   if (!FakeBufferForRecovery)
497*0b57cec5SDimitry Andric     FakeBufferForRecovery =
498*0b57cec5SDimitry Andric         llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
499*0b57cec5SDimitry Andric 
500*0b57cec5SDimitry Andric   return FakeBufferForRecovery.get();
501*0b57cec5SDimitry Andric }
502*0b57cec5SDimitry Andric 
503*0b57cec5SDimitry Andric /// As part of recovering from missing or changed content, produce a
504*0b57cec5SDimitry Andric /// fake content cache.
505*0b57cec5SDimitry Andric const SrcMgr::ContentCache *
506*0b57cec5SDimitry Andric SourceManager::getFakeContentCacheForRecovery() const {
507*0b57cec5SDimitry Andric   if (!FakeContentCacheForRecovery) {
508*0b57cec5SDimitry Andric     FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
509*0b57cec5SDimitry Andric     FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
510*0b57cec5SDimitry Andric                                                /*DoNotFree=*/true);
511*0b57cec5SDimitry Andric   }
512*0b57cec5SDimitry Andric   return FakeContentCacheForRecovery.get();
513*0b57cec5SDimitry Andric }
514*0b57cec5SDimitry Andric 
515*0b57cec5SDimitry Andric /// Returns the previous in-order FileID or an invalid FileID if there
516*0b57cec5SDimitry Andric /// is no previous one.
517*0b57cec5SDimitry Andric FileID SourceManager::getPreviousFileID(FileID FID) const {
518*0b57cec5SDimitry Andric   if (FID.isInvalid())
519*0b57cec5SDimitry Andric     return FileID();
520*0b57cec5SDimitry Andric 
521*0b57cec5SDimitry Andric   int ID = FID.ID;
522*0b57cec5SDimitry Andric   if (ID == -1)
523*0b57cec5SDimitry Andric     return FileID();
524*0b57cec5SDimitry Andric 
525*0b57cec5SDimitry Andric   if (ID > 0) {
526*0b57cec5SDimitry Andric     if (ID-1 == 0)
527*0b57cec5SDimitry Andric       return FileID();
528*0b57cec5SDimitry Andric   } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
529*0b57cec5SDimitry Andric     return FileID();
530*0b57cec5SDimitry Andric   }
531*0b57cec5SDimitry Andric 
532*0b57cec5SDimitry Andric   return FileID::get(ID-1);
533*0b57cec5SDimitry Andric }
534*0b57cec5SDimitry Andric 
535*0b57cec5SDimitry Andric /// Returns the next in-order FileID or an invalid FileID if there is
536*0b57cec5SDimitry Andric /// no next one.
537*0b57cec5SDimitry Andric FileID SourceManager::getNextFileID(FileID FID) const {
538*0b57cec5SDimitry Andric   if (FID.isInvalid())
539*0b57cec5SDimitry Andric     return FileID();
540*0b57cec5SDimitry Andric 
541*0b57cec5SDimitry Andric   int ID = FID.ID;
542*0b57cec5SDimitry Andric   if (ID > 0) {
543*0b57cec5SDimitry Andric     if (unsigned(ID+1) >= local_sloc_entry_size())
544*0b57cec5SDimitry Andric       return FileID();
545*0b57cec5SDimitry Andric   } else if (ID+1 >= -1) {
546*0b57cec5SDimitry Andric     return FileID();
547*0b57cec5SDimitry Andric   }
548*0b57cec5SDimitry Andric 
549*0b57cec5SDimitry Andric   return FileID::get(ID+1);
550*0b57cec5SDimitry Andric }
551*0b57cec5SDimitry Andric 
552*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
553*0b57cec5SDimitry Andric // Methods to create new FileID's and macro expansions.
554*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
555*0b57cec5SDimitry Andric 
556*0b57cec5SDimitry Andric /// createFileID - Create a new FileID for the specified ContentCache and
557*0b57cec5SDimitry Andric /// include position.  This works regardless of whether the ContentCache
558*0b57cec5SDimitry Andric /// corresponds to a file or some other input source.
559*0b57cec5SDimitry Andric FileID SourceManager::createFileID(const ContentCache *File,
560*0b57cec5SDimitry Andric                                    SourceLocation IncludePos,
561*0b57cec5SDimitry Andric                                    SrcMgr::CharacteristicKind FileCharacter,
562*0b57cec5SDimitry Andric                                    int LoadedID, unsigned LoadedOffset) {
563*0b57cec5SDimitry Andric   if (LoadedID < 0) {
564*0b57cec5SDimitry Andric     assert(LoadedID != -1 && "Loading sentinel FileID");
565*0b57cec5SDimitry Andric     unsigned Index = unsigned(-LoadedID) - 2;
566*0b57cec5SDimitry Andric     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
567*0b57cec5SDimitry Andric     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
568*0b57cec5SDimitry Andric     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
569*0b57cec5SDimitry Andric         FileInfo::get(IncludePos, File, FileCharacter));
570*0b57cec5SDimitry Andric     SLocEntryLoaded[Index] = true;
571*0b57cec5SDimitry Andric     return FileID::get(LoadedID);
572*0b57cec5SDimitry Andric   }
573*0b57cec5SDimitry Andric   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
574*0b57cec5SDimitry Andric                                                FileInfo::get(IncludePos, File,
575*0b57cec5SDimitry Andric                                                              FileCharacter)));
576*0b57cec5SDimitry Andric   unsigned FileSize = File->getSize();
577*0b57cec5SDimitry Andric   assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
578*0b57cec5SDimitry Andric          NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
579*0b57cec5SDimitry Andric          "Ran out of source locations!");
580*0b57cec5SDimitry Andric   // We do a +1 here because we want a SourceLocation that means "the end of the
581*0b57cec5SDimitry Andric   // file", e.g. for the "no newline at the end of the file" diagnostic.
582*0b57cec5SDimitry Andric   NextLocalOffset += FileSize + 1;
583*0b57cec5SDimitry Andric 
584*0b57cec5SDimitry Andric   // Set LastFileIDLookup to the newly created file.  The next getFileID call is
585*0b57cec5SDimitry Andric   // almost guaranteed to be from that file.
586*0b57cec5SDimitry Andric   FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
587*0b57cec5SDimitry Andric   return LastFileIDLookup = FID;
588*0b57cec5SDimitry Andric }
589*0b57cec5SDimitry Andric 
590*0b57cec5SDimitry Andric SourceLocation
591*0b57cec5SDimitry Andric SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
592*0b57cec5SDimitry Andric                                           SourceLocation ExpansionLoc,
593*0b57cec5SDimitry Andric                                           unsigned TokLength) {
594*0b57cec5SDimitry Andric   ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
595*0b57cec5SDimitry Andric                                                         ExpansionLoc);
596*0b57cec5SDimitry Andric   return createExpansionLocImpl(Info, TokLength);
597*0b57cec5SDimitry Andric }
598*0b57cec5SDimitry Andric 
599*0b57cec5SDimitry Andric SourceLocation
600*0b57cec5SDimitry Andric SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
601*0b57cec5SDimitry Andric                                   SourceLocation ExpansionLocStart,
602*0b57cec5SDimitry Andric                                   SourceLocation ExpansionLocEnd,
603*0b57cec5SDimitry Andric                                   unsigned TokLength,
604*0b57cec5SDimitry Andric                                   bool ExpansionIsTokenRange,
605*0b57cec5SDimitry Andric                                   int LoadedID,
606*0b57cec5SDimitry Andric                                   unsigned LoadedOffset) {
607*0b57cec5SDimitry Andric   ExpansionInfo Info = ExpansionInfo::create(
608*0b57cec5SDimitry Andric       SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
609*0b57cec5SDimitry Andric   return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
610*0b57cec5SDimitry Andric }
611*0b57cec5SDimitry Andric 
612*0b57cec5SDimitry Andric SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
613*0b57cec5SDimitry Andric                                                   SourceLocation TokenStart,
614*0b57cec5SDimitry Andric                                                   SourceLocation TokenEnd) {
615*0b57cec5SDimitry Andric   assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
616*0b57cec5SDimitry Andric          "token spans multiple files");
617*0b57cec5SDimitry Andric   return createExpansionLocImpl(
618*0b57cec5SDimitry Andric       ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
619*0b57cec5SDimitry Andric       TokenEnd.getOffset() - TokenStart.getOffset());
620*0b57cec5SDimitry Andric }
621*0b57cec5SDimitry Andric 
622*0b57cec5SDimitry Andric SourceLocation
623*0b57cec5SDimitry Andric SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
624*0b57cec5SDimitry Andric                                       unsigned TokLength,
625*0b57cec5SDimitry Andric                                       int LoadedID,
626*0b57cec5SDimitry Andric                                       unsigned LoadedOffset) {
627*0b57cec5SDimitry Andric   if (LoadedID < 0) {
628*0b57cec5SDimitry Andric     assert(LoadedID != -1 && "Loading sentinel FileID");
629*0b57cec5SDimitry Andric     unsigned Index = unsigned(-LoadedID) - 2;
630*0b57cec5SDimitry Andric     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
631*0b57cec5SDimitry Andric     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
632*0b57cec5SDimitry Andric     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
633*0b57cec5SDimitry Andric     SLocEntryLoaded[Index] = true;
634*0b57cec5SDimitry Andric     return SourceLocation::getMacroLoc(LoadedOffset);
635*0b57cec5SDimitry Andric   }
636*0b57cec5SDimitry Andric   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
637*0b57cec5SDimitry Andric   assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
638*0b57cec5SDimitry Andric          NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
639*0b57cec5SDimitry Andric          "Ran out of source locations!");
640*0b57cec5SDimitry Andric   // See createFileID for that +1.
641*0b57cec5SDimitry Andric   NextLocalOffset += TokLength + 1;
642*0b57cec5SDimitry Andric   return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
643*0b57cec5SDimitry Andric }
644*0b57cec5SDimitry Andric 
645*0b57cec5SDimitry Andric const llvm::MemoryBuffer *
646*0b57cec5SDimitry Andric SourceManager::getMemoryBufferForFile(const FileEntry *File, bool *Invalid) {
647*0b57cec5SDimitry Andric   const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
648*0b57cec5SDimitry Andric   assert(IR && "getOrCreateContentCache() cannot return NULL");
649*0b57cec5SDimitry Andric   return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
650*0b57cec5SDimitry Andric }
651*0b57cec5SDimitry Andric 
652*0b57cec5SDimitry Andric void SourceManager::overrideFileContents(const FileEntry *SourceFile,
653*0b57cec5SDimitry Andric                                          llvm::MemoryBuffer *Buffer,
654*0b57cec5SDimitry Andric                                          bool DoNotFree) {
655*0b57cec5SDimitry Andric   const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
656*0b57cec5SDimitry Andric   assert(IR && "getOrCreateContentCache() cannot return NULL");
657*0b57cec5SDimitry Andric 
658*0b57cec5SDimitry Andric   const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
659*0b57cec5SDimitry Andric   const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
660*0b57cec5SDimitry Andric 
661*0b57cec5SDimitry Andric   getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
662*0b57cec5SDimitry Andric }
663*0b57cec5SDimitry Andric 
664*0b57cec5SDimitry Andric void SourceManager::overrideFileContents(const FileEntry *SourceFile,
665*0b57cec5SDimitry Andric                                          const FileEntry *NewFile) {
666*0b57cec5SDimitry Andric   assert(SourceFile->getSize() == NewFile->getSize() &&
667*0b57cec5SDimitry Andric          "Different sizes, use the FileManager to create a virtual file with "
668*0b57cec5SDimitry Andric          "the correct size");
669*0b57cec5SDimitry Andric   assert(FileInfos.count(SourceFile) == 0 &&
670*0b57cec5SDimitry Andric          "This function should be called at the initialization stage, before "
671*0b57cec5SDimitry Andric          "any parsing occurs.");
672*0b57cec5SDimitry Andric   getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
673*0b57cec5SDimitry Andric }
674*0b57cec5SDimitry Andric 
675*0b57cec5SDimitry Andric void SourceManager::disableFileContentsOverride(const FileEntry *File) {
676*0b57cec5SDimitry Andric   if (!isFileOverridden(File))
677*0b57cec5SDimitry Andric     return;
678*0b57cec5SDimitry Andric 
679*0b57cec5SDimitry Andric   const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
680*0b57cec5SDimitry Andric   const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
681*0b57cec5SDimitry Andric   const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
682*0b57cec5SDimitry Andric 
683*0b57cec5SDimitry Andric   assert(OverriddenFilesInfo);
684*0b57cec5SDimitry Andric   OverriddenFilesInfo->OverriddenFiles.erase(File);
685*0b57cec5SDimitry Andric   OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
686*0b57cec5SDimitry Andric }
687*0b57cec5SDimitry Andric 
688*0b57cec5SDimitry Andric void SourceManager::setFileIsTransient(const FileEntry *File) {
689*0b57cec5SDimitry Andric   const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
690*0b57cec5SDimitry Andric   const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
691*0b57cec5SDimitry Andric }
692*0b57cec5SDimitry Andric 
693*0b57cec5SDimitry Andric StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
694*0b57cec5SDimitry Andric   bool MyInvalid = false;
695*0b57cec5SDimitry Andric   const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
696*0b57cec5SDimitry Andric   if (!SLoc.isFile() || MyInvalid) {
697*0b57cec5SDimitry Andric     if (Invalid)
698*0b57cec5SDimitry Andric       *Invalid = true;
699*0b57cec5SDimitry Andric     return "<<<<<INVALID SOURCE LOCATION>>>>>";
700*0b57cec5SDimitry Andric   }
701*0b57cec5SDimitry Andric 
702*0b57cec5SDimitry Andric   const llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
703*0b57cec5SDimitry Andric       Diag, *this, SourceLocation(), &MyInvalid);
704*0b57cec5SDimitry Andric   if (Invalid)
705*0b57cec5SDimitry Andric     *Invalid = MyInvalid;
706*0b57cec5SDimitry Andric 
707*0b57cec5SDimitry Andric   if (MyInvalid)
708*0b57cec5SDimitry Andric     return "<<<<<INVALID SOURCE LOCATION>>>>>";
709*0b57cec5SDimitry Andric 
710*0b57cec5SDimitry Andric   return Buf->getBuffer();
711*0b57cec5SDimitry Andric }
712*0b57cec5SDimitry Andric 
713*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
714*0b57cec5SDimitry Andric // SourceLocation manipulation methods.
715*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
716*0b57cec5SDimitry Andric 
717*0b57cec5SDimitry Andric /// Return the FileID for a SourceLocation.
718*0b57cec5SDimitry Andric ///
719*0b57cec5SDimitry Andric /// This is the cache-miss path of getFileID. Not as hot as that function, but
720*0b57cec5SDimitry Andric /// still very important. It is responsible for finding the entry in the
721*0b57cec5SDimitry Andric /// SLocEntry tables that contains the specified location.
722*0b57cec5SDimitry Andric FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
723*0b57cec5SDimitry Andric   if (!SLocOffset)
724*0b57cec5SDimitry Andric     return FileID::get(0);
725*0b57cec5SDimitry Andric 
726*0b57cec5SDimitry Andric   // Now it is time to search for the correct file. See where the SLocOffset
727*0b57cec5SDimitry Andric   // sits in the global view and consult local or loaded buffers for it.
728*0b57cec5SDimitry Andric   if (SLocOffset < NextLocalOffset)
729*0b57cec5SDimitry Andric     return getFileIDLocal(SLocOffset);
730*0b57cec5SDimitry Andric   return getFileIDLoaded(SLocOffset);
731*0b57cec5SDimitry Andric }
732*0b57cec5SDimitry Andric 
733*0b57cec5SDimitry Andric /// Return the FileID for a SourceLocation with a low offset.
734*0b57cec5SDimitry Andric ///
735*0b57cec5SDimitry Andric /// This function knows that the SourceLocation is in a local buffer, not a
736*0b57cec5SDimitry Andric /// loaded one.
737*0b57cec5SDimitry Andric FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
738*0b57cec5SDimitry Andric   assert(SLocOffset < NextLocalOffset && "Bad function choice");
739*0b57cec5SDimitry Andric 
740*0b57cec5SDimitry Andric   // After the first and second level caches, I see two common sorts of
741*0b57cec5SDimitry Andric   // behavior: 1) a lot of searched FileID's are "near" the cached file
742*0b57cec5SDimitry Andric   // location or are "near" the cached expansion location. 2) others are just
743*0b57cec5SDimitry Andric   // completely random and may be a very long way away.
744*0b57cec5SDimitry Andric   //
745*0b57cec5SDimitry Andric   // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
746*0b57cec5SDimitry Andric   // then we fall back to a less cache efficient, but more scalable, binary
747*0b57cec5SDimitry Andric   // search to find the location.
748*0b57cec5SDimitry Andric 
749*0b57cec5SDimitry Andric   // See if this is near the file point - worst case we start scanning from the
750*0b57cec5SDimitry Andric   // most newly created FileID.
751*0b57cec5SDimitry Andric   const SrcMgr::SLocEntry *I;
752*0b57cec5SDimitry Andric 
753*0b57cec5SDimitry Andric   if (LastFileIDLookup.ID < 0 ||
754*0b57cec5SDimitry Andric       LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
755*0b57cec5SDimitry Andric     // Neither loc prunes our search.
756*0b57cec5SDimitry Andric     I = LocalSLocEntryTable.end();
757*0b57cec5SDimitry Andric   } else {
758*0b57cec5SDimitry Andric     // Perhaps it is near the file point.
759*0b57cec5SDimitry Andric     I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
760*0b57cec5SDimitry Andric   }
761*0b57cec5SDimitry Andric 
762*0b57cec5SDimitry Andric   // Find the FileID that contains this.  "I" is an iterator that points to a
763*0b57cec5SDimitry Andric   // FileID whose offset is known to be larger than SLocOffset.
764*0b57cec5SDimitry Andric   unsigned NumProbes = 0;
765*0b57cec5SDimitry Andric   while (true) {
766*0b57cec5SDimitry Andric     --I;
767*0b57cec5SDimitry Andric     if (I->getOffset() <= SLocOffset) {
768*0b57cec5SDimitry Andric       FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
769*0b57cec5SDimitry Andric 
770*0b57cec5SDimitry Andric       // If this isn't an expansion, remember it.  We have good locality across
771*0b57cec5SDimitry Andric       // FileID lookups.
772*0b57cec5SDimitry Andric       if (!I->isExpansion())
773*0b57cec5SDimitry Andric         LastFileIDLookup = Res;
774*0b57cec5SDimitry Andric       NumLinearScans += NumProbes+1;
775*0b57cec5SDimitry Andric       return Res;
776*0b57cec5SDimitry Andric     }
777*0b57cec5SDimitry Andric     if (++NumProbes == 8)
778*0b57cec5SDimitry Andric       break;
779*0b57cec5SDimitry Andric   }
780*0b57cec5SDimitry Andric 
781*0b57cec5SDimitry Andric   // Convert "I" back into an index.  We know that it is an entry whose index is
782*0b57cec5SDimitry Andric   // larger than the offset we are looking for.
783*0b57cec5SDimitry Andric   unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
784*0b57cec5SDimitry Andric   // LessIndex - This is the lower bound of the range that we're searching.
785*0b57cec5SDimitry Andric   // We know that the offset corresponding to the FileID is is less than
786*0b57cec5SDimitry Andric   // SLocOffset.
787*0b57cec5SDimitry Andric   unsigned LessIndex = 0;
788*0b57cec5SDimitry Andric   NumProbes = 0;
789*0b57cec5SDimitry Andric   while (true) {
790*0b57cec5SDimitry Andric     bool Invalid = false;
791*0b57cec5SDimitry Andric     unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
792*0b57cec5SDimitry Andric     unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
793*0b57cec5SDimitry Andric     if (Invalid)
794*0b57cec5SDimitry Andric       return FileID::get(0);
795*0b57cec5SDimitry Andric 
796*0b57cec5SDimitry Andric     ++NumProbes;
797*0b57cec5SDimitry Andric 
798*0b57cec5SDimitry Andric     // If the offset of the midpoint is too large, chop the high side of the
799*0b57cec5SDimitry Andric     // range to the midpoint.
800*0b57cec5SDimitry Andric     if (MidOffset > SLocOffset) {
801*0b57cec5SDimitry Andric       GreaterIndex = MiddleIndex;
802*0b57cec5SDimitry Andric       continue;
803*0b57cec5SDimitry Andric     }
804*0b57cec5SDimitry Andric 
805*0b57cec5SDimitry Andric     // If the middle index contains the value, succeed and return.
806*0b57cec5SDimitry Andric     // FIXME: This could be made faster by using a function that's aware of
807*0b57cec5SDimitry Andric     // being in the local area.
808*0b57cec5SDimitry Andric     if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
809*0b57cec5SDimitry Andric       FileID Res = FileID::get(MiddleIndex);
810*0b57cec5SDimitry Andric 
811*0b57cec5SDimitry Andric       // If this isn't a macro expansion, remember it.  We have good locality
812*0b57cec5SDimitry Andric       // across FileID lookups.
813*0b57cec5SDimitry Andric       if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
814*0b57cec5SDimitry Andric         LastFileIDLookup = Res;
815*0b57cec5SDimitry Andric       NumBinaryProbes += NumProbes;
816*0b57cec5SDimitry Andric       return Res;
817*0b57cec5SDimitry Andric     }
818*0b57cec5SDimitry Andric 
819*0b57cec5SDimitry Andric     // Otherwise, move the low-side up to the middle index.
820*0b57cec5SDimitry Andric     LessIndex = MiddleIndex;
821*0b57cec5SDimitry Andric   }
822*0b57cec5SDimitry Andric }
823*0b57cec5SDimitry Andric 
824*0b57cec5SDimitry Andric /// Return the FileID for a SourceLocation with a high offset.
825*0b57cec5SDimitry Andric ///
826*0b57cec5SDimitry Andric /// This function knows that the SourceLocation is in a loaded buffer, not a
827*0b57cec5SDimitry Andric /// local one.
828*0b57cec5SDimitry Andric FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
829*0b57cec5SDimitry Andric   // Sanity checking, otherwise a bug may lead to hanging in release build.
830*0b57cec5SDimitry Andric   if (SLocOffset < CurrentLoadedOffset) {
831*0b57cec5SDimitry Andric     assert(0 && "Invalid SLocOffset or bad function choice");
832*0b57cec5SDimitry Andric     return FileID();
833*0b57cec5SDimitry Andric   }
834*0b57cec5SDimitry Andric 
835*0b57cec5SDimitry Andric   // Essentially the same as the local case, but the loaded array is sorted
836*0b57cec5SDimitry Andric   // in the other direction.
837*0b57cec5SDimitry Andric 
838*0b57cec5SDimitry Andric   // First do a linear scan from the last lookup position, if possible.
839*0b57cec5SDimitry Andric   unsigned I;
840*0b57cec5SDimitry Andric   int LastID = LastFileIDLookup.ID;
841*0b57cec5SDimitry Andric   if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
842*0b57cec5SDimitry Andric     I = 0;
843*0b57cec5SDimitry Andric   else
844*0b57cec5SDimitry Andric     I = (-LastID - 2) + 1;
845*0b57cec5SDimitry Andric 
846*0b57cec5SDimitry Andric   unsigned NumProbes;
847*0b57cec5SDimitry Andric   for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
848*0b57cec5SDimitry Andric     // Make sure the entry is loaded!
849*0b57cec5SDimitry Andric     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
850*0b57cec5SDimitry Andric     if (E.getOffset() <= SLocOffset) {
851*0b57cec5SDimitry Andric       FileID Res = FileID::get(-int(I) - 2);
852*0b57cec5SDimitry Andric 
853*0b57cec5SDimitry Andric       if (!E.isExpansion())
854*0b57cec5SDimitry Andric         LastFileIDLookup = Res;
855*0b57cec5SDimitry Andric       NumLinearScans += NumProbes + 1;
856*0b57cec5SDimitry Andric       return Res;
857*0b57cec5SDimitry Andric     }
858*0b57cec5SDimitry Andric   }
859*0b57cec5SDimitry Andric 
860*0b57cec5SDimitry Andric   // Linear scan failed. Do the binary search. Note the reverse sorting of the
861*0b57cec5SDimitry Andric   // table: GreaterIndex is the one where the offset is greater, which is
862*0b57cec5SDimitry Andric   // actually a lower index!
863*0b57cec5SDimitry Andric   unsigned GreaterIndex = I;
864*0b57cec5SDimitry Andric   unsigned LessIndex = LoadedSLocEntryTable.size();
865*0b57cec5SDimitry Andric   NumProbes = 0;
866*0b57cec5SDimitry Andric   while (true) {
867*0b57cec5SDimitry Andric     ++NumProbes;
868*0b57cec5SDimitry Andric     unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
869*0b57cec5SDimitry Andric     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
870*0b57cec5SDimitry Andric     if (E.getOffset() == 0)
871*0b57cec5SDimitry Andric       return FileID(); // invalid entry.
872*0b57cec5SDimitry Andric 
873*0b57cec5SDimitry Andric     ++NumProbes;
874*0b57cec5SDimitry Andric 
875*0b57cec5SDimitry Andric     if (E.getOffset() > SLocOffset) {
876*0b57cec5SDimitry Andric       // Sanity checking, otherwise a bug may lead to hanging in release build.
877*0b57cec5SDimitry Andric       if (GreaterIndex == MiddleIndex) {
878*0b57cec5SDimitry Andric         assert(0 && "binary search missed the entry");
879*0b57cec5SDimitry Andric         return FileID();
880*0b57cec5SDimitry Andric       }
881*0b57cec5SDimitry Andric       GreaterIndex = MiddleIndex;
882*0b57cec5SDimitry Andric       continue;
883*0b57cec5SDimitry Andric     }
884*0b57cec5SDimitry Andric 
885*0b57cec5SDimitry Andric     if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
886*0b57cec5SDimitry Andric       FileID Res = FileID::get(-int(MiddleIndex) - 2);
887*0b57cec5SDimitry Andric       if (!E.isExpansion())
888*0b57cec5SDimitry Andric         LastFileIDLookup = Res;
889*0b57cec5SDimitry Andric       NumBinaryProbes += NumProbes;
890*0b57cec5SDimitry Andric       return Res;
891*0b57cec5SDimitry Andric     }
892*0b57cec5SDimitry Andric 
893*0b57cec5SDimitry Andric     // Sanity checking, otherwise a bug may lead to hanging in release build.
894*0b57cec5SDimitry Andric     if (LessIndex == MiddleIndex) {
895*0b57cec5SDimitry Andric       assert(0 && "binary search missed the entry");
896*0b57cec5SDimitry Andric       return FileID();
897*0b57cec5SDimitry Andric     }
898*0b57cec5SDimitry Andric     LessIndex = MiddleIndex;
899*0b57cec5SDimitry Andric   }
900*0b57cec5SDimitry Andric }
901*0b57cec5SDimitry Andric 
902*0b57cec5SDimitry Andric SourceLocation SourceManager::
903*0b57cec5SDimitry Andric getExpansionLocSlowCase(SourceLocation Loc) const {
904*0b57cec5SDimitry Andric   do {
905*0b57cec5SDimitry Andric     // Note: If Loc indicates an offset into a token that came from a macro
906*0b57cec5SDimitry Andric     // expansion (e.g. the 5th character of the token) we do not want to add
907*0b57cec5SDimitry Andric     // this offset when going to the expansion location.  The expansion
908*0b57cec5SDimitry Andric     // location is the macro invocation, which the offset has nothing to do
909*0b57cec5SDimitry Andric     // with.  This is unlike when we get the spelling loc, because the offset
910*0b57cec5SDimitry Andric     // directly correspond to the token whose spelling we're inspecting.
911*0b57cec5SDimitry Andric     Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
912*0b57cec5SDimitry Andric   } while (!Loc.isFileID());
913*0b57cec5SDimitry Andric 
914*0b57cec5SDimitry Andric   return Loc;
915*0b57cec5SDimitry Andric }
916*0b57cec5SDimitry Andric 
917*0b57cec5SDimitry Andric SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
918*0b57cec5SDimitry Andric   do {
919*0b57cec5SDimitry Andric     std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
920*0b57cec5SDimitry Andric     Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
921*0b57cec5SDimitry Andric     Loc = Loc.getLocWithOffset(LocInfo.second);
922*0b57cec5SDimitry Andric   } while (!Loc.isFileID());
923*0b57cec5SDimitry Andric   return Loc;
924*0b57cec5SDimitry Andric }
925*0b57cec5SDimitry Andric 
926*0b57cec5SDimitry Andric SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
927*0b57cec5SDimitry Andric   do {
928*0b57cec5SDimitry Andric     if (isMacroArgExpansion(Loc))
929*0b57cec5SDimitry Andric       Loc = getImmediateSpellingLoc(Loc);
930*0b57cec5SDimitry Andric     else
931*0b57cec5SDimitry Andric       Loc = getImmediateExpansionRange(Loc).getBegin();
932*0b57cec5SDimitry Andric   } while (!Loc.isFileID());
933*0b57cec5SDimitry Andric   return Loc;
934*0b57cec5SDimitry Andric }
935*0b57cec5SDimitry Andric 
936*0b57cec5SDimitry Andric 
937*0b57cec5SDimitry Andric std::pair<FileID, unsigned>
938*0b57cec5SDimitry Andric SourceManager::getDecomposedExpansionLocSlowCase(
939*0b57cec5SDimitry Andric                                              const SrcMgr::SLocEntry *E) const {
940*0b57cec5SDimitry Andric   // If this is an expansion record, walk through all the expansion points.
941*0b57cec5SDimitry Andric   FileID FID;
942*0b57cec5SDimitry Andric   SourceLocation Loc;
943*0b57cec5SDimitry Andric   unsigned Offset;
944*0b57cec5SDimitry Andric   do {
945*0b57cec5SDimitry Andric     Loc = E->getExpansion().getExpansionLocStart();
946*0b57cec5SDimitry Andric 
947*0b57cec5SDimitry Andric     FID = getFileID(Loc);
948*0b57cec5SDimitry Andric     E = &getSLocEntry(FID);
949*0b57cec5SDimitry Andric     Offset = Loc.getOffset()-E->getOffset();
950*0b57cec5SDimitry Andric   } while (!Loc.isFileID());
951*0b57cec5SDimitry Andric 
952*0b57cec5SDimitry Andric   return std::make_pair(FID, Offset);
953*0b57cec5SDimitry Andric }
954*0b57cec5SDimitry Andric 
955*0b57cec5SDimitry Andric std::pair<FileID, unsigned>
956*0b57cec5SDimitry Andric SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
957*0b57cec5SDimitry Andric                                                 unsigned Offset) const {
958*0b57cec5SDimitry Andric   // If this is an expansion record, walk through all the expansion points.
959*0b57cec5SDimitry Andric   FileID FID;
960*0b57cec5SDimitry Andric   SourceLocation Loc;
961*0b57cec5SDimitry Andric   do {
962*0b57cec5SDimitry Andric     Loc = E->getExpansion().getSpellingLoc();
963*0b57cec5SDimitry Andric     Loc = Loc.getLocWithOffset(Offset);
964*0b57cec5SDimitry Andric 
965*0b57cec5SDimitry Andric     FID = getFileID(Loc);
966*0b57cec5SDimitry Andric     E = &getSLocEntry(FID);
967*0b57cec5SDimitry Andric     Offset = Loc.getOffset()-E->getOffset();
968*0b57cec5SDimitry Andric   } while (!Loc.isFileID());
969*0b57cec5SDimitry Andric 
970*0b57cec5SDimitry Andric   return std::make_pair(FID, Offset);
971*0b57cec5SDimitry Andric }
972*0b57cec5SDimitry Andric 
973*0b57cec5SDimitry Andric /// getImmediateSpellingLoc - Given a SourceLocation object, return the
974*0b57cec5SDimitry Andric /// spelling location referenced by the ID.  This is the first level down
975*0b57cec5SDimitry Andric /// towards the place where the characters that make up the lexed token can be
976*0b57cec5SDimitry Andric /// found.  This should not generally be used by clients.
977*0b57cec5SDimitry Andric SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
978*0b57cec5SDimitry Andric   if (Loc.isFileID()) return Loc;
979*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
980*0b57cec5SDimitry Andric   Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
981*0b57cec5SDimitry Andric   return Loc.getLocWithOffset(LocInfo.second);
982*0b57cec5SDimitry Andric }
983*0b57cec5SDimitry Andric 
984*0b57cec5SDimitry Andric /// getImmediateExpansionRange - Loc is required to be an expansion location.
985*0b57cec5SDimitry Andric /// Return the start/end of the expansion information.
986*0b57cec5SDimitry Andric CharSourceRange
987*0b57cec5SDimitry Andric SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
988*0b57cec5SDimitry Andric   assert(Loc.isMacroID() && "Not a macro expansion loc!");
989*0b57cec5SDimitry Andric   const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
990*0b57cec5SDimitry Andric   return Expansion.getExpansionLocRange();
991*0b57cec5SDimitry Andric }
992*0b57cec5SDimitry Andric 
993*0b57cec5SDimitry Andric SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
994*0b57cec5SDimitry Andric   while (isMacroArgExpansion(Loc))
995*0b57cec5SDimitry Andric     Loc = getImmediateSpellingLoc(Loc);
996*0b57cec5SDimitry Andric   return Loc;
997*0b57cec5SDimitry Andric }
998*0b57cec5SDimitry Andric 
999*0b57cec5SDimitry Andric /// getExpansionRange - Given a SourceLocation object, return the range of
1000*0b57cec5SDimitry Andric /// tokens covered by the expansion in the ultimate file.
1001*0b57cec5SDimitry Andric CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
1002*0b57cec5SDimitry Andric   if (Loc.isFileID())
1003*0b57cec5SDimitry Andric     return CharSourceRange(SourceRange(Loc, Loc), true);
1004*0b57cec5SDimitry Andric 
1005*0b57cec5SDimitry Andric   CharSourceRange Res = getImmediateExpansionRange(Loc);
1006*0b57cec5SDimitry Andric 
1007*0b57cec5SDimitry Andric   // Fully resolve the start and end locations to their ultimate expansion
1008*0b57cec5SDimitry Andric   // points.
1009*0b57cec5SDimitry Andric   while (!Res.getBegin().isFileID())
1010*0b57cec5SDimitry Andric     Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
1011*0b57cec5SDimitry Andric   while (!Res.getEnd().isFileID()) {
1012*0b57cec5SDimitry Andric     CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
1013*0b57cec5SDimitry Andric     Res.setEnd(EndRange.getEnd());
1014*0b57cec5SDimitry Andric     Res.setTokenRange(EndRange.isTokenRange());
1015*0b57cec5SDimitry Andric   }
1016*0b57cec5SDimitry Andric   return Res;
1017*0b57cec5SDimitry Andric }
1018*0b57cec5SDimitry Andric 
1019*0b57cec5SDimitry Andric bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1020*0b57cec5SDimitry Andric                                         SourceLocation *StartLoc) const {
1021*0b57cec5SDimitry Andric   if (!Loc.isMacroID()) return false;
1022*0b57cec5SDimitry Andric 
1023*0b57cec5SDimitry Andric   FileID FID = getFileID(Loc);
1024*0b57cec5SDimitry Andric   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1025*0b57cec5SDimitry Andric   if (!Expansion.isMacroArgExpansion()) return false;
1026*0b57cec5SDimitry Andric 
1027*0b57cec5SDimitry Andric   if (StartLoc)
1028*0b57cec5SDimitry Andric     *StartLoc = Expansion.getExpansionLocStart();
1029*0b57cec5SDimitry Andric   return true;
1030*0b57cec5SDimitry Andric }
1031*0b57cec5SDimitry Andric 
1032*0b57cec5SDimitry Andric bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1033*0b57cec5SDimitry Andric   if (!Loc.isMacroID()) return false;
1034*0b57cec5SDimitry Andric 
1035*0b57cec5SDimitry Andric   FileID FID = getFileID(Loc);
1036*0b57cec5SDimitry Andric   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1037*0b57cec5SDimitry Andric   return Expansion.isMacroBodyExpansion();
1038*0b57cec5SDimitry Andric }
1039*0b57cec5SDimitry Andric 
1040*0b57cec5SDimitry Andric bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1041*0b57cec5SDimitry Andric                                              SourceLocation *MacroBegin) const {
1042*0b57cec5SDimitry Andric   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1043*0b57cec5SDimitry Andric 
1044*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1045*0b57cec5SDimitry Andric   if (DecompLoc.second > 0)
1046*0b57cec5SDimitry Andric     return false; // Does not point at the start of expansion range.
1047*0b57cec5SDimitry Andric 
1048*0b57cec5SDimitry Andric   bool Invalid = false;
1049*0b57cec5SDimitry Andric   const SrcMgr::ExpansionInfo &ExpInfo =
1050*0b57cec5SDimitry Andric       getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1051*0b57cec5SDimitry Andric   if (Invalid)
1052*0b57cec5SDimitry Andric     return false;
1053*0b57cec5SDimitry Andric   SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1054*0b57cec5SDimitry Andric 
1055*0b57cec5SDimitry Andric   if (ExpInfo.isMacroArgExpansion()) {
1056*0b57cec5SDimitry Andric     // For macro argument expansions, check if the previous FileID is part of
1057*0b57cec5SDimitry Andric     // the same argument expansion, in which case this Loc is not at the
1058*0b57cec5SDimitry Andric     // beginning of the expansion.
1059*0b57cec5SDimitry Andric     FileID PrevFID = getPreviousFileID(DecompLoc.first);
1060*0b57cec5SDimitry Andric     if (!PrevFID.isInvalid()) {
1061*0b57cec5SDimitry Andric       const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1062*0b57cec5SDimitry Andric       if (Invalid)
1063*0b57cec5SDimitry Andric         return false;
1064*0b57cec5SDimitry Andric       if (PrevEntry.isExpansion() &&
1065*0b57cec5SDimitry Andric           PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1066*0b57cec5SDimitry Andric         return false;
1067*0b57cec5SDimitry Andric     }
1068*0b57cec5SDimitry Andric   }
1069*0b57cec5SDimitry Andric 
1070*0b57cec5SDimitry Andric   if (MacroBegin)
1071*0b57cec5SDimitry Andric     *MacroBegin = ExpLoc;
1072*0b57cec5SDimitry Andric   return true;
1073*0b57cec5SDimitry Andric }
1074*0b57cec5SDimitry Andric 
1075*0b57cec5SDimitry Andric bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1076*0b57cec5SDimitry Andric                                                SourceLocation *MacroEnd) const {
1077*0b57cec5SDimitry Andric   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1078*0b57cec5SDimitry Andric 
1079*0b57cec5SDimitry Andric   FileID FID = getFileID(Loc);
1080*0b57cec5SDimitry Andric   SourceLocation NextLoc = Loc.getLocWithOffset(1);
1081*0b57cec5SDimitry Andric   if (isInFileID(NextLoc, FID))
1082*0b57cec5SDimitry Andric     return false; // Does not point at the end of expansion range.
1083*0b57cec5SDimitry Andric 
1084*0b57cec5SDimitry Andric   bool Invalid = false;
1085*0b57cec5SDimitry Andric   const SrcMgr::ExpansionInfo &ExpInfo =
1086*0b57cec5SDimitry Andric       getSLocEntry(FID, &Invalid).getExpansion();
1087*0b57cec5SDimitry Andric   if (Invalid)
1088*0b57cec5SDimitry Andric     return false;
1089*0b57cec5SDimitry Andric 
1090*0b57cec5SDimitry Andric   if (ExpInfo.isMacroArgExpansion()) {
1091*0b57cec5SDimitry Andric     // For macro argument expansions, check if the next FileID is part of the
1092*0b57cec5SDimitry Andric     // same argument expansion, in which case this Loc is not at the end of the
1093*0b57cec5SDimitry Andric     // expansion.
1094*0b57cec5SDimitry Andric     FileID NextFID = getNextFileID(FID);
1095*0b57cec5SDimitry Andric     if (!NextFID.isInvalid()) {
1096*0b57cec5SDimitry Andric       const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1097*0b57cec5SDimitry Andric       if (Invalid)
1098*0b57cec5SDimitry Andric         return false;
1099*0b57cec5SDimitry Andric       if (NextEntry.isExpansion() &&
1100*0b57cec5SDimitry Andric           NextEntry.getExpansion().getExpansionLocStart() ==
1101*0b57cec5SDimitry Andric               ExpInfo.getExpansionLocStart())
1102*0b57cec5SDimitry Andric         return false;
1103*0b57cec5SDimitry Andric     }
1104*0b57cec5SDimitry Andric   }
1105*0b57cec5SDimitry Andric 
1106*0b57cec5SDimitry Andric   if (MacroEnd)
1107*0b57cec5SDimitry Andric     *MacroEnd = ExpInfo.getExpansionLocEnd();
1108*0b57cec5SDimitry Andric   return true;
1109*0b57cec5SDimitry Andric }
1110*0b57cec5SDimitry Andric 
1111*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1112*0b57cec5SDimitry Andric // Queries about the code at a SourceLocation.
1113*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1114*0b57cec5SDimitry Andric 
1115*0b57cec5SDimitry Andric /// getCharacterData - Return a pointer to the start of the specified location
1116*0b57cec5SDimitry Andric /// in the appropriate MemoryBuffer.
1117*0b57cec5SDimitry Andric const char *SourceManager::getCharacterData(SourceLocation SL,
1118*0b57cec5SDimitry Andric                                             bool *Invalid) const {
1119*0b57cec5SDimitry Andric   // Note that this is a hot function in the getSpelling() path, which is
1120*0b57cec5SDimitry Andric   // heavily used by -E mode.
1121*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1122*0b57cec5SDimitry Andric 
1123*0b57cec5SDimitry Andric   // Note that calling 'getBuffer()' may lazily page in a source file.
1124*0b57cec5SDimitry Andric   bool CharDataInvalid = false;
1125*0b57cec5SDimitry Andric   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1126*0b57cec5SDimitry Andric   if (CharDataInvalid || !Entry.isFile()) {
1127*0b57cec5SDimitry Andric     if (Invalid)
1128*0b57cec5SDimitry Andric       *Invalid = true;
1129*0b57cec5SDimitry Andric 
1130*0b57cec5SDimitry Andric     return "<<<<INVALID BUFFER>>>>";
1131*0b57cec5SDimitry Andric   }
1132*0b57cec5SDimitry Andric   const llvm::MemoryBuffer *Buffer =
1133*0b57cec5SDimitry Andric       Entry.getFile().getContentCache()->getBuffer(
1134*0b57cec5SDimitry Andric           Diag, *this, SourceLocation(), &CharDataInvalid);
1135*0b57cec5SDimitry Andric   if (Invalid)
1136*0b57cec5SDimitry Andric     *Invalid = CharDataInvalid;
1137*0b57cec5SDimitry Andric   return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1138*0b57cec5SDimitry Andric }
1139*0b57cec5SDimitry Andric 
1140*0b57cec5SDimitry Andric /// getColumnNumber - Return the column # for the specified file position.
1141*0b57cec5SDimitry Andric /// this is significantly cheaper to compute than the line number.
1142*0b57cec5SDimitry Andric unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1143*0b57cec5SDimitry Andric                                         bool *Invalid) const {
1144*0b57cec5SDimitry Andric   bool MyInvalid = false;
1145*0b57cec5SDimitry Andric   const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1146*0b57cec5SDimitry Andric   if (Invalid)
1147*0b57cec5SDimitry Andric     *Invalid = MyInvalid;
1148*0b57cec5SDimitry Andric 
1149*0b57cec5SDimitry Andric   if (MyInvalid)
1150*0b57cec5SDimitry Andric     return 1;
1151*0b57cec5SDimitry Andric 
1152*0b57cec5SDimitry Andric   // It is okay to request a position just past the end of the buffer.
1153*0b57cec5SDimitry Andric   if (FilePos > MemBuf->getBufferSize()) {
1154*0b57cec5SDimitry Andric     if (Invalid)
1155*0b57cec5SDimitry Andric       *Invalid = true;
1156*0b57cec5SDimitry Andric     return 1;
1157*0b57cec5SDimitry Andric   }
1158*0b57cec5SDimitry Andric 
1159*0b57cec5SDimitry Andric   const char *Buf = MemBuf->getBufferStart();
1160*0b57cec5SDimitry Andric   // See if we just calculated the line number for this FilePos and can use
1161*0b57cec5SDimitry Andric   // that to lookup the start of the line instead of searching for it.
1162*0b57cec5SDimitry Andric   if (LastLineNoFileIDQuery == FID &&
1163*0b57cec5SDimitry Andric       LastLineNoContentCache->SourceLineCache != nullptr &&
1164*0b57cec5SDimitry Andric       LastLineNoResult < LastLineNoContentCache->NumLines) {
1165*0b57cec5SDimitry Andric     unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1166*0b57cec5SDimitry Andric     unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1167*0b57cec5SDimitry Andric     unsigned LineEnd = SourceLineCache[LastLineNoResult];
1168*0b57cec5SDimitry Andric     if (FilePos >= LineStart && FilePos < LineEnd) {
1169*0b57cec5SDimitry Andric       // LineEnd is the LineStart of the next line.
1170*0b57cec5SDimitry Andric       // A line ends with separator LF or CR+LF on Windows.
1171*0b57cec5SDimitry Andric       // FilePos might point to the last separator,
1172*0b57cec5SDimitry Andric       // but we need a column number at most 1 + the last column.
1173*0b57cec5SDimitry Andric       if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1174*0b57cec5SDimitry Andric         if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1175*0b57cec5SDimitry Andric           --FilePos;
1176*0b57cec5SDimitry Andric       }
1177*0b57cec5SDimitry Andric       return FilePos - LineStart + 1;
1178*0b57cec5SDimitry Andric     }
1179*0b57cec5SDimitry Andric   }
1180*0b57cec5SDimitry Andric 
1181*0b57cec5SDimitry Andric   unsigned LineStart = FilePos;
1182*0b57cec5SDimitry Andric   while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1183*0b57cec5SDimitry Andric     --LineStart;
1184*0b57cec5SDimitry Andric   return FilePos-LineStart+1;
1185*0b57cec5SDimitry Andric }
1186*0b57cec5SDimitry Andric 
1187*0b57cec5SDimitry Andric // isInvalid - Return the result of calling loc.isInvalid(), and
1188*0b57cec5SDimitry Andric // if Invalid is not null, set its value to same.
1189*0b57cec5SDimitry Andric template<typename LocType>
1190*0b57cec5SDimitry Andric static bool isInvalid(LocType Loc, bool *Invalid) {
1191*0b57cec5SDimitry Andric   bool MyInvalid = Loc.isInvalid();
1192*0b57cec5SDimitry Andric   if (Invalid)
1193*0b57cec5SDimitry Andric     *Invalid = MyInvalid;
1194*0b57cec5SDimitry Andric   return MyInvalid;
1195*0b57cec5SDimitry Andric }
1196*0b57cec5SDimitry Andric 
1197*0b57cec5SDimitry Andric unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1198*0b57cec5SDimitry Andric                                                 bool *Invalid) const {
1199*0b57cec5SDimitry Andric   if (isInvalid(Loc, Invalid)) return 0;
1200*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1201*0b57cec5SDimitry Andric   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1202*0b57cec5SDimitry Andric }
1203*0b57cec5SDimitry Andric 
1204*0b57cec5SDimitry Andric unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1205*0b57cec5SDimitry Andric                                                  bool *Invalid) const {
1206*0b57cec5SDimitry Andric   if (isInvalid(Loc, Invalid)) return 0;
1207*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1208*0b57cec5SDimitry Andric   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1209*0b57cec5SDimitry Andric }
1210*0b57cec5SDimitry Andric 
1211*0b57cec5SDimitry Andric unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1212*0b57cec5SDimitry Andric                                                 bool *Invalid) const {
1213*0b57cec5SDimitry Andric   PresumedLoc PLoc = getPresumedLoc(Loc);
1214*0b57cec5SDimitry Andric   if (isInvalid(PLoc, Invalid)) return 0;
1215*0b57cec5SDimitry Andric   return PLoc.getColumn();
1216*0b57cec5SDimitry Andric }
1217*0b57cec5SDimitry Andric 
1218*0b57cec5SDimitry Andric #ifdef __SSE2__
1219*0b57cec5SDimitry Andric #include <emmintrin.h>
1220*0b57cec5SDimitry Andric #endif
1221*0b57cec5SDimitry Andric 
1222*0b57cec5SDimitry Andric static LLVM_ATTRIBUTE_NOINLINE void
1223*0b57cec5SDimitry Andric ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1224*0b57cec5SDimitry Andric                    llvm::BumpPtrAllocator &Alloc,
1225*0b57cec5SDimitry Andric                    const SourceManager &SM, bool &Invalid);
1226*0b57cec5SDimitry Andric static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1227*0b57cec5SDimitry Andric                                llvm::BumpPtrAllocator &Alloc,
1228*0b57cec5SDimitry Andric                                const SourceManager &SM, bool &Invalid) {
1229*0b57cec5SDimitry Andric   // Note that calling 'getBuffer()' may lazily page in the file.
1230*0b57cec5SDimitry Andric   const MemoryBuffer *Buffer =
1231*0b57cec5SDimitry Andric       FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
1232*0b57cec5SDimitry Andric   if (Invalid)
1233*0b57cec5SDimitry Andric     return;
1234*0b57cec5SDimitry Andric 
1235*0b57cec5SDimitry Andric   // Find the file offsets of all of the *physical* source lines.  This does
1236*0b57cec5SDimitry Andric   // not look at trigraphs, escaped newlines, or anything else tricky.
1237*0b57cec5SDimitry Andric   SmallVector<unsigned, 256> LineOffsets;
1238*0b57cec5SDimitry Andric 
1239*0b57cec5SDimitry Andric   // Line #1 starts at char 0.
1240*0b57cec5SDimitry Andric   LineOffsets.push_back(0);
1241*0b57cec5SDimitry Andric 
1242*0b57cec5SDimitry Andric   const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1243*0b57cec5SDimitry Andric   const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1244*0b57cec5SDimitry Andric   unsigned I = 0;
1245*0b57cec5SDimitry Andric   while (true) {
1246*0b57cec5SDimitry Andric     // Skip over the contents of the line.
1247*0b57cec5SDimitry Andric     while (Buf[I] != '\n' && Buf[I] != '\r' && Buf[I] != '\0')
1248*0b57cec5SDimitry Andric       ++I;
1249*0b57cec5SDimitry Andric 
1250*0b57cec5SDimitry Andric     if (Buf[I] == '\n' || Buf[I] == '\r') {
1251*0b57cec5SDimitry Andric       // If this is \r\n, skip both characters.
1252*0b57cec5SDimitry Andric       if (Buf[I] == '\r' && Buf[I+1] == '\n')
1253*0b57cec5SDimitry Andric         ++I;
1254*0b57cec5SDimitry Andric       ++I;
1255*0b57cec5SDimitry Andric       LineOffsets.push_back(I);
1256*0b57cec5SDimitry Andric     } else {
1257*0b57cec5SDimitry Andric       // Otherwise, this is a NUL. If end of file, exit.
1258*0b57cec5SDimitry Andric       if (Buf+I == End) break;
1259*0b57cec5SDimitry Andric       ++I;
1260*0b57cec5SDimitry Andric     }
1261*0b57cec5SDimitry Andric   }
1262*0b57cec5SDimitry Andric 
1263*0b57cec5SDimitry Andric   // Copy the offsets into the FileInfo structure.
1264*0b57cec5SDimitry Andric   FI->NumLines = LineOffsets.size();
1265*0b57cec5SDimitry Andric   FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1266*0b57cec5SDimitry Andric   std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1267*0b57cec5SDimitry Andric }
1268*0b57cec5SDimitry Andric 
1269*0b57cec5SDimitry Andric /// getLineNumber - Given a SourceLocation, return the spelling line number
1270*0b57cec5SDimitry Andric /// for the position indicated.  This requires building and caching a table of
1271*0b57cec5SDimitry Andric /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1272*0b57cec5SDimitry Andric /// about to emit a diagnostic.
1273*0b57cec5SDimitry Andric unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1274*0b57cec5SDimitry Andric                                       bool *Invalid) const {
1275*0b57cec5SDimitry Andric   if (FID.isInvalid()) {
1276*0b57cec5SDimitry Andric     if (Invalid)
1277*0b57cec5SDimitry Andric       *Invalid = true;
1278*0b57cec5SDimitry Andric     return 1;
1279*0b57cec5SDimitry Andric   }
1280*0b57cec5SDimitry Andric 
1281*0b57cec5SDimitry Andric   ContentCache *Content;
1282*0b57cec5SDimitry Andric   if (LastLineNoFileIDQuery == FID)
1283*0b57cec5SDimitry Andric     Content = LastLineNoContentCache;
1284*0b57cec5SDimitry Andric   else {
1285*0b57cec5SDimitry Andric     bool MyInvalid = false;
1286*0b57cec5SDimitry Andric     const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1287*0b57cec5SDimitry Andric     if (MyInvalid || !Entry.isFile()) {
1288*0b57cec5SDimitry Andric       if (Invalid)
1289*0b57cec5SDimitry Andric         *Invalid = true;
1290*0b57cec5SDimitry Andric       return 1;
1291*0b57cec5SDimitry Andric     }
1292*0b57cec5SDimitry Andric 
1293*0b57cec5SDimitry Andric     Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1294*0b57cec5SDimitry Andric   }
1295*0b57cec5SDimitry Andric 
1296*0b57cec5SDimitry Andric   // If this is the first use of line information for this buffer, compute the
1297*0b57cec5SDimitry Andric   /// SourceLineCache for it on demand.
1298*0b57cec5SDimitry Andric   if (!Content->SourceLineCache) {
1299*0b57cec5SDimitry Andric     bool MyInvalid = false;
1300*0b57cec5SDimitry Andric     ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1301*0b57cec5SDimitry Andric     if (Invalid)
1302*0b57cec5SDimitry Andric       *Invalid = MyInvalid;
1303*0b57cec5SDimitry Andric     if (MyInvalid)
1304*0b57cec5SDimitry Andric       return 1;
1305*0b57cec5SDimitry Andric   } else if (Invalid)
1306*0b57cec5SDimitry Andric     *Invalid = false;
1307*0b57cec5SDimitry Andric 
1308*0b57cec5SDimitry Andric   // Okay, we know we have a line number table.  Do a binary search to find the
1309*0b57cec5SDimitry Andric   // line number that this character position lands on.
1310*0b57cec5SDimitry Andric   unsigned *SourceLineCache = Content->SourceLineCache;
1311*0b57cec5SDimitry Andric   unsigned *SourceLineCacheStart = SourceLineCache;
1312*0b57cec5SDimitry Andric   unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1313*0b57cec5SDimitry Andric 
1314*0b57cec5SDimitry Andric   unsigned QueriedFilePos = FilePos+1;
1315*0b57cec5SDimitry Andric 
1316*0b57cec5SDimitry Andric   // FIXME: I would like to be convinced that this code is worth being as
1317*0b57cec5SDimitry Andric   // complicated as it is, binary search isn't that slow.
1318*0b57cec5SDimitry Andric   //
1319*0b57cec5SDimitry Andric   // If it is worth being optimized, then in my opinion it could be more
1320*0b57cec5SDimitry Andric   // performant, simpler, and more obviously correct by just "galloping" outward
1321*0b57cec5SDimitry Andric   // from the queried file position. In fact, this could be incorporated into a
1322*0b57cec5SDimitry Andric   // generic algorithm such as lower_bound_with_hint.
1323*0b57cec5SDimitry Andric   //
1324*0b57cec5SDimitry Andric   // If someone gives me a test case where this matters, and I will do it! - DWD
1325*0b57cec5SDimitry Andric 
1326*0b57cec5SDimitry Andric   // If the previous query was to the same file, we know both the file pos from
1327*0b57cec5SDimitry Andric   // that query and the line number returned.  This allows us to narrow the
1328*0b57cec5SDimitry Andric   // search space from the entire file to something near the match.
1329*0b57cec5SDimitry Andric   if (LastLineNoFileIDQuery == FID) {
1330*0b57cec5SDimitry Andric     if (QueriedFilePos >= LastLineNoFilePos) {
1331*0b57cec5SDimitry Andric       // FIXME: Potential overflow?
1332*0b57cec5SDimitry Andric       SourceLineCache = SourceLineCache+LastLineNoResult-1;
1333*0b57cec5SDimitry Andric 
1334*0b57cec5SDimitry Andric       // The query is likely to be nearby the previous one.  Here we check to
1335*0b57cec5SDimitry Andric       // see if it is within 5, 10 or 20 lines.  It can be far away in cases
1336*0b57cec5SDimitry Andric       // where big comment blocks and vertical whitespace eat up lines but
1337*0b57cec5SDimitry Andric       // contribute no tokens.
1338*0b57cec5SDimitry Andric       if (SourceLineCache+5 < SourceLineCacheEnd) {
1339*0b57cec5SDimitry Andric         if (SourceLineCache[5] > QueriedFilePos)
1340*0b57cec5SDimitry Andric           SourceLineCacheEnd = SourceLineCache+5;
1341*0b57cec5SDimitry Andric         else if (SourceLineCache+10 < SourceLineCacheEnd) {
1342*0b57cec5SDimitry Andric           if (SourceLineCache[10] > QueriedFilePos)
1343*0b57cec5SDimitry Andric             SourceLineCacheEnd = SourceLineCache+10;
1344*0b57cec5SDimitry Andric           else if (SourceLineCache+20 < SourceLineCacheEnd) {
1345*0b57cec5SDimitry Andric             if (SourceLineCache[20] > QueriedFilePos)
1346*0b57cec5SDimitry Andric               SourceLineCacheEnd = SourceLineCache+20;
1347*0b57cec5SDimitry Andric           }
1348*0b57cec5SDimitry Andric         }
1349*0b57cec5SDimitry Andric       }
1350*0b57cec5SDimitry Andric     } else {
1351*0b57cec5SDimitry Andric       if (LastLineNoResult < Content->NumLines)
1352*0b57cec5SDimitry Andric         SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1353*0b57cec5SDimitry Andric     }
1354*0b57cec5SDimitry Andric   }
1355*0b57cec5SDimitry Andric 
1356*0b57cec5SDimitry Andric   unsigned *Pos
1357*0b57cec5SDimitry Andric     = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1358*0b57cec5SDimitry Andric   unsigned LineNo = Pos-SourceLineCacheStart;
1359*0b57cec5SDimitry Andric 
1360*0b57cec5SDimitry Andric   LastLineNoFileIDQuery = FID;
1361*0b57cec5SDimitry Andric   LastLineNoContentCache = Content;
1362*0b57cec5SDimitry Andric   LastLineNoFilePos = QueriedFilePos;
1363*0b57cec5SDimitry Andric   LastLineNoResult = LineNo;
1364*0b57cec5SDimitry Andric   return LineNo;
1365*0b57cec5SDimitry Andric }
1366*0b57cec5SDimitry Andric 
1367*0b57cec5SDimitry Andric unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1368*0b57cec5SDimitry Andric                                               bool *Invalid) const {
1369*0b57cec5SDimitry Andric   if (isInvalid(Loc, Invalid)) return 0;
1370*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1371*0b57cec5SDimitry Andric   return getLineNumber(LocInfo.first, LocInfo.second);
1372*0b57cec5SDimitry Andric }
1373*0b57cec5SDimitry Andric unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1374*0b57cec5SDimitry Andric                                                bool *Invalid) const {
1375*0b57cec5SDimitry Andric   if (isInvalid(Loc, Invalid)) return 0;
1376*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1377*0b57cec5SDimitry Andric   return getLineNumber(LocInfo.first, LocInfo.second);
1378*0b57cec5SDimitry Andric }
1379*0b57cec5SDimitry Andric unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1380*0b57cec5SDimitry Andric                                               bool *Invalid) const {
1381*0b57cec5SDimitry Andric   PresumedLoc PLoc = getPresumedLoc(Loc);
1382*0b57cec5SDimitry Andric   if (isInvalid(PLoc, Invalid)) return 0;
1383*0b57cec5SDimitry Andric   return PLoc.getLine();
1384*0b57cec5SDimitry Andric }
1385*0b57cec5SDimitry Andric 
1386*0b57cec5SDimitry Andric /// getFileCharacteristic - return the file characteristic of the specified
1387*0b57cec5SDimitry Andric /// source location, indicating whether this is a normal file, a system
1388*0b57cec5SDimitry Andric /// header, or an "implicit extern C" system header.
1389*0b57cec5SDimitry Andric ///
1390*0b57cec5SDimitry Andric /// This state can be modified with flags on GNU linemarker directives like:
1391*0b57cec5SDimitry Andric ///   # 4 "foo.h" 3
1392*0b57cec5SDimitry Andric /// which changes all source locations in the current file after that to be
1393*0b57cec5SDimitry Andric /// considered to be from a system header.
1394*0b57cec5SDimitry Andric SrcMgr::CharacteristicKind
1395*0b57cec5SDimitry Andric SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1396*0b57cec5SDimitry Andric   assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1397*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1398*0b57cec5SDimitry Andric   bool Invalid = false;
1399*0b57cec5SDimitry Andric   const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1400*0b57cec5SDimitry Andric   if (Invalid || !SEntry.isFile())
1401*0b57cec5SDimitry Andric     return C_User;
1402*0b57cec5SDimitry Andric 
1403*0b57cec5SDimitry Andric   const SrcMgr::FileInfo &FI = SEntry.getFile();
1404*0b57cec5SDimitry Andric 
1405*0b57cec5SDimitry Andric   // If there are no #line directives in this file, just return the whole-file
1406*0b57cec5SDimitry Andric   // state.
1407*0b57cec5SDimitry Andric   if (!FI.hasLineDirectives())
1408*0b57cec5SDimitry Andric     return FI.getFileCharacteristic();
1409*0b57cec5SDimitry Andric 
1410*0b57cec5SDimitry Andric   assert(LineTable && "Can't have linetable entries without a LineTable!");
1411*0b57cec5SDimitry Andric   // See if there is a #line directive before the location.
1412*0b57cec5SDimitry Andric   const LineEntry *Entry =
1413*0b57cec5SDimitry Andric     LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1414*0b57cec5SDimitry Andric 
1415*0b57cec5SDimitry Andric   // If this is before the first line marker, use the file characteristic.
1416*0b57cec5SDimitry Andric   if (!Entry)
1417*0b57cec5SDimitry Andric     return FI.getFileCharacteristic();
1418*0b57cec5SDimitry Andric 
1419*0b57cec5SDimitry Andric   return Entry->FileKind;
1420*0b57cec5SDimitry Andric }
1421*0b57cec5SDimitry Andric 
1422*0b57cec5SDimitry Andric /// Return the filename or buffer identifier of the buffer the location is in.
1423*0b57cec5SDimitry Andric /// Note that this name does not respect \#line directives.  Use getPresumedLoc
1424*0b57cec5SDimitry Andric /// for normal clients.
1425*0b57cec5SDimitry Andric StringRef SourceManager::getBufferName(SourceLocation Loc,
1426*0b57cec5SDimitry Andric                                        bool *Invalid) const {
1427*0b57cec5SDimitry Andric   if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1428*0b57cec5SDimitry Andric 
1429*0b57cec5SDimitry Andric   return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1430*0b57cec5SDimitry Andric }
1431*0b57cec5SDimitry Andric 
1432*0b57cec5SDimitry Andric /// getPresumedLoc - This method returns the "presumed" location of a
1433*0b57cec5SDimitry Andric /// SourceLocation specifies.  A "presumed location" can be modified by \#line
1434*0b57cec5SDimitry Andric /// or GNU line marker directives.  This provides a view on the data that a
1435*0b57cec5SDimitry Andric /// user should see in diagnostics, for example.
1436*0b57cec5SDimitry Andric ///
1437*0b57cec5SDimitry Andric /// Note that a presumed location is always given as the expansion point of an
1438*0b57cec5SDimitry Andric /// expansion location, not at the spelling location.
1439*0b57cec5SDimitry Andric PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1440*0b57cec5SDimitry Andric                                           bool UseLineDirectives) const {
1441*0b57cec5SDimitry Andric   if (Loc.isInvalid()) return PresumedLoc();
1442*0b57cec5SDimitry Andric 
1443*0b57cec5SDimitry Andric   // Presumed locations are always for expansion points.
1444*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1445*0b57cec5SDimitry Andric 
1446*0b57cec5SDimitry Andric   bool Invalid = false;
1447*0b57cec5SDimitry Andric   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1448*0b57cec5SDimitry Andric   if (Invalid || !Entry.isFile())
1449*0b57cec5SDimitry Andric     return PresumedLoc();
1450*0b57cec5SDimitry Andric 
1451*0b57cec5SDimitry Andric   const SrcMgr::FileInfo &FI = Entry.getFile();
1452*0b57cec5SDimitry Andric   const SrcMgr::ContentCache *C = FI.getContentCache();
1453*0b57cec5SDimitry Andric 
1454*0b57cec5SDimitry Andric   // To get the source name, first consult the FileEntry (if one exists)
1455*0b57cec5SDimitry Andric   // before the MemBuffer as this will avoid unnecessarily paging in the
1456*0b57cec5SDimitry Andric   // MemBuffer.
1457*0b57cec5SDimitry Andric   FileID FID = LocInfo.first;
1458*0b57cec5SDimitry Andric   StringRef Filename;
1459*0b57cec5SDimitry Andric   if (C->OrigEntry)
1460*0b57cec5SDimitry Andric     Filename = C->OrigEntry->getName();
1461*0b57cec5SDimitry Andric   else
1462*0b57cec5SDimitry Andric     Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1463*0b57cec5SDimitry Andric 
1464*0b57cec5SDimitry Andric   unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1465*0b57cec5SDimitry Andric   if (Invalid)
1466*0b57cec5SDimitry Andric     return PresumedLoc();
1467*0b57cec5SDimitry Andric   unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1468*0b57cec5SDimitry Andric   if (Invalid)
1469*0b57cec5SDimitry Andric     return PresumedLoc();
1470*0b57cec5SDimitry Andric 
1471*0b57cec5SDimitry Andric   SourceLocation IncludeLoc = FI.getIncludeLoc();
1472*0b57cec5SDimitry Andric 
1473*0b57cec5SDimitry Andric   // If we have #line directives in this file, update and overwrite the physical
1474*0b57cec5SDimitry Andric   // location info if appropriate.
1475*0b57cec5SDimitry Andric   if (UseLineDirectives && FI.hasLineDirectives()) {
1476*0b57cec5SDimitry Andric     assert(LineTable && "Can't have linetable entries without a LineTable!");
1477*0b57cec5SDimitry Andric     // See if there is a #line directive before this.  If so, get it.
1478*0b57cec5SDimitry Andric     if (const LineEntry *Entry =
1479*0b57cec5SDimitry Andric           LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1480*0b57cec5SDimitry Andric       // If the LineEntry indicates a filename, use it.
1481*0b57cec5SDimitry Andric       if (Entry->FilenameID != -1) {
1482*0b57cec5SDimitry Andric         Filename = LineTable->getFilename(Entry->FilenameID);
1483*0b57cec5SDimitry Andric         // The contents of files referenced by #line are not in the
1484*0b57cec5SDimitry Andric         // SourceManager
1485*0b57cec5SDimitry Andric         FID = FileID::get(0);
1486*0b57cec5SDimitry Andric       }
1487*0b57cec5SDimitry Andric 
1488*0b57cec5SDimitry Andric       // Use the line number specified by the LineEntry.  This line number may
1489*0b57cec5SDimitry Andric       // be multiple lines down from the line entry.  Add the difference in
1490*0b57cec5SDimitry Andric       // physical line numbers from the query point and the line marker to the
1491*0b57cec5SDimitry Andric       // total.
1492*0b57cec5SDimitry Andric       unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1493*0b57cec5SDimitry Andric       LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1494*0b57cec5SDimitry Andric 
1495*0b57cec5SDimitry Andric       // Note that column numbers are not molested by line markers.
1496*0b57cec5SDimitry Andric 
1497*0b57cec5SDimitry Andric       // Handle virtual #include manipulation.
1498*0b57cec5SDimitry Andric       if (Entry->IncludeOffset) {
1499*0b57cec5SDimitry Andric         IncludeLoc = getLocForStartOfFile(LocInfo.first);
1500*0b57cec5SDimitry Andric         IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1501*0b57cec5SDimitry Andric       }
1502*0b57cec5SDimitry Andric     }
1503*0b57cec5SDimitry Andric   }
1504*0b57cec5SDimitry Andric 
1505*0b57cec5SDimitry Andric   return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1506*0b57cec5SDimitry Andric }
1507*0b57cec5SDimitry Andric 
1508*0b57cec5SDimitry Andric /// Returns whether the PresumedLoc for a given SourceLocation is
1509*0b57cec5SDimitry Andric /// in the main file.
1510*0b57cec5SDimitry Andric ///
1511*0b57cec5SDimitry Andric /// This computes the "presumed" location for a SourceLocation, then checks
1512*0b57cec5SDimitry Andric /// whether it came from a file other than the main file. This is different
1513*0b57cec5SDimitry Andric /// from isWrittenInMainFile() because it takes line marker directives into
1514*0b57cec5SDimitry Andric /// account.
1515*0b57cec5SDimitry Andric bool SourceManager::isInMainFile(SourceLocation Loc) const {
1516*0b57cec5SDimitry Andric   if (Loc.isInvalid()) return false;
1517*0b57cec5SDimitry Andric 
1518*0b57cec5SDimitry Andric   // Presumed locations are always for expansion points.
1519*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1520*0b57cec5SDimitry Andric 
1521*0b57cec5SDimitry Andric   bool Invalid = false;
1522*0b57cec5SDimitry Andric   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1523*0b57cec5SDimitry Andric   if (Invalid || !Entry.isFile())
1524*0b57cec5SDimitry Andric     return false;
1525*0b57cec5SDimitry Andric 
1526*0b57cec5SDimitry Andric   const SrcMgr::FileInfo &FI = Entry.getFile();
1527*0b57cec5SDimitry Andric 
1528*0b57cec5SDimitry Andric   // Check if there is a line directive for this location.
1529*0b57cec5SDimitry Andric   if (FI.hasLineDirectives())
1530*0b57cec5SDimitry Andric     if (const LineEntry *Entry =
1531*0b57cec5SDimitry Andric             LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1532*0b57cec5SDimitry Andric       if (Entry->IncludeOffset)
1533*0b57cec5SDimitry Andric         return false;
1534*0b57cec5SDimitry Andric 
1535*0b57cec5SDimitry Andric   return FI.getIncludeLoc().isInvalid();
1536*0b57cec5SDimitry Andric }
1537*0b57cec5SDimitry Andric 
1538*0b57cec5SDimitry Andric /// The size of the SLocEntry that \p FID represents.
1539*0b57cec5SDimitry Andric unsigned SourceManager::getFileIDSize(FileID FID) const {
1540*0b57cec5SDimitry Andric   bool Invalid = false;
1541*0b57cec5SDimitry Andric   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1542*0b57cec5SDimitry Andric   if (Invalid)
1543*0b57cec5SDimitry Andric     return 0;
1544*0b57cec5SDimitry Andric 
1545*0b57cec5SDimitry Andric   int ID = FID.ID;
1546*0b57cec5SDimitry Andric   unsigned NextOffset;
1547*0b57cec5SDimitry Andric   if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1548*0b57cec5SDimitry Andric     NextOffset = getNextLocalOffset();
1549*0b57cec5SDimitry Andric   else if (ID+1 == -1)
1550*0b57cec5SDimitry Andric     NextOffset = MaxLoadedOffset;
1551*0b57cec5SDimitry Andric   else
1552*0b57cec5SDimitry Andric     NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1553*0b57cec5SDimitry Andric 
1554*0b57cec5SDimitry Andric   return NextOffset - Entry.getOffset() - 1;
1555*0b57cec5SDimitry Andric }
1556*0b57cec5SDimitry Andric 
1557*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1558*0b57cec5SDimitry Andric // Other miscellaneous methods.
1559*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1560*0b57cec5SDimitry Andric 
1561*0b57cec5SDimitry Andric /// Retrieve the inode for the given file entry, if possible.
1562*0b57cec5SDimitry Andric ///
1563*0b57cec5SDimitry Andric /// This routine involves a system call, and therefore should only be used
1564*0b57cec5SDimitry Andric /// in non-performance-critical code.
1565*0b57cec5SDimitry Andric static Optional<llvm::sys::fs::UniqueID>
1566*0b57cec5SDimitry Andric getActualFileUID(const FileEntry *File) {
1567*0b57cec5SDimitry Andric   if (!File)
1568*0b57cec5SDimitry Andric     return None;
1569*0b57cec5SDimitry Andric 
1570*0b57cec5SDimitry Andric   llvm::sys::fs::UniqueID ID;
1571*0b57cec5SDimitry Andric   if (llvm::sys::fs::getUniqueID(File->getName(), ID))
1572*0b57cec5SDimitry Andric     return None;
1573*0b57cec5SDimitry Andric 
1574*0b57cec5SDimitry Andric   return ID;
1575*0b57cec5SDimitry Andric }
1576*0b57cec5SDimitry Andric 
1577*0b57cec5SDimitry Andric /// Get the source location for the given file:line:col triplet.
1578*0b57cec5SDimitry Andric ///
1579*0b57cec5SDimitry Andric /// If the source file is included multiple times, the source location will
1580*0b57cec5SDimitry Andric /// be based upon an arbitrary inclusion.
1581*0b57cec5SDimitry Andric SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1582*0b57cec5SDimitry Andric                                                   unsigned Line,
1583*0b57cec5SDimitry Andric                                                   unsigned Col) const {
1584*0b57cec5SDimitry Andric   assert(SourceFile && "Null source file!");
1585*0b57cec5SDimitry Andric   assert(Line && Col && "Line and column should start from 1!");
1586*0b57cec5SDimitry Andric 
1587*0b57cec5SDimitry Andric   FileID FirstFID = translateFile(SourceFile);
1588*0b57cec5SDimitry Andric   return translateLineCol(FirstFID, Line, Col);
1589*0b57cec5SDimitry Andric }
1590*0b57cec5SDimitry Andric 
1591*0b57cec5SDimitry Andric /// Get the FileID for the given file.
1592*0b57cec5SDimitry Andric ///
1593*0b57cec5SDimitry Andric /// If the source file is included multiple times, the FileID will be the
1594*0b57cec5SDimitry Andric /// first inclusion.
1595*0b57cec5SDimitry Andric FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1596*0b57cec5SDimitry Andric   assert(SourceFile && "Null source file!");
1597*0b57cec5SDimitry Andric 
1598*0b57cec5SDimitry Andric   // Find the first file ID that corresponds to the given file.
1599*0b57cec5SDimitry Andric   FileID FirstFID;
1600*0b57cec5SDimitry Andric 
1601*0b57cec5SDimitry Andric   // First, check the main file ID, since it is common to look for a
1602*0b57cec5SDimitry Andric   // location in the main file.
1603*0b57cec5SDimitry Andric   Optional<llvm::sys::fs::UniqueID> SourceFileUID;
1604*0b57cec5SDimitry Andric   Optional<StringRef> SourceFileName;
1605*0b57cec5SDimitry Andric   if (MainFileID.isValid()) {
1606*0b57cec5SDimitry Andric     bool Invalid = false;
1607*0b57cec5SDimitry Andric     const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1608*0b57cec5SDimitry Andric     if (Invalid)
1609*0b57cec5SDimitry Andric       return FileID();
1610*0b57cec5SDimitry Andric 
1611*0b57cec5SDimitry Andric     if (MainSLoc.isFile()) {
1612*0b57cec5SDimitry Andric       const ContentCache *MainContentCache
1613*0b57cec5SDimitry Andric         = MainSLoc.getFile().getContentCache();
1614*0b57cec5SDimitry Andric       if (!MainContentCache || !MainContentCache->OrigEntry) {
1615*0b57cec5SDimitry Andric         // Can't do anything
1616*0b57cec5SDimitry Andric       } else if (MainContentCache->OrigEntry == SourceFile) {
1617*0b57cec5SDimitry Andric         FirstFID = MainFileID;
1618*0b57cec5SDimitry Andric       } else {
1619*0b57cec5SDimitry Andric         // Fall back: check whether we have the same base name and inode
1620*0b57cec5SDimitry Andric         // as the main file.
1621*0b57cec5SDimitry Andric         const FileEntry *MainFile = MainContentCache->OrigEntry;
1622*0b57cec5SDimitry Andric         SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1623*0b57cec5SDimitry Andric         if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1624*0b57cec5SDimitry Andric           SourceFileUID = getActualFileUID(SourceFile);
1625*0b57cec5SDimitry Andric           if (SourceFileUID) {
1626*0b57cec5SDimitry Andric             if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1627*0b57cec5SDimitry Andric                     getActualFileUID(MainFile)) {
1628*0b57cec5SDimitry Andric               if (*SourceFileUID == *MainFileUID) {
1629*0b57cec5SDimitry Andric                 FirstFID = MainFileID;
1630*0b57cec5SDimitry Andric                 SourceFile = MainFile;
1631*0b57cec5SDimitry Andric               }
1632*0b57cec5SDimitry Andric             }
1633*0b57cec5SDimitry Andric           }
1634*0b57cec5SDimitry Andric         }
1635*0b57cec5SDimitry Andric       }
1636*0b57cec5SDimitry Andric     }
1637*0b57cec5SDimitry Andric   }
1638*0b57cec5SDimitry Andric 
1639*0b57cec5SDimitry Andric   if (FirstFID.isInvalid()) {
1640*0b57cec5SDimitry Andric     // The location we're looking for isn't in the main file; look
1641*0b57cec5SDimitry Andric     // through all of the local source locations.
1642*0b57cec5SDimitry Andric     for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1643*0b57cec5SDimitry Andric       bool Invalid = false;
1644*0b57cec5SDimitry Andric       const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1645*0b57cec5SDimitry Andric       if (Invalid)
1646*0b57cec5SDimitry Andric         return FileID();
1647*0b57cec5SDimitry Andric 
1648*0b57cec5SDimitry Andric       if (SLoc.isFile() &&
1649*0b57cec5SDimitry Andric           SLoc.getFile().getContentCache() &&
1650*0b57cec5SDimitry Andric           SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1651*0b57cec5SDimitry Andric         FirstFID = FileID::get(I);
1652*0b57cec5SDimitry Andric         break;
1653*0b57cec5SDimitry Andric       }
1654*0b57cec5SDimitry Andric     }
1655*0b57cec5SDimitry Andric     // If that still didn't help, try the modules.
1656*0b57cec5SDimitry Andric     if (FirstFID.isInvalid()) {
1657*0b57cec5SDimitry Andric       for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1658*0b57cec5SDimitry Andric         const SLocEntry &SLoc = getLoadedSLocEntry(I);
1659*0b57cec5SDimitry Andric         if (SLoc.isFile() &&
1660*0b57cec5SDimitry Andric             SLoc.getFile().getContentCache() &&
1661*0b57cec5SDimitry Andric             SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1662*0b57cec5SDimitry Andric           FirstFID = FileID::get(-int(I) - 2);
1663*0b57cec5SDimitry Andric           break;
1664*0b57cec5SDimitry Andric         }
1665*0b57cec5SDimitry Andric       }
1666*0b57cec5SDimitry Andric     }
1667*0b57cec5SDimitry Andric   }
1668*0b57cec5SDimitry Andric 
1669*0b57cec5SDimitry Andric   // If we haven't found what we want yet, try again, but this time stat()
1670*0b57cec5SDimitry Andric   // each of the files in case the files have changed since we originally
1671*0b57cec5SDimitry Andric   // parsed the file.
1672*0b57cec5SDimitry Andric   if (FirstFID.isInvalid() &&
1673*0b57cec5SDimitry Andric       (SourceFileName ||
1674*0b57cec5SDimitry Andric        (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1675*0b57cec5SDimitry Andric       (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
1676*0b57cec5SDimitry Andric     bool Invalid = false;
1677*0b57cec5SDimitry Andric     for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1678*0b57cec5SDimitry Andric       FileID IFileID;
1679*0b57cec5SDimitry Andric       IFileID.ID = I;
1680*0b57cec5SDimitry Andric       const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1681*0b57cec5SDimitry Andric       if (Invalid)
1682*0b57cec5SDimitry Andric         return FileID();
1683*0b57cec5SDimitry Andric 
1684*0b57cec5SDimitry Andric       if (SLoc.isFile()) {
1685*0b57cec5SDimitry Andric         const ContentCache *FileContentCache
1686*0b57cec5SDimitry Andric           = SLoc.getFile().getContentCache();
1687*0b57cec5SDimitry Andric         const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1688*0b57cec5SDimitry Andric                                                   : nullptr;
1689*0b57cec5SDimitry Andric         if (Entry &&
1690*0b57cec5SDimitry Andric             *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1691*0b57cec5SDimitry Andric           if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1692*0b57cec5SDimitry Andric                   getActualFileUID(Entry)) {
1693*0b57cec5SDimitry Andric             if (*SourceFileUID == *EntryUID) {
1694*0b57cec5SDimitry Andric               FirstFID = FileID::get(I);
1695*0b57cec5SDimitry Andric               SourceFile = Entry;
1696*0b57cec5SDimitry Andric               break;
1697*0b57cec5SDimitry Andric             }
1698*0b57cec5SDimitry Andric           }
1699*0b57cec5SDimitry Andric         }
1700*0b57cec5SDimitry Andric       }
1701*0b57cec5SDimitry Andric     }
1702*0b57cec5SDimitry Andric   }
1703*0b57cec5SDimitry Andric 
1704*0b57cec5SDimitry Andric   (void) SourceFile;
1705*0b57cec5SDimitry Andric   return FirstFID;
1706*0b57cec5SDimitry Andric }
1707*0b57cec5SDimitry Andric 
1708*0b57cec5SDimitry Andric /// Get the source location in \arg FID for the given line:col.
1709*0b57cec5SDimitry Andric /// Returns null location if \arg FID is not a file SLocEntry.
1710*0b57cec5SDimitry Andric SourceLocation SourceManager::translateLineCol(FileID FID,
1711*0b57cec5SDimitry Andric                                                unsigned Line,
1712*0b57cec5SDimitry Andric                                                unsigned Col) const {
1713*0b57cec5SDimitry Andric   // Lines are used as a one-based index into a zero-based array. This assert
1714*0b57cec5SDimitry Andric   // checks for possible buffer underruns.
1715*0b57cec5SDimitry Andric   assert(Line && Col && "Line and column should start from 1!");
1716*0b57cec5SDimitry Andric 
1717*0b57cec5SDimitry Andric   if (FID.isInvalid())
1718*0b57cec5SDimitry Andric     return SourceLocation();
1719*0b57cec5SDimitry Andric 
1720*0b57cec5SDimitry Andric   bool Invalid = false;
1721*0b57cec5SDimitry Andric   const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1722*0b57cec5SDimitry Andric   if (Invalid)
1723*0b57cec5SDimitry Andric     return SourceLocation();
1724*0b57cec5SDimitry Andric 
1725*0b57cec5SDimitry Andric   if (!Entry.isFile())
1726*0b57cec5SDimitry Andric     return SourceLocation();
1727*0b57cec5SDimitry Andric 
1728*0b57cec5SDimitry Andric   SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1729*0b57cec5SDimitry Andric 
1730*0b57cec5SDimitry Andric   if (Line == 1 && Col == 1)
1731*0b57cec5SDimitry Andric     return FileLoc;
1732*0b57cec5SDimitry Andric 
1733*0b57cec5SDimitry Andric   ContentCache *Content
1734*0b57cec5SDimitry Andric     = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1735*0b57cec5SDimitry Andric   if (!Content)
1736*0b57cec5SDimitry Andric     return SourceLocation();
1737*0b57cec5SDimitry Andric 
1738*0b57cec5SDimitry Andric   // If this is the first use of line information for this buffer, compute the
1739*0b57cec5SDimitry Andric   // SourceLineCache for it on demand.
1740*0b57cec5SDimitry Andric   if (!Content->SourceLineCache) {
1741*0b57cec5SDimitry Andric     bool MyInvalid = false;
1742*0b57cec5SDimitry Andric     ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1743*0b57cec5SDimitry Andric     if (MyInvalid)
1744*0b57cec5SDimitry Andric       return SourceLocation();
1745*0b57cec5SDimitry Andric   }
1746*0b57cec5SDimitry Andric 
1747*0b57cec5SDimitry Andric   if (Line > Content->NumLines) {
1748*0b57cec5SDimitry Andric     unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1749*0b57cec5SDimitry Andric     if (Size > 0)
1750*0b57cec5SDimitry Andric       --Size;
1751*0b57cec5SDimitry Andric     return FileLoc.getLocWithOffset(Size);
1752*0b57cec5SDimitry Andric   }
1753*0b57cec5SDimitry Andric 
1754*0b57cec5SDimitry Andric   const llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
1755*0b57cec5SDimitry Andric   unsigned FilePos = Content->SourceLineCache[Line - 1];
1756*0b57cec5SDimitry Andric   const char *Buf = Buffer->getBufferStart() + FilePos;
1757*0b57cec5SDimitry Andric   unsigned BufLength = Buffer->getBufferSize() - FilePos;
1758*0b57cec5SDimitry Andric   if (BufLength == 0)
1759*0b57cec5SDimitry Andric     return FileLoc.getLocWithOffset(FilePos);
1760*0b57cec5SDimitry Andric 
1761*0b57cec5SDimitry Andric   unsigned i = 0;
1762*0b57cec5SDimitry Andric 
1763*0b57cec5SDimitry Andric   // Check that the given column is valid.
1764*0b57cec5SDimitry Andric   while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1765*0b57cec5SDimitry Andric     ++i;
1766*0b57cec5SDimitry Andric   return FileLoc.getLocWithOffset(FilePos + i);
1767*0b57cec5SDimitry Andric }
1768*0b57cec5SDimitry Andric 
1769*0b57cec5SDimitry Andric /// Compute a map of macro argument chunks to their expanded source
1770*0b57cec5SDimitry Andric /// location. Chunks that are not part of a macro argument will map to an
1771*0b57cec5SDimitry Andric /// invalid source location. e.g. if a file contains one macro argument at
1772*0b57cec5SDimitry Andric /// offset 100 with length 10, this is how the map will be formed:
1773*0b57cec5SDimitry Andric ///     0   -> SourceLocation()
1774*0b57cec5SDimitry Andric ///     100 -> Expanded macro arg location
1775*0b57cec5SDimitry Andric ///     110 -> SourceLocation()
1776*0b57cec5SDimitry Andric void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1777*0b57cec5SDimitry Andric                                           FileID FID) const {
1778*0b57cec5SDimitry Andric   assert(FID.isValid());
1779*0b57cec5SDimitry Andric 
1780*0b57cec5SDimitry Andric   // Initially no macro argument chunk is present.
1781*0b57cec5SDimitry Andric   MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1782*0b57cec5SDimitry Andric 
1783*0b57cec5SDimitry Andric   int ID = FID.ID;
1784*0b57cec5SDimitry Andric   while (true) {
1785*0b57cec5SDimitry Andric     ++ID;
1786*0b57cec5SDimitry Andric     // Stop if there are no more FileIDs to check.
1787*0b57cec5SDimitry Andric     if (ID > 0) {
1788*0b57cec5SDimitry Andric       if (unsigned(ID) >= local_sloc_entry_size())
1789*0b57cec5SDimitry Andric         return;
1790*0b57cec5SDimitry Andric     } else if (ID == -1) {
1791*0b57cec5SDimitry Andric       return;
1792*0b57cec5SDimitry Andric     }
1793*0b57cec5SDimitry Andric 
1794*0b57cec5SDimitry Andric     bool Invalid = false;
1795*0b57cec5SDimitry Andric     const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1796*0b57cec5SDimitry Andric     if (Invalid)
1797*0b57cec5SDimitry Andric       return;
1798*0b57cec5SDimitry Andric     if (Entry.isFile()) {
1799*0b57cec5SDimitry Andric       SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1800*0b57cec5SDimitry Andric       if (IncludeLoc.isInvalid())
1801*0b57cec5SDimitry Andric         continue;
1802*0b57cec5SDimitry Andric       if (!isInFileID(IncludeLoc, FID))
1803*0b57cec5SDimitry Andric         return; // No more files/macros that may be "contained" in this file.
1804*0b57cec5SDimitry Andric 
1805*0b57cec5SDimitry Andric       // Skip the files/macros of the #include'd file, we only care about macros
1806*0b57cec5SDimitry Andric       // that lexed macro arguments from our file.
1807*0b57cec5SDimitry Andric       if (Entry.getFile().NumCreatedFIDs)
1808*0b57cec5SDimitry Andric         ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1809*0b57cec5SDimitry Andric       continue;
1810*0b57cec5SDimitry Andric     }
1811*0b57cec5SDimitry Andric 
1812*0b57cec5SDimitry Andric     const ExpansionInfo &ExpInfo = Entry.getExpansion();
1813*0b57cec5SDimitry Andric 
1814*0b57cec5SDimitry Andric     if (ExpInfo.getExpansionLocStart().isFileID()) {
1815*0b57cec5SDimitry Andric       if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1816*0b57cec5SDimitry Andric         return; // No more files/macros that may be "contained" in this file.
1817*0b57cec5SDimitry Andric     }
1818*0b57cec5SDimitry Andric 
1819*0b57cec5SDimitry Andric     if (!ExpInfo.isMacroArgExpansion())
1820*0b57cec5SDimitry Andric       continue;
1821*0b57cec5SDimitry Andric 
1822*0b57cec5SDimitry Andric     associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1823*0b57cec5SDimitry Andric                                  ExpInfo.getSpellingLoc(),
1824*0b57cec5SDimitry Andric                                  SourceLocation::getMacroLoc(Entry.getOffset()),
1825*0b57cec5SDimitry Andric                                  getFileIDSize(FileID::get(ID)));
1826*0b57cec5SDimitry Andric   }
1827*0b57cec5SDimitry Andric }
1828*0b57cec5SDimitry Andric 
1829*0b57cec5SDimitry Andric void SourceManager::associateFileChunkWithMacroArgExp(
1830*0b57cec5SDimitry Andric                                          MacroArgsMap &MacroArgsCache,
1831*0b57cec5SDimitry Andric                                          FileID FID,
1832*0b57cec5SDimitry Andric                                          SourceLocation SpellLoc,
1833*0b57cec5SDimitry Andric                                          SourceLocation ExpansionLoc,
1834*0b57cec5SDimitry Andric                                          unsigned ExpansionLength) const {
1835*0b57cec5SDimitry Andric   if (!SpellLoc.isFileID()) {
1836*0b57cec5SDimitry Andric     unsigned SpellBeginOffs = SpellLoc.getOffset();
1837*0b57cec5SDimitry Andric     unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1838*0b57cec5SDimitry Andric 
1839*0b57cec5SDimitry Andric     // The spelling range for this macro argument expansion can span multiple
1840*0b57cec5SDimitry Andric     // consecutive FileID entries. Go through each entry contained in the
1841*0b57cec5SDimitry Andric     // spelling range and if one is itself a macro argument expansion, recurse
1842*0b57cec5SDimitry Andric     // and associate the file chunk that it represents.
1843*0b57cec5SDimitry Andric 
1844*0b57cec5SDimitry Andric     FileID SpellFID; // Current FileID in the spelling range.
1845*0b57cec5SDimitry Andric     unsigned SpellRelativeOffs;
1846*0b57cec5SDimitry Andric     std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1847*0b57cec5SDimitry Andric     while (true) {
1848*0b57cec5SDimitry Andric       const SLocEntry &Entry = getSLocEntry(SpellFID);
1849*0b57cec5SDimitry Andric       unsigned SpellFIDBeginOffs = Entry.getOffset();
1850*0b57cec5SDimitry Andric       unsigned SpellFIDSize = getFileIDSize(SpellFID);
1851*0b57cec5SDimitry Andric       unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1852*0b57cec5SDimitry Andric       const ExpansionInfo &Info = Entry.getExpansion();
1853*0b57cec5SDimitry Andric       if (Info.isMacroArgExpansion()) {
1854*0b57cec5SDimitry Andric         unsigned CurrSpellLength;
1855*0b57cec5SDimitry Andric         if (SpellFIDEndOffs < SpellEndOffs)
1856*0b57cec5SDimitry Andric           CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1857*0b57cec5SDimitry Andric         else
1858*0b57cec5SDimitry Andric           CurrSpellLength = ExpansionLength;
1859*0b57cec5SDimitry Andric         associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1860*0b57cec5SDimitry Andric                       Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1861*0b57cec5SDimitry Andric                       ExpansionLoc, CurrSpellLength);
1862*0b57cec5SDimitry Andric       }
1863*0b57cec5SDimitry Andric 
1864*0b57cec5SDimitry Andric       if (SpellFIDEndOffs >= SpellEndOffs)
1865*0b57cec5SDimitry Andric         return; // we covered all FileID entries in the spelling range.
1866*0b57cec5SDimitry Andric 
1867*0b57cec5SDimitry Andric       // Move to the next FileID entry in the spelling range.
1868*0b57cec5SDimitry Andric       unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1869*0b57cec5SDimitry Andric       ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1870*0b57cec5SDimitry Andric       ExpansionLength -= advance;
1871*0b57cec5SDimitry Andric       ++SpellFID.ID;
1872*0b57cec5SDimitry Andric       SpellRelativeOffs = 0;
1873*0b57cec5SDimitry Andric     }
1874*0b57cec5SDimitry Andric   }
1875*0b57cec5SDimitry Andric 
1876*0b57cec5SDimitry Andric   assert(SpellLoc.isFileID());
1877*0b57cec5SDimitry Andric 
1878*0b57cec5SDimitry Andric   unsigned BeginOffs;
1879*0b57cec5SDimitry Andric   if (!isInFileID(SpellLoc, FID, &BeginOffs))
1880*0b57cec5SDimitry Andric     return;
1881*0b57cec5SDimitry Andric 
1882*0b57cec5SDimitry Andric   unsigned EndOffs = BeginOffs + ExpansionLength;
1883*0b57cec5SDimitry Andric 
1884*0b57cec5SDimitry Andric   // Add a new chunk for this macro argument. A previous macro argument chunk
1885*0b57cec5SDimitry Andric   // may have been lexed again, so e.g. if the map is
1886*0b57cec5SDimitry Andric   //     0   -> SourceLocation()
1887*0b57cec5SDimitry Andric   //     100 -> Expanded loc #1
1888*0b57cec5SDimitry Andric   //     110 -> SourceLocation()
1889*0b57cec5SDimitry Andric   // and we found a new macro FileID that lexed from offset 105 with length 3,
1890*0b57cec5SDimitry Andric   // the new map will be:
1891*0b57cec5SDimitry Andric   //     0   -> SourceLocation()
1892*0b57cec5SDimitry Andric   //     100 -> Expanded loc #1
1893*0b57cec5SDimitry Andric   //     105 -> Expanded loc #2
1894*0b57cec5SDimitry Andric   //     108 -> Expanded loc #1
1895*0b57cec5SDimitry Andric   //     110 -> SourceLocation()
1896*0b57cec5SDimitry Andric   //
1897*0b57cec5SDimitry Andric   // Since re-lexed macro chunks will always be the same size or less of
1898*0b57cec5SDimitry Andric   // previous chunks, we only need to find where the ending of the new macro
1899*0b57cec5SDimitry Andric   // chunk is mapped to and update the map with new begin/end mappings.
1900*0b57cec5SDimitry Andric 
1901*0b57cec5SDimitry Andric   MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1902*0b57cec5SDimitry Andric   --I;
1903*0b57cec5SDimitry Andric   SourceLocation EndOffsMappedLoc = I->second;
1904*0b57cec5SDimitry Andric   MacroArgsCache[BeginOffs] = ExpansionLoc;
1905*0b57cec5SDimitry Andric   MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1906*0b57cec5SDimitry Andric }
1907*0b57cec5SDimitry Andric 
1908*0b57cec5SDimitry Andric /// If \arg Loc points inside a function macro argument, the returned
1909*0b57cec5SDimitry Andric /// location will be the macro location in which the argument was expanded.
1910*0b57cec5SDimitry Andric /// If a macro argument is used multiple times, the expanded location will
1911*0b57cec5SDimitry Andric /// be at the first expansion of the argument.
1912*0b57cec5SDimitry Andric /// e.g.
1913*0b57cec5SDimitry Andric ///   MY_MACRO(foo);
1914*0b57cec5SDimitry Andric ///             ^
1915*0b57cec5SDimitry Andric /// Passing a file location pointing at 'foo', will yield a macro location
1916*0b57cec5SDimitry Andric /// where 'foo' was expanded into.
1917*0b57cec5SDimitry Andric SourceLocation
1918*0b57cec5SDimitry Andric SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1919*0b57cec5SDimitry Andric   if (Loc.isInvalid() || !Loc.isFileID())
1920*0b57cec5SDimitry Andric     return Loc;
1921*0b57cec5SDimitry Andric 
1922*0b57cec5SDimitry Andric   FileID FID;
1923*0b57cec5SDimitry Andric   unsigned Offset;
1924*0b57cec5SDimitry Andric   std::tie(FID, Offset) = getDecomposedLoc(Loc);
1925*0b57cec5SDimitry Andric   if (FID.isInvalid())
1926*0b57cec5SDimitry Andric     return Loc;
1927*0b57cec5SDimitry Andric 
1928*0b57cec5SDimitry Andric   std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1929*0b57cec5SDimitry Andric   if (!MacroArgsCache) {
1930*0b57cec5SDimitry Andric     MacroArgsCache = llvm::make_unique<MacroArgsMap>();
1931*0b57cec5SDimitry Andric     computeMacroArgsCache(*MacroArgsCache, FID);
1932*0b57cec5SDimitry Andric   }
1933*0b57cec5SDimitry Andric 
1934*0b57cec5SDimitry Andric   assert(!MacroArgsCache->empty());
1935*0b57cec5SDimitry Andric   MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1936*0b57cec5SDimitry Andric   --I;
1937*0b57cec5SDimitry Andric 
1938*0b57cec5SDimitry Andric   unsigned MacroArgBeginOffs = I->first;
1939*0b57cec5SDimitry Andric   SourceLocation MacroArgExpandedLoc = I->second;
1940*0b57cec5SDimitry Andric   if (MacroArgExpandedLoc.isValid())
1941*0b57cec5SDimitry Andric     return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1942*0b57cec5SDimitry Andric 
1943*0b57cec5SDimitry Andric   return Loc;
1944*0b57cec5SDimitry Andric }
1945*0b57cec5SDimitry Andric 
1946*0b57cec5SDimitry Andric std::pair<FileID, unsigned>
1947*0b57cec5SDimitry Andric SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1948*0b57cec5SDimitry Andric   if (FID.isInvalid())
1949*0b57cec5SDimitry Andric     return std::make_pair(FileID(), 0);
1950*0b57cec5SDimitry Andric 
1951*0b57cec5SDimitry Andric   // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1952*0b57cec5SDimitry Andric 
1953*0b57cec5SDimitry Andric   using DecompTy = std::pair<FileID, unsigned>;
1954*0b57cec5SDimitry Andric   auto InsertOp = IncludedLocMap.try_emplace(FID);
1955*0b57cec5SDimitry Andric   DecompTy &DecompLoc = InsertOp.first->second;
1956*0b57cec5SDimitry Andric   if (!InsertOp.second)
1957*0b57cec5SDimitry Andric     return DecompLoc; // already in map.
1958*0b57cec5SDimitry Andric 
1959*0b57cec5SDimitry Andric   SourceLocation UpperLoc;
1960*0b57cec5SDimitry Andric   bool Invalid = false;
1961*0b57cec5SDimitry Andric   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1962*0b57cec5SDimitry Andric   if (!Invalid) {
1963*0b57cec5SDimitry Andric     if (Entry.isExpansion())
1964*0b57cec5SDimitry Andric       UpperLoc = Entry.getExpansion().getExpansionLocStart();
1965*0b57cec5SDimitry Andric     else
1966*0b57cec5SDimitry Andric       UpperLoc = Entry.getFile().getIncludeLoc();
1967*0b57cec5SDimitry Andric   }
1968*0b57cec5SDimitry Andric 
1969*0b57cec5SDimitry Andric   if (UpperLoc.isValid())
1970*0b57cec5SDimitry Andric     DecompLoc = getDecomposedLoc(UpperLoc);
1971*0b57cec5SDimitry Andric 
1972*0b57cec5SDimitry Andric   return DecompLoc;
1973*0b57cec5SDimitry Andric }
1974*0b57cec5SDimitry Andric 
1975*0b57cec5SDimitry Andric /// Given a decomposed source location, move it up the include/expansion stack
1976*0b57cec5SDimitry Andric /// to the parent source location.  If this is possible, return the decomposed
1977*0b57cec5SDimitry Andric /// version of the parent in Loc and return false.  If Loc is the top-level
1978*0b57cec5SDimitry Andric /// entry, return true and don't modify it.
1979*0b57cec5SDimitry Andric static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1980*0b57cec5SDimitry Andric                                    const SourceManager &SM) {
1981*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1982*0b57cec5SDimitry Andric   if (UpperLoc.first.isInvalid())
1983*0b57cec5SDimitry Andric     return true; // We reached the top.
1984*0b57cec5SDimitry Andric 
1985*0b57cec5SDimitry Andric   Loc = UpperLoc;
1986*0b57cec5SDimitry Andric   return false;
1987*0b57cec5SDimitry Andric }
1988*0b57cec5SDimitry Andric 
1989*0b57cec5SDimitry Andric /// Return the cache entry for comparing the given file IDs
1990*0b57cec5SDimitry Andric /// for isBeforeInTranslationUnit.
1991*0b57cec5SDimitry Andric InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1992*0b57cec5SDimitry Andric                                                             FileID RFID) const {
1993*0b57cec5SDimitry Andric   // This is a magic number for limiting the cache size.  It was experimentally
1994*0b57cec5SDimitry Andric   // derived from a small Objective-C project (where the cache filled
1995*0b57cec5SDimitry Andric   // out to ~250 items).  We can make it larger if necessary.
1996*0b57cec5SDimitry Andric   enum { MagicCacheSize = 300 };
1997*0b57cec5SDimitry Andric   IsBeforeInTUCacheKey Key(LFID, RFID);
1998*0b57cec5SDimitry Andric 
1999*0b57cec5SDimitry Andric   // If the cache size isn't too large, do a lookup and if necessary default
2000*0b57cec5SDimitry Andric   // construct an entry.  We can then return it to the caller for direct
2001*0b57cec5SDimitry Andric   // use.  When they update the value, the cache will get automatically
2002*0b57cec5SDimitry Andric   // updated as well.
2003*0b57cec5SDimitry Andric   if (IBTUCache.size() < MagicCacheSize)
2004*0b57cec5SDimitry Andric     return IBTUCache[Key];
2005*0b57cec5SDimitry Andric 
2006*0b57cec5SDimitry Andric   // Otherwise, do a lookup that will not construct a new value.
2007*0b57cec5SDimitry Andric   InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2008*0b57cec5SDimitry Andric   if (I != IBTUCache.end())
2009*0b57cec5SDimitry Andric     return I->second;
2010*0b57cec5SDimitry Andric 
2011*0b57cec5SDimitry Andric   // Fall back to the overflow value.
2012*0b57cec5SDimitry Andric   return IBTUCacheOverflow;
2013*0b57cec5SDimitry Andric }
2014*0b57cec5SDimitry Andric 
2015*0b57cec5SDimitry Andric /// Determines the order of 2 source locations in the translation unit.
2016*0b57cec5SDimitry Andric ///
2017*0b57cec5SDimitry Andric /// \returns true if LHS source location comes before RHS, false otherwise.
2018*0b57cec5SDimitry Andric bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2019*0b57cec5SDimitry Andric                                               SourceLocation RHS) const {
2020*0b57cec5SDimitry Andric   assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2021*0b57cec5SDimitry Andric   if (LHS == RHS)
2022*0b57cec5SDimitry Andric     return false;
2023*0b57cec5SDimitry Andric 
2024*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2025*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2026*0b57cec5SDimitry Andric 
2027*0b57cec5SDimitry Andric   // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2028*0b57cec5SDimitry Andric   // is a serialized one referring to a file that was removed after we loaded
2029*0b57cec5SDimitry Andric   // the PCH.
2030*0b57cec5SDimitry Andric   if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2031*0b57cec5SDimitry Andric     return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2032*0b57cec5SDimitry Andric 
2033*0b57cec5SDimitry Andric   std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2034*0b57cec5SDimitry Andric   if (InSameTU.first)
2035*0b57cec5SDimitry Andric     return InSameTU.second;
2036*0b57cec5SDimitry Andric 
2037*0b57cec5SDimitry Andric   // If we arrived here, the location is either in a built-ins buffer or
2038*0b57cec5SDimitry Andric   // associated with global inline asm. PR5662 and PR22576 are examples.
2039*0b57cec5SDimitry Andric 
2040*0b57cec5SDimitry Andric   StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2041*0b57cec5SDimitry Andric   StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2042*0b57cec5SDimitry Andric   bool LIsBuiltins = LB == "<built-in>";
2043*0b57cec5SDimitry Andric   bool RIsBuiltins = RB == "<built-in>";
2044*0b57cec5SDimitry Andric   // Sort built-in before non-built-in.
2045*0b57cec5SDimitry Andric   if (LIsBuiltins || RIsBuiltins) {
2046*0b57cec5SDimitry Andric     if (LIsBuiltins != RIsBuiltins)
2047*0b57cec5SDimitry Andric       return LIsBuiltins;
2048*0b57cec5SDimitry Andric     // Both are in built-in buffers, but from different files. We just claim that
2049*0b57cec5SDimitry Andric     // lower IDs come first.
2050*0b57cec5SDimitry Andric     return LOffs.first < ROffs.first;
2051*0b57cec5SDimitry Andric   }
2052*0b57cec5SDimitry Andric   bool LIsAsm = LB == "<inline asm>";
2053*0b57cec5SDimitry Andric   bool RIsAsm = RB == "<inline asm>";
2054*0b57cec5SDimitry Andric   // Sort assembler after built-ins, but before the rest.
2055*0b57cec5SDimitry Andric   if (LIsAsm || RIsAsm) {
2056*0b57cec5SDimitry Andric     if (LIsAsm != RIsAsm)
2057*0b57cec5SDimitry Andric       return RIsAsm;
2058*0b57cec5SDimitry Andric     assert(LOffs.first == ROffs.first);
2059*0b57cec5SDimitry Andric     return false;
2060*0b57cec5SDimitry Andric   }
2061*0b57cec5SDimitry Andric   bool LIsScratch = LB == "<scratch space>";
2062*0b57cec5SDimitry Andric   bool RIsScratch = RB == "<scratch space>";
2063*0b57cec5SDimitry Andric   // Sort scratch after inline asm, but before the rest.
2064*0b57cec5SDimitry Andric   if (LIsScratch || RIsScratch) {
2065*0b57cec5SDimitry Andric     if (LIsScratch != RIsScratch)
2066*0b57cec5SDimitry Andric       return LIsScratch;
2067*0b57cec5SDimitry Andric     return LOffs.second < ROffs.second;
2068*0b57cec5SDimitry Andric   }
2069*0b57cec5SDimitry Andric   llvm_unreachable("Unsortable locations found");
2070*0b57cec5SDimitry Andric }
2071*0b57cec5SDimitry Andric 
2072*0b57cec5SDimitry Andric std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2073*0b57cec5SDimitry Andric     std::pair<FileID, unsigned> &LOffs,
2074*0b57cec5SDimitry Andric     std::pair<FileID, unsigned> &ROffs) const {
2075*0b57cec5SDimitry Andric   // If the source locations are in the same file, just compare offsets.
2076*0b57cec5SDimitry Andric   if (LOffs.first == ROffs.first)
2077*0b57cec5SDimitry Andric     return std::make_pair(true, LOffs.second < ROffs.second);
2078*0b57cec5SDimitry Andric 
2079*0b57cec5SDimitry Andric   // If we are comparing a source location with multiple locations in the same
2080*0b57cec5SDimitry Andric   // file, we get a big win by caching the result.
2081*0b57cec5SDimitry Andric   InBeforeInTUCacheEntry &IsBeforeInTUCache =
2082*0b57cec5SDimitry Andric     getInBeforeInTUCache(LOffs.first, ROffs.first);
2083*0b57cec5SDimitry Andric 
2084*0b57cec5SDimitry Andric   // If we are comparing a source location with multiple locations in the same
2085*0b57cec5SDimitry Andric   // file, we get a big win by caching the result.
2086*0b57cec5SDimitry Andric   if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2087*0b57cec5SDimitry Andric     return std::make_pair(
2088*0b57cec5SDimitry Andric         true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2089*0b57cec5SDimitry Andric 
2090*0b57cec5SDimitry Andric   // Okay, we missed in the cache, start updating the cache for this query.
2091*0b57cec5SDimitry Andric   IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2092*0b57cec5SDimitry Andric                           /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2093*0b57cec5SDimitry Andric 
2094*0b57cec5SDimitry Andric   // We need to find the common ancestor. The only way of doing this is to
2095*0b57cec5SDimitry Andric   // build the complete include chain for one and then walking up the chain
2096*0b57cec5SDimitry Andric   // of the other looking for a match.
2097*0b57cec5SDimitry Andric   // We use a map from FileID to Offset to store the chain. Easier than writing
2098*0b57cec5SDimitry Andric   // a custom set hash info that only depends on the first part of a pair.
2099*0b57cec5SDimitry Andric   using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2100*0b57cec5SDimitry Andric   LocSet LChain;
2101*0b57cec5SDimitry Andric   do {
2102*0b57cec5SDimitry Andric     LChain.insert(LOffs);
2103*0b57cec5SDimitry Andric     // We catch the case where LOffs is in a file included by ROffs and
2104*0b57cec5SDimitry Andric     // quit early. The other way round unfortunately remains suboptimal.
2105*0b57cec5SDimitry Andric   } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2106*0b57cec5SDimitry Andric   LocSet::iterator I;
2107*0b57cec5SDimitry Andric   while((I = LChain.find(ROffs.first)) == LChain.end()) {
2108*0b57cec5SDimitry Andric     if (MoveUpIncludeHierarchy(ROffs, *this))
2109*0b57cec5SDimitry Andric       break; // Met at topmost file.
2110*0b57cec5SDimitry Andric   }
2111*0b57cec5SDimitry Andric   if (I != LChain.end())
2112*0b57cec5SDimitry Andric     LOffs = *I;
2113*0b57cec5SDimitry Andric 
2114*0b57cec5SDimitry Andric   // If we exited because we found a nearest common ancestor, compare the
2115*0b57cec5SDimitry Andric   // locations within the common file and cache them.
2116*0b57cec5SDimitry Andric   if (LOffs.first == ROffs.first) {
2117*0b57cec5SDimitry Andric     IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2118*0b57cec5SDimitry Andric     return std::make_pair(
2119*0b57cec5SDimitry Andric         true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2120*0b57cec5SDimitry Andric   }
2121*0b57cec5SDimitry Andric   // Clear the lookup cache, it depends on a common location.
2122*0b57cec5SDimitry Andric   IsBeforeInTUCache.clear();
2123*0b57cec5SDimitry Andric   return std::make_pair(false, false);
2124*0b57cec5SDimitry Andric }
2125*0b57cec5SDimitry Andric 
2126*0b57cec5SDimitry Andric void SourceManager::PrintStats() const {
2127*0b57cec5SDimitry Andric   llvm::errs() << "\n*** Source Manager Stats:\n";
2128*0b57cec5SDimitry Andric   llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2129*0b57cec5SDimitry Andric                << " mem buffers mapped.\n";
2130*0b57cec5SDimitry Andric   llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2131*0b57cec5SDimitry Andric                << llvm::capacity_in_bytes(LocalSLocEntryTable)
2132*0b57cec5SDimitry Andric                << " bytes of capacity), "
2133*0b57cec5SDimitry Andric                << NextLocalOffset << "B of Sloc address space used.\n";
2134*0b57cec5SDimitry Andric   llvm::errs() << LoadedSLocEntryTable.size()
2135*0b57cec5SDimitry Andric                << " loaded SLocEntries allocated, "
2136*0b57cec5SDimitry Andric                << MaxLoadedOffset - CurrentLoadedOffset
2137*0b57cec5SDimitry Andric                << "B of Sloc address space used.\n";
2138*0b57cec5SDimitry Andric 
2139*0b57cec5SDimitry Andric   unsigned NumLineNumsComputed = 0;
2140*0b57cec5SDimitry Andric   unsigned NumFileBytesMapped = 0;
2141*0b57cec5SDimitry Andric   for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2142*0b57cec5SDimitry Andric     NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2143*0b57cec5SDimitry Andric     NumFileBytesMapped  += I->second->getSizeBytesMapped();
2144*0b57cec5SDimitry Andric   }
2145*0b57cec5SDimitry Andric   unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2146*0b57cec5SDimitry Andric 
2147*0b57cec5SDimitry Andric   llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2148*0b57cec5SDimitry Andric                << NumLineNumsComputed << " files with line #'s computed, "
2149*0b57cec5SDimitry Andric                << NumMacroArgsComputed << " files with macro args computed.\n";
2150*0b57cec5SDimitry Andric   llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2151*0b57cec5SDimitry Andric                << NumBinaryProbes << " binary.\n";
2152*0b57cec5SDimitry Andric }
2153*0b57cec5SDimitry Andric 
2154*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void SourceManager::dump() const {
2155*0b57cec5SDimitry Andric   llvm::raw_ostream &out = llvm::errs();
2156*0b57cec5SDimitry Andric 
2157*0b57cec5SDimitry Andric   auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2158*0b57cec5SDimitry Andric                            llvm::Optional<unsigned> NextStart) {
2159*0b57cec5SDimitry Andric     out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2160*0b57cec5SDimitry Andric         << " <SourceLocation " << Entry.getOffset() << ":";
2161*0b57cec5SDimitry Andric     if (NextStart)
2162*0b57cec5SDimitry Andric       out << *NextStart << ">\n";
2163*0b57cec5SDimitry Andric     else
2164*0b57cec5SDimitry Andric       out << "???\?>\n";
2165*0b57cec5SDimitry Andric     if (Entry.isFile()) {
2166*0b57cec5SDimitry Andric       auto &FI = Entry.getFile();
2167*0b57cec5SDimitry Andric       if (FI.NumCreatedFIDs)
2168*0b57cec5SDimitry Andric         out << "  covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2169*0b57cec5SDimitry Andric             << ">\n";
2170*0b57cec5SDimitry Andric       if (FI.getIncludeLoc().isValid())
2171*0b57cec5SDimitry Andric         out << "  included from " << FI.getIncludeLoc().getOffset() << "\n";
2172*0b57cec5SDimitry Andric       if (auto *CC = FI.getContentCache()) {
2173*0b57cec5SDimitry Andric         out << "  for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2174*0b57cec5SDimitry Andric             << "\n";
2175*0b57cec5SDimitry Andric         if (CC->BufferOverridden)
2176*0b57cec5SDimitry Andric           out << "  contents overridden\n";
2177*0b57cec5SDimitry Andric         if (CC->ContentsEntry != CC->OrigEntry) {
2178*0b57cec5SDimitry Andric           out << "  contents from "
2179*0b57cec5SDimitry Andric               << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2180*0b57cec5SDimitry Andric               << "\n";
2181*0b57cec5SDimitry Andric         }
2182*0b57cec5SDimitry Andric       }
2183*0b57cec5SDimitry Andric     } else {
2184*0b57cec5SDimitry Andric       auto &EI = Entry.getExpansion();
2185*0b57cec5SDimitry Andric       out << "  spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2186*0b57cec5SDimitry Andric       out << "  macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2187*0b57cec5SDimitry Andric           << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2188*0b57cec5SDimitry Andric           << EI.getExpansionLocEnd().getOffset() << ">\n";
2189*0b57cec5SDimitry Andric     }
2190*0b57cec5SDimitry Andric   };
2191*0b57cec5SDimitry Andric 
2192*0b57cec5SDimitry Andric   // Dump local SLocEntries.
2193*0b57cec5SDimitry Andric   for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2194*0b57cec5SDimitry Andric     DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2195*0b57cec5SDimitry Andric                   ID == NumIDs - 1 ? NextLocalOffset
2196*0b57cec5SDimitry Andric                                    : LocalSLocEntryTable[ID + 1].getOffset());
2197*0b57cec5SDimitry Andric   }
2198*0b57cec5SDimitry Andric   // Dump loaded SLocEntries.
2199*0b57cec5SDimitry Andric   llvm::Optional<unsigned> NextStart;
2200*0b57cec5SDimitry Andric   for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2201*0b57cec5SDimitry Andric     int ID = -(int)Index - 2;
2202*0b57cec5SDimitry Andric     if (SLocEntryLoaded[Index]) {
2203*0b57cec5SDimitry Andric       DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2204*0b57cec5SDimitry Andric       NextStart = LoadedSLocEntryTable[Index].getOffset();
2205*0b57cec5SDimitry Andric     } else {
2206*0b57cec5SDimitry Andric       NextStart = None;
2207*0b57cec5SDimitry Andric     }
2208*0b57cec5SDimitry Andric   }
2209*0b57cec5SDimitry Andric }
2210*0b57cec5SDimitry Andric 
2211*0b57cec5SDimitry Andric ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2212*0b57cec5SDimitry Andric 
2213*0b57cec5SDimitry Andric /// Return the amount of memory used by memory buffers, breaking down
2214*0b57cec5SDimitry Andric /// by heap-backed versus mmap'ed memory.
2215*0b57cec5SDimitry Andric SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2216*0b57cec5SDimitry Andric   size_t malloc_bytes = 0;
2217*0b57cec5SDimitry Andric   size_t mmap_bytes = 0;
2218*0b57cec5SDimitry Andric 
2219*0b57cec5SDimitry Andric   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2220*0b57cec5SDimitry Andric     if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2221*0b57cec5SDimitry Andric       switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2222*0b57cec5SDimitry Andric         case llvm::MemoryBuffer::MemoryBuffer_MMap:
2223*0b57cec5SDimitry Andric           mmap_bytes += sized_mapped;
2224*0b57cec5SDimitry Andric           break;
2225*0b57cec5SDimitry Andric         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2226*0b57cec5SDimitry Andric           malloc_bytes += sized_mapped;
2227*0b57cec5SDimitry Andric           break;
2228*0b57cec5SDimitry Andric       }
2229*0b57cec5SDimitry Andric 
2230*0b57cec5SDimitry Andric   return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2231*0b57cec5SDimitry Andric }
2232*0b57cec5SDimitry Andric 
2233*0b57cec5SDimitry Andric size_t SourceManager::getDataStructureSizes() const {
2234*0b57cec5SDimitry Andric   size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2235*0b57cec5SDimitry Andric     + llvm::capacity_in_bytes(LocalSLocEntryTable)
2236*0b57cec5SDimitry Andric     + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2237*0b57cec5SDimitry Andric     + llvm::capacity_in_bytes(SLocEntryLoaded)
2238*0b57cec5SDimitry Andric     + llvm::capacity_in_bytes(FileInfos);
2239*0b57cec5SDimitry Andric 
2240*0b57cec5SDimitry Andric   if (OverriddenFilesInfo)
2241*0b57cec5SDimitry Andric     size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2242*0b57cec5SDimitry Andric 
2243*0b57cec5SDimitry Andric   return size;
2244*0b57cec5SDimitry Andric }
2245*0b57cec5SDimitry Andric 
2246*0b57cec5SDimitry Andric SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2247*0b57cec5SDimitry Andric                                            StringRef Content) {
2248*0b57cec5SDimitry Andric   // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2249*0b57cec5SDimitry Andric   // is deleted.
2250*0b57cec5SDimitry Andric   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2251*0b57cec5SDimitry Andric       new llvm::vfs::InMemoryFileSystem);
2252*0b57cec5SDimitry Andric   InMemoryFileSystem->addFile(
2253*0b57cec5SDimitry Andric       FileName, 0,
2254*0b57cec5SDimitry Andric       llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2255*0b57cec5SDimitry Andric                                        /*RequiresNullTerminator=*/false));
2256*0b57cec5SDimitry Andric   // This is passed to `SM` as reference, so the pointer has to be referenced
2257*0b57cec5SDimitry Andric   // in `Environment` so that `FileMgr` can out-live this function scope.
2258*0b57cec5SDimitry Andric   FileMgr =
2259*0b57cec5SDimitry Andric       llvm::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2260*0b57cec5SDimitry Andric   // This is passed to `SM` as reference, so the pointer has to be referenced
2261*0b57cec5SDimitry Andric   // by `Environment` due to the same reason above.
2262*0b57cec5SDimitry Andric   Diagnostics = llvm::make_unique<DiagnosticsEngine>(
2263*0b57cec5SDimitry Andric       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2264*0b57cec5SDimitry Andric       new DiagnosticOptions);
2265*0b57cec5SDimitry Andric   SourceMgr = llvm::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2266*0b57cec5SDimitry Andric   FileID ID = SourceMgr->createFileID(FileMgr->getFile(FileName),
2267*0b57cec5SDimitry Andric                                       SourceLocation(), clang::SrcMgr::C_User);
2268*0b57cec5SDimitry Andric   assert(ID.isValid());
2269*0b57cec5SDimitry Andric   SourceMgr->setMainFileID(ID);
2270*0b57cec5SDimitry Andric }
2271