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