R600/SI: add all the other missing asm operands v2
[oota-llvm.git] / lib / Support / MemoryBuffer.cpp
1 //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the MemoryBuffer interface.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/MemoryBuffer.h"
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/Config/config.h"
18 #include "llvm/Support/Errno.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/Process.h"
23 #include "llvm/Support/Program.h"
24 #include "llvm/Support/system_error.h"
25 #include <cassert>
26 #include <cerrno>
27 #include <cstdio>
28 #include <cstring>
29 #include <new>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #if !defined(_MSC_VER) && !defined(__MINGW32__)
33 #include <unistd.h>
34 #else
35 #include <io.h>
36 // Simplistic definitinos of these macros to allow files to be read with
37 // MapInFilePages.
38 #ifndef S_ISREG
39 #define S_ISREG(x) (1)
40 #endif
41 #ifndef S_ISBLK
42 #define S_ISBLK(x) (0)
43 #endif
44 #endif
45 #include <fcntl.h>
46 using namespace llvm;
47
48 //===----------------------------------------------------------------------===//
49 // MemoryBuffer implementation itself.
50 //===----------------------------------------------------------------------===//
51
52 MemoryBuffer::~MemoryBuffer() { }
53
54 /// init - Initialize this MemoryBuffer as a reference to externally allocated
55 /// memory, memory that we know is already null terminated.
56 void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
57                         bool RequiresNullTerminator) {
58   assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
59          "Buffer is not null terminated!");
60   BufferStart = BufStart;
61   BufferEnd = BufEnd;
62 }
63
64 //===----------------------------------------------------------------------===//
65 // MemoryBufferMem implementation.
66 //===----------------------------------------------------------------------===//
67
68 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
69 /// null-terminates it.
70 static void CopyStringRef(char *Memory, StringRef Data) {
71   memcpy(Memory, Data.data(), Data.size());
72   Memory[Data.size()] = 0; // Null terminate string.
73 }
74
75 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
76 template <typename T>
77 static T *GetNamedBuffer(StringRef Buffer, StringRef Name,
78                          bool RequiresNullTerminator) {
79   char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
80   CopyStringRef(Mem + sizeof(T), Name);
81   return new (Mem) T(Buffer, RequiresNullTerminator);
82 }
83
84 namespace {
85 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
86 class MemoryBufferMem : public MemoryBuffer {
87 public:
88   MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
89     init(InputData.begin(), InputData.end(), RequiresNullTerminator);
90   }
91
92   virtual const char *getBufferIdentifier() const LLVM_OVERRIDE {
93      // The name is stored after the class itself.
94     return reinterpret_cast<const char*>(this + 1);
95   }
96
97   virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
98     return MemoryBuffer_Malloc;
99   }
100 };
101 }
102
103 /// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
104 /// that InputData must be a null terminated if RequiresNullTerminator is true!
105 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
106                                          StringRef BufferName,
107                                          bool RequiresNullTerminator) {
108   return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName,
109                                          RequiresNullTerminator);
110 }
111
112 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
113 /// copying the contents and taking ownership of it.  This has no requirements
114 /// on EndPtr[0].
115 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
116                                              StringRef BufferName) {
117   MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
118   if (!Buf) return 0;
119   memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
120          InputData.size());
121   return Buf;
122 }
123
124 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
125 /// that is not initialized.  Note that the caller should initialize the
126 /// memory allocated by this method.  The memory is owned by the MemoryBuffer
127 /// object.
128 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
129                                                   StringRef BufferName) {
130   // Allocate space for the MemoryBuffer, the data and the name. It is important
131   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
132   size_t AlignedStringLen =
133     RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
134                        sizeof(void*)); // TODO: Is sizeof(void*) enough?
135   size_t RealLen = AlignedStringLen + Size + 1;
136   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
137   if (!Mem) return 0;
138
139   // The name is stored after the class itself.
140   CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
141
142   // The buffer begins after the name and must be aligned.
143   char *Buf = Mem + AlignedStringLen;
144   Buf[Size] = 0; // Null terminate buffer.
145
146   return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
147 }
148
149 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
150 /// is completely initialized to zeros.  Note that the caller should
151 /// initialize the memory allocated by this method.  The memory is owned by
152 /// the MemoryBuffer object.
153 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
154   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
155   if (!SB) return 0;
156   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
157   return SB;
158 }
159
160
161 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
162 /// if the Filename is "-".  If an error occurs, this returns null and fills
163 /// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
164 /// returns an empty buffer.
165 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
166                                         OwningPtr<MemoryBuffer> &result,
167                                         int64_t FileSize) {
168   if (Filename == "-")
169     return getSTDIN(result);
170   return getFile(Filename, result, FileSize);
171 }
172
173 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
174                                         OwningPtr<MemoryBuffer> &result,
175                                         int64_t FileSize) {
176   if (strcmp(Filename, "-") == 0)
177     return getSTDIN(result);
178   return getFile(Filename, result, FileSize);
179 }
180
181 //===----------------------------------------------------------------------===//
182 // MemoryBuffer::getFile implementation.
183 //===----------------------------------------------------------------------===//
184
185 namespace {
186 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
187 /// sys::Path::MapInFilePages method.  When destroyed, it calls the
188 /// sys::Path::UnMapFilePages method.
189 class MemoryBufferMMapFile : public MemoryBufferMem {
190 public:
191   MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
192     : MemoryBufferMem(Buffer, RequiresNullTerminator) { }
193
194   ~MemoryBufferMMapFile() {
195     static int PageSize = sys::process::get_self()->page_size();
196
197     uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
198     size_t Size = getBufferSize();
199     uintptr_t RealStart = Start & ~(PageSize - 1);
200     size_t RealSize = Size + (Start - RealStart);
201
202     sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
203                               RealSize);
204   }
205
206   virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
207     return MemoryBuffer_MMap;
208   }
209 };
210 }
211
212 static error_code getMemoryBufferForStream(int FD, 
213                                            StringRef BufferName,
214                                            OwningPtr<MemoryBuffer> &result) {
215   const ssize_t ChunkSize = 4096*4;
216   SmallString<ChunkSize> Buffer;
217   ssize_t ReadBytes;
218   // Read into Buffer until we hit EOF.
219   do {
220     Buffer.reserve(Buffer.size() + ChunkSize);
221     ReadBytes = read(FD, Buffer.end(), ChunkSize);
222     if (ReadBytes == -1) {
223       if (errno == EINTR) continue;
224       return error_code(errno, posix_category());
225     }
226     Buffer.set_size(Buffer.size() + ReadBytes);
227   } while (ReadBytes != 0);
228
229   result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
230   return error_code::success();
231 }
232
233 error_code MemoryBuffer::getFile(StringRef Filename,
234                                  OwningPtr<MemoryBuffer> &result,
235                                  int64_t FileSize,
236                                  bool RequiresNullTerminator) {
237   // Ensure the path is null terminated.
238   SmallString<256> PathBuf(Filename.begin(), Filename.end());
239   return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize,
240                                RequiresNullTerminator);
241 }
242
243 error_code MemoryBuffer::getFile(const char *Filename,
244                                  OwningPtr<MemoryBuffer> &result,
245                                  int64_t FileSize,
246                                  bool RequiresNullTerminator) {
247   // First check that the "file" is not a directory
248   bool is_dir = false;
249   error_code err = sys::fs::is_directory(Filename, is_dir);
250   if (err)
251     return err;
252   if (is_dir)
253     return make_error_code(errc::is_a_directory);
254
255   int OpenFlags = O_RDONLY;
256 #ifdef O_BINARY
257   OpenFlags |= O_BINARY;  // Open input file in binary mode on win32.
258 #endif
259   int FD = ::open(Filename, OpenFlags);
260   if (FD == -1)
261     return error_code(errno, posix_category());
262
263   error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize,
264                                0, RequiresNullTerminator);
265   close(FD);
266   return ret;
267 }
268
269 static bool shouldUseMmap(int FD,
270                           size_t FileSize,
271                           size_t MapSize,
272                           off_t Offset,
273                           bool RequiresNullTerminator,
274                           int PageSize) {
275   // We don't use mmap for small files because this can severely fragment our
276   // address space.
277   if (MapSize < 4096*4)
278     return false;
279
280   if (!RequiresNullTerminator)
281     return true;
282
283
284   // If we don't know the file size, use fstat to find out.  fstat on an open
285   // file descriptor is cheaper than stat on a random path.
286   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
287   // RequiresNullTerminator = false and MapSize != -1.
288   if (FileSize == size_t(-1)) {
289     struct stat FileInfo;
290     // TODO: This should use fstat64 when available.
291     if (fstat(FD, &FileInfo) == -1) {
292       return error_code(errno, posix_category());
293     }
294     FileSize = FileInfo.st_size;
295   }
296
297   // If we need a null terminator and the end of the map is inside the file,
298   // we cannot use mmap.
299   size_t End = Offset + MapSize;
300   assert(End <= FileSize);
301   if (End != FileSize)
302     return false;
303
304   // Don't try to map files that are exactly a multiple of the system page size
305   // if we need a null terminator.
306   if ((FileSize & (PageSize -1)) == 0)
307     return false;
308
309   return true;
310 }
311
312 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
313                                      OwningPtr<MemoryBuffer> &result,
314                                      uint64_t FileSize, uint64_t MapSize,
315                                      int64_t Offset,
316                                      bool RequiresNullTerminator) {
317   static int PageSize = sys::process::get_self()->page_size();
318
319   // Default is to map the full file.
320   if (MapSize == uint64_t(-1)) {
321     // If we don't know the file size, use fstat to find out.  fstat on an open
322     // file descriptor is cheaper than stat on a random path.
323     if (FileSize == uint64_t(-1)) {
324       struct stat FileInfo;
325       // TODO: This should use fstat64 when available.
326       if (fstat(FD, &FileInfo) == -1) {
327         return error_code(errno, posix_category());
328       }
329
330       // If this not a file or a block device (e.g. it's a named pipe
331       // or character device), we can't trust the size. Create the memory
332       // buffer by copying off the stream.
333       if (!S_ISREG(FileInfo.st_mode) && !S_ISBLK(FileInfo.st_mode)) {
334         return getMemoryBufferForStream(FD, Filename, result);
335       }
336
337       FileSize = FileInfo.st_size;
338     }
339     MapSize = FileSize;
340   }
341
342   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
343                     PageSize)) {
344     off_t RealMapOffset = Offset & ~(PageSize - 1);
345     off_t Delta = Offset - RealMapOffset;
346     size_t RealMapSize = MapSize + Delta;
347
348     if (const char *Pages = sys::Path::MapInFilePages(FD,
349                                                       RealMapSize,
350                                                       RealMapOffset)) {
351       result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
352           StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
353       return error_code::success();
354     }
355   }
356
357   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
358   if (!Buf) {
359     // Failed to create a buffer. The only way it can fail is if
360     // new(std::nothrow) returns 0.
361     return make_error_code(errc::not_enough_memory);
362   }
363
364   OwningPtr<MemoryBuffer> SB(Buf);
365   char *BufPtr = const_cast<char*>(SB->getBufferStart());
366
367   size_t BytesLeft = MapSize;
368 #ifndef HAVE_PREAD
369   if (lseek(FD, Offset, SEEK_SET) == -1)
370     return error_code(errno, posix_category());
371 #endif
372
373   while (BytesLeft) {
374 #ifdef HAVE_PREAD
375     ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
376 #else
377     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
378 #endif
379     if (NumRead == -1) {
380       if (errno == EINTR)
381         continue;
382       // Error while reading.
383       return error_code(errno, posix_category());
384     }
385     if (NumRead == 0) {
386       assert(0 && "We got inaccurate FileSize value or fstat reported an "
387                    "invalid file size.");
388       *BufPtr = '\0'; // null-terminate at the actual size.
389       break;
390     }
391     BytesLeft -= NumRead;
392     BufPtr += NumRead;
393   }
394
395   result.swap(SB);
396   return error_code::success();
397 }
398
399 //===----------------------------------------------------------------------===//
400 // MemoryBuffer::getSTDIN implementation.
401 //===----------------------------------------------------------------------===//
402
403 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
404   // Read in all of the data from stdin, we cannot mmap stdin.
405   //
406   // FIXME: That isn't necessarily true, we should try to mmap stdin and
407   // fallback if it fails.
408   sys::Program::ChangeStdinToBinary();
409
410   return getMemoryBufferForStream(0, "<stdin>", result);
411 }