Fix the ridiculous SubtargetFeatures API where it implicitly expects CPU name to
[oota-llvm.git] / lib / MC / SubtargetFeature.cpp
1 //===- SubtargetFeature.cpp - CPU characteristics 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 SubtargetFeature interface.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/MC/SubtargetFeature.h"
15 #include "llvm/Support/Debug.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include <algorithm>
19 #include <cassert>
20 #include <cctype>
21 #include <cstdlib>
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 //                          Static Helper Functions
26 //===----------------------------------------------------------------------===//
27
28 /// hasFlag - Determine if a feature has a flag; '+' or '-'
29 ///
30 static inline bool hasFlag(const std::string &Feature) {
31   assert(!Feature.empty() && "Empty string");
32   // Get first character
33   char Ch = Feature[0];
34   // Check if first character is '+' or '-' flag
35   return Ch == '+' || Ch =='-';
36 }
37
38 /// StripFlag - Return string stripped of flag.
39 ///
40 static inline std::string StripFlag(const std::string &Feature) {
41   return hasFlag(Feature) ? Feature.substr(1) : Feature;
42 }
43
44 /// isEnabled - Return true if enable flag; '+'.
45 ///
46 static inline bool isEnabled(const std::string &Feature) {
47   assert(!Feature.empty() && "Empty string");
48   // Get first character
49   char Ch = Feature[0];
50   // Check if first character is '+' for enabled
51   return Ch == '+';
52 }
53
54 /// PrependFlag - Return a string with a prepended flag; '+' or '-'.
55 ///
56 static inline std::string PrependFlag(const std::string &Feature,
57                                       bool IsEnabled) {
58   assert(!Feature.empty() && "Empty string");
59   if (hasFlag(Feature)) return Feature;
60   return std::string(IsEnabled ? "+" : "-") + Feature;
61 }
62
63 /// Split - Splits a string of comma separated items in to a vector of strings.
64 ///
65 static void Split(std::vector<std::string> &V, const std::string &S) {
66   if (S.empty())
67     return;
68
69   // Start at beginning of string.
70   size_t Pos = 0;
71   while (true) {
72     // Find the next comma
73     size_t Comma = S.find(',', Pos);
74     // If no comma found then the rest of the string is used
75     if (Comma == std::string::npos) {
76       // Add string to vector
77       V.push_back(S.substr(Pos));
78       break;
79     }
80     // Otherwise add substring to vector
81     V.push_back(S.substr(Pos, Comma - Pos));
82     // Advance to next item
83     Pos = Comma + 1;
84   }
85 }
86
87 /// Join a vector of strings to a string with a comma separating each element.
88 ///
89 static std::string Join(const std::vector<std::string> &V) {
90   // Start with empty string.
91   std::string Result;
92   // If the vector is not empty 
93   if (!V.empty()) {
94     // Start with the first feature
95     Result = V[0];
96     // For each successive feature
97     for (size_t i = 1; i < V.size(); i++) {
98       // Add a comma
99       Result += ",";
100       // Add the feature
101       Result += V[i];
102     }
103   }
104   // Return the features string 
105   return Result;
106 }
107
108 /// Adding features.
109 void SubtargetFeatures::AddFeature(const std::string &String,
110                                    bool IsEnabled) {
111   // Don't add empty features
112   if (!String.empty()) {
113     // Convert to lowercase, prepend flag and add to vector
114     Features.push_back(PrependFlag(LowercaseString(String), IsEnabled));
115   }
116 }
117
118 /// Find KV in array using binary search.
119 template<typename T> const T *Find(const std::string &S, const T *A, size_t L) {
120   // Make the lower bound element we're looking for
121   T KV;
122   KV.Key = S.c_str();
123   // Determine the end of the array
124   const T *Hi = A + L;
125   // Binary search the array
126   const T *F = std::lower_bound(A, Hi, KV);
127   // If not found then return NULL
128   if (F == Hi || std::string(F->Key) != S) return NULL;
129   // Return the found array item
130   return F;
131 }
132
133 /// getLongestEntryLength - Return the length of the longest entry in the table.
134 ///
135 static size_t getLongestEntryLength(const SubtargetFeatureKV *Table,
136                                     size_t Size) {
137   size_t MaxLen = 0;
138   for (size_t i = 0; i < Size; i++)
139     MaxLen = std::max(MaxLen, std::strlen(Table[i].Key));
140   return MaxLen;
141 }
142
143 /// Display help for feature choices.
144 ///
145 static void Help(const SubtargetFeatureKV *CPUTable, size_t CPUTableSize,
146                  const SubtargetFeatureKV *FeatTable, size_t FeatTableSize) {
147   // Determine the length of the longest CPU and Feature entries.
148   unsigned MaxCPULen  = getLongestEntryLength(CPUTable, CPUTableSize);
149   unsigned MaxFeatLen = getLongestEntryLength(FeatTable, FeatTableSize);
150
151   // Print the CPU table.
152   errs() << "Available CPUs for this target:\n\n";
153   for (size_t i = 0; i != CPUTableSize; i++)
154     errs() << "  " << CPUTable[i].Key
155          << std::string(MaxCPULen - std::strlen(CPUTable[i].Key), ' ')
156          << " - " << CPUTable[i].Desc << ".\n";
157   errs() << "\n";
158   
159   // Print the Feature table.
160   errs() << "Available features for this target:\n\n";
161   for (size_t i = 0; i != FeatTableSize; i++)
162     errs() << "  " << FeatTable[i].Key
163          << std::string(MaxFeatLen - std::strlen(FeatTable[i].Key), ' ')
164          << " - " << FeatTable[i].Desc << ".\n";
165   errs() << "\n";
166   
167   errs() << "Use +feature to enable a feature, or -feature to disable it.\n"
168        << "For example, llc -mcpu=mycpu -mattr=+feature1,-feature2\n";
169   std::exit(1);
170 }
171
172 //===----------------------------------------------------------------------===//
173 //                    SubtargetFeatures Implementation
174 //===----------------------------------------------------------------------===//
175
176 SubtargetFeatures::SubtargetFeatures(const std::string &Initial) {
177   // Break up string into separate features
178   Split(Features, Initial);
179 }
180
181
182 std::string SubtargetFeatures::getString() const {
183   return Join(Features);
184 }
185 void SubtargetFeatures::setString(const std::string &Initial) {
186   // Throw out old features
187   Features.clear();
188   // Break up string into separate features
189   Split(Features, LowercaseString(Initial));
190 }
191
192 /// SetImpliedBits - For each feature that is (transitively) implied by this
193 /// feature, set it.
194 ///
195 static
196 void SetImpliedBits(uint64_t &Bits, const SubtargetFeatureKV *FeatureEntry,
197                     const SubtargetFeatureKV *FeatureTable,
198                     size_t FeatureTableSize) {
199   for (size_t i = 0; i < FeatureTableSize; ++i) {
200     const SubtargetFeatureKV &FE = FeatureTable[i];
201
202     if (FeatureEntry->Value == FE.Value) continue;
203
204     if (FeatureEntry->Implies & FE.Value) {
205       Bits |= FE.Value;
206       SetImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);
207     }
208   }
209 }
210
211 /// ClearImpliedBits - For each feature that (transitively) implies this
212 /// feature, clear it.
213 /// 
214 static
215 void ClearImpliedBits(uint64_t &Bits, const SubtargetFeatureKV *FeatureEntry,
216                       const SubtargetFeatureKV *FeatureTable,
217                       size_t FeatureTableSize) {
218   for (size_t i = 0; i < FeatureTableSize; ++i) {
219     const SubtargetFeatureKV &FE = FeatureTable[i];
220
221     if (FeatureEntry->Value == FE.Value) continue;
222
223     if (FE.Implies & FeatureEntry->Value) {
224       Bits &= ~FE.Value;
225       ClearImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);
226     }
227   }
228 }
229
230 /// getFeatureBits - Get feature bits a CPU.
231 ///
232 uint64_t SubtargetFeatures::getFeatureBits(const std::string &CPU,
233                                          const SubtargetFeatureKV *CPUTable,
234                                          size_t CPUTableSize,
235                                          const SubtargetFeatureKV *FeatureTable,
236                                          size_t FeatureTableSize) {
237   assert(CPUTable && "missing CPU table");
238   assert(FeatureTable && "missing features table");
239 #ifndef NDEBUG
240   for (size_t i = 1; i < CPUTableSize; i++) {
241     assert(strcmp(CPUTable[i - 1].Key, CPUTable[i].Key) < 0 &&
242            "CPU table is not sorted");
243   }
244   for (size_t i = 1; i < FeatureTableSize; i++) {
245     assert(strcmp(FeatureTable[i - 1].Key, FeatureTable[i].Key) < 0 &&
246           "CPU features table is not sorted");
247   }
248 #endif
249   uint64_t Bits = 0;                    // Resulting bits
250
251   // Check if help is needed
252   if (CPU == "help")
253     Help(CPUTable, CPUTableSize, FeatureTable, FeatureTableSize);
254   
255   // Find CPU entry
256   const SubtargetFeatureKV *CPUEntry = Find(CPU, CPUTable, CPUTableSize);
257   // If there is a match
258   if (CPUEntry) {
259     // Set base feature bits
260     Bits = CPUEntry->Value;
261
262     // Set the feature implied by this CPU feature, if any.
263     for (size_t i = 0; i < FeatureTableSize; ++i) {
264       const SubtargetFeatureKV &FE = FeatureTable[i];
265       if (CPUEntry->Value & FE.Value)
266         SetImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);
267     }
268   } else {
269     errs() << "'" << CPU
270            << "' is not a recognized processor for this target"
271            << " (ignoring processor)\n";
272   }
273   // Iterate through each feature
274   for (size_t i = 0, E = Features.size(); i < E; i++) {
275     const std::string &Feature = Features[i];
276     
277     // Check for help
278     if (Feature == "+help")
279       Help(CPUTable, CPUTableSize, FeatureTable, FeatureTableSize);
280     
281     // Find feature in table.
282     const SubtargetFeatureKV *FeatureEntry =
283                        Find(StripFlag(Feature), FeatureTable, FeatureTableSize);
284     // If there is a match
285     if (FeatureEntry) {
286       // Enable/disable feature in bits
287       if (isEnabled(Feature)) {
288         Bits |=  FeatureEntry->Value;
289
290         // For each feature that this implies, set it.
291         SetImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize);
292       } else {
293         Bits &= ~FeatureEntry->Value;
294
295         // For each feature that implies this, clear it.
296         ClearImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize);
297       }
298     } else {
299       errs() << "'" << Feature
300              << "' is not a recognized feature for this target"
301              << " (ignoring feature)\n";
302     }
303   }
304
305   return Bits;
306 }
307
308 /// Get scheduling itinerary of a CPU.
309 void *SubtargetFeatures::getItinerary(const std::string &CPU,
310                                       const SubtargetInfoKV *Table,
311                                       size_t TableSize) {
312   assert(Table && "missing table");
313 #ifndef NDEBUG
314   for (size_t i = 1; i < TableSize; i++) {
315     assert(strcmp(Table[i - 1].Key, Table[i].Key) < 0 && "Table is not sorted");
316   }
317 #endif
318
319   // Find entry
320   const SubtargetInfoKV *Entry = Find(CPU, Table, TableSize);
321   
322   if (Entry) {
323     return Entry->Value;
324   } else {
325     errs() << "'" << CPU
326            << "' is not a recognized processor for this target"
327            << " (ignoring processor)\n";
328     return NULL;
329   }
330 }
331
332 /// print - Print feature string.
333 ///
334 void SubtargetFeatures::print(raw_ostream &OS) const {
335   for (size_t i = 0, e = Features.size(); i != e; ++i)
336     OS << Features[i] << "  ";
337   OS << "\n";
338 }
339
340 /// dump - Dump feature info.
341 ///
342 void SubtargetFeatures::dump() const {
343   print(dbgs());
344 }
345
346 /// getDefaultSubtargetFeatures - Return a string listing the features
347 /// associated with the target triple.
348 ///
349 /// FIXME: This is an inelegant way of specifying the features of a
350 /// subtarget. It would be better if we could encode this information
351 /// into the IR. See <rdar://5972456>.
352 ///
353 void SubtargetFeatures::getDefaultSubtargetFeatures(const Triple& Triple) {
354   if (Triple.getVendor() == Triple::Apple) {
355     if (Triple.getArch() == Triple::ppc) {
356       // powerpc-apple-*
357       AddFeature("altivec");
358     } else if (Triple.getArch() == Triple::ppc64) {
359       // powerpc64-apple-*
360       AddFeature("64bit");
361       AddFeature("altivec");
362     }
363   }
364 }