Fix a bug in previous checkin
[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 <cmath>
20 #include <fstream>
21 #include <iostream>
22
23 using namespace llvm;
24
25 /// DiffFiles - Compare the two files specified, returning true if they are
26 /// different or if there is a file error.  If you specify a string to fill in
27 /// for the error option, it will set the string to an error message if an error
28 /// occurs, allowing the caller to distinguish between a failed diff and a file
29 /// system error.
30 ///
31 bool llvm::DiffFiles(const std::string &FileA, const std::string &FileB,
32                      std::string *Error) {
33   std::ios::openmode io_mode = std::ios::in | std::ios::binary;
34   std::ifstream FileAStream(FileA.c_str(), io_mode);
35   if (!FileAStream) {
36     if (Error) *Error = "Couldn't open file '" + FileA + "'";
37     return true;
38   }
39
40   std::ifstream FileBStream(FileB.c_str(), io_mode);
41   if (!FileBStream) {
42     if (Error) *Error = "Couldn't open file '" + FileB + "'";
43     return true;
44   }
45
46   // Compare the two files...
47   int C1, C2;
48   do {
49     C1 = FileAStream.get();
50     C2 = FileBStream.get();
51     if (C1 != C2) return true;
52   } while (C1 != EOF);
53
54   return false;
55 }
56
57 /// MoveFileOverIfUpdated - If the file specified by New is different than Old,
58 /// or if Old does not exist, move the New file over the Old file.  Otherwise,
59 /// remove the New file.
60 ///
61 void llvm::MoveFileOverIfUpdated(const std::string &New,
62                                  const std::string &Old) {
63   if (DiffFiles(New, Old)) {
64     if (std::rename(New.c_str(), Old.c_str()))
65       std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n";
66   } else {
67     std::remove(New.c_str());
68   }  
69 }
70
71 static bool isNumberChar(char C) {
72   switch (C) {
73   case '0': case '1': case '2': case '3': case '4':
74   case '5': case '6': case '7': case '8': case '9': 
75   case '.': case '+': case '-':
76   case 'e':
77   case 'E': return true;
78   default: return false;
79   }
80 }
81
82 static char *BackupNumber(char *Pos, char *FirstChar) {
83   // If we didn't stop in the middle of a number, don't backup.
84   if (!isNumberChar(*Pos)) return Pos;
85
86   // Otherwise, return to the start of the number.
87   while (Pos > FirstChar && isNumberChar(Pos[-1]))
88     --Pos;
89   return Pos;
90 }
91
92 /// CompareNumbers - compare two numbers, returning true if they are different.
93 static bool CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End,
94                            double AbsTolerance, double RelTolerance,
95                            std::string *ErrorMsg) {
96   char *F1NumEnd, *F2NumEnd;
97   double V1 = 0.0, V2 = 0.0; 
98   // If we stop on numbers, compare their difference.
99   if (isNumberChar(*F1P) && isNumberChar(*F2P)) {
100     V1 = strtod(F1P, &F1NumEnd);
101     V2 = strtod(F2P, &F2NumEnd);
102   } else {
103     // Otherwise, the diff failed.
104     F1NumEnd = F1P;
105     F2NumEnd = F2P;
106   }
107
108   if (F1NumEnd == F1P || F2NumEnd == F2P) {
109     if (ErrorMsg) *ErrorMsg = "Comparison failed, not a numeric difference.";
110     return true;
111   }
112
113   // Check to see if these are inside the absolute tolerance
114   if (AbsTolerance < std::abs(V1-V2)) {
115     // Nope, check the relative tolerance...
116     double Diff;
117     if (V2)
118       Diff = std::abs(V1/V2 - 1.0);
119     else if (V1)
120       Diff = std::abs(V2/V1 - 1.0);
121     else
122       Diff = 0;  // Both zero.
123     if (Diff > RelTolerance) {
124       if (ErrorMsg) {
125         *ErrorMsg = "Compared: " + ftostr(V1) + " and " + ftostr(V2) +
126                     ": diff = " + ftostr(Diff) + "\n";
127         *ErrorMsg += "Out of tolerance: rel/abs: " + ftostr(RelTolerance) +
128                      "/" + ftostr(AbsTolerance);
129       }
130       return true;
131     }
132   }
133
134   // Otherwise, advance our read pointers to the end of the numbers.
135   F1P = F1NumEnd;  F2P = F2NumEnd;
136   return false;
137 }
138
139 // PadFileIfNeeded - If the files are not identical, we will have to be doing
140 // numeric comparisons in here.  There are bad cases involved where we (i.e.,
141 // strtod) might run off the beginning or end of the file if it starts or ends
142 // with a number.  Because of this, if needed, we pad the file so that it starts
143 // and ends with a null character.
144 static void PadFileIfNeeded(char *&FileStart, char *&FileEnd, char *&FP) {
145   if (isNumberChar(FileStart[0]) || isNumberChar(FileEnd[-1])) {
146     unsigned FileLen = FileEnd-FileStart;
147     char *NewFile = new char[FileLen+2];
148     NewFile[0] = 0;              // Add null padding
149     NewFile[FileLen+1] = 0;      // Add null padding
150     memcpy(NewFile+1, FileStart, FileLen);
151     FP = NewFile+(FP-FileStart)+1;
152     FileStart = NewFile+1;
153     FileEnd = FileStart+FileLen;
154   }
155 }
156
157 /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the
158 /// files match, 1 if they are different, and 2 if there is a file error.  This
159 /// function differs from DiffFiles in that you can specify an absolete and
160 /// relative FP error that is allowed to exist.  If you specify a string to fill
161 /// in for the error option, it will set the string to an error message if an
162 /// error occurs, allowing the caller to distinguish between a failed diff and a
163 /// file system error.
164 ///
165 int llvm::DiffFilesWithTolerance(const std::string &FileA,
166                                  const std::string &FileB,
167                                  double AbsTol, double RelTol,
168                                  std::string *Error) {
169   try {
170     // Map in the files into memory.
171     sys::MappedFile F1((sys::Path(FileA)));
172     sys::MappedFile F2((sys::Path(FileB)));
173     F1.map();
174     F2.map();
175
176     // Okay, now that we opened the files, scan them for the first difference.
177     char *File1Start = F1.charBase();
178     char *File2Start = F2.charBase();
179     char *File1End = File1Start+F1.size();
180     char *File2End = File2Start+F2.size();
181     char *F1P = File1Start;
182     char *F2P = File2Start;
183
184     // Scan for the end of file or first difference.
185     while (F1P < File1End && F2P < File2End && *F1P == *F2P)
186       ++F1P, ++F2P;
187
188     // Common case: identifical files.
189     if (F1P == File1End && F2P == File2End) return 0;
190
191     char *OrigFile1Start = File1Start;
192     char *OrigFile2Start = File2Start;
193
194     // If the files need padding, do so now.
195     PadFileIfNeeded(File1Start, File1End, F1P);
196     PadFileIfNeeded(File2Start, File2End, F2P);
197     
198     bool CompareFailed = false;
199     while (1) {
200       // Scan for the end of file or next difference.
201       while (F1P < File1End && F2P < File2End && *F1P == *F2P)
202         ++F1P, ++F2P;
203
204       if (F1P >= File1End || F2P >= File2End) break;
205
206       // Okay, we must have found a difference.  Backup to the start of the
207       // current number each stream is at so that we can compare from the
208       // beginning.
209       F1P = BackupNumber(F1P, File1Start);
210       F2P = BackupNumber(F2P, File2Start);
211
212       // Now that we are at the start of the numbers, compare them, exiting if
213       // they don't match.
214       if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) {
215         CompareFailed = true;
216         break;
217       }
218     }
219
220     // Okay, we reached the end of file.  If both files are at the end, we
221     // succeeded.
222     bool F1AtEnd = F1P >= File1End;
223     bool F2AtEnd = F2P >= File2End;
224     if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) {
225       // Else, we might have run off the end due to a number: backup and retry.
226       if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;
227       if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;
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
236       // If we found the end, we succeeded.
237       if (F1P < File1End || F2P < File2End)
238         CompareFailed = true;
239     }
240
241     if (OrigFile1Start != File1Start)
242       delete[] File1Start-1;   // Back up past null byte
243     if (OrigFile2Start != File2Start)
244       delete[] File2Start-1;   // Back up past null byte
245     return CompareFailed;
246   } catch (const std::string &Msg) {
247     if (Error) *Error = Msg;
248     return 2;
249   }
250 }