ea7822a2c4b466aa4ed802c8fd4b84b3625f4e58
[oota-llvm.git] / lib / Support / FileUtilities.cpp
1 //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a family of utility functions which are useful for doing
11 // various things with files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Support/FileUtilities.h"
16 #include "llvm/System/Path.h"
17 #include "llvm/System/MappedFile.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include <cstring>
20 #include <cctype>
21 using namespace llvm;
22
23 static bool isNumberChar(char C) {
24   switch (C) {
25   case '0': case '1': case '2': case '3': case '4':
26   case '5': case '6': case '7': case '8': case '9':
27   case '.': case '+': case '-':
28   case 'D':  // Strange exponential notation.
29   case 'd':  // Strange exponential notation.
30   case 'e':
31   case 'E': return true;
32   default: return false;
33   }
34 }
35
36 static char *BackupNumber(char *Pos, char *FirstChar) {
37   // If we didn't stop in the middle of a number, don't backup.
38   if (!isNumberChar(*Pos)) return Pos;
39
40   // Otherwise, return to the start of the number.
41   while (Pos > FirstChar && isNumberChar(Pos[-1]))
42     --Pos;
43   return Pos;
44 }
45
46 /// CompareNumbers - compare two numbers, returning true if they are different.
47 static bool CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End,
48                            double AbsTolerance, double RelTolerance,
49                            std::string *ErrorMsg) {
50   char *F1NumEnd, *F2NumEnd;
51   double V1 = 0.0, V2 = 0.0;
52
53   // If one of the positions is at a space and the other isn't, chomp up 'til
54   // the end of the space.
55   while (isspace(*F1P) && F1P != F1End)
56     ++F1P;
57   while (isspace(*F2P) && F2P != F2End)
58     ++F2P;
59
60   // If we stop on numbers, compare their difference.  Note that some ugliness
61   // is built into this to permit support for numbers that use "D" or "d" as
62   // their exponential marker, e.g. "1.234D45".  This occurs in 200.sixtrack in
63   // spec2k.
64   if (isNumberChar(*F1P) && isNumberChar(*F2P)) {
65     bool isDNotation;
66     do {
67       isDNotation = false;
68       V1 = strtod(F1P, &F1NumEnd);
69       V2 = strtod(F2P, &F2NumEnd);
70
71       if (*F1NumEnd == 'D' || *F1NumEnd == 'd') {
72         *F1NumEnd = 'e';  // Strange exponential notation!
73         isDNotation = true;
74       }
75       if (*F2NumEnd == 'D' || *F2NumEnd == 'd') {
76         *F2NumEnd = 'e';  // Strange exponential notation!
77         isDNotation = true;
78       }
79     } while (isDNotation);
80   } else {
81     // Otherwise, the diff failed.
82     F1NumEnd = F1P;
83     F2NumEnd = F2P;
84   }
85
86   if (F1NumEnd == F1P || F2NumEnd == F2P) {
87     if (ErrorMsg) {
88       *ErrorMsg = "FP Comparison failed, not a numeric difference between '";
89       *ErrorMsg += F1P[0];
90       *ErrorMsg += "' and '";
91       *ErrorMsg += F2P[0];
92       *ErrorMsg += "'";
93     }
94     return true;
95   }
96
97   // Check to see if these are inside the absolute tolerance
98   if (AbsTolerance < std::abs(V1-V2)) {
99     // Nope, check the relative tolerance...
100     double Diff;
101     if (V2)
102       Diff = std::abs(V1/V2 - 1.0);
103     else if (V1)
104       Diff = std::abs(V2/V1 - 1.0);
105     else
106       Diff = 0;  // Both zero.
107     if (Diff > RelTolerance) {
108       if (ErrorMsg) {
109         *ErrorMsg = "Compared: " + ftostr(V1) + " and " + ftostr(V2) +
110                     ": diff = " + ftostr(Diff) + "\n";
111         *ErrorMsg += "Out of tolerance: rel/abs: " + ftostr(RelTolerance) +
112                      "/" + ftostr(AbsTolerance);
113       }
114       return true;
115     }
116   }
117
118   // Otherwise, advance our read pointers to the end of the numbers.
119   F1P = F1NumEnd;  F2P = F2NumEnd;
120   return false;
121 }
122
123 // PadFileIfNeeded - If the files are not identical, we will have to be doing
124 // numeric comparisons in here.  There are bad cases involved where we (i.e.,
125 // strtod) might run off the beginning or end of the file if it starts or ends
126 // with a number.  Because of this, if needed, we pad the file so that it starts
127 // and ends with a null character.
128 static void PadFileIfNeeded(char *&FileStart, char *&FileEnd, char *&FP) {
129   if (FileStart-FileEnd < 2 ||
130       isNumberChar(FileStart[0]) || isNumberChar(FileEnd[-1])) {
131     unsigned FileLen = FileEnd-FileStart;
132     char *NewFile = new char[FileLen+2];
133     NewFile[0] = 0;              // Add null padding
134     NewFile[FileLen+1] = 0;      // Add null padding
135     memcpy(NewFile+1, FileStart, FileLen);
136     FP = NewFile+(FP-FileStart)+1;
137     FileStart = NewFile+1;
138     FileEnd = FileStart+FileLen;
139   }
140 }
141
142 /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the
143 /// files match, 1 if they are different, and 2 if there is a file error.  This
144 /// function differs from DiffFiles in that you can specify an absolete and
145 /// relative FP error that is allowed to exist.  If you specify a string to fill
146 /// in for the error option, it will set the string to an error message if an
147 /// error occurs, allowing the caller to distinguish between a failed diff and a
148 /// file system error.
149 ///
150 int llvm::DiffFilesWithTolerance(const sys::Path &FileA,
151                                  const sys::Path &FileB,
152                                  double AbsTol, double RelTol,
153                                  std::string *Error) {
154   sys::FileStatus FileAStat, FileBStat;
155   if (FileA.getFileStatus(FileAStat, Error))
156     return 2;
157   if (FileB.getFileStatus(FileBStat, Error))
158     return 2;
159
160   // Check for zero length files because some systems croak when you try to
161   // mmap an empty file.
162   size_t A_size = FileAStat.getSize();
163   size_t B_size = FileBStat.getSize();
164
165   // If they are both zero sized then they're the same
166   if (A_size == 0 && B_size == 0)
167     return 0;
168
169   // If only one of them is zero sized then they can't be the same
170   if ((A_size == 0 || B_size == 0)) {
171     if (Error)
172       *Error = "Files differ: one is zero-sized, the other isn't";
173     return 1;
174   }
175
176   // Now its safe to mmap the files into memory becasue both files
177   // have a non-zero size.
178   sys::MappedFile F1;
179   if (F1.open(FileA, sys::MappedFile::READ_ACCESS, Error))
180     return 2;
181   sys::MappedFile F2;
182   if (F2.open(FileB, sys::MappedFile::READ_ACCESS, Error))
183     return 2;
184   if (!F1.map(Error))
185     return 2;
186   if (!F2.map(Error))
187     return 2;
188
189   // Okay, now that we opened the files, scan them for the first difference.
190   char *File1Start = F1.charBase();
191   char *File2Start = F2.charBase();
192   char *File1End = File1Start+A_size;
193   char *File2End = File2Start+B_size;
194   char *F1P = File1Start;
195   char *F2P = File2Start;
196
197   if (A_size == B_size) {
198     // Are the buffers identical?
199     if (std::memcmp(File1Start, File2Start, A_size) == 0)
200       return 0;
201
202     if (AbsTol == 0 && RelTol == 0) {
203       if (Error)
204         *Error = "Files differ without tolerance allowance";
205       return 1;   // Files different!
206     }
207   }
208
209   char *OrigFile1Start = File1Start;
210   char *OrigFile2Start = File2Start;
211
212   // If the files need padding, do so now.
213   PadFileIfNeeded(File1Start, File1End, F1P);
214   PadFileIfNeeded(File2Start, File2End, F2P);
215
216   bool CompareFailed = false;
217   while (1) {
218     // Scan for the end of file or next difference.
219     while (F1P < File1End && F2P < File2End && *F1P == *F2P)
220       ++F1P, ++F2P;
221
222     if (F1P >= File1End || F2P >= File2End) break;
223
224     // Okay, we must have found a difference.  Backup to the start of the
225     // current number each stream is at so that we can compare from the
226     // beginning.
227     F1P = BackupNumber(F1P, File1Start);
228     F2P = BackupNumber(F2P, File2Start);
229
230     // Now that we are at the start of the numbers, compare them, exiting if
231     // they don't match.
232     if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) {
233       CompareFailed = true;
234       break;
235     }
236   }
237
238   // Okay, we reached the end of file.  If both files are at the end, we
239   // succeeded.
240   bool F1AtEnd = F1P >= File1End;
241   bool F2AtEnd = F2P >= File2End;
242   if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) {
243     // Else, we might have run off the end due to a number: backup and retry.
244     if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;
245     if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;
246     F1P = BackupNumber(F1P, File1Start);
247     F2P = BackupNumber(F2P, File2Start);
248
249     // Now that we are at the start of the numbers, compare them, exiting if
250     // they don't match.
251     if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error))
252       CompareFailed = true;
253
254     // If we found the end, we succeeded.
255     if (F1P < File1End || F2P < File2End)
256       CompareFailed = true;
257   }
258
259   if (OrigFile1Start != File1Start)
260     delete[] (File1Start-1);   // Back up past null byte
261   if (OrigFile2Start != File2Start)
262     delete[] (File2Start-1);   // Back up past null byte
263   return CompareFailed;
264 }