blob: a7b1b64c2951f8780f7ad8304129539109f136e4 [file] [log] [blame]
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001//===- subzero/src/IceGlobalContext.cpp - Global context defs ---*- C++ -*-===//
2//
3// The Subzero Code Generator
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 defines aspects of the compilation that persist across
11// multiple functions.
12//
13//===----------------------------------------------------------------------===//
14
Jim Stichnoth217dc082014-07-11 14:06:55 -070015#include <ctype.h> // isdigit(), isupper()
Jim Stichnothd97c7df2014-06-04 11:57:08 -070016
Jim Stichnothf7c9a142014-04-29 10:52:43 -070017#include "IceDefs.h"
18#include "IceTypes.h"
19#include "IceCfg.h"
20#include "IceGlobalContext.h"
21#include "IceOperand.h"
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070022#include "IceTargetLowering.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070023
24namespace Ice {
25
26// TypePool maps constants of type KeyType (e.g. float) to pointers to
27// type ValueType (e.g. ConstantFloat). KeyType values are compared
28// using memcmp() because of potential NaN values in KeyType values.
29// KeyTypeHasFP indicates whether KeyType is a floating-point type
30// whose values need to be compared using memcmp() for NaN
31// correctness. TODO: use std::is_floating_point<KeyType> instead of
32// KeyTypeHasFP with C++11.
33template <typename KeyType, typename ValueType, bool KeyTypeHasFP = false>
34class TypePool {
35 TypePool(const TypePool &) LLVM_DELETED_FUNCTION;
36 TypePool &operator=(const TypePool &) LLVM_DELETED_FUNCTION;
37
38public:
Jim Stichnothf61d5b22014-05-23 13:31:24 -070039 TypePool() : NextPoolID(0) {}
Jim Stichnothf7c9a142014-04-29 10:52:43 -070040 ValueType *getOrAdd(GlobalContext *Ctx, Type Ty, KeyType Key) {
41 TupleType TupleKey = std::make_pair(Ty, Key);
42 typename ContainerType::const_iterator Iter = Pool.find(TupleKey);
43 if (Iter != Pool.end())
44 return Iter->second;
Jim Stichnothf61d5b22014-05-23 13:31:24 -070045 ValueType *Result = ValueType::create(Ctx, Ty, Key, NextPoolID++);
Jim Stichnothf7c9a142014-04-29 10:52:43 -070046 Pool[TupleKey] = Result;
47 return Result;
48 }
Jim Stichnothf61d5b22014-05-23 13:31:24 -070049 ConstantList getConstantPool() const {
50 ConstantList Constants;
51 Constants.reserve(Pool.size());
52 // TODO: replace the loop with std::transform + lambdas.
53 for (typename ContainerType::const_iterator I = Pool.begin(),
54 E = Pool.end();
55 I != E; ++I) {
56 Constants.push_back(I->second);
57 }
58 return Constants;
59 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -070060
61private:
62 typedef std::pair<Type, KeyType> TupleType;
63 struct TupleCompare {
64 bool operator()(const TupleType &A, const TupleType &B) {
65 if (A.first != B.first)
66 return A.first < B.first;
67 if (KeyTypeHasFP)
68 return memcmp(&A.second, &B.second, sizeof(KeyType)) < 0;
69 return A.second < B.second;
70 }
71 };
72 typedef std::map<const TupleType, ValueType *, TupleCompare> ContainerType;
73 ContainerType Pool;
Jim Stichnothf61d5b22014-05-23 13:31:24 -070074 uint32_t NextPoolID;
Jim Stichnothf7c9a142014-04-29 10:52:43 -070075};
76
Matt Walad8f4a7d2014-06-18 09:55:03 -070077// UndefPool maps ICE types to the corresponding ConstantUndef values.
78class UndefPool {
79 UndefPool(const UndefPool &) LLVM_DELETED_FUNCTION;
80 UndefPool &operator=(const UndefPool &) LLVM_DELETED_FUNCTION;
81
82public:
83 UndefPool() : NextPoolID(0) {}
84
85 ConstantUndef *getOrAdd(GlobalContext *Ctx, Type Ty) {
86 ContainerType::iterator I = Pool.find(Ty);
87 if (I != Pool.end())
88 return I->second;
89 ConstantUndef *Undef = ConstantUndef::create(Ctx, Ty, NextPoolID++);
90 Pool[Ty] = Undef;
91 return Undef;
92 }
93
94private:
95 uint32_t NextPoolID;
96 typedef std::map<Type, ConstantUndef *> ContainerType;
97 ContainerType Pool;
98};
99
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700100// The global constant pool bundles individual pools of each type of
101// interest.
102class ConstantPool {
103 ConstantPool(const ConstantPool &) LLVM_DELETED_FUNCTION;
104 ConstantPool &operator=(const ConstantPool &) LLVM_DELETED_FUNCTION;
105
106public:
107 ConstantPool() {}
108 TypePool<float, ConstantFloat, true> Floats;
109 TypePool<double, ConstantDouble, true> Doubles;
110 TypePool<uint64_t, ConstantInteger> Integers;
111 TypePool<RelocatableTuple, ConstantRelocatable> Relocatables;
Matt Walad8f4a7d2014-06-18 09:55:03 -0700112 UndefPool Undefs;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700113};
114
115GlobalContext::GlobalContext(llvm::raw_ostream *OsDump,
116 llvm::raw_ostream *OsEmit, VerboseMask Mask,
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700117 TargetArch Arch, OptLevel Opt,
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700118 IceString TestPrefix)
119 : StrDump(OsDump), StrEmit(OsEmit), VMask(Mask),
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700120 ConstPool(new ConstantPool()), Arch(Arch), Opt(Opt),
121 TestPrefix(TestPrefix), HasEmittedFirstMethod(false) {}
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700122
Jim Stichnoth217dc082014-07-11 14:06:55 -0700123// Scan a string for S[0-9A-Z]*_ patterns and replace them with
124// S<num>_ where <num> is the next base-36 value. If a type name
125// legitimately contains that pattern, then the substitution will be
126// made in error and most likely the link will fail. In this case,
127// the test classes can be rewritten not to use that pattern, which is
128// much simpler and more reliable than implementing a full demangling
129// parser. Another substitution-in-error may occur if a type
130// identifier ends with the pattern S[0-9A-Z]*, because an immediately
131// following substitution string like "S1_" or "PS1_" may be combined
132// with the previous type.
133void GlobalContext::incrementSubstitutions(ManglerVector &OldName) const {
134 const std::locale CLocale("C");
135 // Provide extra space in case the length of <num> increases.
136 ManglerVector NewName(OldName.size() * 2);
137 size_t OldPos = 0;
138 size_t NewPos = 0;
139 size_t OldLen = OldName.size();
140 for (; OldPos < OldLen; ++OldPos, ++NewPos) {
141 if (OldName[OldPos] == '\0')
142 break;
143 if (OldName[OldPos] == 'S') {
144 // Search forward until we find _ or invalid character (including \0).
145 bool AllZs = true;
146 bool Found = false;
147 size_t Last;
148 for (Last = OldPos + 1; Last < OldLen; ++Last) {
149 char Ch = OldName[Last];
150 if (Ch == '_') {
151 Found = true;
152 break;
153 } else if (std::isdigit(Ch) || std::isupper(Ch, CLocale)) {
154 if (Ch != 'Z')
155 AllZs = false;
156 } else {
157 // Invalid character, stop searching.
158 break;
159 }
160 }
161 if (Found) {
162 NewName[NewPos++] = OldName[OldPos++]; // 'S'
163 size_t Length = Last - OldPos;
164 // NewPos and OldPos point just past the 'S'.
165 assert(NewName[NewPos - 1] == 'S');
166 assert(OldName[OldPos - 1] == 'S');
167 assert(OldName[OldPos + Length] == '_');
168 if (AllZs) {
Jim Stichnoth78b4c0b2014-07-11 15:29:23 -0700169 // Replace N 'Z' characters with a '0' (if N=0) or '1' (if
170 // N>0) followed by N '0' characters.
171 NewName[NewPos++] = (Length ? '1' : '0');
172 for (size_t i = 0; i < Length; ++i) {
Jim Stichnoth217dc082014-07-11 14:06:55 -0700173 NewName[NewPos++] = '0';
174 }
175 } else {
176 // Iterate right-to-left and increment the base-36 number.
177 bool Carry = true;
178 for (size_t i = 0; i < Length; ++i) {
179 size_t Offset = Length - 1 - i;
180 char Ch = OldName[OldPos + Offset];
181 if (Carry) {
182 Carry = false;
183 switch (Ch) {
184 case '9':
185 Ch = 'A';
186 break;
187 case 'Z':
188 Ch = '0';
189 Carry = true;
190 break;
191 default:
192 ++Ch;
193 break;
194 }
195 }
196 NewName[NewPos + Offset] = Ch;
197 }
198 NewPos += Length;
199 }
200 OldPos = Last;
201 // Fall through and let the '_' be copied across.
202 }
203 }
204 NewName[NewPos] = OldName[OldPos];
205 }
206 assert(NewName[NewPos] == '\0');
207 OldName = NewName;
208}
209
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700210// In this context, name mangling means to rewrite a symbol using a
211// given prefix. For a C++ symbol, nest the original symbol inside
212// the "prefix" namespace. For other symbols, just prepend the
213// prefix.
214IceString GlobalContext::mangleName(const IceString &Name) const {
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700215 // An already-nested name like foo::bar() gets pushed down one
216 // level, making it equivalent to Prefix::foo::bar().
217 // _ZN3foo3barExyz ==> _ZN6Prefix3foo3barExyz
218 // A non-nested but mangled name like bar() gets nested, making it
219 // equivalent to Prefix::bar().
220 // _Z3barxyz ==> ZN6Prefix3barExyz
221 // An unmangled, extern "C" style name, gets a simple prefix:
222 // bar ==> Prefixbar
223 if (getTestPrefix().empty())
224 return Name;
225
226 unsigned PrefixLength = getTestPrefix().length();
Jim Stichnoth217dc082014-07-11 14:06:55 -0700227 ManglerVector NameBase(1 + Name.length());
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700228 const size_t BufLen = 30 + Name.length() + PrefixLength;
Jim Stichnoth217dc082014-07-11 14:06:55 -0700229 ManglerVector NewName(BufLen);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700230 uint32_t BaseLength = 0; // using uint32_t due to sscanf format string
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700231
Derek Schuff44712d12014-06-17 14:34:34 -0700232 int ItemsParsed = sscanf(Name.c_str(), "_ZN%s", NameBase.data());
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700233 if (ItemsParsed == 1) {
234 // Transform _ZN3foo3barExyz ==> _ZN6Prefix3foo3barExyz
235 // (splice in "6Prefix") ^^^^^^^
Derek Schuff44712d12014-06-17 14:34:34 -0700236 snprintf(NewName.data(), BufLen, "_ZN%u%s%s", PrefixLength,
237 getTestPrefix().c_str(), NameBase.data());
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700238 // We ignore the snprintf return value (here and below). If we
239 // somehow miscalculated the output buffer length, the output will
240 // be truncated, but it will be truncated consistently for all
241 // mangleName() calls on the same input string.
Jim Stichnoth217dc082014-07-11 14:06:55 -0700242 incrementSubstitutions(NewName);
Derek Schuff44712d12014-06-17 14:34:34 -0700243 return NewName.data();
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700244 }
245
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700246 // Artificially limit BaseLength to 9 digits (less than 1 billion)
247 // because sscanf behavior is undefined on integer overflow. If
248 // there are more than 9 digits (which we test by looking at the
249 // beginning of NameBase), then we consider this a failure to parse
250 // a namespace mangling, and fall back to the simple prefixing.
Derek Schuff44712d12014-06-17 14:34:34 -0700251 ItemsParsed = sscanf(Name.c_str(), "_Z%9u%s", &BaseLength, NameBase.data());
252 if (ItemsParsed == 2 && BaseLength <= strlen(NameBase.data()) &&
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700253 !isdigit(NameBase[0])) {
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700254 // Transform _Z3barxyz ==> _ZN6Prefix3barExyz
255 // ^^^^^^^^ ^
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700256 // (splice in "N6Prefix", and insert "E" after "3bar")
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700257 // But an "I" after the identifier indicates a template argument
258 // list terminated with "E"; insert the new "E" before/after the
259 // old "E". E.g.:
260 // Transform _Z3barIabcExyz ==> _ZN6Prefix3barIabcEExyz
261 // ^^^^^^^^ ^
262 // (splice in "N6Prefix", and insert "E" after "3barIabcE")
Jim Stichnoth217dc082014-07-11 14:06:55 -0700263 ManglerVector OrigName(Name.length());
264 ManglerVector OrigSuffix(Name.length());
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700265 uint32_t ActualBaseLength = BaseLength;
266 if (NameBase[ActualBaseLength] == 'I') {
267 ++ActualBaseLength;
268 while (NameBase[ActualBaseLength] != 'E' &&
269 NameBase[ActualBaseLength] != '\0')
270 ++ActualBaseLength;
271 }
Derek Schuff44712d12014-06-17 14:34:34 -0700272 strncpy(OrigName.data(), NameBase.data(), ActualBaseLength);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700273 OrigName[ActualBaseLength] = '\0';
Derek Schuff44712d12014-06-17 14:34:34 -0700274 strcpy(OrigSuffix.data(), NameBase.data() + ActualBaseLength);
275 snprintf(NewName.data(), BufLen, "_ZN%u%s%u%sE%s", PrefixLength,
276 getTestPrefix().c_str(), BaseLength, OrigName.data(),
277 OrigSuffix.data());
Jim Stichnoth217dc082014-07-11 14:06:55 -0700278 incrementSubstitutions(NewName);
Derek Schuff44712d12014-06-17 14:34:34 -0700279 return NewName.data();
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700280 }
281
282 // Transform bar ==> Prefixbar
283 // ^^^^^^
284 return getTestPrefix() + Name;
285}
286
287GlobalContext::~GlobalContext() {}
288
289Constant *GlobalContext::getConstantInt(Type Ty, uint64_t ConstantInt64) {
290 return ConstPool->Integers.getOrAdd(this, Ty, ConstantInt64);
291}
292
293Constant *GlobalContext::getConstantFloat(float ConstantFloat) {
294 return ConstPool->Floats.getOrAdd(this, IceType_f32, ConstantFloat);
295}
296
297Constant *GlobalContext::getConstantDouble(double ConstantDouble) {
298 return ConstPool->Doubles.getOrAdd(this, IceType_f64, ConstantDouble);
299}
300
301Constant *GlobalContext::getConstantSym(Type Ty, int64_t Offset,
302 const IceString &Name,
303 bool SuppressMangling) {
304 return ConstPool->Relocatables.getOrAdd(
305 this, Ty, RelocatableTuple(Offset, Name, SuppressMangling));
306}
307
Matt Walad8f4a7d2014-06-18 09:55:03 -0700308Constant *GlobalContext::getConstantUndef(Type Ty) {
309 return ConstPool->Undefs.getOrAdd(this, Ty);
310}
311
312Constant *GlobalContext::getConstantZero(Type Ty) {
313 switch (Ty) {
314 case IceType_i1:
315 case IceType_i8:
316 case IceType_i16:
317 case IceType_i32:
318 case IceType_i64:
319 return getConstantInt(Ty, 0);
320 case IceType_f32:
321 return getConstantFloat(0);
322 case IceType_f64:
323 return getConstantDouble(0);
Matt Wala928f1292014-07-07 16:50:46 -0700324 case IceType_v4i1:
325 case IceType_v8i1:
326 case IceType_v16i1:
327 case IceType_v16i8:
328 case IceType_v8i16:
329 case IceType_v4i32:
330 case IceType_v4f32: {
331 IceString Str;
332 llvm::raw_string_ostream BaseOS(Str);
333 Ostream OS(&BaseOS);
334 OS << "Unsupported constant type: " << Ty;
335 llvm_unreachable(BaseOS.str().c_str());
336 } break;
Matt Walad8f4a7d2014-06-18 09:55:03 -0700337 case IceType_void:
338 case IceType_NUM:
339 break;
340 }
341 llvm_unreachable("Unknown type");
342}
343
Jim Stichnothf61d5b22014-05-23 13:31:24 -0700344ConstantList GlobalContext::getConstantPool(Type Ty) const {
345 switch (Ty) {
346 case IceType_i1:
347 case IceType_i8:
348 case IceType_i16:
349 case IceType_i32:
350 case IceType_i64:
351 return ConstPool->Integers.getConstantPool();
352 case IceType_f32:
353 return ConstPool->Floats.getConstantPool();
354 case IceType_f64:
355 return ConstPool->Doubles.getConstantPool();
Matt Wala928f1292014-07-07 16:50:46 -0700356 case IceType_v4i1:
357 case IceType_v8i1:
358 case IceType_v16i1:
359 case IceType_v16i8:
360 case IceType_v8i16:
361 case IceType_v4i32:
362 case IceType_v4f32: {
363 IceString Str;
364 llvm::raw_string_ostream BaseOS(Str);
365 Ostream OS(&BaseOS);
366 OS << "Unsupported constant type: " << Ty;
367 llvm_unreachable(BaseOS.str().c_str());
368 } break;
Jim Stichnothf61d5b22014-05-23 13:31:24 -0700369 case IceType_void:
370 case IceType_NUM:
371 break;
372 }
373 llvm_unreachable("Unknown type");
374}
375
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700376void Timer::printElapsedUs(GlobalContext *Ctx, const IceString &Tag) const {
377 if (Ctx->isVerbose(IceV_Timing)) {
378 // Prefixing with '#' allows timing strings to be included
379 // without error in textual assembly output.
380 Ctx->getStrDump() << "# " << getElapsedUs() << " usec " << Tag << "\n";
381 }
382}
383
384} // end of namespace Ice