llvmc: First stab at better -march handling.
[oota-llvm.git] / tools / llvmc / src / Hooks.cpp
1 #include "llvm/ADT/StringMap.h"
2
3 #include <string>
4 #include <vector>
5
6 namespace hooks {
7 typedef std::vector<std::string> StrVec;
8 typedef llvm::StringMap<const char*> ArgMap;
9
10 /// ConvertToMAttrImpl - Common implementation of ConvertMArchToMAttr and
11 /// ConvertToMAttr. The optional Args parameter contains information about how
12 /// to transform special-cased values (for example, '-march=armv6' must be
13 /// forwarded as '-mattr=+v6').
14 std::string ConvertToMAttrImpl(const StrVec& Opts, const ArgMap* Args = 0) {
15   std::string out("-mattr=");
16   bool firstIter = true;
17
18   for (StrVec::const_iterator B = Opts.begin(), E = Opts.end(); B!=E; ++B) {
19     const std::string& Arg = *B;
20
21     if (firstIter)
22       firstIter = false;
23     else
24       out += ",";
25
26     // Check if the argument is a special case.
27     if (Args != 0) {
28       ArgMap::const_iterator I = Args->find(Arg);
29
30       if (I != Args->end()) {
31         out += '+';
32         out += I->getValue();
33         continue;
34       }
35     }
36
37     // Convert 'no-foo' to '-foo'.
38     if (Arg.find("no-") == 0 && Arg[3] != 0) {
39       out += '-';
40       out += Arg.c_str() + 3;
41     }
42     // Convert 'foo' to '+foo'.
43     else {
44       out += '+';
45       out += Arg;
46     }
47   }
48
49   return out;
50 }
51
52 // Values needed to be special-cased by ConvertMArchToMAttr.
53 const char* MArchMapKeys[] = { "armv6" };
54 const char* MArchMapValues[] = { "v6" };
55 const unsigned NumMArchMapKeys = sizeof(MArchMapKeys) / sizeof(const char*);
56
57 void InitializeMArchMap(ArgMap& Args) {
58   for (unsigned i = 0; i < NumMArchMapKeys; ++i) {
59     // Explicit cast to StringRef here is necessary to pick up the right
60     // overload.
61     Args.GetOrCreateValue(llvm::StringRef(MArchMapKeys[i]), MArchMapValues[i]);
62   }
63 }
64
65 /// ConvertMArchToMAttr - Try to convert -march from the gcc dialect to
66 /// something llc can understand.
67 std::string ConvertMArchToMAttr(const StrVec& Opts) {
68   static ArgMap MArchMap(NumMArchMapKeys);
69   static bool MArchMapInitialized = false;
70
71   if (!MArchMapInitialized) {
72     InitializeMArchMap(MArchMap);
73     MArchMapInitialized = true;
74   }
75
76   return ConvertToMAttrImpl(Opts, &MArchMap);
77 }
78
79 /// ConvertToMAttr - Convert '-mfoo' and '-mno-bar' to '-mattr=+foo,-bar'.
80 std::string ConvertToMAttr(const StrVec& Opts) {
81   return ConvertToMAttrImpl(Opts);
82 }
83
84 }